query
stringlengths 7
9.5k
| document
stringlengths 10
1.07M
| negatives
listlengths 19
19
| metadata
dict |
---|---|---|---|
Triggers given action on a specific resource.
|
def trigger(resource_type_identifier, action)
# TODO: not tested
if @model.kinds.select { |kind| kind.term == resource_type }.any?
type_identifier = @model.kinds.select {
|kind| kind.term == resource_type_identifier
}.first.type_identifier
location = @model.get_by_id(type_identifier).location
resource_type_identifier = @endpoint + location
end
# check some basic pre-conditions
raise "Endpoint is not connected!" unless @connected
raise "Unknown resource identifier! #{resource_type_identifier}" unless resource_type_identifier.start_with? @endpoint
# encapsulate the acion in a collection
collection = Occi::Collection.new
scheme, term = action.split(' #')
collection.actions << Occi::Core::Action.new(scheme + '#', term)
# make the request
path = sanitize_resource_link(resource_type_identifier) + '?action=' + term
post path, collection
end
|
[
"def trigger(resource_type_identifier, action); end",
"def resource_action(resource)\n resource.action if resource.respond_to?(:action)\n end",
"def enqueue_action_single_resource(action, type, id)\n raise BadRequestError, \"Must specify an id for changing a #{type} resource\" unless id\n\n physical_switch = resource_search(id, type, collection_class(type))\n\n api_action(type, id) do\n begin\n desc = \"Performing #{action} for #{physical_switch_ident(physical_switch)}\"\n api_log_info(desc)\n task_id = queue_object_action(physical_switch, desc, :method_name => action, :role => :ems_operations)\n action_result(true, desc, :task_id => task_id)\n rescue StandardError => err\n action_result(false, err.to_s)\n end\n end\n end",
"def enqueue_action_single_resource(action, type, id)\n raise BadRequestError, \"Must specify an id for changing a #{type} resource\" unless id\n\n resource = resource_search(id, type, collection_class(type))\n\n api_action(type, id) do\n begin\n desc = \"Performing #{action} for #{resource_identify(resource)}\"\n api_log_info(desc)\n task_id = queue_object_action(resource, desc, :method_name => action, :role => :ems_operations)\n action_result(true, desc, :task_id => task_id)\n rescue StandardError => err\n action_result(false, err.to_s)\n end\n end\n end",
"def render_actions_for(resource)\n render 'actions', resource: resource\n end",
"def resource_action(name, options = {})\n action = TableObject::Action.new(name, options)\n resource_actions << action\n action\n end",
"def _call_action(action)\n send(action)\n end",
"def run_now(resource = nil)\n resource ||= self\n actions = Array(resource.action)\n Chef::Log.debug \"Immediate execution of #{resource.name} #{actions}\"\n resource.action(:nothing)\n actions.each { |action| resource.run_action(action) }\n end",
"def perform(action)\n case action\n when :index, :new then get action\n when :show, :edit then get action, id: 1\n when :update then put :update, id: 1\n when :create then post :create\n when :destroy then delete :destroy, id: 1\n end\n end",
"def proxy_action(action)\n Chef::Log.debug(\"[#{new_resource} Running proxied #{action} action\")\n new_resource.subresources.each do |r|\n begin\n r.run_action(action) if r.allowed_actions.include?(action)\n rescue Chef::Exceptions::UnsupportedAction\n # Don't care, just move on.\n end\n end\n end",
"def _one_item_action(func, resource_id, action, data = nil)\n url = detail_action_url(resource_id, action)\n @api_request.send(\n func,\n url,\n data,\n nil,\n self,\n resource_id\n )\n end",
"def apply\n @item.run_action(@action_name, *@action_args, current_intention: self)\n end",
"def triggering_action\n phase! Plan\n @triggering_action\n end",
"def run_action(action, notification_type = nil, notifying_resource = nil)\n source(notifying_resource) if source.nil? && !notifying_resource.nil?\n super\nend",
"def execute_todo(resource, action)\n if action == \"approve\"\n resource.approved = true \n resource.flagged = false\n if resource.save \n redirect_to review_resources_url, notice: \"#{resource.name} is approved!\"\n else \n redirect_to review_resources_url, alert: \"#{resource.name} could not be approved!\"\n end \n elsif action == \"destroy\"\n if resource.destroy\n redirect_to review_resources_url, notice: \"#{resource.name} has been deleted!\"\n else \n redirect_to review_resources_url, alert: \"#{topic.name} could not be deleted!\"\n end \n end \n end",
"def action_succeeded(**args)\n description, updated = super\n if updated\n resource.events.resource_update_applied(resource, action, description)\n resource.updated_by_last_action true\n end\n end",
"def run_all_actions(resource)\n Array(resource.action).each { |action| run_action(resource, action) }\n if run_context.unified_mode\n run_context.reverse_immediate_notifications(resource).each do |n|\n if updated_resources.include?(n.notifying_resource.declared_key)\n n.resolve_resource_reference(run_context.resource_collection)\n Chef::Log.info(\"#{resource} sent #{n.action} action to #{n.resource} (immediate at declaration time)\")\n run_action(n.resource, n.action, :immediate, n.notifying_resource)\n end\n end\n end\n ensure\n resource.executed_by_runner = true\n end",
"def invoke_action(name)\n end",
"def resource_action_command\n ACTION_COMMANDS[action_name.to_sym]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Refreshes the Occi::Model used inside the client. Useful for updating the model without creating a new instance or reconnecting. Saves a lot of time in an interactive mode.
|
def refresh
# re-download the model from the server
set_model
end
|
[
"def refresh\n # re-download the model from the server\n set_model\n end",
"def reload!\n # TODO reload OData entity\n #reset_changes\n end",
"def refresh(model)\n response = client.get(find_path(model.primary_key))\n if (200..299).include?(response.code)\n return transform_model(response.body, origin_model: model)\n else\n return transform_model(response.body, model_class: WscSdk::Models::Error)\n end\n end",
"def reload!\n ensure_service!\n @gapi_json = service.get_model dataset_id, model_id\n @reference = nil\n @exists = nil\n self\n end",
"def reload_models\n app.reload_models\n nil\n end",
"def reload_models\n clear_models\n require_models\n end",
"def refresh\n if persisted?\n self.update_from_user_obj!(self.class.find self.id)\n end\n end",
"def reload!\n # get the values from the persistence layer\n fetch!\n clear_changes!\n end",
"def reload\n properties(true)\n self\n end",
"def refresh!\n fetch_data\n end",
"def _save_refresh\n _save_set_values(_refresh_get(this.server?(:default)) || raise(NoExistingObject, \"Record not found\"))\n changed_columns.clear\n end",
"def save_and_reload! model\n model.save!\n model.reload\nend",
"def reload_models\n @models.values.each(&:reload)\n end",
"def synchronize()\n save()\n reload()\n end",
"def refresh\n do_refresh\n end",
"def refresh\n begin\n self.load_product\n self.refreshed_at = Time.now \n self.save \n rescue => exception\n # Failed to refresh \n end\n end",
"def reload\n begin_reset_model\n clear\n\n @items_to_models = Hash.new\n @models_to_items = Hash.new\n @names_to_item = Hash.new\n @items_metadata = Hash[self => Metadata.new([], [], Set.new)]\n @resolver_from_model = Hash.new\n\n seen = Set.new\n sorted_roots = @root_models.\n sort_by(&:priority).reverse\n\n sorted_roots.each do |root_model|\n models = discover_model_hierarchy(root_model.model, root_model.categories, root_model.resolver, seen)\n models.each do |m|\n @resolver_from_model[m] = root_model.resolver\n end\n end\n\n rowCount.times do |row|\n compute_and_store_metadata(item(row))\n end\n self.horizontal_header_labels = [\"\"]\n ensure\n end_reset_model\n end",
"def reload!\n reset!\n collection #force reload\n end",
"def reload!\n associations.clear\n\n remote = self.class.fetch(id, _prefix)\n return self if remote.nil?\n\n remote._attributes.each do |key, value|\n update_attribute(key, value)\n end\n\n self\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Performs POST requests and returns URI locations. Resource data must be provided in an Occi::Collection instance.
|
def post(path, collection)
# remove the leading slash
path = path.gsub(/\A\//, '')
headers = self.class.headers.clone
headers['Content-Type'] = @media_type
response = case @media_type
when 'application/occi+json'
self.class.post(@endpoint + path,
:body => collection.to_json,
:headers => headers)
when 'text/occi'
self.class.post(@endpoint + path,
:headers => collection.to_header.merge(headers))
else
self.class.post(@endpoint + path,
:body => collection.to_text,
:headers => headers)
end
response_msg = response_message response
case response.code
when 200
collection = Occi::Parser.parse(response.header["content-type"].split(";").first, response)
if collection.empty?
Occi::Parser.locations(response.header["content-type"].split(";").first, response.body, response.header).first
else
collection.resources.first.location if collection.resources.first
end
when 201
Occi::Parser.locations(response.header["content-type"].split(";").first, response.body, response.header).first
else
raise "HTTP POST failed! #{response_msg}"
end
end
|
[
"def post(path, collection)\n # remove the leading slash\n path = path.gsub(/\\A\\//, '')\n\n headers = self.class.headers.clone\n headers['Content-Type'] = @media_type\n\n response = case @media_type\n when 'application/occi+json'\n self.class.post(@endpoint + path,\n :body => collection.to_json,\n :headers => headers)\n when 'text/occi'\n self.class.post(@endpoint + path,\n :headers => collection.to_header.merge(headers))\n else\n self.class.post(@endpoint + path,\n :body => collection.to_text,\n :headers => headers)\n end\n\n response_msg = response_message response\n\n case response.code\n when 200\n collection = Occi::Parser.parse(response.header[\"content-type\"].split(\";\").first, response.body)\n\n if collection.empty?\n Occi::Parser.locations(response.header[\"content-type\"].split(\";\").first, response.body, response.headers).first\n else\n collection.resources.first.location if collection.resources.first\n end\n when 201\n # TODO: OCCI-OS hack, look for header Location instead of uri-list\n # This should be probably implemented in Occi::Parser.locations\n if response.header['location']\n response.header['location']\n else\n Occi::Parser.locations(response.header[\"content-type\"].split(\";\").first, response.body, response.headers).first\n end\n else\n raise \"HTTP POST failed! #{response_msg}\"\n end\n end",
"def perform_post_with_objects_from_collection(path, options, klass, collection_name)\n perform_request_with_objects_from_collection(:post, path, options, klass, collection_name)\n end",
"def perform_post_with_object_from_collection(path, options, klass, collection_name)\n perform_request_with_object_from_collection(:post, path, options, klass, collection_name)\n end",
"def map\n @post_locations = []\n @picture_locations = []\n \n unless params[:post_location_ids].blank?\n \n # Pass through each comma-delimited post location id\n params[:post_location_ids].split(',').each do |l|\n if !@location = Location.find_by_id(l)\n raise ActiveRecord::RecordNotFound\n end\n @post_locations.push @location\n end\n end\n \n unless params[:picture_location_ids].blank?\n \n # Pass through each comma-delimited picture location id\n params[:picture_location_ids].split(',').each do |l|\n if !@location = Location.find_by_id(l)\n ActiveRecord::RecordNotFound\n end\n @picture_locations.push @location\n end\n end\n end",
"def location_submissions\n\t\t\n\tend",
"def get_locations\n response = execute_get(\"/reference/location\")\n Location.from_array(decode(response))\n end",
"def post_to_cities!\n set_emails\n cl_uris = []\n if emails.present? && messages.present?\n\n # us_cities = CRAIGSLIST_CITIES_URLS\n craigslist_users = CraigslistUser.all\n cities_post_to = cities_a_day > craigslist_users.length ? craigslist_users.length : cities_a_day\n (0..(cities_post_to - 1)).each do |i|\n p = post_to_city(messages[i % messages.length], craigslist_users[(city_index + i) % craigslist_users.length])\n cl_uris << p.uri\n end\n self.city_index = cities_post_to\n end\n save!\n cl_uris\n end",
"def post\n resource.post(request, response)\n end",
"def submissions\n __log_activity\n __debug_route\n default_format(:json)\n @name, @list = get_submission_records\n respond_to(request.format)\n end",
"def sitelist_data\n res = \"val/wxfcs/all/#{@format}/sitelist?\"\n url = \"#{@base_url}#{res}key=#{@apikey}\"\n pp url\n url = URI.parse(url)\n resp = Net::HTTP.get(url)\n pp resp\n data = ::JSON.parse(resp)\n data['Locations']['Location'] # Step into the array to get location list\nend",
"def post endpoint, data\n do_request :post, endpoint, data\n end",
"def aggregate_internal_resource(ro_uri, respath=nil, options={})\n if respath\n options[:headers] ||= {}\n options[:headers]['slug'] = respath\n end\n # POST resource content to indicated URI\n code, reason, headers = do_request(\"POST\", ro_uri, options)\n unless [200,201].include?(code)\n error(code, \"Error creating aggregated resource content\",\n \"#{code}, #{reason}, #{respath}\")\n end\n proxyuri = headers[\"location\"]\n resource_uri = parse_links(headers)[RDF::ORE.proxyFor.to_s].first\n [code, reason, proxyuri, resource_uri]\n end",
"def post index_dir, url, body\n xtractr = nil\n xtractr = xtractr_for index_dir\n xtractr.post url, body\n end",
"def entries_to_http entries, url, http = Atom::HTTP.new\n coll = Atom::Collection.new url, http\n\n entries.each { |entry| coll.post! entry }\n end",
"def make_batch_request\n\t\trequest = Net::HTTP::Post.new( self.endpoint.path )\n\t\trequest[ 'Content-Type' ] = 'application/json'\n\n\t\treturn request\n\tend",
"def all(options = {})\n uri = options[:resolved] ? File.join(@uri, \"_resolved\") : @uri\n result = Rest.get(Rest.paramify_url(uri, options))\n options[:resolved] ? result[\"documents\"].map { |d| new(d) } : result[\"uris\"]\n end",
"def remote_search(*args)\n params = args.extract_options!\n collection = args.flatten\n ::FactoryGirl::RemoteStrategy.register_request(:get, FactoryGirl::RemoteStrategy.collection_url(collection, params),\n body: (collection.first.is_a?(Class) ? \"[]\" : collection.map { |e| FactoryGirl::RemoteStrategy.entity_hash(e, params) }.to_json))\nend",
"def create\n @postulate_collection = PostulateCollection.new(postulate_collection_params)\n\n respond_to do |format|\n if @postulate_collection.save\n format.html { redirect_to @postulate_collection }\n format.json { render action: 'show', status: :created, location: @postulate_collection }\n else\n format.html { render action: 'new' }\n format.json { render json: @postulate_collection.errors, status: :unprocessable_entity }\n end\n end\n end",
"def list_locations\n headers = default_headers\n headers['Accept'] = 'text/xml'\t# JSON locations not supported\n Nokogiri.XML(get('/locations', headers))\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Checks whether the given endpoint URI is valid and adds a trailing slash if necessary.
|
def prepare_endpoint(endpoint)
raise 'Endpoint not a valid URI' if (endpoint =~ URI::ABS_URI).nil?
@endpoint = endpoint.chomp('/') + '/'
end
|
[
"def ensure_url_ends_with_slash(url)\n return \"#{url}/\" unless url.end_with?(\"/\")\n\n return url\n end",
"def valid_endpoint(ep)\n if ep == nil\n raise ArgumentError, \"Request: An endpoint must be set\", caller\n elsif not ep.is_a? String\n raise TypeError, \"Request: An endpoint must be a string\", caller\n elsif ep.length == 0 # If endpoint was set to \"\"\n raise TypeError, \"Request: Endpoint cannot be empty\", caller\n elsif ep[0] != '/'\n raise ArgumentError, \"Request: Endpoint must begin with a '/'\", caller\n end\n\n # If we make it to here, we're good - so just return the endpoint\n ep\n end",
"def add_trailing_slash uri # :nodoc:\n uri = uri.to_s\n\n uri << '/' unless uri.end_with? '/'\n\n URI uri\n end",
"def trailing_slash?\n # If fullpath isn't defined (e.g., in testing), then just return true\n # so we don't do unnecessary redirects.\n return true if request.env['REQUEST_URI'].blank?\n \n request.env['REQUEST_URI'].match(/[^\\?]+/).to_s.last == '/'\n end",
"def get_endpoint_uri(endpoint)\n unless endpoint =~ URI::ABS_URI\n raise \"Endpoint not a valid absolute URI! #{endpoint.inspect}\"\n end\n\n # normalize URIs, remove trailing slashes\n endpoint = URI(endpoint)\n endpoint.path = endpoint.path.gsub(/\\/+/, '/').chomp('/')\n endpoint.query = nil\n\n endpoint\n end",
"def has_trailing_slash?\n !! (self =~ /\\/$/)\n end",
"def invalid_uri?(uri)\n uri.grep(/^(#{PROTOCOLS.join('|')}):\\/\\/\\w/).empty?\n end",
"def ensure_trailing_slash\n redirect_to url_for(params.merge(:trailing_slash => true)), :status => 301 unless trailing_slash?\n end",
"def valid_uri?\n URI.new(@chain_url).valid?\n end",
"def validate\n if self.scheme != nil &&\n (self.host == nil || self.host == \"\") &&\n (self.path == nil || self.path == \"\")\n raise InvalidURIError,\n \"Absolute URI missing hierarchical segment.\"\n end\n if self.host == nil\n if self.specified_port != nil ||\n self.user != nil ||\n self.password != nil\n raise InvalidURIError, \"Hostname not supplied.\"\n end\n end\n end",
"def validate_full_uri!(full_uri)\n return unless full_uri.scheme == 'http'\n\n begin\n return if ip_loopback?(IPAddr.new(full_uri.host))\n rescue IPAddr::InvalidAddressError\n addresses = Resolv.getaddresses(full_uri.host)\n return if addresses.all? { |addr| ip_loopback?(IPAddr.new(addr)) }\n end\n\n raise ArgumentError,\n 'AWS_CONTAINER_CREDENTIALS_FULL_URI must use a loopback '\\\n 'address when using the http scheme.'\n end",
"def endpoint_present?\n endpoint = Endpoint.find_by(user_id: user_id, verb: verb, path: path)\n if endpoint && (id.present? ? id != endpoint[:id] : true)\n errors.add(:verb, \"Endpoint already exist for the combination verb: #{verb} and path: #{path}\")\n errors.add(:path, \"Endpoint already exist for the combination path: #{path} and verb #{verb}\")\n end\n end",
"def url?(uri)\n /\\w+\\:\\/\\// =~ uri\n end",
"def valid_endpoint?(target)\n endpoints.include? target\n end",
"def ensure_no_trailing_slash(dir)\n dir[-1] != '/' ? dir : dir[0..-2]\n end",
"def redirect_trailing_slash?\n @redirect_trailing_slash\n end",
"def validate_relative_uri( uri, dir, doc )\n return validate_anchor(uri, doc) if uri.path.empty?\n\n path = if uri.path =~ %r/^\\//\n ::File.join(::Webby.site.output_dir, uri.path)\n else\n ::File.join(dir, uri.path)\n end\n path = ::File.join(path, 'index.html') if ::File.extname(path).empty?\n\n uri_str = path.dup\n (uri_str << '#' << uri.fragment) if uri.fragment\n return if @valid_uris.include? uri_str\n\n if test ?f, path\n valid = if uri.fragment\n validate_anchor(uri, Hpricot(::File.read(path)))\n else true end\n @valid_uris << uri_str if valid\n else\n @log.error \"invalid URI '#{uri.to_s}'\"\n end\n end",
"def sanitize_endpoint(endpoint, interface_specification)\n if endpoint.kind_of? String\n return sanitize_endpoint(@context.lookup_uri(endpoint), interface_specification)\n end\n unless endpoint.respond_to? interface_specification\n endpoint = @context.lookup_uri(\"#{endpoint.uri()}?api=#{interface_specification}\")\n end\n endpoint\n end",
"def validate_full_url\n uri = URI.parse(full_url)\n rescue URI::Error\n errors.add(:full_url, 'is not a valid url')\n ensure\n if uri.present?\n errors.add(:full_url, 'must be HTTP or HTTPS') unless uri.is_a?(URI::HTTP)\n errors.add(:full_url, 'is missing hostname') if uri.host.nil?\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Sets media type. Will choose either application/occi+json or text/plain based on the formats supported by the server.
|
def set_media_type
media_types = self.class.head(@endpoint).headers['accept']
Occi::Log.debug("Available media types: #{media_types}")
@media_type = case media_types
when /application\/occi\+json/
'application/occi+json'
else
'text/plain'
end
end
|
[
"def content_type=(value)\n self.header['Content-Type'] = value\n end",
"def set_content_type(response, format)\n response[:content_type] = format_to_mime(format)\n end",
"def media_type\n @media_type ||= MediaType.new(env['HTTP_ACCEPT'])\n end",
"def media_type=(value)\n @media_type = value\n end",
"def content_type=(ctype)\n @response_headers[\"Content-Type\"] = ctype\n end",
"def content_type=(val)\n write_attribute(:content_type, val)\n headers.merge!('Content-Type' => val)\n val\n end",
"def content_type=(value)\n @content_type = value\n end",
"def set_content_type raw_type\n response_object.mime_raw raw_type\n end",
"def content_type=(value)\n @content_type = value\n end",
"def content_type=(value)\n raise ArgumentError, \"content_type must be set to :data or :header, was: #{value.inspect}\" unless [:data, :header].include?(value)\n @content_type = value\n end",
"def set_content_type(response, format)\n raise NotImplementedError\n end",
"def media_type format\n Rack::Mime.mime_type \".#{format}\", format\n end",
"def set_content_type(override=false)\n if override || file.content_type.blank? || generic_content_type?\n new_content_type = ::MIME::Types.type_for(current_path).first.to_s\n if file.respond_to?(:content_type=)\n file.content_type = new_content_type\n else\n file.instance_variable_set(:@content_type, new_content_type)\n end\n end\n rescue ::MIME::InvalidContentType => e\n raise CarrierWave::ProcessingError, I18n.translate(:\"errors.messages.mime_types_processing_error\", :e => e)\n end",
"def add_content_type_header_version\n media_type = \"#{JSONAPI::MEDIA_TYPE}, #{OpenWebslides::MEDIA_TYPE}; version=#{OpenWebslides.config.api.version}\"\n response.headers['Content-Type'] = media_type\n end",
"def set_content_type(m, user_content_type, class_default) # :doc:\n params = m.content_type_parameters || {}\n case\n when user_content_type.present?\n user_content_type\n when m.has_attachments?\n if m.attachments.all?(&:inline?)\n [\"multipart\", \"related\", params]\n else\n [\"multipart\", \"mixed\", params]\n end\n when m.multipart?\n [\"multipart\", \"alternative\", params]\n else\n m.content_type || class_default\n end\n end",
"def mime_type=(type)\n write_attr 'mime-type', type\n end",
"def content_type=(contentType)\n @content_type = contentType\n end",
"def type\n # Default to 'text/plain'\n if @media_type_raw.nil? or @media_subtype_raw.nil?\n 'text/plain'\n else\n \"#{@media_type_raw}/#{@media_subtype_raw}\".downcase\n end\n end",
"def set_content_type(type, params = {})\n @header['content-type'] = [type + params.map{|k,v|\"; #{k}=#{v}\"}.join('')]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /employees_courses GET /employees_courses.json
|
def index
@employees_courses = EmployeesCourse.all
end
|
[
"def getCourses\n\t\treturn getFromAPI(API_URL)\n\tend",
"def index\n\t\t@courses = @teacher.courses\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @courses }\n end\n end",
"def index\n @courses = @student.courses\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @courses }\n end\n end",
"def index\n # Restituisce tutti i corsi di studio del degree e dell'anno indicati\n @courses = @degree.courses.year(params[:year])\n\n render json: @courses\n end",
"def index\n @api_v1_courses = Api::V1::Course.all\n end",
"def course\n get_course(params)\n if @course.nil?\n all_semesters = Semester.all\n (all_semesters.size..1).each do |i|\n semester = all_semesters[i-1]\n semester_subjects = semester.subjects.find_by_code( params[:subject_code] )\n next if semester_subjects.nil?\n course = semester_subjects.courses.find_by_number( params[:course_number] )\n next if course.nil?\n\n redirect_to show_course_path( semester.season, semester.year, params[:subject_code], params[:course_number] )\n return\n end\n redirect_to \"/\"\n return\n end\n @sections = @course.sections\n @meetings = []\n for section in @sections\n for meeting in section.meetings \n @meetings << meeting\n end\n end \n\t\t@types_of_sections = get_different_sections()\n course_ids = []\n course_list = []\n course_list << @course\n course_ids << @course.id\n @schedule = Scheduler.initial_schedule(course_list)\n# for sec in @course.sections\n# @schedule << sec\n# end\n @course_ids = course_ids.to_json\n\t\trender 'course'\n end",
"def fetch_course_enrollments\n bad_request_error('Unauthorized Access to Course Enrollments') && return unless enrollment_course_tutor_or_admin?\n @enrollments = Enrollment.where(course_id: @course.id)\n # TODO: Add pagination, fetch only first 20 by default\n render json: @enrollments\n end",
"def get_courses(opts = {})\n data, _status_code, _headers = get_courses_with_http_info(opts)\n data\n end",
"def index\n @current_courses = CurrentCourse.all\n render json: @current_courses\n end",
"def get_course_enrollments(course_id)\n open_canvas_http\n\n request = Net::HTTP::Get.new(\n \"/api/v1/courses/#{course_id}/enrollments?access_token=#{Rails.application.secrets.canvas_access_token}\"\n )\n response = @canvas_http.request(request)\n info = JSON.parse response.body\n\n info\n end",
"def index\n # @yearly_detail_courses = YearlyDetailCourse.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @yearly_detail_courses }\n end\n end",
"def index\n @assessment_courses = AssessmentCourse.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @assessment_courses }\n end\n end",
"def list_courses\n if current_user.is_admin?\n @user = User.find(params[:id])\n @courses = @user.courses\n respond_to do |format|\n format.xml { render :xml => @courses }\n end\n else\n respond_to do |format|\n format.xml { render :text => \"error\" }\n end\n end\n end",
"def courses\n respond_with Course.find_all_by_user_id(params[:id],:select => [:course_name])\n end",
"def index\n @educourses = Educourse.all\n end",
"def index\n @courses_people = CoursesPerson.all\n end",
"def index\n @given_courses = GivenCourse.all\n end",
"def index\n @course = Course.find(params[:course_id])\n @enrollments = @course.enrollments\n end",
"def index\n # Check for filters\n @courses = Course.getCourseInformation(params[:dept],params[:course])\n @page_title = \"Browse Courses\"\n respond_to do |format|\n format.html\n format.json {render json: @courses }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /employees_courses POST /employees_courses.json
|
def create
@employees_course = EmployeesCourse.new(employees_course_params)
respond_to do |format|
if @employees_course.save
format.html { redirect_to @employees_course, notice: 'Employees course was successfully created.' }
format.json { render :show, status: :created, location: @employees_course }
else
format.html { render :new }
format.json { render json: @employees_course.errors, status: :unprocessable_entity }
end
end
end
|
[
"def create\n # render plain: params[:courses].inspect\n @courses = Courses.new(courses_params)\n\n respond_to do |format|\n if @courses.save\n format.html { redirect_to @courses, notice: 'Course was successfully created.' }\n format.json { render :show, status: :created, location: @courses }\n else\n format.html { render :new }\n format.json { render json: @courses.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_courses\n objects = JSON.parse(request.raw_post)\n result = []\n objects.each do |item|\n obj = {}\n obj['number'] = item[\"number\"]\n coursenumber = @unilib.course_normalize(item[\"number\"])\n course = find_by_number(coursenumber)\n if not course\n obj['success'] = false\n else\n u = UserCourse.where(:user_id => @user[:id], :course_id => course[\"id\"],\n :group => 0).first_or_create\n obj['success'] = true\n end\n result.push(obj)\n end\n\n render :text => JSON.dump(result)\n end",
"def create\n @educourse = @educourse = current_educator.educourses.build(educourse_params)\n\n respond_to do |format|\n if @educourse.save\n format.html { redirect_to @educourse, notice: 'Course Added' }\n format.json { render :show, status: :created, location: @educourse }\n else\n format.html { render :new }\n format.json { render json: @educourse.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_and_get_courses\n objects = JSON.parse(request.raw_post)\n result = []\n objects.each do |item|\n coursenumber = @unilib.course_normalize(item[\"number\"])\n course = find_by_number(coursenumber)\n if not course\n course = {}\n course['number'] = item['number']\n course['success'] = false\n else\n u = UserCourse.where(:user_id => @user[:id], :course_id => course[\"id\"],\n :group => 0).first_or_create\n course['success'] = true\n end\n result.push(course)\n end\n\n render :text => JSON.dump(result)\n end",
"def create\n\t\t@enrollcourse = Enrollcourse.new(enrollcourse_params)\n\n\t\trespond_to do |format|\n\t\t\tif @enrollcourse.save\n\t\t\t\tformat.html { redirect_to @enrollcourse, notice: 'Enrollcourse was successfully created.' }\n\t\t\t\tformat.json { render :show, status: :created, location: @enrollcourse }\n\t\t\telse\n\t\t\t\tformat.html { render :new }\n\t\t\t\tformat.json { render json: @enrollcourse.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend",
"def create\n @course = Course.new(courses_params)\n\n respond_to do |format|\n if @course.save\n format.html { redirect_to @course, notice: 'Course was successfully created.' }\n format.json { render :show, status: :created, location: @course }\n else\n format.html { render :new }\n format.json { render json: @course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_courses\n uri = \"https://apis-dev.berkeley.edu/cxf/asws/course?departmentCode=#{CGI.escape(self.department_code)}&_type=xml&app_id=#{@@app_id}&app_key=#{@@app_key}\"\n puts uri\n begin\n doc = Department.call_api(uri)\n courses = doc.xpath(\"//CanonicalCourse\")\n courses.each do |course|\n course_number = course.xpath(\"courseNumber\").text\n course_uid = course.xpath(\"courseUID\").text\n begin\n self.courses << Course.make_course(course_number, course_uid, self.department_code)\n rescue => e\n puts \"error in multiple course creation: \" + e.message\n next\n end\n end\n self.last_updated = DateTime.now\n self.save\n rescue => e\n puts \"error in course creation: \" + e.message\n end\n end",
"def create\n @people_course = PeopleCourse.new(people_course_params)\n\n respond_to do |format|\n if @people_course.save\n format.html { redirect_to @people_course, notice: 'People course was successfully created.' }\n format.json { render :show, status: :created, location: @people_course }\n else\n format.html { render :new }\n format.json { render json: @people_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @courses_teacher = CoursesTeacher.new(courses_teacher_params)\n\n respond_to do |format|\n if @courses_teacher.save\n format.html { redirect_to @courses_teacher, notice: 'Courses teacher was successfully created.' }\n format.json { render :show, status: :created, location: @courses_teacher }\n else\n format.html { render :new }\n format.json { render json: @courses_teacher.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @courses_instructor = CoursesInstructor.new(params[:courses_instructor])\n\n respond_to do |format|\n if @courses_instructor.save\n format.html { redirect_to @courses_instructor, notice: 'Courses instructor was successfully created.' }\n format.json { render json: @courses_instructor, status: :created, location: @courses_instructor }\n else\n format.html { render action: \"new\" }\n format.json { render json: @courses_instructor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create(params)\n response = self.class.post(\n '/webservice/rest/server.php',\n {\n :query => query_hash('core_course_create_courses', token),\n :body => {\n :courses => {\n '0' => {\n :fullname => params[:full_name],\n :shortname => params[:short_name],\n :categoryid => params[:parent_category],\n :idnumber => params[:idnumber]\n }\n }\n }\n }.merge(query_options)\n )\n check_for_errors(response)\n response.parsed_response.first\n end",
"def create\n course = Course.includes(:professors).new(course_params)\n course.professor_ids=(params[:professors])\n\n if course.save\n render json: course.to_json(include: :professors)\n else\n render :json => { :errors => course.errors }, :status => 422\n end\n end",
"def create\n @exam_course = ExamCourse.new(params[:exam_course])\n\n respond_to do |format|\n if @exam_course.save\n format.html { redirect_to @exam_course, notice: 'Exam course was successfully created.' }\n format.json { render json: @exam_course, status: :created, location: @exam_course }\n else\n format.html { render action: \"new\" }\n format.json { render json: @exam_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n professor = Professor.new(professor_params)\n \n if professor.save\n render json: professor.to_json(include: :courses)\n else\n render :json => { :errors => professor.errors }, :status => 422\n end\n end",
"def create\n @teacher_course = TeacherCourse.new(teacher_course_params)\n\n respond_to do |format|\n if @teacher_course.save\n format.html { redirect_to @teacher_course, notice: 'Teacher course was successfully created.' }\n format.json { render :show, status: :created, location: @teacher_course }\n else\n format.html { render :new }\n format.json { render json: @teacher_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @question_course = QuestionCourse.new(params[:question_course])\n\n respond_to do |format|\n if @question_course.save\n format.html { redirect_to @question_course, notice: 'Question course was successfully created.' }\n format.json { render json: @question_course, status: :created, location: @question_course }\n else\n format.html { render action: \"new\" }\n format.json { render json: @question_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @enrolled_course = EnrolledCourse.new(enrolled_course_params)\n\n respond_to do |format|\n if @enrolled_course.save\n format.html { redirect_to courses_path, notice: 'Enrolled course was successfully created.' }\n format.json { render :show, status: :created, location: @enrolled_course }\n else\n format.html { redirect_to new_enrolled_course_path, notice: 'Both student and class should be selected.' }\n format.json { render json: @enrolled_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def addDegreeCourse\n\t\tcourse_id = params[:course_id]\n\t\tdegree_id = params[:degree_id]\n\n\t\tdata = AcdDegreeCourse.new(degree_id: degree_id , course_id: course_id)\n\t\tdata.save\n\t\trender json:{data:data , success:true}\n\tend",
"def create\n @admin_course = City.find(session[:current_city_id]).utility.courses.new(admin_course_params)\n\n respond_to do |format|\n if @admin_course.save\n format.html { redirect_to admin_courses_url, notice: 'Course was successfully created.' }\n format.json { render :show, status: :created, location: @admin_course }\n else\n format.html { render :new }\n format.json { render json: @admin_course.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PATCH/PUT /employees_courses/1 PATCH/PUT /employees_courses/1.json
|
def update
respond_to do |format|
if @employees_course.update(employees_course_params)
format.html { redirect_to @employees_course, notice: 'Employees course was successfully updated.' }
format.json { render :show, status: :ok, location: @employees_course }
else
format.html { render :edit }
format.json { render json: @employees_course.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n # TODO Strip company_id out of params here\n @v1_employee = V1::Employee.find(params[:id])\n\n if @v1_employee.update_attributes(employee_params)\n render json: @v1_employee, status: :ok\n else\n render json: @v1_employee.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @empire_course.update(empire_course_params)\n format.html { redirect_to @empire_course, notice: 'Empire course was successfully updated.' }\n format.json { render :show, status: :ok, location: @empire_course }\n else\n format.html { render :edit }\n format.json { render json: @empire_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @people_course.update(people_course_params)\n format.html { redirect_to @people_course, notice: 'People course was successfully updated.' }\n format.json { render :show, status: :ok, location: @people_course }\n else\n format.html { render :edit }\n format.json { render json: @people_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @studentcourse = Studentcourse.find(params[:id])\n if @studentcourse.update_attributes(studentcourse_params)\n render json: @studentcourse\n else\n render 'edit'\n end\n end",
"def update\n\n @company = Company.find(1)\n @employees = @company.get_employees()\n @proyecto_examen = @company.get_proyecto_exams\n\n\n respond_to do |format|\n if @proyecto_exam.update(proyecto_exam_params)\n format.html { redirect_to @proyecto_exam, notice: 'Proyecto exam was successfully updated.' }\n format.json { render :show, status: :ok, location: @proyecto_exam }\n else\n format.html { render :edit }\n format.json { render json: @proyecto_exam.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n course = Course.includes(:professors).find(params[:id])\n course.update!(course_params)\n \n course.professor_ids=(params[:professors])\n\n render json: course.to_json(include: :professors)\n end",
"def update\n @employee = Employee.find(params[:id])\n @employee.update(employee_params)\n render :json => {:employee => @employee}\n end",
"def update\n @exam_course = ExamCourse.find(params[:id])\n\n respond_to do |format|\n if @exam_course.update_attributes(params[:exam_course])\n format.html { redirect_to @exam_course, notice: 'Exam course was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @exam_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @person_course.update(person_course_params)\n format.html { redirect_to @person_course, notice: 'Person course was successfully updated.' }\n format.json { render :show, status: :ok, location: @person_course }\n else\n format.html { render :edit }\n format.json { render json: @person_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n professor = Professor.find(params[:id])\n professor.update!(professor_params)\n\n render json: professor.to_json(include: :courses)\n end",
"def update\n @question_course = QuestionCourse.find(params[:id])\n\n respond_to do |format|\n if @question_course.update_attributes(params[:question_course])\n format.html { redirect_to @question_course, notice: 'Question course was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @question_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @college_employee.update(college_employee_params)\n format.html { redirect_to @college_employee, notice: 'College employee was successfully updated.' }\n format.json { render :show, status: :ok, location: @college_employee }\n else\n format.html { render :edit }\n format.json { render json: @college_employee.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n # @yearly_detail_course = YearlyDetailCourse.find(params[:id])\n\n respond_to do |format|\n if @yearly_detail_course.update_attributes(params[:yearly_detail_course])\n format.html { redirect_to @yearly_detail_course, notice: 'Yearly detail course was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @yearly_detail_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @api_v1_course.update(api_v1_course_params)\n format.html { redirect_to @api_v1_course, notice: 'Course was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_course }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @courses_person.update(courses_person_params)\n format.html { redirect_to @courses_person, notice: 'Courses person was successfully updated.' }\n format.json { render :show, status: :ok, location: @courses_person }\n else\n format.html { render :edit }\n format.json { render json: @courses_person.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @course.update(course_params)\n render_jsonapi_response(@course)\n end",
"def update\n @employe = Employe.find(params[:id])\n\n respond_to do |format|\n if @employe.update_attributes(params[:employe])\n format.html { redirect_to @employe, notice: 'Employe was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @employe.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @admin_course.update(admin_course_params)\n format.html { redirect_to (params[:ref] || @admin_course), notice: t('crud.updated_successfully!', name: Admin::Course.model_name.human) }\n format.json { render :show, status: :ok, location: @admin_course }\n else\n format.html { render :edit }\n format.json { render json: @admin_course.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n inputs = { college_student: find_college_student! }.reverse_merge(params[:college_student])\n outcome = UpdateCollegeStudent.run(inputs)\n\n if outcome.valid?\n render json: outcome.result\n else\n @college_student = outcome\n render(:edit)\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /employees_courses/1 DELETE /employees_courses/1.json
|
def destroy
@employees_course.destroy
respond_to do |format|
format.html { redirect_to employees_courses_url, notice: 'Employees course was successfully destroyed.' }
format.json { head :no_content }
end
end
|
[
"def destroy\n @exam_course = ExamCourse.find(params[:id])\n @exam_course.destroy\n\n respond_to do |format|\n format.html { redirect_to exam_courses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lab_course = LabCourse.find(params[:id])\n @lab_course.destroy\n\n respond_to do |format|\n format.html { redirect_to lab_courses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_course.destroy\n respond_to do |format|\n format.html { redirect_to line_courses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n \t@studentcourse = Studentcourse.find(params[:id])\n @studentcourse.destroy\n render json: {success: \"ok\"}\n end",
"def destroy\n @admin_course.destroy\n respond_to do |format|\n format.html { redirect_to admin_courses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n # @yearly_detail_course = YearlyDetailCourse.find(params[:id])\n @yearly_detail_course.destroy\n\n respond_to do |format|\n format.html { redirect_to yearly_detail_courses_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @api_v1_course.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_courses_url, notice: 'Course was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @coursev2.destroy\n respond_to do |format|\n format.html { redirect_to coursev2s_path, notice: 'Course was successfully deleted.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @course.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_courses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @course.destroy\n respond_to do |format|\n format.html { redirect_to courses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @concourse = Concourse.find(params[:id])\n @concourse.destroy\n\n respond_to do |format|\n format.html { redirect_to concourses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @sele_course = SeleCourse.find(params[:id])\n @sele_course.destroy\n\n respond_to do |format|\n format.html { redirect_to sele_courses_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lab_course_student = LabCourseStudent.find(params[:id])\n @lab_course_student.destroy\n\n respond_to do |format|\n format.html { redirect_to lab_course_students_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @enrollment_course.destroy\n respond_to do |format|\n format.html { redirect_to enrollment_courses_url }\n format.json { head :no_content }\n end\n end",
"def delete_course_by_id(org_unit_id)\n path = \"/d2l/api/lp/#{$lp_ver}/courses/#{org_unit_id}\" # setup user path\n # ap path\n _delete(path)\n puts '[+] Course data deleted successfully'.green\nend",
"def destroy\n @oncourse_exercise.destroy\n respond_to do |format|\n format.html { redirect_to oncourse_exercises_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @course = Course.find(params[:id])\n @course.destroy\n\n respond_to do |format|\n format.html { redirect_to coursees_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @path_course.destroy\n respond_to do |format|\n format.html { redirect_to path_courses_url, notice: 'Path course was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @course = Course.find(params[:id])\n @course.destroy\n\n respond_to do |format|\n format.html { redirect_to courses_url }\n format.json { head :ok }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
==========Validating book, with unique UUID=================================================
|
def validate_books
csv_text = open(file.url)
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
book_hash = Book.new
book_hash.title = row["Book title"]
book_hash.author = Author.find_or_create_by(name: row["Book author"])
book_hash.published_at = Date.parse(row["Date published"])
book_hash.uuid = row["Unique identifier for the book"]
book_hash.publisher_name = row["Publisher name"]
book_hash.user_id = user_id
unless book_hash.valid?
self.errors[:base] << "UUID Already exist for #{row["Unique identifier for the book"]}"
end
end
end
|
[
"def valid?\n UUID_REGEX.match?(uuid)\n end",
"def valid_uuid?\n UUID_REGEX.match?(uuid)\n end",
"def verify_uuid(uuid,data)\n\t\tgenerate_uuid(data) == uuid\n\tend",
"def uuid?\n !match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/).nil?\n end",
"def valid_uuid?(uuid)\n if UUID_RE.match(uuid)\n true\n else\n false\n end\n end",
"def valid_undashed_uuid?(value)\n value =~ /\\A[[:xdigit:]]{32}\\z/\n end",
"def validate_uuid(uuid)\n unless uuid.is_a?(String)\n @log.error \"UUID is not a string\"\n return false\n end\n\n unless !!/^\\S{8}-\\S{4}-4\\S{3}-[89abAB]\\S{3}-\\S{12}$/.match(uuid.to_s)\n @log.error \"UUID is not a valid V4 UUID\"\n return false\n end\n return true\n end",
"def uuid?(item)\n item.to_s.match?(UUID_FORMAT)\n end",
"def uuid?(str)\n !!(str && str.size == 36 && str.match(/\\A\\h{8}-\\h{4}-\\h{4}-\\h{4}-\\h{12}\\z/))\n end",
"def is_uuid?(uuid)\n uuid =~ /[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}/i\n end",
"def guid_valid?(guid)\n guid.match(/^\\{?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\\}?$/i)\n end",
"def uuid_format?(str)\n return false unless 36 == str.length\n UUID_REGEX === str\n end",
"def test_validate_book_data\n b = Book.new('OL26412312M')\n assert_equal(b.title, 'The bazaar of bad dreams')\n assert_equal(b.author, 'Stephen King')\n assert_equal(true, b.cover?)\n\n b = Book.new('OL145191W')\n assert_equal(b.title, 'Picasso')\n assert_equal(true, b.subjects.include?('Amsterdam (Netherlands)'))\n assert_equal(b.cover_img_small, 'https://covers.openlibrary.org/b/id/2238306-S.jpg')\n\n b = Book.new('OL8141930M')\n assert_equal(b.isbn.to_s, '0786806931')\n assert_equal(true, b.rating > 3.5 && b.rating < 5) if set_goodreads_key\n assert_equal(b.cover_id, 544_129)\n assert_equal(b.publish_date, 'May 1, 2004')\n\n b = Book.new('OL24229110M')\n assert_equal(b.amazon_link, 'https://www.amazon.com/dp/0451149513')\n end",
"def is_valid(uuid)\n unless has? uuid\n return INVALID\n end\n if expired? uuid\n return EXPIRED\n end\n if locked? uuid\n return LOCKED\n end\n true\n end",
"def skip_uid_uniqueness?\n false\n end",
"def checkEventIdentifier(identifier)\n # Check for nil & empty\n if identifier.to_s.empty?\n return nil\n end\n\n # Check for UUID conformity\n uuid_regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n if !(identifier.to_s.downcase =~ uuid_regex)\n BigBlueButton.logger.info( \"The given identifier <#{identifier}> is not a valid UUID. Will be using generated UUID instead.\")\n return nil\n end\n\n # Check for existence in Opencast\n existsInOpencast = true\n begin\n response = RestClient::Request.new(\n :method => :get,\n :url => $oc_server + \"/api/events/\" + identifier,\n :user => $oc_user,\n :password => $oc_password,\n ).execute\n rescue RestClient::Exception => e\n existsInOpencast = false\n end\n if existsInOpencast\n BigBlueButton.logger.info( \"The given identifier <#{identifier}> already exists within Opencast. Will be using generated UUID instead.\")\n return nil\n end\n\n return identifier\nend",
"def valid_id?\n strip =~ /^[a-z0-9]{32}$/ ? true : false\n end",
"def ensure_unique\n end",
"def allows_unique?\n true\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
INSTANCE METHODS Returns the date the last email of a specified category was sent
|
def email_sent_at(category)
emails = self.email_logs.select {|e| e.category == category}
emails.collect {|e| e.created_at}.sort.last
end
|
[
"def emails_sent_at(category)\r\n emails = self.email_logs.select {|e|e.category == category}\r\n emails.collect {|e| e.created_at}.sort\r\n end",
"def last_activity\n if topics.empty?\n # If there are no topics yet in thic category then:\n updated_at\n else\n # Otherwise last activity is newest topic in this category is returned.\n topics.first.last_activity\n end\n end",
"def last_contacted_date_time\n return @last_contacted_date_time\n end",
"def last_delivered_date_time\n return @last_delivered_date_time\n end",
"def last_delivered_mail\n Merb::Mailer.deliveries.last\n end",
"def latest_mail(options = {})\n return only_latest(mail(options))\n end",
"def last_delivered_mail\n Merb::Mailer.deliveries.last\n end",
"def last_certification_date_time\n return @last_certification_date_time\n end",
"def last_message_time\n\t\tself.messages.last.created_at\n\tend",
"def time_last_received\n a = emails_received.order(\"created_at DESC\").first\n a.created_at if a\n end",
"def emails(category = nil)\r\n return category ? self.email_logs.select {|e| e.category == category} : self.email_logs\r\n end",
"def last_message_at\n @fetched_last_message_at ||= begin\n if @last_message_at.present?\n @last_message_at.to_i\n else\n created_at = Message.redis.hget(\"message:#{message_ids.last}:attrs\", :created_at)\n attrs['last_message_at'] = created_at.to_i if created_at.present?\n end\n end\n end",
"def last_update_date\n if self.forum_threads.empty?\n self.created_at\n else\n self.forum_threads.maximum('forum_posts.created_at', joins: :forum_posts)\n end\n end",
"def sent_at\n # Use date it arrived (created_at) if mail itself doesn't have Date: header\n self.mail.date || self.created_at\n end",
"def email_date\n strftime(MO.email_time_format)\n end",
"def last_mail\r\n # Uncomment if you use Sidekiq with ActionMailer\r\n # Sidekiq::Extensions::DelayedMailer.drain\r\n ActionMailer::Base.deliveries.first\r\n end",
"def last_updated\n self.dig_for_datetime(\"companySummary\", \"lastUpdateOn\")\n end",
"def last_update_date\n self.forum_posts.last_posting_date\n end",
"def last_update\n convert_time(@channel.pubDate)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns an array of the dates the email of a specified category was sent
|
def emails_sent_at(category)
emails = self.email_logs.select {|e|e.category == category}
emails.collect {|e| e.created_at}.sort
end
|
[
"def email_sent_at(category)\r\n emails = self.email_logs.select {|e| e.category == category}\r\n emails.collect {|e| e.created_at}.sort.last\r\n end",
"def emails(category = nil)\r\n return category ? self.email_logs.select {|e| e.category == category} : self.email_logs\r\n end",
"def daily_messenger_send\n # Check authorization\n if(ryan? || authorized_email?)\n message = authorized_email? ? parse_dm_email : params[:dailymessage]\n \n # If there's a daily message to send.\n if(message && ! message.empty?)\n \n mymessage = \"\"\n if(params[:mymessage] && ! params[:mymessage].empty?)\n mymessage = \"\\n\\n\\n\" + \n \"----------------------------------------------------\" + \"\\n\" +\n \"\\t\" + \"Message from Ryan\" + \"\\n\" +\n \"----------------------------------------------------\" + \"\\n\"\n mymessage = mymessage + params[:mymessage]\n end\n \n # These two lines of code will probably cause some heartache for me\n # in the future. Be aware.\n msg = DailyMessage.new(content: message)\n msg.save\n \n # Messages stores the original messages (with my date modification)\n messages = []\n \n #DailyMessage.all.reverse.each {|ms|\n # date_created = ms.created_at.in_time_zone.strftime(\"%a, %b %d\")\n # days_messages = ms.content.split(\"\\r\\n\\r\\n\").map do |x|\n # x = (!x.include? \"===\") ? date_created + \"\\r\\n\" + x :\n # x\n # end\n \n # messages = messages.concat(days_messages)\n #}\n \n days_messages = DailyMessage.last.content.split(\"\\r\\n\\r\\n\")\n \n messages = messages.concat(days_messages)\n \n current_date = Date.current.in_time_zone\n #messages = messages.reject {|ms| \n # last_relevant_date = Stringutils::get_dm_date(ms, current_date)\n # last_relevant_date != [] && last_relevant_date < current_date\n #}\n \n # Now I want to organize messages by category.\n category_test = Proc.new {|x| x.include?(\"===\")}\n ms_categorized = Arrayutils::group(messages, category_test, false, true)\n ms_categorized[\"all\"] = messages.reject{|ms| ms.include?(\"===\")}\n \n # TODO: Increase robustness. Currently useless.\n # Check for repeated messages and remove them.\n #redundant_indices = Arrayutils::redundant_indices(messagesComp)\n #messagesComp = Arrayutils::delete_at(messagesComp, redundant_indices)\n #senders = Arrayutils::delete_at(senders, redundant_indices)\n \n # Mappings store the messages \n mappings = {}\n \n DAILY_MESSENGER_KEYWORDS.each do |topic, keywords|\n category = DAILY_MESSENGER_CATEGORY_MAPS.fetch(topic, \"all\")\n ms_map = ms_categorized[category] # An array of messages in the category.\n \n anti_keywords = DAILY_MESSENGER_ANTI_KEYWORDS.fetch(topic, nil)\n if anti_keywords\n anti_keywords = anti_keywords.split(\",\")\n end\n mappings[topic] = DailyMessengerUtils::filter(ms_map, keywords.split(\",\"), anti_keywords)\n end\n \n DAILY_MESSENGER_SENDERS.each do |sender, sender_words|\n mappings[sender] = DailyMessengerUtils::filter_sender(ms_categorized[\"all\"], sender_words.split(\",\"))\n end\n \n # FOR DEBUGGING\n puts \"MAPPINGS: \"\n puts mappings\n \n # For each service daily, we get the correct messages,\n # put them together, and then send them to the person.\n ServiceDaily.all.each {|dm|\n \n email = dm.user.email\n dm_keys = dm.key_words.concat(dm.sender)\n \n filtered_content = mymessage.empty? ? \"\\r\\n\" : mymessage + \"\\r\\n\\r\\n\"\n filtered_content = Stringutils::to_html(filtered_content)\n \n preview = \"\"\n body = \"\"\n \n daily_messages = ms_categorized\n \n # If the user is an advanced user, we must manually construct their\n # mapping.\n filtered_messages = dm.advanced? ? DailyMessengerUtils.adv_filter(daily_messages, dm) :\n mappings.slice(*dm_keys)\n \n # DEBUGGING \n puts email + \"'s filtered messages are below:\"\n puts \"Advanced: \" + dm.advanced?.to_s\n puts \"ANTI: \" + dm.anti?.to_s\n puts \"ADV KEYWORDS: \" + dm.adv_keys.to_s\n \n puts \"FILTERED: \" \n puts filtered_messages.to_s\n \n if dm.anti?\n daily_messages.delete(\"all\")\n \n messages_to_remove = filtered_messages.values.flatten\n \n filtered_messages = DailyMessengerUtils.anti_filter(daily_messages, messages_to_remove)\n end\n \n preview = filtered_messages.keys.map{|key| DailyMessengerUtils::preview(key, filtered_messages[key])}.join\n body = filtered_messages.keys.map{|key| DailyMessengerUtils::body(key, filtered_messages[key])}.join\n \n filtered_content = filtered_content + preview + body\n \n # Assume that Daily Messenger is empty.\n subject = preview.blank? ? \"Daily Messenger: Nothing Interesting Going On\" :\n 'Your Daily Messenger for ' + Date.current.in_time_zone.strftime(\"%a, %b %d\")\n \n header = \"----------------------------------------------------\" + \"\\n\" +\n \"Change preferences at http://www.arg.press/my_daily_messenger\" + \"\\n\" +\n \"----------------------------------------------------\"\n header = Stringutils::to_html(header)\n \n filtered_content = header + filtered_content\n \n ## We try to send the email. If it fails, we send an email to me informing\n ## me of the issue.\n begin\n ServiceMailer::daily_messenger(email, subject, filtered_content).deliver\n rescue Postmark::InvalidMessageError => error_message\n ServiceMailer::email(email + \" was not able to receive their DM\", \"rynkwn@gmail.com\", error_message.to_s).deliver\n end\n }\n end\n end\n end",
"def get_sent_mails\n\n\t\t# setting request params\n\t\tparams = {\n\t\t\tbegin: Time.zone.now.to_i,\n\t\t\tascending: \"no\",\n\t\t\tpretty: \"yes\"\n\t\t}\n\n\t\tresult = @mg_client.get(\"#{ENV['DOMAIN']}/events\", params).to_h\n\t\treturn result[\"items\"]\n\tend",
"def delivery_dates\n dispatch_delivery_dates.map(&:delivery_date)\n end",
"def categories\n if !is_a_number?(params[:category])\n c = Category.find_by_name(params[:category])\n cat = c.id\n else\n cat = params[:category]\n end\n params[:id] = Time.now.strftime(\"%Y-%m-%d\") if !params[:id]\n if cat\n start = DateTime.strptime(\"#{params[:id]}T00:00:00+00:00\")\n month = start.strftime(\"%Y-%m\")\n \n @events = Calendar.filter_events(month, cat)\n \n @daily_events = @events.group_by { |d| d.start_date }\n else\n start = DateTime.strptime(\"#{params[:id]}T00:00:00+00:00\")\n month = start.strftime(\"%Y-%m\")\n @events = Calendar.current_events(params[:id])\n @daily_events = @events.group_by { |d| d.start_date }\n end\n end",
"def email_stat_by_campaigns(email)\n return handle_error('Empty email') if email.to_s.empty?\n send_request(\"emails/#{email}/campaigns\")\n end",
"def messages_to_send_since(start_time, end_time = Time.now)\n return [] if @calendar.nil?\n\n messages = []\n \n @location.alert_offset_list.each do |offset|\n events = events_in_range(start_time + offset.hours, end_time + offset.hours)\n unless events.empty?\n suffix = Schedule.offset_to_suffix(offset)\n messages += events.map do |event|\n compose_message(event, suffix, @location.sponsor)\n end\n end\n end\n \n return messages\n end",
"def changelog_posts_grouped\n changelog_posts.group_by { |post| post.data.posted.strftime('%Y-%m') }\n end",
"def emails_by_date\n puts params[:start_date]\n puts params[:end_date]\n\n #convert time to SG Time\n @start_date = Time.parse(params[:start_date])\n @end_date = Time.parse(params[:end_date])\n\n @emails = Email.where(\"created_at >= ?\", @start_date.beginning_of_day).where(\"created_at <= ?\", @end_date.end_of_day)\n\n #@emails_hash = @emails.group_by(&:email)\n @emails_hash = @emails.group_by {|email| email.created_at.strftime('%Y-%m-%d') }\n render json: @emails_hash\n end",
"def messages_from_daily(status)\n daily = http_get 'daily'\n doc = REXML::Document.new(daily.body)\n messages = []\n doc.elements.each('daily/day_entries/day_entry') do |ele|\n if ele.elements['timer_started_at']\n messages << [ele.elements['id'].text, \n \"<request><notes>#{ele.elements['notes'].text}\\n#{status}</notes><hours>#{ele.elements['hours'].text}</hours></request>\"]\n end\n end\n messages\n end",
"def failed_email_delivery_contacts\n \n failed_email_delivery_contacts = Array.new \n \n mailout_contacts.each do |mc|\n failed_email_delivery_contacts.push(mc) if !mc.delivery_timestamp.blank? && mc.delivery_failed\n end\n \n return failed_email_delivery_contacts\n end",
"def dailydigest_email(user)\n @user = user\n\n @profile_posts, @group_posts = Post.new_day_posts(@user)\n\n # @profile_posts is an array with posts. Add an element to the beginning of the array with a string \n # declaring how many new posts the user has\n if @profile_posts.length==1\n string = \"1 new post on your profile today\" #. Answer or thank them! // www.projecthelp.co/users/\" +user.id.to_s\n @profile_posts.unshift(string)\n elsif @profile_posts.length>1\n string = @profile_posts.length.to_s + \" new posts on your profile today. Answer or thank them! // www.projecthelp.co/users/\" +user.id.to_s\n @profile_posts.unshift(string)\n end\n\n subject = \"New posts for you today\"\n # @group_posts is an array with posts. Add an element to the beginning of the array with a string \n # declaring how many new posts the user has\n @group_posts.each do |group_id, posts|\n if !posts[0].title.blank?\n subject = posts[0].title\n end\n\n if posts.length == 1\n string = \"1 new post in \" +Group.find(group_id).name+ \" today\" #. Answer or thank them! // www.projecthelp.co/groups/\" +group_id.to_s\n posts.unshift(string)\n elsif posts.length > 1\n string = posts.length.to_s+ \" new posts in \" +Group.find(group_id).name+ \" today. Answer or thank them! // www.projecthelp.co/groups/\" +group_id.to_s\n posts.unshift(string)\n end\n\n end\n\n if (@profile_posts!=nil && @profile_posts.length>0) || (@group_posts!=nil && @group_posts.length>0)\n mail :to => user.email,\n :subject => subject\n end\n end",
"def get_all_response_of_user(mail)\n mail.mail_events\n end",
"def recent_activity_feeds\n return [] if current_course.nil?\n\n current_course.notifications.feed.order(created_at: :desc)\n end",
"def get_mail_clients\n if self.campaign_info\n analytics_api = ANALYTICS_CLASS.constantize.new\n return analytics_api.get_mail_clients(self.campaign_info.campaign_id)\n else\n return {}\n end\n end",
"def technical_notification_mails\n return @technical_notification_mails\n end",
"def read_email_by_date\n # Search by date. Unfortunately, IMAP date searching isn't very\n # granular. To ensure we get all emails we go back two full\n # days. We filter out duplicates later.\n date_string = 2.days.ago.strftime(\"%d-%b-%Y\")\n uids = client.uid_search([\"SINCE\", date_string])\n uids.each do |uid|\n break if stopping?\n process_uid(uid) unless stopping?\n end\n\n return uids.count\n end",
"def notify_couriers\n @current_time = Time.zone.now\n\n @packages = find_packages(application_params[:city_db_id])\n\n @emails = find_emails(application_params[:city_db_id])\n\n ## Create list of recipients as array of strings\n @recipients = []\n @emails.each do |email|\n @recipients << email.email_value\n end\n\n # Tell the Emailer to send a notification email to all couriers\n Emailer.packages_notification(@current_time,@packages,@recipients).deliver\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns all emails or all emails of a specified category (if given)
|
def emails(category = nil)
return category ? self.email_logs.select {|e| e.category == category} : self.email_logs
end
|
[
"def email_sent_at(category)\r\n emails = self.email_logs.select {|e| e.category == category}\r\n emails.collect {|e| e.created_at}.sort.last\r\n end",
"def emails_sent_at(category)\r\n emails = self.email_logs.select {|e|e.category == category}\r\n emails.collect {|e| e.created_at}.sort\r\n end",
"def get_emails_by_type(email_type=nil)\n\n if email_type.nil?\n return [self.email]\n else\n ret = []\n [\n [self.email_sub1, self.email_sub1_type],\n [self.email_sub2, self.email_sub2_type]\n ].each do |sub_entry|\n sub_addr, sub_type = sub_entry\n if sub_type == email_type\n unless sub_addr.nil? or sub_addr.empty?\n ret << sub_addr\n end\n end\n end\n return ret\n end\n end",
"def filter_mail(email, threaded=false)\n\n unless check_email_addresses(email) #first check if email address matches category\n check_subject_and_body(email) #Second check each word in subject and body against keywords in categories\n end\n\n if !threaded\n email.save\n email.category.cases << email.case\n end\n\n return email\n end",
"def check_email_addresses(email)\n @all_categories.each do |cat|\n cat.email_accounts.each do |account|\n #see if theres a matching email address\n if account.email_address.downcase.eql? email.to.downcase\n attach_category_to_email(email,cat)\n return true\n end\n end\n end\n return false\n end",
"def find_emails(opts)\n emails.reverse.select do |email|\n email.to.include?(opts[:to]) || email.subject == opts[:subject]\n end\n end",
"def scrape_all_emoji_in_category!(category, delay = 2)\n scrape_all_emoji_in_category(@all_emoji[category], delay)\n end",
"def email_stat_by_campaigns(email)\n return handle_error('Empty email') if email.to_s.empty?\n send_request(\"emails/#{email}/campaigns\")\n end",
"def send_inquiry_mailers\n @contact = self\n \n if category == \"wholesale\"\n \n ContactMailer.wholesale_inquiry(@contact).deliver\n ContactMailer.sent_wholesale_inquiry(@contact).deliver\n \n elsif category == \"volunteer\"\n \n ContactMailer.volunteer_inquiry(@contact).deliver\n ContactMailer.sent_volunteer_inquiry(@contact).deliver\n \n elsif category == \"suggest\"\n \n ContactMailer.suggest_inquiry(@contact).deliver\n ContactMailer.sent_suggest_inquiry(@contact).deliver\n \n end\n end",
"def articles_with_category(category, items = articles)\n items.select { |article| has_category?(category, article) }\n end",
"def get_all_from_category(category)\n @dishes.find_all do |dish|\n dish.category == category\n end\n end",
"def select_email\n read_contacts.select { |contact|\n contact.any? { |key, value|\n value.include?('.org')\n }\n }\nend",
"def select_by_email(contacts)\n mail_select = contacts.select {|contact| contact[:email] =~ /\\b#{\".org\"}/}\n\n print mail_select\nend",
"def get_email_in_group_ids(type)\n result = []\n broadcast_group_ids.each do |g_id|\n begin\n grp = Group.find(g_id)\n eo = grp.email_option\n options = (type == :text) ? [:premium, :standard_and_premium, :all, :premium_and_tts] : [:tts, :premium_and_tts, :all, :standard_and_tts]\n if grp.need_review\n result << g_id if (grp.get_topic(self.coded_subject).is_approved? && options.include?(eo.send_text) rescue false)\n else\n result << g_id if options.include?(eo.send_text)\n end\n rescue\n next\n end\n end\n result.compact\n end",
"def items_with_category(category, items=nil)\n items = @items if items.nil?\n items.select { |item| has_category?( item, category ) }\n end",
"def search_emails(search, subject)\n @gmail.in_mailbox(self) do\n email_results = @gmail.imap.uid_search(search).collect { |uid| messages[uid] ||= Message.new(@gmail, self, uid) }\n # If subject is not nil, filter results by subject and mark the rest of the emails as unread.\n if subject\n result = email_results.select {|email| email.subject == subject} \n email_results.reject {|email| email.subject == subject}.each do |email|\n email.mark(:unread)\n end\n return result\n end\n return email_results\n end\n end",
"def meals_by_category(category)\n # API EXAMPLE: https://www.themealdb.com/api/json/v1/1/filter.php?c=Seafood\n content = api_call(\"filter.php?c=#{category}\")\n validate(content)\n content\n end",
"def get_category_gifs(category)\n category_gifs = []\n\n @gifs.each do |gif|\n unless gif[:category] == nil\n if gif[:category] == category\n category_gifs << gif\n end\n else\n if get_categoryless_gif( gif[:name] ) == category\n return gif\n end\n end\n end\n\n category_gifs\n end",
"def get_emails(limit = 100, offset = 0, conditions = {})\n params = extract_query_params conditions\n\n params['limit'] = limit\n params['offset'] = offset\n\n request :get, \"/v3/emails.json\", params\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Public: Deposit Money in a pot amount The amount to deposit, in pennies. source_account_id The account_id of the account to withdraw from. dedupe_id (optional) A random string, to prevent duplicate deposits. Returns self: a single Monzo::Pot
|
def deposit!(amount, source_account_id, dedupe_id = SecureRandom.uuid)
data = {
amount: amount,
source_account_id: source_account_id,
dedupe_id: dedupe_id,
}
response = Monzo.client.put("/pots/#{@id}/deposit", data)
parsed_response = parse_response(response)
update_self(parsed_response)
end
|
[
"def withdraw!(amount, destination_account_id, dedupe_id = SecureRandom.uuid)\n data = {\n amount: amount,\n destination_account_id: destination_account_id,\n dedupe_id: dedupe_id,\n }\n\n response = Monzo.client.put(\"/pots/#{@id}/withdraw\", data)\n parsed_response = parse_response(response)\n update_self(parsed_response)\n end",
"def money(input)\n MoneyDrop.new(input.to_money)\n end",
"def deposit\n entidad.deposit(monto, operadora)\n end",
"def deposit amount, account\n if account == \"checkings\"\n @checkings += amount.round(2)\n else\n @savings += amount.round(2)\n end\n self\n end",
"def deposit(money_to_deposit)\n @balance += money_to_deposit\n end",
"def deposit(amount)\n if self.account == nil\n missing_account\n else\n self.account.deposit(amount)\n @cash -= amount\n end\n end",
"def total_debt\n Money.new(all_debts.sum { |_, debt| debt }, 'PLN')\n end",
"def deduct_money_from_account(balance_to_deduct)\n self.balance -= balance_to_deduct\n self.save\n end",
"def auto_traded_deposit\n\t\tself.deposits.find_by(:exchange_address => self.pool.coin.cryptsy_address)\n\tend",
"def dollars!(total, exp = {})\n @expenditures.clear\n newexp = Expenditure.new\n if exp[\"name\"]\n newexp.BudgetObject.name = exp[\"name\"]\n else\n newexp.BudgetObject.name = \"cash\"\n end\n newexp.dollars = total\n add(newexp)\n end",
"def collect_deposit!(deposit, deposit_spread)\n @adapter.configure(wallet: @wallet.to_wallet_api_settings,\n currency: deposit.currency.to_blockchain_api_settings)\n\n pa = PaymentAddress.find_by(wallet_id: @wallet.id, member: deposit.member, address: deposit.address)\n # NOTE: Deposit wallet configuration is tricky because wallet UIR\n # is saved on Wallet model but wallet address and secret\n # are saved in PaymentAddress.\n @adapter.configure(\n wallet: @wallet.to_wallet_api_settings\n .merge(pa.details.symbolize_keys)\n .merge(address: pa.address)\n .tap { |s| s.merge!(secret: pa.secret) if pa.secret.present? }\n .compact\n )\n\n deposit_spread.map do |transaction|\n # In #spread_deposit valid transactions saved with pending state\n if transaction.status.pending?\n transaction = @adapter.create_transaction!(transaction, subtract_fee: true)\n save_transaction(transaction.as_json.merge(from_address: deposit.address), deposit) if transaction.present?\n end\n transaction\n end\n end",
"def send_penny_amount(id, opts = {})\n data, _status_code, _headers = send_penny_amount_with_http_info(id, opts)\n data\n end",
"def deposits\n Transfer.where(\n to: id,\n transfer_type: 'deposit'\n )\n end",
"def deposit (amount, options={})\n options[:memo] ||= 'Regular deposit.'\n @transactions.push({:amount => amount, :memo => options[:memo]})\n end",
"def deposit(amount, coinbase_account_id, &block)\n order = { \n 'type' => 'deposit',\n 'amount' => amount,\n 'coinbase_account_id' => coinbase_account_id\n }\n post('orders', order, &block)\n end",
"def money(key)\n Money.new @config.fetch(key)\n end",
"def deposit(amount)\n amount = amount.abs\n @balance = @balance + amount\n one_transaction\n return @balance\n end",
"def liquidity_pool_deposit(liquidity_pool_id:, max_amount_a:, max_amount_b:, min_price:, max_price:, source_account: nil)\n op = LiquidityPoolDepositOp.new(\n liquidity_pool_id: PoolID.from_xdr(liquidity_pool_id, :hex),\n max_amount_a: interpret_amount(max_amount_a),\n max_amount_b: interpret_amount(max_amount_b),\n min_price: Price.from(min_price),\n max_price: Price.from(max_price)\n )\n\n make(source_account: source_account, body: [:liquidity_pool_deposit, op])\n rescue XDR::ReadError\n raise ArgumentError, \"invalid liquidity pool ID '#{balance_id}'\"\n end",
"def get_dkp_spent id\n if @chars[id][:dkp][:spent].nil? then\n sql = \"SELECT SUM(l.price) AS spent FROM loots as l WHERE l.character_id = #{id}\"\n @chars[id][:dkp][:spent] = conn.query(sql).first[:spent]\n end\n\n @chars[id][:dkp][:spent]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Public: Withdraw Money from a pot amount The amount to withdraw, in pennies. destination_account_id The account_id of the account to deposit into. dedupe_id (optional) A random string, to prevent duplicate deposits. Returns self: a single Monzo::Pot
|
def withdraw!(amount, destination_account_id, dedupe_id = SecureRandom.uuid)
data = {
amount: amount,
destination_account_id: destination_account_id,
dedupe_id: dedupe_id,
}
response = Monzo.client.put("/pots/#{@id}/withdraw", data)
parsed_response = parse_response(response)
update_self(parsed_response)
end
|
[
"def deposit!(amount, source_account_id, dedupe_id = SecureRandom.uuid)\n data = {\n amount: amount,\n source_account_id: source_account_id,\n dedupe_id: dedupe_id,\n }\n\n response = Monzo.client.put(\"/pots/#{@id}/deposit\", data)\n parsed_response = parse_response(response)\n update_self(parsed_response)\n end",
"def deposit amount, account\n if account == \"checkings\"\n @checkings += amount.round(2)\n else\n @savings += amount.round(2)\n end\n self\n end",
"def withdraw acct, amount\n\t\t\treturn \"Invalid account: '#{acct}'\" unless valid_acct acct\n\n\t\t\tamount = to_money -(amount)\n\n\t\t\tadjust acct, amount\n\t\tend",
"def deduct_money_from_account(balance_to_deduct)\n self.balance -= balance_to_deduct\n self.save\n end",
"def deposit(amount)\n if self.account == nil\n missing_account\n else\n self.account.deposit(amount)\n @cash -= amount\n end\n end",
"def deposit(money_to_deposit)\n @balance += money_to_deposit\n end",
"def pay_for_drink(drink)\n @wallet -= drink.price\n end",
"def withdraw\n copy self.class.withdraw(@id)\n true\n end",
"def withdraw amount, account\n if account == \"checkings\"\n if amount > @checkings\n raise InsufficientFundsError\n else\n @checkings -= amount.round(2)\n end\n else\n if amount > @savings\n raise InsufficientFundsError\n else\n @savings -= amount.round(2)\n end\n end\n self\n end",
"def deposit\n entidad.deposit(monto, operadora)\n end",
"def +(other)\n Money.new(amount + other.amount)\n end",
"def money(input)\n MoneyDrop.new(input.to_money)\n end",
"def withdraw(amount)\n @balance = @balance - amount\n end",
"def collect_deposit!(deposit, deposit_spread)\n @adapter.configure(wallet: @wallet.to_wallet_api_settings,\n currency: deposit.currency.to_blockchain_api_settings)\n\n pa = PaymentAddress.find_by(wallet_id: @wallet.id, member: deposit.member, address: deposit.address)\n # NOTE: Deposit wallet configuration is tricky because wallet UIR\n # is saved on Wallet model but wallet address and secret\n # are saved in PaymentAddress.\n @adapter.configure(\n wallet: @wallet.to_wallet_api_settings\n .merge(pa.details.symbolize_keys)\n .merge(address: pa.address)\n .tap { |s| s.merge!(secret: pa.secret) if pa.secret.present? }\n .compact\n )\n\n deposit_spread.map do |transaction|\n # In #spread_deposit valid transactions saved with pending state\n if transaction.status.pending?\n transaction = @adapter.create_transaction!(transaction, subtract_fee: true)\n save_transaction(transaction.as_json.merge(from_address: deposit.address), deposit) if transaction.present?\n end\n transaction\n end\n end",
"def buys_drink(pub, drink_name)\n drink_to_buy = pub.sell_drink(self, drink_name)\n @wallet -= drink_to_buy.price\n end",
"def deduct_wallet\n user = User::find(self.user_id)\n user.budget -= self.pending_money\n user.save\n\n self.pending_money = 0\n self.save\n end",
"def depositing_money_saving amount\n @saving_amount += amount\n self\n end",
"def buy_drink(drink)\n if drink.price <= @wallet\n @wallet -= drink.price\n @drunk_level += drink.alcohol_level\n end\n end",
"def withdraw(amount, options={})\n options = {:fee => false}.merge(options).symbolize_keys\n adjust_and_save(amount.abs * -1, :withdraw, options)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Private: Update the Pot instance variables parsed_response a hash whose keys exactly match the instance variables for Monzo::Pot. Returns self (an instance of Monzo::Pot)
|
def update_self(parsed_response)
instance_variables.each do |iv|
instance_variable_set(iv, parsed_response[iv.to_s[1..-1].to_sym])
end
self
end
|
[
"def update_from(response)\n load_response_api(response.is_a?(Hash) ? response : JSON.parse(response))\n\n # attributes to remove\n (@values.keys - raw['response'].keys).each { |key| remove_accessor(key) }\n\n update_attributes(raw['response'])\n\n self\n end",
"def parse(response)\n\n injection_response = get_injection_response_dto(response)\n result_enum = determine_send_result(injection_response, response)\n new_response = SendResponse.new(result_enum)\n new_response.transaction_receipt = injection_response.transaction_receipt\n\n if result_enum == SendResult.enum[\"Warning\"]\n unless injection_response.message_results.nil? || injection_response.message_results.length == 0\n error_code = injection_response.message_results[0].error_code\n result_enum = SendResult.enum[error_code]\n new_response.result = result_enum\n end\n end\n\n unless injection_response.message_results.nil? || injection_response.message_results.length == 0\n new_response.address_results = injection_response.message_results[0].address_results\n end\n\n new_response\n\n end",
"def parse_response(response)\n response = sanitize_response_keys(response.parsed_response)\n end",
"def update\n pot = Pot.find_by(game_id: params[:id])\n\n player_list = []\n g = Game.find(pot.game_id)\n player_list << Player.find(g.player1_id) if g.player1_id != nil\n player_list << Player.find(g.player2_id) if g.player2_id != nil\n player_list << Player.find(g.player3_id) if g.player3_id != nil\n player_list << Player.find(g.player4_id) if g.player4_id != nil\n if match?(player_list, g.current_high_bet) == true\n player_list.each do |player|\n pot.total_chips += player.betting\n player.betting = 0\n player.save\n end\n end\n pot.update_attributes(pot_params)\n pot.save\n render json: pot\n end",
"def update\n respond_to do |format|\n if @pot.update(pot_params)\n format.html { redirect_to @pot, notice: 'Pot was successfully updated.' }\n format.json { render :show, status: :ok, location: @pot }\n else\n format.html { render :edit }\n format.json { render json: @pot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def parse_response(response)\n response = sanitize_response_keys(response)\n end",
"def update\n @pot = Pot.find(params[:id])\n\n respond_to do |format|\n if @pot.update_attributes(params[:pot])\n format.html { redirect_to @pot, notice: 'Pot was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @pot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_responses( )\n build_responses(options, true)\n end",
"def update_settings(response)\n @etag = response.headers['Etag'] if response.headers['Etag']\n @poll = response.headers['X-Poll-Interval'] if response.headers['X-Poll-Interval']\n @poll = @poll.to_i\n # Never drop below minute polling\n if(@poll < 60)\n @poll = 60\n end\n debug \"Current Etag value: #{etag}\"\n debug \"Current polling value: #{poll}\"\n end",
"def read_pokemon_response\n parsed = JSON.parse(@current_response.body)\n Pokemon.find_or_create_by_name(parsed[\"name\"]).tap do |p|\n p.height = parsed[\"height\"]\n p.weight = parsed[\"weight\"]\n p.pokedex_entry = read_pokedex_entry(parsed[\"species\"][\"url\"])\n parsed[\"types\"].each_with_index do |type, i|\n name = type[\"type\"][\"name\"]\n p.types_array[i] = Type.find_or_create_through_pokemon_search(name, p)\n end\n end\n end",
"def parse_response!\n if response.body\n response.body = JSON response.body\n end\n end",
"def parse_response!\n response.body = case @response_format\n when :xml then Hash.from_xml response.body\n when :json then JSON response.body\n end if response.body\n end",
"def parse(response)\n Hpricot.XML(response || '')\n end",
"def merge(updating_response)\n if updating_response == nil or updating_response.data == nil\n return self\n end\n \n if updating_response.status > status\n @status = updating_response.status\n end\n \n if data == nil\n @data = updating_response.data\n return self\n end\n \n if updating_response.body != nil\n if @body == nil\n @body = updating_response.body\n else\n @body += updating_response.body\n end\n end\n\n @data['msgs'] += updating_response.msgs\n \n if updating_response.files != nil\n f = files\n if f != nil\n @data['results']['files'] += updating_response.files\n else\n @data['results']['files'] = updating_response.files\n end\n end\n \n return self\n end",
"def update\n @potz = Potz.find(params[:id])\n\n respond_to do |format|\n if @potz.update_attributes(params[:potz])\n format.html { redirect_to @potz, notice: 'Potz was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @potz.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n response = @api.request(:get, @location, @req_opts)\n\n unless response.status == 200\n raise Gini::Api::DocumentError.new(\n \"Failed to fetch extractions from #{@location}\",\n response\n )\n end\n\n # Entire response\n @raw = response.parsed\n\n # raise exception if parsing failed\n if response.parsed.nil?\n raise Gini::Api::DocumentError.new(\n \"Failed to parse extractions from #{@location}\",\n response\n )\n end\n\n response.parsed[:extractions].each do |k,v|\n instance_variable_set(\"@#{k}\", v)\n end\n\n instance_variable_set(\"@candidates\", response.parsed[:candidates])\n end",
"def parse_response(response)\n\n if response[\"outcome\"]==\"success\"\n\n #Assign calorie counts and grams breakdown\n self.total_calories=response[\"fields\"][\"total_calories\"].to_i\n self.protein_grams=response[\"fields\"][\"total_calories\"].to_i\n self.fat_grams=response[\"fields\"][\"fat_grams\"].to_i\n self.carbohydrate_grams=response[\"fields\"][\"carbohydrate_grams\"].to_i\n self.fiber_grams=response[\"fields\"][\"fiber_grams\"].to_i\n\n #Number of coffees\n self.number_of_coffees=response[\"fields\"][\"number_of_coffees\"].to_i\n\n #Assign medications based on response\n if response[\"choice\"]=='only_took_morning_meds'\n self.morning_medications=true\n self.evening_medications=false\n\n elsif response[\"choice\"]=='only_took_evening_meds'\n self.morning_medications=false\n self.evening_medications=true\n\n elsif response[\"choice\"]=='took_both_morning_and_evening'\n self.morning_medications=true\n self.evening_medications=true\n\n else\n self.morning_medications=false\n self.evening_medications=false\n\n end\n\n self.save \n\n else\n raise \"Bad Scale API callback data\"\n end\n\n end",
"def set_response\n @response = TdTip::Models::Response.new(parameters).get\n end",
"def update\n respond_to do |format|\n if @potluck.update(potluck_params)\n format.json { render :show, status: :ok, location: @potluck }\n else\n format.json { render json: @potluck.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Initializes a FSEvent worker and adds a watcher for each directory passed to the adapter.
|
def init_worker
FSEvent.new.tap do |worker|
worker.watch(@directories.dup, :latency => @latency) do |changes|
next if @paused
@mutex.synchronize do
changes.each { |path| @changed_dirs << path.sub(LAST_SEPARATOR_REGEX, '') }
end
end
end
end
|
[
"def _init_worker\n FSEvent.new.tap do |worker|\n worker.watch(_directories_path, latency: _latency) do |changes|\n paths = _changes_path(changes)\n paths.each { |path| _notify_change(path, type: 'Dir') }\n end\n end\n end",
"def init_worker\n worker = FChange::Notifier.new\n @directories.each do |directory|\n watcher = worker.watch(directory, :all_events, :recursive) do |event|\n next if @paused\n @mutex.synchronize do\n @changed_dirs << File.expand_path(event.watcher.path)\n end\n end\n worker.add_watcher(watcher)\n end\n worker\n end",
"def initialize_worker\n require 'find'\n\n callback = lambda do |event|\n path = event.watcher.path\n mutex.synchronize do\n # kqueue watches everything, but Listen only needs the\n # directory where stuffs happens.\n @changed_directories << (File.directory?(path) ? path : File.dirname(path))\n\n # If it is a directory, and it has a write flag, it means a\n # file has been added so find out which and deal with it.\n # No need to check for removed files, kqueue will forget them\n # when the vfs does.\n if File.directory?(path) && event.flags.include?(:write)\n queue = event.watcher.queue\n Find.find(path) do |file|\n unless queue.watchers.detect { |k,v| v.path == file.to_s }\n queue.watch_file(file, *EVENTS, &callback)\n end\n end\n end\n end\n end\n\n KQueue::Queue.new.tap do |queue|\n directories.each do |directory|\n Find.find(directory) do |path|\n queue.watch_file(path, *EVENTS, &callback)\n end\n end\n end\n end",
"def initialize_worker\n callback = lambda do |event|\n if paused || (\n # Event on root directory\n event.name == \"\"\n ) || (\n # INotify reports changes to files inside directories as events\n # on the directories themselves too.\n #\n # @see http://linux.die.net/man/7/inotify\n event.flags.include?(:isdir) and (event.flags & [:close, :modify]).any?\n )\n # Skip all of these!\n next\n end\n\n mutex.synchronize do\n @changed_directories << File.dirname(event.absolute_name)\n end\n end\n\n INotify::Notifier.new.tap do |worker|\n directories.each { |dir| worker.watch(dir, *EVENTS, &callback) }\n end\n end",
"def _init_worker\n INotify::Notifier.new.tap do |worker|\n _directories_path.each { |path| worker.watch(path, *EVENTS, &_worker_callback) }\n end\n end",
"def init_worker\n @worker = FSEvent.new\n @worker.watch(@directory, :latency => @latency) do |changed_dirs|\n next if @paused\n\n changed_dirs.map! { |path| path.sub /\\/$/, '' }\n @callback.call(changed_dirs, {})\n end\n end",
"def init_worker\n @worker = INotify::Notifier.new\n @worker.watch(@directory, *EVENTS.map(&:to_sym)) do |event|\n next if @paused\n \n unless event.name == \"\" # Event on root directory\n @changed_dirs << File.dirname(event.absolute_name)\n end\n end\n end",
"def _init_worker\n WDM::Monitor.new.tap do |worker|\n _directories_path.each { |path| worker.watch_recursively(path, &_worker_callback) }\n end\n end",
"def init_worker\n callback = Proc.new do |change|\n next if @paused\n @mutex.synchronize do\n @changed_dirs << File.dirname(change.path)\n end\n end\n\n WDM::Monitor.new.tap do |worker|\n @directories.each { |d| worker.watch_recursively(d, &callback) }\n end\n end",
"def _init_worker\n KQueue::Queue.new.tap do |queue|\n _directories_path.each do |path|\n Find.find(path) { |file_path| _watch_file(file_path, queue) }\n end\n end\n end",
"def init_kqueue\n require 'find'\n\n callback = lambda do |event|\n path = event.watcher.path\n @mutex.synchronize do\n # kqueue watches everything, but Listen only needs the\n # directory where stuffs happens.\n @changed_dirs << (File.directory?(path) ? path : File.dirname(path))\n\n # If it is a directory, and it has a write flag, it means a\n # file has been added so find out which and deal with it.\n # No need to check for removed file, kqueue will forget them\n # when the vfs does..\n if File.directory?(path) && !(event.flags & [:write]).empty?\n queue = event.watcher.queue\n Find.find(path) do |file|\n unless queue.watchers.detect {|k,v| v.path == file.to_s}\n queue.watch_file(file, *EVENTS, &callback)\n end\n end\n end\n end\n end\n\n KQueue::Queue.new.tap do |queue|\n @directories.each do |directory|\n Find.find(directory) do |path|\n queue.watch_file(path, *EVENTS, &callback)\n end\n end\n end\n end",
"def attach\n @monitored_paths.each {|path| SingleFileWatcher.new(path.to_s).attach(@loop) }\n end",
"def listen\n @listener ||= Listen.to(@directory) do |modified, added, removed|\n to_reload = Set[] # list of component path to reload\n\n (added + modified + removed).each do |file|\n to_reload.add(file) if file.end_with? @suffix # add the file to the reload list if it's a component\n\n dependent_comps = @loaded_components.select{ |comp| comp.depend_on? file } # find every components that depend on the current file\n to_reload += dependent_comps.map(&:path) if dependent_comps # add their path to the reload list\n end\n\n unless to_reload.empty?\n @mutex.synchronize do\n info 'Waiting for all event threads to finish...' unless @bot.event_threads.empty?\n @bot.event_threads.each(&:join)\n\n to_reload.each { |file| reload! file }\n end\n end\n end\n\n @listener.start unless @listener.processing?\n end",
"def setup_monitor\n @notifier = INotify::Notifier.new\n @options.parsed.dirs_to_monitor.each do |dir|\n foo = @notifier.watch(dir, :modify, :recursive) { run_command }\n end\n end",
"def listen\n autoload\n unless roots.any?\n raise NoRootsError, 'No folders to watch!'\n end\n roots.uniq!\n logger.debug(\"[#{Time.now.utc}] - Listening to #{roots.join(',')}\")\n args = roots + [{:latency => 0.1}]\n listener = Listen.to(*args) do |modified, added, removed|\n EVENTS.each do |event|\n eval(event).each do |path|\n logger.debug %([#{Time.now.utc}] - #{event}: #{path})\n begin\n uuid = path[/^#{roots_regex}\\/([^\\/]+)\\/.+$/, 1] || next\n begin\n base = Base.find_by_uuid(uuid)\n base.handle(event, path)\n rescue Mongoid::Errors::DocumentNotFound\n logger.error %([#{Time.now.utc}] - Can't find Vidibus::WatchFolder::Base #{uuid})\n end\n rescue => e\n logger.error(\"[#{Time.now.utc}] - ERROR in Vidibus::WatchFolder.listen:\\n#{e.inspect}\\n---\\n#{e.backtrace.join(\"\\n\")}\")\n end\n end\n end\n end\n listener.start\n sleep\n end",
"def do_listening\n in_dir @config.base_path do\n\n # Notify people if we are using fallback mode\n if @config.force_poll\n puts statusbar \"Using polling fallback listener\", &:yellow\n end\n\n # Force a change to start with\n run_command\n\n params = {\n latency: 0.5,\n }\n\n params[:only] = Regexp.new(@config.filters.join(\"|\")) unless @config.filters.empty?\n params[:ignore] = Regexp.new(@config.ignored.join(\"|\")) unless @config.ignored.empty?\n\n if @config.force_poll\n params[:latency] = @config.force_poll\n params[:force_poll] = true\n end\n\n @listener = Listen.to(*@config.paths, params) do |*args|\n self.on_change *args\n end\n \n @listener.start\n end\n end",
"def watch(watched_dirs)\n watched_dirs << @directory\n end",
"def setup_watcher!(watch_type, opts)\n return unless opts.delete(:watch)\n\n synchronize do\n set = @outstanding_watches.fetch(watch_type)\n path = opts[:path]\n\n if set.add?(path)\n # this path has no outstanding watchers, let it do its thing\n opts[:watcher] = watcher_callback \n else\n # outstanding watch for path and data pair already exists, so ignore\n# logger.debug { \"outstanding watch request for path #{path.inspect} and watcher type #{watch_type.inspect}, not re-registering\" }\n end\n end\n end",
"def start\n @threads ||= []\n if @threads.empty?\n @watchers.each do |watcher|\n @threads << watcher.start\n end\n end\n\n Log.debug('Watcher thread started')\n self\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /providers/1 GET /providers/1.json
|
def show
@provider = current_company.providers.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @provider }
end
end
|
[
"def index\n @providers = Provider.all\n\n render json: @providers\n end",
"def providers(params = {})\n response = default_scope.get('providers/') do |request|\n request.params = params\n end\n JSON.parse(response.body)\n end",
"def providers\n url = url_with_api_version(@base_url, 'providers')\n resp = rest_get(url)\n JSON.parse(resp.body)[\"value\"]\n end",
"def list_providers(params = nil, headers = nil)\n get(\"/api/v1/providers\", params, headers)\n end",
"def index\n @providers = Provider.all\n\n respond_to do |format|\n format.json { render json: @providers }\n format.xml { render xml: @providers }\n end\n end",
"def new\n @provider = current_company.providers.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @provider }\n end\n end",
"def show\n @cloud_provider = current_user.cloud_providers.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @cloud_provider }\n end\n end",
"def index\n @info_providers = Info::Provider.all\n end",
"def show\n @c_provider = CProvider.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @c_provider }\n end\n end",
"def index\n @providers = apply_scopes(Provider).page(params.fetch(:page, 1))\n .per(params.fetch(:per_page, 20))\n end",
"def new\n @provider = Provider.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @provider }\n end\n end",
"def index\n @providerservices = Providerservice.all\n end",
"def providers\n filter = params.except :utf8, :commit, :action, :controller\n if filter.empty?\n render :json => Provider.all.order(:name)\n else\n geo_ids, services = get_queries filter\n providers = Provider.where(:id => geo_ids).where(services).order(\"name\") \n render :json => providers\n end\n end",
"def new\n @title = t('view.providers.new_title')\n @provider = Provider.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @provider }\n end\n end",
"def index\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @service_providers }\n end\n end",
"def list_providers(limit=0, currency='MXN')\n uri = @client.deploy_uri+'providers/'\n\n if limit > 0\n uri = uri+'?order_total='+limit.to_s\n end\n\n if limit > 0 && !currency.nil? && currency != 'MXN'\n uri = uri+'¤cy='+currency\n end\n\n response = EasyRequest::get(uri, get_auth())\n\n Factory::get_instance_of 'ListProviders', response\n end",
"def show\n @payment_provider = PaymentProvider.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @payment_provider }\n end\n end",
"def new\n @cloud_provider = current_user.cloud_providers.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cloud_provider }\n end\n end",
"def retrieve_identity_providers()\n start.uri('/api/identity-provider')\n .get()\n .go()\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /providers/new GET /providers/new.json
|
def new
@provider = current_company.providers.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @provider }
end
end
|
[
"def new\n @title = t('view.providers.new_title')\n @provider = Provider.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @provider }\n end\n end",
"def new\n @provider = Provider.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @provider }\n end\n end",
"def new\n @provider = Provider.new\n respond_to do |format|\n format.json { render json: @provider }\n format.xml { render xml: @provider }\n end\n end",
"def provider_new\n @page_title = _('New_provider')\n @page_icon = \"add.png\"\n @provider, @tariffs, @servers = Provider.provider_new(session)\n\n if not @tariffs\n flash[:notice] = _('No_tariffs_available')\n redirect_to :action => 'list'\n end\n end",
"def new\n @cloud_provider = current_user.cloud_providers.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @cloud_provider }\n end\n end",
"def create\n @provider = current_company.providers.new(params[:provider])\n\n respond_to do |format|\n if @provider.save\n format.html { redirect_to @provider, notice: 'Provider was successfully created.' }\n format.json { render json: @provider, status: :created, location: @provider }\n else\n format.html { render action: \"new\" }\n format.json { render json: @provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @provider = Provider.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @provider }\n end\n end",
"def new\n @data_provider = DataProvider.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @data_provider }\n end\n end",
"def create\n @provider = Provider.new(provider_params)\n\n respond_to do |format|\n if @provider.save\n format.html { redirect_to providers_path, notice: 'Provider was successfully created.' }\n format.json { render :show, status: :created, location: @provider }\n else\n format.html { render :new }\n format.json { render json: @provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @provider = Provider.new(provider_params)\n\n if @provider.save\n render json: @provider, status: :created, location: @provider\n else\n render json: @provider.errors, status: :unprocessable_entity\n end\n end",
"def new\n @payment_provider = PaymentProvider.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @payment_provider }\n end\n end",
"def new\n @supplies_providers_loan = SuppliesProvidersLoan.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @supplies_providers_loan }\n end\n end",
"def new\n @provider_type = ProviderType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @provider_type }\n end\n end",
"def create\n @info_provider = Info::Provider.new(info_provider_params)\n\n respond_to do |format|\n if @info_provider.save\n format.html { redirect_to @info_provider, notice: 'Provider was successfully created.' }\n format.json { render :show, status: :created, location: @info_provider }\n else\n format.html { render :new }\n format.json { render json: @info_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @provider_stat = ProviderStat.new\n @provider = Provider.find(params[:id])\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @provider_stat }\n end\n end",
"def new\n @supply = Supply.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @supply }\n end\n end",
"def new\n @social = Social.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @social }\n end\n end",
"def new\n @supplysite = Supplysite.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @supplysite }\n end\n end",
"def create\n @provider = Provider.new(params[:provider])\n\n respond_to do |format|\n if @provider.save\n flash[:notice] = 'Provider was successfully created.'\n format.html { redirect_to providers_path }\n format.xml { render :xml => @provider, :status => :created, :location => @provider }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @provider.errors, :status => :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /providers POST /providers.json
|
def create
@provider = current_company.providers.new(params[:provider])
respond_to do |format|
if @provider.save
format.html { redirect_to @provider, notice: 'Provider was successfully created.' }
format.json { render json: @provider, status: :created, location: @provider }
else
format.html { render action: "new" }
format.json { render json: @provider.errors, status: :unprocessable_entity }
end
end
end
|
[
"def create\n @provider = Provider.new(provider_params)\n\n if @provider.save\n render json: @provider, status: :created, location: @provider\n else\n render json: @provider.errors, status: :unprocessable_entity\n end\n end",
"def create\n @provider = Provider.new(provider_params)\n\n respond_to do |format|\n if @provider.save\n format.html { redirect_to providers_path, notice: 'Provider was successfully created.' }\n format.json { render :show, status: :created, location: @provider }\n else\n format.html { render :new }\n format.json { render json: @provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @info_provider = Info::Provider.new(info_provider_params)\n\n respond_to do |format|\n if @info_provider.save\n format.html { redirect_to @info_provider, notice: 'Provider was successfully created.' }\n format.json { render :show, status: :created, location: @info_provider }\n else\n format.html { render :new }\n format.json { render json: @info_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def providers(params = {})\n response = default_scope.get('providers/') do |request|\n request.params = params\n end\n JSON.parse(response.body)\n end",
"def create\n @auth_provider = AuthProvider.new(auth_provider_params)\n\n respond_to do |format|\n if @auth_provider.save\n format.html { redirect_to @auth_provider, notice: 'Auth provider was successfully created.' }\n format.json { render :show, status: :created, location: @auth_provider }\n else\n format.html { render :new }\n format.json { render json: @auth_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @provider = current_company.providers.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @provider }\n end\n end",
"def create\n @user_provider = UserProvider.new(user_provider_params)\n\n respond_to do |format|\n if @user_provider.save\n format.html { redirect_to @user_provider, notice: 'User provider was successfully created.' }\n format.json { render :show, status: :created, location: @user_provider }\n else\n format.html { render :new }\n format.json { render json: @user_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @provider = Provider.new(params[:provider])\n\n respond_to do |format|\n if @provider.save\n flash[:notice] = 'Provider was successfully created.'\n format.html { redirect_to providers_path }\n format.xml { render :xml => @provider, :status => :created, :location => @provider }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @provider.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @data_provider = DataProvider.new(params[:data_provider])\n\n respond_to do |format|\n if @data_provider.save\n format.html { redirect_to root_path, notice: 'Data provider was successfully created.' }\n format.json { render json: @data_provider, status: :created, location: @data_provider }\n else\n format.html { render action: \"new\" }\n format.json { render json: @data_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @supplier_provider = Supplier::Provider.new(supplier_provider_params)\n\n respond_to do |format|\n if @supplier_provider.save\n format.html { redirect_to @supplier_provider, notice: 'Provider was successfully created.' }\n format.json { render :show, status: :created, location: @supplier_provider }\n else\n format.html { render :new }\n format.json { render json: @supplier_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @provider_info = ProviderInfo.new(provider_info_params)\n\n respond_to do |format|\n if @provider_info.save\n format.html { redirect_to @provider_info, notice: 'Provider info was successfully created.' }\n format.json { render :show, status: :created, location: @provider_info }\n else\n format.html { render :new }\n format.json { render json: @provider_info.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @provider = Provider.new(params[:provider])\n\n respond_to do |format|\n if @provider.save\n format.html { redirect_to(@provider, :notice => 'Provider was successfully created.') }\n format.xml { render :xml => @provider, :status => :created, :location => @provider }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @provider.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @service_provider = ServiceProvider.new(service_provider_params)\n\n respond_to do |format|\n if @service_provider.save\n format.html { redirect_to @service_provider, notice: \"Service provider was successfully created.\" }\n format.json { render :show, status: :created, location: @service_provider }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @service_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @alpha_provider = Alpha::Provider.new(alpha_provider_params)\n\n respond_to do |format|\n if @alpha_provider.save\n format.html { redirect_to alpha_providers_path, notice: 'Provider was successfully created.' }\n format.json { render action: 'show', status: :created, location: @alpha_provider }\n else\n format.html { render action: 'new' }\n format.json { render json: @alpha_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @provider_provider_type = Provider::ProviderType.new(provider_provider_type_params)\n @provider_provider_type.user_created_id = current_user.id\n respond_to do |format|\n if @provider_provider_type.save\n format.html { redirect_to provider_provider_types_path, notice: I18n.t('provider_types.controller.create') }\n format.json { render :show, status: :created, location: @provider_provider_type }\n else\n format.html { render :new }\n format.json { render json: @provider_provider_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @provider = Provider.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @provider }\n end\n end",
"def create\n @providerservice = Providerservice.new(providerservice_params)\n\n respond_to do |format|\n if @providerservice.save\n format.html { redirect_to @providerservice, notice: 'Providerservice was successfully created.' }\n format.json { render :show, status: :created, location: @providerservice }\n else\n format.html { render :new }\n format.json { render json: @providerservice.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_provider!(provider, provider_info = {}, access = {})\n Api::Request.new do |request|\n request[:access] = access\n request[:method] = :POST\n request[:path] = \"/mgmt/{{client_id}}/storages/#{provider}\"\n request[:request_body] = provider_info\n end.execute!\n\n end",
"def create\n @provider = Provider.new(params[:provider])\n\n respond_to do |format|\n if @provider.save\n flash[:notice] = 'Provider was successfully created.'\n format.html { redirect_to(@provider) }\n format.xml { render :xml => @provider, :status => :created, :location => @provider }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @provider.errors, :status => :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PUT /providers/1 PUT /providers/1.json
|
def update
@provider = current_company.providers.find(params[:id])
respond_to do |format|
if @provider.update_attributes(params[:provider])
format.html { redirect_to @provider, notice: 'Provider was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @provider.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n @provider = Provider.find(params[:id])\n\n if @provider.update(provider_params)\n head :no_content\n else\n render json: @provider.errors, status: :unprocessable_entity\n end\n end",
"def update\n if @provider.update(provider_params)\n head :no_content\n else\n render json: @provider.errors, status: :unprocessable_entity\n end\n end",
"def update_provider!(provider, provider_info = {}, access = {})\n Api::Request.new do |request|\n request[:access] = access\n request[:method] = :PUT\n request[:path] = \"/mgmt/{{client_id}}/storages/#{provider}\"\n request[:request_body] = provider_info\n end.execute!\n\n end",
"def update\n respond_to do |format|\n if @v1_provider.update(v1_provider_params)\n format.html { redirect_to @v1_provider, notice: 'Provider was successfully updated.' }\n format.json { render :show, status: :ok, location: @v1_provider }\n else\n format.html { render :edit }\n format.json { render json: @v1_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @provider = Provider.find(params[:id])\n\n respond_to do |format|\n if @provider.update_attributes(params[:provider])\n format.html { redirect_to(@provider, :notice => 'Provider was successfully updated.') }\n format.xml { head :ok }\n format.json { render :json => { :resp=> \"ok\" }}\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @provider.errors, :status => :unprocessable_entity }\n format.json { render :json => { :resp=> \"error\" }}\n end\n end\n end",
"def update\n respond_to do |format|\n if @info_provider.update(info_provider_params)\n format.html { redirect_to @info_provider, notice: 'Provider was successfully updated.' }\n format.json { render :show, status: :ok, location: @info_provider }\n else\n format.html { render :edit }\n format.json { render json: @info_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @provider = Provider.find(params[:id])\n\n respond_to do |format|\n if @provider.update_attributes(params[:provider])\n format.html { redirect_to(@provider, :notice => 'Provider was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @provider.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @provider_info.update(provider_info_params)\n format.html { redirect_to @provider_info, notice: 'Provider info was successfully updated.' }\n format.json { render :show, status: :ok, location: @provider_info }\n else\n format.html { render :edit }\n format.json { render json: @provider_info.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n \n respond_to do |format|\n if @service_provider.update(service_provider_params)\n format.html { redirect_to @service_provider, notice: 'Service provider was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @service_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @providerservice.update(providerservice_params)\n format.html { redirect_to @providerservice, notice: 'Providerservice was successfully updated.' }\n format.json { render :show, status: :ok, location: @providerservice }\n else\n format.html { render :edit }\n format.json { render json: @providerservice.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @id_provider.update(id_provider_params)\n flash.now[:notice] = 'Id provider information was successfully updated.'\n format.any { render :edit }\n format.json { render :show, status: :ok, location: @id_provider }\n else\n format.any { render :edit }\n format.json { render json: @id_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @sprovider.update(sprovider_params)\n format.html { redirect_to @sprovider, notice: 'Sprovider was successfully updated.' }\n format.json { render :show, status: :ok, location: @sprovider }\n else\n format.html { render :edit }\n format.json { render json: @sprovider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @cloud_provider = current_user.cloud_providers.find(params[:id])\n\n respond_to do |format|\n if @cloud_provider.update_attributes(params[:cloud_provider])\n format.html { redirect_to @cloud_provider, notice: 'Cloud provider was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cloud_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_identity_provider(identity_provider_id, request)\n start.uri('/api/identity-provider')\n .url_segment(identity_provider_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .put()\n .go()\n end",
"def update\n respond_to do |format|\n if @v1_provider_operation.update(v1_provider_operation_params)\n format.html { redirect_to @v1_provider_operation, notice: 'Provider operation was successfully updated.' }\n format.json { render :show, status: :ok, location: @v1_provider_operation }\n else\n format.html { render :edit }\n format.json { render json: @v1_provider_operation.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @service_provider.update(service_provider_params)\n format.html { redirect_to @service_provider, notice: \"Service provider was successfully updated.\" }\n format.json { render :show, status: :ok, location: @service_provider }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @service_provider.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_identity_provider(identity_provider_id, request)\n start.uri('/api/identity-provider')\n .url_segment(identity_provider_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .put()\n .go()\n end",
"def put\n request_method('PUT')\n end",
"def update\n respond_to do |format|\n if @auth_provider.update(auth_provider_params)\n format.html { redirect_to @auth_provider, notice: 'Auth provider was successfully updated.' }\n format.json { render :show, status: :ok, location: @auth_provider }\n else\n format.html { render :edit }\n format.json { render json: @auth_provider.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
it can start if all requests are valid
|
def validate_can_start
if aasm_states_to_check
cannot_start! if requests_have_notices?
end
end
|
[
"def check_requests\n if requests.empty?\n errors.add('requests', 'there were no requests')\n return\n end\n\n requests.each do |request|\n next if request.valid?\n\n request.errors.each do |k, v|\n errors.add(k, v)\n end\n end\n end",
"def valid?\n !@requests.empty?\n end",
"def wait_for_sinatra_to_startup!\n (1..10).each do |_|\n begin\n Net::HTTP.get(URI.parse('http://localhost:7000/'))\n return\n rescue Errno::ECONNREFUSED => exception\n sleep(1)\n end\n end\n\n raise StandardError, \"Our dummy webservice did not start up in time!\"\n end",
"def validate_request\n begin\n key_exists = $redis.exists(@key)\n updated_api_request_count = $redis.incrby(@key,1)\n if !key_exists\n $redis.expire(@key, @expiry_time)\n end\n return false if updated_api_request_count > @req_per_time_slot\n rescue Redis::CannotConnectError\n Rails.logger.info 'redis server is down, allowing api call'\n end\n true\n end",
"def consider_all_requests_local; end",
"def check_status\n # only check the status if running\n if self.running?\n # first check to see if anyone is blocked\n total_blocked = blocked_requests_count\n if total_blocked > 0 && self.may_block?\n self.block!\n elsif total_blocked == 0 && self.blocked?\n self.start!\n elsif self.started?\n # check for all complete\n total_members = self.plan_members.count\n completed_members = self.requests.complete.count\n if total_members == completed_members && self.may_complete?\n self.complete!\n else\n #check for others to start up\n currently_running = self.requests.started.count + self.requests.hold.count + self.requests.problem.count\n eligible_to_start = self.requests.planned.count\n start_next_eligible_request if currently_running == 0 && eligible_to_start > 0\n end\n end\n end\n # check for anything new and move it to at least planned if running or planned\n plan_new_requests\n end",
"def each_request(options = {}, &block) # :yields: request\n return true\n end",
"def initialize\n @requests = {}\n ::Log.info \"Loading all requests in : #{PATH_REQUEST}\"\n Dir[File.join(PATH_REQUEST, '*')].count { |file| each_files(file) }\n end",
"def wait_for_sinatra_to_startup!\n 10.times do\n Net::HTTP.get(URI.parse(\"http://#{@host}:#{@port}/up_and_running\"))\n return\n rescue Errno::ECONNREFUSED => e # rubocop:todo Lint/UselessAssignment\n sleep(1)\n end\n\n raise StandardError, \"Our dummy webservice did not start up in time!\"\n end",
"def wait_for_all_requests\n wait_for('pending requests complete') do\n finished_all_rack_reqiests? &&\n finished_all_js_requests?\n end\n end",
"def wait_for_all_requests\n wait_for('pending requests complete') do\n finished_all_rack_requests? &&\n finished_all_js_requests?\n end\n end",
"def wait_for_api\n uri = URI \"http://#{@hostname}:#{@port}/v1\"\n\n 15.times do |i|\n begin\n Net::HTTP.get_response uri\n break\n rescue\n return false if i == 15\n sleep 10\n end\n end\n\n true\n end",
"def outlet\n loop do\n http = Net::HTTP.new(@logplex_url.host, @logplex_url.port)\n http.use_ssl = true if @logplex_url.scheme == 'https'\n begin\n http.start do |conn|\n num_reqs = 0\n while num_reqs < @max_reqs_per_conn\n #Blocks waiting for a request.\n req = @request_queue.deq\n @req_in_flight += 1\n resp = nil\n begin\n Timeout::timeout(@conn_timeout) {resp = conn.request(req)}\n rescue => e\n next\n ensure\n @req_in_flight -= 1\n end\n num_reqs += 1\n end\n end\n rescue => e\n ensure\n http.finish if http.started?\n end\n end\n end",
"def start_accepting_requests\n\t\tself.start_heartbeat\n\t\tsuper\n\tend",
"def canStart()\n\t\t\t\treturn true\n\t\t\tend",
"def perform_requests\n return unless perform_requests_mutex.try_lock\n\n loop do\n begin\n request = requests.pop(true)\n perform_request(request)\n rescue HTTP2::Error::StreamLimitExceeded\n requests.push(request)\n break\n rescue ThreadError\n break\n end\n end\n\n perform_requests_mutex.unlock\n end",
"def wait_for_manager\n timeout(60, \"waiting for manager to start\") {\n while true do\n sleep 0.5\n return if http_get(\"http://localhost/\").code < 500\n end\n }\n end",
"def validate!\n Server.config.validate!\n Server.config.workers.each { |w| w.validate! }\n end",
"def before_create\n start_thread { start_webserver }\n start_thread { start_regserver }\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Is the passed candidate a better match than any of the current matches? ARG: `other` another Candidate instance to check against the current set
|
def better_match?( other )
return true if prefers?( other ) && free?
preference_index = preferences.index other
match_preference_indexes = matches.map { | match | preferences.index match }
preference_index and match_preference_indexes.any? { |i| i > preference_index }
end
|
[
"def respond_to_proposal_from( other )\n case\n # Is there a preference for the candidate?\n when !prefers?( other )\n false\n\n # Are there available positions for more matches?\n when free?\n match! other\n\n # Is the passed Candidate a better match than any other match?\n when better_match?( other )\n free!\n match! other\n\n else\n false\n end\n end",
"def matched?( other = nil )\n return full? if other.nil?\n matches.include? other\n end",
"def eql? other\n object_id == other.object_id ||\n (specification == other.specification && \n candidate_types == other.candidate_types && \n candidate_types_excluded == other.candidate_types_excluded && \n candidate_objects == other.candidate_objects && \n join_points_not_matched == other.join_points_not_matched &&\n join_points_matched == other.join_points_matched) # not_matched is probably smaller, so do first.\n end",
"def match!( other )\n return false unless prefers?( other ) && !matched?( other )\n matches << other\n other.matches << self\n end",
"def nondominated_vs? (other, criteria)\n nondominated_vs_other = true\n \n criteria.each do |score_name|\n self_score = self.get_score(score_name)\n other_score = other.get_score(score_name)\n \n if self_score < other_score\n nondominated_vs_other = true\n break\n elsif nondominated_vs_other\n nondominated_vs_other &&= (self_score == other_score)\n end\n end\n \n nondominated_vs_other\n end",
"def check_solution\n @matches.each_with_index do |m, w|\n #check woman\n w_better_candidates = @women[w].take(@women[w].find_index(m))\n # all these are prefered over current spouse. If they prefer her over their current spouse, matching is not stable.\n w_better_candidates.each do |better_man|\n spouse = @matches.find_index(better_man)\n m_better_spouses = @men[better_man].take(@men[better_man].find_index(spouse))\n return false if m_better_spouses.include? w\n end\n end\n true\n end",
"def minimal_match?(other)\n super and tolerant_match?(other, TOLERANT_MATCH_ATTRS)\n end",
"def two_candidates?\n @candidates.count == 2\n end",
"def is_better_match?(person, first_better, second_better)\n @preferences[person].detect { |pref| pref == first_better || pref == second_better }\n end",
"def match?(opts = { :score => 3 })\n if opts[:score]\n # combined operations\n self.score <= opts[:score]\n\n elsif opts[:max]\n !(self.deletions > opts[:max]) and !(self.insertions > opts[:max]) \\\n and !(self.substitutions > opts[:max]) \\\n and !(self.transpositions > opts[:max])\n\n else\n plausable = true\n\n if opts[:deletions]\n plausable &= self.deletions <= opts[:deletions]\n end\n if opts[:insertions]\n plausable &= self.insertions <= opts[:insertions]\n end\n if opts[:substitutions]\n plausable &= self.substitutions <= opts[:substitutions]\n end\n if opts[:transpositions]\n plausable &= self.transpositions <= opts[:transpositions]\n end\n\n plausable\n end\n end",
"def match?(other)\n @children.any? { |child| child.match?(other) || other.match?(child) }\n end",
"def amicable_with?(other)\n factors.reduce(:+) == other &&\n other.factors.reduce(:+) == self &&\n self != other\n end",
"def is_a_match(total_in_common)\n total_in_common >= 2 ? true : false\n end",
"def similarTo?( otherObj )\n\t\t\treturn false unless otherObj.is_a?( self.class )\n\t\t\totherAry = otherObj.to_ary\n\t\t\trval = true\n\t\t\tself.to_ary.each_with_index {|elem,i|\n\t\t\t\tif (elem - otherAry[i]).abs > 1e-10\n\t\t\t\t\trval = false\n\t\t\t\t\tbreak\n\t\t\t\tend\n\t\t\t}\n\t\t\treturn rval\n\t\tend",
"def covers?(other)\n fail 'Argument must be an Implicant' unless other.is_a?(Implicant)\n\n @inputs.zip(other.inputs).each do |a, b|\n return false unless a.bit == b.bit || a.bit == Bit::DC\n end\n\n true\n end",
"def better_partner?(matchable)\r\n rank(matchable) > rank(@partner)\r\n end",
"def eql? other\n object_id == other.object_id || \n (self.class == other.class &&\n specification == other.specification && \n candidate_types == other.candidate_types && \n candidate_types_excluded == other.candidate_types_excluded && \n candidate_objects == other.candidate_objects && \n join_points_matched == other.join_points_matched &&\n join_points_not_matched == other.join_points_not_matched)\n end",
"def is_stable?\n # Every person's partner should match up\n @matches.all? { |k,v| is_matched?(k, v) }\n end",
"def match(other)\n settings = get_match_settings\n return nil unless settings\n\n potential_prompt_match_attributes = {:offer => other, :request => self}\n full_request_tag_set = self.optional_tag_set ? self.tag_set + self.optional_tag_set : self.tag_set\n full_offer_tag_set = other.optional_tag_set ? (other.tag_set + other.optional_tag_set) : other.tag_set\n\n TagSet::TAG_TYPES.each do |type|\n if self.send(\"any_#{type}\") || other.send(\"any_#{type}\")\n match_count = ALL\n else\n required_count = settings.send(\"num_required_#{type.pluralize}\")\n if settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n else\n # we don't use optional tags to count towards required\n match_count = self.tag_set.match_rank(other.tag_set, type)\n end\n \n # if we have to match all and don't, not a match\n return nil if required_count == ALL && match_count != ALL\n\n # we are a match only if we either match all or at least as many as required\n return nil if match_count != ALL && match_count < required_count\n\n # now get the match rank including optional tags if we didn't before\n if !settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n end\n end\n\n potential_prompt_match_attributes[\"num_#{type.pluralize}_matched\"] = match_count\n end\n return PotentialPromptMatch.new(potential_prompt_match_attributes)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Have all possible preferences been cycled through?
|
def exhausted_preferences?
preference_position >= preferences.size - 1
end
|
[
"def has_pref?(preference)\n !prefs[preference].to_s.empty?\nend",
"def empty_preferences?\n preferences.empty?\n end",
"def check_if_all_donors_ready\n self.donor_preferences.each do |donor_preference|\n return false if !donor_preference.is_ready\n end\n return true\n end",
"def prefers?( other )\n preferences.include? other\n end",
"def chosen_all_strands?\n chosen_strands.size >= strands.keys.size\n end",
"def there_are_twelve_enabled_puppies\n expect(Puppy.enabled.size).to eql 12\nend",
"def run\n while ( rcs = remaining_candidates ).any?\n rcs.each do | candidate |\n while !candidate.exhausted_preferences? && candidate.free?\n candidate.propose_to_next_preference\n end\n end\n end\n self\n end",
"def puzzles_available\n available = puzzles.select do |puzzle|\n puzzle.available == true\n end\n end",
"def of_presence!\n requested_user_preferences.each do |requested|\n validate_pref_code!(requested)\n validate_user_pref_key!(requested)\n\n requested.dig('user_preferences').each do |user_preference|\n validate_user_pref!(user_preference)\n validate_user_pref_code!(user_preference)\n end\n end\n\n requested_user_preferences\n end",
"def test_should_verify_if_is_true\n a_preference = preferences(:store_use_inventory_control)\n assert a_preference.is_true?\n\n a_preference = preferences(:store_require_login)\n assert !a_preference.is_true?\n end",
"def all_correct?\n @failed_winners.empty?\n end",
"def remaining_candidates\n case strategy.to_sym\n when :symmetric\n candidates.reject { | candidate | candidate.full? || candidate.exhausted_preferences? }\n when :asymmetric\n candidate_set1.values.reject { | candidate | candidate.full? || candidate.exhausted_preferences? }\n end\n end",
"def choices_resolved?\n @choices.values.map(&:size).all? {|size| size == 1 }\n end",
"def enabled_all?\n !disabled? && all_cops?\n end",
"def print_prefs\n puts \"____________\"\n puts \"Reduced Sets\"\n @people_prefs.each_with_index do |prefs, i|\n puts \"#{i}| #{prefs.join(' ')} \"\n end\n puts \"____________\"\n end",
"def show_preferences\n\t\tputs \"Your preferences are as follows:\"\n\t\tputs\n\t\t67.times do print \"*\" end \n\t\tputs\n\t\tputs\n\t\tputs \"1. Species - #{self.preferred_species}\"\n\t\tputs \"2. Temperament - #{self.preferred_temperament}\"\n\t\tputs \"3. Size - #{self.preferred_size}\"\n\t\tputs \"4. Zip - #{self.zip}\"\n\t\tputs \"To update your preferences, enter 'change'. Otherwise, enter 'done' to return to the main menu\"\n\t\tputs\n\t\t67.times do print \"*\" end \n\t\tputs\n\t\tputs\n\t\tself.change_preferences\n\t\tself.save\n\tend",
"def meets_contract_preferences?(user)\n\t\t#-------------------------\n\t\t# NOTE: Similar logic is in BountiesController and ContractsController\n\t\t#-------------------------\n\t\tmeets_prefs = true\n\t\tmeets_prefs = meets_prefs && personality_rating >= user.required_personality_rating if personality_rating > 0\n\t\tmeets_prefs = meets_prefs && skill_rating >= user.required_skill_rating if skill_rating > 0\n\t\tmeets_prefs = meets_prefs && approval_rating >= user.required_approval_rating if approval_rating > 0\n\t\tmeets_prefs = meets_prefs && psa_rating >= user.required_psa_rating if psa_rating > 0\n\t\tmeets_prefs = meets_prefs && cancellation_rate <= user.required_cancellation_rate if cancellation_rate.present?\n\n\t\tmeets_prefs\n\tend",
"def candidate_all_agreed\n ethics == true and code_of_conduct == true and candidate_terms == true\n end",
"def pref?\n type? 'PREF'\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Delete the leastpreferred candidate from the matches array
|
def free!
return false if matches.empty?
match_preference_indexes = matches.map { | match | preferences.index match }
max = match_preference_indexes.max # The index of the match with the lowest preference
candidate_to_reject = preferences[ max ]
# Delete from both sides
candidate_to_reject.matches.delete self
self.matches.delete candidate_to_reject
end
|
[
"def delete_candidate(val)\n\t\t@candidates.delete(val)\n\tend",
"def remove_match\n contest = Contest.get_contest_with_id(params[:contest]) \n winning_scores = contest.get_team_scores(Team.get_team_with_id(contest.get_winner))\n losing_scores = contest.get_team_scores(Team.get_team_with_id(contest.get_loser))\n \n #First, remove all of the game scores.\n score_ids = Array.new\n for i in 0..winning_scores.length - 1 \n score_ids.insert(-1, winning_scores[i].id);\n score_ids.insert(-1, losing_scores[i].id);\n end\n GameScore.delete(score_ids)\n \n #Next, remove all games.\n game_ids = Array.new\n for game in contest.games\n game_ids.insert(-1, game.id)\n end\n Game.delete(game_ids)\n contest.destroy\n \n recalculate_data\n redirect_to :action => :show_player_info, :username => params[:player_name]\n end",
"def remove_best_mark\n question.update_attribute(:best_answer, nil) if\n question.best_answer == self\n end",
"def remove_duplicate_matches(matches)\r\n # Sort the items.\r\n # Sort the array without matches[0], since we need it to\r\n # stay in place no matter what.\r\n if matches.length>0\r\n matches[1..-2] = matches[1..-2].sort.uniq\r\n end\r\n matches\r\n end",
"def identify_and_destroy_choice_with_no_first_choices(first_choice_rankings, survey)\n #byebug\n\n\n first_choice_ids = []\n choice_ids = []\n first_choice_rankings.each { |ranking|\n if ranking[0]\n first_choice_ids.push(ranking[0][\"choice_id\"])\n end}\n\n survey.choices.each { |choice|\n choice_ids.push(choice.id)}\n #byebug\n least_popular_choice_id = choice_ids - first_choice_ids\n #choice = Choice.find(least_popular_choice_id[0])\n least_popular_choice_id.each { |id|\n choice = Choice.find(id)\n survey_id = choice.survey_id\n choice.destroy\n @survey = Survey.find(survey_id)\n @survey.calculate_winner}\n\n\n end",
"def delete_least_common\n lc = least_common_word\n self.word_counts.delete(lc) unless lc.nil? || self.word_counts.nil?\n end",
"def shortlist_nominees (nominees,votes_sum,election_summary)\n idx = 0\n votes_sum.each do | a |\n idx += 1\n if a != votes_sum.max\n nominees.delete(election_summary[idx-1][:nominee])\n end\n end\n return nominees\nend",
"def remove(index)\n\t\t@candidates.delete_at(index)\n\tend",
"def eliminate_worst_chromosome\n # Check if the elitist chromosome is duplicated after crossoverred\n # This may occur if the self object is better than offsprings so self is returned and added to @chromosomes array\n ind = -1\n @chromosomes.each_with_index do |ch, index|\n ind = index if ch.object_id == @chromosomes[0].object_id and index != 0 \n end\n if ind > 0\n @chromosomes.delete_at ind\n return\n end \n \n min, will_be_deleted = -1, -1\n @chromosomes.each_with_index do |ch, ind|\n if ch.fitness_value < min or min == -1\n will_be_deleted = ind\n min = ch.fitness_value\n end\n end\n \n @chromosomes.delete_at will_be_deleted\n end",
"def remove_played_space_from_acceptable_choices(choice)\n if @acceptable_choices[0].include? choice\n @acceptable_choices[0].delete(choice)\n elsif @acceptable_choices[1].include? choice\n @acceptable_choices[1].delete(choice)\n elsif @acceptable_choices[2].include? choice\n @acceptable_choices[2].delete(choice)\n else\n puts \"Something weird happened when removing choice from array\"\n end\n end",
"def identify_and_destroy_choices_with_no_first_place_votes(choices_with_first_place_votes)\n\n first_choice_ids = []\n choice_ids = []\n #first_choice_rankings only have choices with first choices\n choices_with_first_place_votes.each { |ranking|\n if ranking[0]\n #extracting choice_id\n first_choice_ids.push(ranking[0][\"choice_id\"])\n end}\n\n self.choices.each { |choice|\n choice_ids.push(choice.id)}\n\n #remove choices with first place votes\n choices_with_no_first_place_votes_ids = choice_ids - first_choice_ids\n \n choices_with_no_first_place_votes_ids.each { |id|\n choice = Choice.find(id)\n\n choice.destroy\n\n }\n end",
"def pop_pair\n if selected = pair_candidates.min { |a,b| a[1].length <=> b[1].length }\n first_in_pair = selected[0]\n else\n return nil\n end\n\n candidates = pair_candidates[first_in_pair]\n # From the pair candidates of first_in_pair find the one with the least candidates.\n candidates_candidates = pair_candidates.select do |k,v|\n candidates.include?(k)\n end\n second_in_pair =\n candidates_candidates.min { |a,b| a[1].length <=> b[1].length }[0]\n\n # Remove the pair from humans\n humans.delete_if { |k,v| [first_in_pair, second_in_pair].include?(k) }\n\n [first_in_pair, second_in_pair].sort\n end",
"def reset\n @players = @players.sort_by{rand}\n load_matches\n @matches\n end",
"def subtractSet(chosenCards)\n @cardsOnTable.each { |c|\n if c = chosenCards[0]\n @cardsOnTable.delete_at(0)\n elsif c = chosencards[1]\n @cardsOnTable.delete_at(1)\n elsif c = chosenCards[2]\n @cardsOnTable.delete_at(2)\n end\n }\n end",
"def remove_unreviewed_suggestions_not_matching_suggestions(suggestions)\n unreviewed_abstractor_suggestions.each do |abstractor_suggestion|\n not_detritus = suggestions.detect { |suggestion| suggestion[:suggestion] == abstractor_suggestion.suggested_value }\n unless not_detritus\n abstractor_suggestion.destroy\n end\n end\n end",
"def eliminate\n @list.each do |candidate|\n candidate.ballots.list.clear\n end\n end",
"def delete_unecessary_query\n\t\tdelete_middle_query\n\t\tscore = calculate_score\n\t\tself.delete if score.zero?\n\tend",
"def remove_players\n @players, broke_players = @players.partition{ |p| p.wallet >= @table_minimum }\n broke_players.each{ |p|\n puts \"#{p.name}, you no longer have enough money to meet the table minimum. Better luck next time.\"\n linebreak\n }\n end",
"def remove_smallest(numbers)\n return [] if numbers == []\n worst_exhibition = numbers.min\n numbers.delete_at(numbers.index(worst_exhibition)) # but this mutates the array. had to look up delete at\n numbers\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Match with another Candidate ARG: `other` another Candidate instance to match with
|
def match!( other )
return false unless prefers?( other ) && !matched?( other )
matches << other
other.matches << self
end
|
[
"def respond_to_proposal_from( other )\n case\n # Is there a preference for the candidate?\n when !prefers?( other )\n false\n\n # Are there available positions for more matches?\n when free?\n match! other\n\n # Is the passed Candidate a better match than any other match?\n when better_match?( other )\n free!\n match! other\n\n else\n false\n end\n end",
"def match(other)\n settings = get_match_settings\n return nil unless settings\n\n potential_prompt_match_attributes = {:offer => other, :request => self}\n full_request_tag_set = self.optional_tag_set ? self.tag_set + self.optional_tag_set : self.tag_set\n full_offer_tag_set = other.optional_tag_set ? (other.tag_set + other.optional_tag_set) : other.tag_set\n\n TagSet::TAG_TYPES.each do |type|\n if self.send(\"any_#{type}\") || other.send(\"any_#{type}\")\n match_count = ALL\n else\n required_count = settings.send(\"num_required_#{type.pluralize}\")\n if settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n else\n # we don't use optional tags to count towards required\n match_count = self.tag_set.match_rank(other.tag_set, type)\n end\n \n # if we have to match all and don't, not a match\n return nil if required_count == ALL && match_count != ALL\n\n # we are a match only if we either match all or at least as many as required\n return nil if match_count != ALL && match_count < required_count\n\n # now get the match rank including optional tags if we didn't before\n if !settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n end\n end\n\n potential_prompt_match_attributes[\"num_#{type.pluralize}_matched\"] = match_count\n end\n return PotentialPromptMatch.new(potential_prompt_match_attributes)\n end",
"def match(other)\n return @type.match(other)\n end",
"def matched?( other = nil )\n return full? if other.nil?\n matches.include? other\n end",
"def match(other, settings=nil)\n return nil if settings.nil?\n potential_prompt_match_attributes = {:offer => other, :request => self}\n full_request_tag_set = self.optional_tag_set ? self.tag_set + self.optional_tag_set : self.tag_set\n full_offer_tag_set = other.optional_tag_set ? (other.tag_set + other.optional_tag_set) : other.tag_set\n\n TagSet::TAG_TYPES.each do |type|\n if self.send(\"any_#{type}\") || other.send(\"any_#{type}\")\n match_count = ALL\n else\n required_count = settings.send(\"num_required_#{type.pluralize}\")\n if settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n else\n # we don't use optional tags to count towards required\n match_count = self.tag_set.match_rank(other.tag_set, type)\n end\n \n # if we have to match all and don't, not a match\n return nil if required_count == ALL && match_count != ALL\n\n # we are a match only if we either match all or at least as many as required\n return nil if match_count != ALL && match_count < required_count\n\n # now get the match rank including optional tags if we didn't before\n if !settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n end\n end\n\n potential_prompt_match_attributes[\"num_#{type.pluralize}_matched\"] = match_count\n end\n return PotentialPromptMatch.new(potential_prompt_match_attributes)\n end",
"def match(other, settings=nil)\n no_match_required = settings.nil? || settings.no_match_required?\n potential_match_attributes = {:offer_signup => other, :request_signup => self, :collection => self.collection}\n prompt_matches = []\n unless no_match_required\n self.requests.each do |request|\n other.offers.each do |offer|\n if (match = request.match(offer, settings))\n prompt_matches << match\n end\n end\n end\n return nil if settings.num_required_prompts == ALL && prompt_matches.size != self.requests.size\n end\n if no_match_required || prompt_matches.size >= settings.num_required_prompts\n # we have a match\n potential_match_attributes[:num_prompts_matched] = prompt_matches.size\n potential_match = PotentialMatch.new(potential_match_attributes)\n potential_match.potential_prompt_matches = prompt_matches unless prompt_matches.empty?\n potential_match\n else\n nil\n end\n end",
"def minimal_match?(other)\n super and tolerant_match?(other, TOLERANT_MATCH_ATTRS)\n end",
"def base_match other\n\t\t\tother.base.to_s =~ @baseregex\n\t\tend",
"def better_match?( other )\n return true if prefers?( other ) && free?\n preference_index = preferences.index other\n match_preference_indexes = matches.map { | match | preferences.index match }\n preference_index and match_preference_indexes.any? { |i| i > preference_index }\n end",
"def match_in(others)\n # trivial case: self is in others\n return self if others.include?(self)\n # filter for the same type\n unless others.all? { |other| self.class === other } then\n others = others.filter { |other| self.class === other }\n end\n # match on primary, secondary or alternate key\n match_unique_object_with_attributes(others, self.class.primary_key_attributes) or\n match_unique_object_with_attributes(others, self.class.secondary_key_attributes) or\n match_unique_object_with_attributes(others, self.class.alternate_key_attributes)\n end",
"def refute_match(matcher, obj, msg = T.unsafe(nil)); end",
"def match\n extract!\n policy_failure_match! || self\n end",
"def match(left, right)\n IdentityParade::Match.new(left, right).score\n end",
"def matches\n post_process(candidate.empty? ? completions : completions.select { |c| c.start_with?(candidate) })\n end",
"def match\n self.class.match.with_instance(self)\n end",
"def match_arg(expected, actual)\n expected === actual ||\n expected == actual ||\n ( Regexp === expected && expected === actual.to_s )\n end",
"def match(left, right, options)\n s = [:match, sexpr(left), sexpr(right)]\n s << options unless options.nil?\n _factor_predicate(s)\n end",
"def match_named(arg, other)\n match = OptionMatch.new\n\n # Match command line arg against command options\n if arg.class == String && other.class == Command\n match.arg = arg\n options = other.nodes.select{|x| x.class == Option && !x.key.nil? }\n\n if arg.start_with?('-')\n short = arg[@short_regex, 1]\n long = arg[@long_regex, 1]\n match.value = arg[@value_regex, 1]\n\n # Set symbol converting dashes to underscores for named options\n if (match.opt = options.find{|x| (short && short == x.short) || (long && long == x.long)})\n match.sym = match.opt.to_sym\n end\n end\n\n # Match command option against command line args\n elsif arg.class == Option && other.class == Array\n match.arg = arg.key\n\n other.select{|x| x.start_with?('-')}.any?{|x|\n short = x[@short_regex, 1]\n long = x[@long_regex, 1]\n value = x[@value_regex, 1]\n if (short && short == arg.short) || (long && long == arg.long)\n match.opt = arg\n match.value = value\n match.sym = match.opt.to_sym\n end\n }\n end\n\n return match\n end",
"def == other\n other.is_a?(MatchWrapper) &&\n other.given_class == @given_class &&\n other.matcher == @matcher &&\n falsy_or_equal?(other.name, @name) &&\n falsy_or_equal?(other.temp, @temp) &&\n falsy_or_equal?(other.defs, @defs)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
If no argument is passed: Do we have at least as many matches as available `match_positions`? If another Candidate is passed: Is that candidate included in the matches? ARG: `other` [optional] another Candidate instance
|
def matched?( other = nil )
return full? if other.nil?
matches.include? other
end
|
[
"def respond_to_proposal_from( other )\n case\n # Is there a preference for the candidate?\n when !prefers?( other )\n false\n\n # Are there available positions for more matches?\n when free?\n match! other\n\n # Is the passed Candidate a better match than any other match?\n when better_match?( other )\n free!\n match! other\n\n else\n false\n end\n end",
"def match(other)\n settings = get_match_settings\n return nil unless settings\n\n potential_prompt_match_attributes = {:offer => other, :request => self}\n full_request_tag_set = self.optional_tag_set ? self.tag_set + self.optional_tag_set : self.tag_set\n full_offer_tag_set = other.optional_tag_set ? (other.tag_set + other.optional_tag_set) : other.tag_set\n\n TagSet::TAG_TYPES.each do |type|\n if self.send(\"any_#{type}\") || other.send(\"any_#{type}\")\n match_count = ALL\n else\n required_count = settings.send(\"num_required_#{type.pluralize}\")\n if settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n else\n # we don't use optional tags to count towards required\n match_count = self.tag_set.match_rank(other.tag_set, type)\n end\n \n # if we have to match all and don't, not a match\n return nil if required_count == ALL && match_count != ALL\n\n # we are a match only if we either match all or at least as many as required\n return nil if match_count != ALL && match_count < required_count\n\n # now get the match rank including optional tags if we didn't before\n if !settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n end\n end\n\n potential_prompt_match_attributes[\"num_#{type.pluralize}_matched\"] = match_count\n end\n return PotentialPromptMatch.new(potential_prompt_match_attributes)\n end",
"def matches\n post_process(candidate.empty? ? completions : completions.select { |c| c.start_with?(candidate) })\n end",
"def better_match?( other )\n return true if prefers?( other ) && free?\n preference_index = preferences.index other\n match_preference_indexes = matches.map { | match | preferences.index match }\n preference_index and match_preference_indexes.any? { |i| i > preference_index }\n end",
"def match!( other )\n return false unless prefers?( other ) && !matched?( other )\n matches << other\n other.matches << self\n end",
"def is_matchsuitable_forscore?\r\n tot_points = 0\r\n @points_curr_match.each{|v| tot_points += v[1] }\r\n if tot_points > 0 or @mano_count > 4\r\n return true\r\n end\r\n return false\r\n end",
"def match(other, settings=nil)\n no_match_required = settings.nil? || settings.no_match_required?\n potential_match_attributes = {:offer_signup => other, :request_signup => self, :collection => self.collection}\n prompt_matches = []\n unless no_match_required\n self.requests.each do |request|\n other.offers.each do |offer|\n if (match = request.match(offer, settings))\n prompt_matches << match\n end\n end\n end\n return nil if settings.num_required_prompts == ALL && prompt_matches.size != self.requests.size\n end\n if no_match_required || prompt_matches.size >= settings.num_required_prompts\n # we have a match\n potential_match_attributes[:num_prompts_matched] = prompt_matches.size\n potential_match = PotentialMatch.new(potential_match_attributes)\n potential_match.potential_prompt_matches = prompt_matches unless prompt_matches.empty?\n potential_match\n else\n nil\n end\n end",
"def match(other, settings=nil)\n return nil if settings.nil?\n potential_prompt_match_attributes = {:offer => other, :request => self}\n full_request_tag_set = self.optional_tag_set ? self.tag_set + self.optional_tag_set : self.tag_set\n full_offer_tag_set = other.optional_tag_set ? (other.tag_set + other.optional_tag_set) : other.tag_set\n\n TagSet::TAG_TYPES.each do |type|\n if self.send(\"any_#{type}\") || other.send(\"any_#{type}\")\n match_count = ALL\n else\n required_count = settings.send(\"num_required_#{type.pluralize}\")\n if settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n else\n # we don't use optional tags to count towards required\n match_count = self.tag_set.match_rank(other.tag_set, type)\n end\n \n # if we have to match all and don't, not a match\n return nil if required_count == ALL && match_count != ALL\n\n # we are a match only if we either match all or at least as many as required\n return nil if match_count != ALL && match_count < required_count\n\n # now get the match rank including optional tags if we didn't before\n if !settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n end\n end\n\n potential_prompt_match_attributes[\"num_#{type.pluralize}_matched\"] = match_count\n end\n return PotentialPromptMatch.new(potential_prompt_match_attributes)\n end",
"def minimal_match?(other)\n super and tolerant_match?(other, TOLERANT_MATCH_ATTRS)\n end",
"def matches(options = {})\n Match.all(options.merge(championship: source_id))\n end",
"def has_match_clauses?\n !!match_clauses\n end",
"def requires_matching?\n !required_matches.nil?\n end",
"def near_matches(other_code)\n num_matches = 0\n matches = []\n i = 0\n while (i < self.pegs.length)\n j = 0\n while (j < other_code.pegs.length)\n if(self[i] == other_code[j])\n if(i != j)\n unless (matches.include?(self[i]))\n num_matches += 1\n matches << self[i]\n end\n else\n if(matches.include?(self[i]))\n num_matches -= 1\n end\n end\n end\n j += 1\n end\n i += 1\n end\n num_matches\n end",
"def match\n @argument_matchers[0...-1].each_with_index do |argument_matcher, index|\n @argument_matchers[index + 1].successor = argument_matcher\n end\n\n chain_matcher = @argument_matchers.last\n chain_matcher.check_to_assing_and_match(@data)\n end",
"def match?(opts = { :score => 3 })\n if opts[:score]\n # combined operations\n self.score <= opts[:score]\n\n elsif opts[:max]\n !(self.deletions > opts[:max]) and !(self.insertions > opts[:max]) \\\n and !(self.substitutions > opts[:max]) \\\n and !(self.transpositions > opts[:max])\n\n else\n plausable = true\n\n if opts[:deletions]\n plausable &= self.deletions <= opts[:deletions]\n end\n if opts[:insertions]\n plausable &= self.insertions <= opts[:insertions]\n end\n if opts[:substitutions]\n plausable &= self.substitutions <= opts[:substitutions]\n end\n if opts[:transpositions]\n plausable &= self.transpositions <= opts[:transpositions]\n end\n\n plausable\n end\n end",
"def matched_positions\n _response_entity.fetch(\"matchingTokens\", [])\n end",
"def satisfy?(o, data={})\n # Future optimizations: \n # * Shortcut matching sibling\n subject_matches = index_matches(subject, o)\n return nil if subject_matches.empty?\n \n sibling_matches = index_matches(sibling, o)\n return nil if sibling_matches.empty?\n\n subject_matches.each do |i1, data_1|\n sibling_matches.each do |i2, data_2|\n if (distance ? (i2-i1 == distance) : i2 > i1)\n data = data.merge(data_1).merge(data_2)\n return capture_match(o, data)\n end\n end\n end\n \n nil\n end",
"def match_scores_are_at_match_count\n match_count = League.find(league_id).match_count\n\n # Make sure that scores can't be negative. \n if p1_score < 0 || p2_score < 0\n errors.add(:match_score, \" cannot be negative\")\n \n # Don't allow 0-0 score for tournament matches\n elsif tournament_id != nil && p1_score == 0 && p2_score == 0\n errors.add(:at_least_one_match_score, \"must be above 0\")\n\n # Score is being changed\n elsif p1_score > 0 || p2_score > 0\n\n # Tournament matches don't adhere to league's match count.\n if tournament_id != nil\n\n # Make sure there isn't a tie for a tournament match.\n if p1_score == p2_score\n errors.add(:there_cannot, \" be a tie\")\n end\n\n # Either player's score are not HIGHER than match count\n elsif p1_score <= match_count && p2_score <= match_count\n\n # At least one of the scores is at the league match count\n if p1_score == match_count || p2_score == match_count\n\n # Make sure that BOTH aren't at match count\n if p1_score == match_count && p2_score == match_count\n errors.add(:only_one_match_score, \" can be at \" + match_count.to_s)\n end\n\n # Neither of the scores are at the match count\n else\n errors.add(:at_least_one_match_score, \"must be at \" + match_count.to_s)\n end\n\n # One of the player's score is HIGHER than match count \n else\n errors.add(:match_score, \" cannot be higher than \" + match_count.to_s)\n end\n end\n end",
"def is_a_match(total_in_common)\n total_in_common >= 2 ? true : false\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Increment `preference_position` and return the preference at that position
|
def next_preference!
self.preference_position += 1
preferences.fetch preference_position
end
|
[
"def preference\n return @preference\n end",
"def preference=(value)\n @preference = value\n end",
"def increment_position\n in_list? && update_position(current_position + 1)\n end",
"def add_preference(name, value); end",
"def add_preference(name, value)\n prefs[name] = value\n end",
"def pref(pref_item_name)\n id, key = preference_items_hash[pref_item_name]\n preference_hash[id][key]\n end",
"def preference(value)\n fresh.tap do |criteria|\n criteria.preference_value = value\n end\n end",
"def increment_position\n return unless in_list?\n set_list_position(current_position + 1)\n end",
"def write_pref(name, value)\n #override the preference value or add new preference if not exist\n preferences[name] = value\n write_attribute(:preferences, preferences)\n value\n end",
"def increment_position\n return unless in_list?\n update_position( self.send(position_column).to_i+1 )\n end",
"def update_position\n predecessor = params[:section][:predecessor]\n return unless predecessor.present?\n position = predecessor.to_i\n if position > @section.position && @old_chapter == @section.chapter\n position -= 1\n end\n @section.insert_at(position + 1)\n end",
"def preference(key)\n session[\"preference_#{key}\"]\n end",
"def remember_preference settings\n self.preference = Preference.find_or_create_by user_id: self\n self.preference.update settings\n end",
"def assign_position\n\t\t\tself.position = num_of_ranks_in_activity + 1\n\t\tend",
"def preference\n redirect_to NextPageFinder.get_next_page current_user: current_user, next_response: @response\n end",
"def assign_pid\n start = Setting.starting_pid\n\n self.pid = if Pilot.exists?\n last = Pilot.order(pid: :asc).last\n (last.pid >= start ? last.pid + 1 : start)\n else\n start\n end\n end",
"def get_preference(prefs_section, pref)\n @driver.getPref(prefs_section, pref)\n end",
"def update_position(index)\n relationships = self.property_relations\n last = relationships.count \n relationships.each do |r|\n if r.position.nil?\n r.update_attribute(:position, last -= 1)\n else\n if r.position > index\n r.update_attribute(:position, r.position - 1)\n end\n end\n end\n end",
"def create_preference(preference)\r\n\t\t@rest_client.post(\"/checkout/preferences\", preference)\r\n\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Is there a preference for the passed Candidate? ARG: `other` another Candidate instance
|
def prefers?( other )
preferences.include? other
end
|
[
"def respond_to_proposal_from( other )\n case\n # Is there a preference for the candidate?\n when !prefers?( other )\n false\n\n # Are there available positions for more matches?\n when free?\n match! other\n\n # Is the passed Candidate a better match than any other match?\n when better_match?( other )\n free!\n match! other\n\n else\n false\n end\n end",
"def prefer_that actual, preference = DEFAULT_PREFERENCE, msg = ''\n add_preference\n unless @frame_of_reference.is_true(preference.is_preferred? actual)\n raise DifferingOpinion, \"Preferred #{preference.description}, got <#{actual}>. #{msg}\"\n end\n\t\tend",
"def better_match?( other )\n return true if prefers?( other ) && free?\n preference_index = preferences.index other\n match_preference_indexes = matches.map { | match | preferences.index match }\n preference_index and match_preference_indexes.any? { |i| i > preference_index }\n end",
"def default?(preference)\n self.send(preference.to_sym) == self.class.new.send(preference.to_sym)\n end",
"def candidate?\n !!candidate\n end",
"def preferred?\n self.preferred\n end",
"def other?\n self.name == 'Other'\n end",
"def is_better_match?(person, first_better, second_better)\n @preferences[person].detect { |pref| pref == first_better || pref == second_better }\n end",
"def candidate?\n\t\t@candidate = true if @type == \"politician\"\n\tend",
"def compatible_with?(other_option)\n self.is_a? other_option.class\n end",
"def is_other?\n\t\tkey == 'other'\n\tend",
"def case?(other)\n other === self\n end",
"def connects?(other)\n other &&\n (self == other ||\n (suited? &&\n suit == other.suit &&\n (rank - other.rank).abs <= 2))\n end",
"def in_contest?(pet)\n pet.id == challenger.id || pet.id == challenged.id\n end",
"def better_partner?(matchable)\r\n rank(matchable) > rank(@partner)\r\n end",
"def user_is_candidate\n current_user && current_user.isCandidate\n end",
"def preferred?(name, group = nil)\n name = name.to_s\n assert_valid_preference(name)\n\n value = preferred(name, group)\n preference_definitions[name].query(value)\n end",
"def one_candidate?\n @candidates.count == 1\n end",
"def two_candidates?\n @candidates.count == 2\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Track that a proposal was made then ask the other Candidate to respond to a proposal ARG: `other` another Candidate instance
|
def propose_to( other )
proposals << other
other.respond_to_proposal_from self
end
|
[
"def respond_to_proposal_from( other )\n case\n # Is there a preference for the candidate?\n when !prefers?( other )\n false\n\n # Are there available positions for more matches?\n when free?\n match! other\n\n # Is the passed Candidate a better match than any other match?\n when better_match?( other )\n free!\n match! other\n\n else\n false\n end\n end",
"def vote( to_proposal )\r\n sender = @voters[msg.sender]\r\n assert sender.voted? == false && to_proposal < @proposals.length\r\n sender.voted = true\r\n sender.vote = to_proposal\r\n @proposals[to_proposal].vote_count += sender.weight\r\nend",
"def update_and_send_candidate\n @candidate = @candidates.first\n @models.each { |m| m.tell([:prime?,@candidate],self.getContext) }\n end",
"def delegate( to: ) ## address to\r\n sender = @voters[msg.sender]\r\n return if sender.voted\r\n\r\n ### todo/fix:\r\n ## check add address to Contract base\r\n ## address(0) !!!\r\n ## address(0) is nil / empty address ????\r\n\r\n while @voters[to].delegate != nil &&\r\n @voters[to].delegate != msg.sender\r\n to = @voters[to].delegate\r\n end\r\n\r\n return if to == msg.sender\r\n\r\n sender.voted = true\r\n sender.delegate = to\r\n\r\n delegate_to = @voters[to]\r\n if delegate_to.voted\r\n ## note/fix/bug!! - delegate_to.vote must reference a proposal 0..n (defaults to nil!!!)\r\n ## default to 0 - why? why not?\r\n @proposals[delegate_to.vote].vote_count += sender.weight if delegate_to.vote\r\n else\r\n delegate_to.weight += sender.weight\r\n end\r\n end",
"def on_proposal_update(proposal)\n proposal.approvals.approved.each{|approval|\n CommunicartMailer.notification_for_approver(approval.user_email_address, approval, \"already_approved\").deliver\n }\n proposal.currently_awaiting_approvals.each{|approval|\n if approval.api_token # Approver's been notified through some other means\n CommunicartMailer.actions_for_approver(approval.user_email_address, approval, \"updated\").deliver\n else\n approval.create_api_token!\n CommunicartMailer.actions_for_approver(approval.user_email_address, approval).deliver\n end\n }\n end",
"def vote( to_proposal: ) ## uint8 toProposal\r\n sender = @voters[msg.sender]\r\n\r\n return if sender.voted || to_proposal >= @proposals.size\r\n\r\n sender.voted = true\r\n sender.vote = to_proposal\r\n @proposals[to_proposal].vote_count += sender.weight\r\n end",
"def delegate( to )\r\n sender = @voters[msg.sender] # assigns reference\r\n assert sender.voted? == false\r\n\r\n while @voters[to].delegate != Address(0) && @voters[to].delegate != msg.sender do\r\n to = @voters[to].delegate\r\n end\r\n assert to != msg.sender\r\n\r\n sender.voted = true\r\n sender.delegate = to\r\n delegate_to = @voters[to]\r\n if delegate_to.voted\r\n @proposals[delegate_to.vote].vote_count += sender.weight\r\n else\r\n delegate_to.weight += sender.weight\r\n end\r\nend",
"def on_proposal_update(proposal)\n proposal.individual_approvals.approved.each{|approval|\n CommunicartMailer.notification_for_subscriber(approval.user_email_address, proposal, \"already_approved\", approval).deliver_later\n }\n\n proposal.currently_awaiting_approvals.each{|approval|\n if approval.api_token # Approver's been notified through some other means\n CommunicartMailer.actions_for_approver(approval, \"updated\").deliver_later\n else\n CommunicartMailer.actions_for_approver(approval).deliver_later\n end\n }\n\n proposal.observers.each{|observer|\n if observer.role_on(proposal).active_observer?\n CommunicartMailer.notification_for_subscriber(observer.email_address, proposal, \"updated\").deliver_later\n end\n }\n end",
"def other_proposals\n request_for_proposal.proposals.where('id != ?', id)\n end",
"def meet(other_person)\n\t\tif have_met? other_person\n\t\t\tputs \"They already know each other!\"\n\t\tend\n\n\t\t@knows << other_person\n\n\t\tother_person.knows << self\n\tend",
"def proposal\n @proposal ||= begin\n if params[:id] == \"mine\" && current_user\n request_for_proposal.proposals.find_by!(person: current_user)\n else\n require_team_admin_or_developer\n request_for_proposal.proposals.find_by!(id: params[:id])\n end\n end\n end",
"def send_approval_email\n # person.send_email(:proposal_approved, proposal: self)\n end",
"def reject_other_pending_proposals!\n # TODO find_each would be better\n other_proposals.pending.each(&:reject!)\n end",
"def inform_goal_of_new_contribution\n self.goal.check_for_completion!(self.goal_participant)\n end",
"def candidate_interview_request(interview, employer, candidate)\n @interview = interview\n @employer = employer\n @candidate = candidate\n \n subject = \"Congrats!! You have been selected for an Interview\"\n \n mail to: @candidate.email, subject: subject\n end",
"def try_to_convince_other_responders(poll)\n\t\tif poll.expert_user == self\n\t\t\t# Create a hash to remember who will have been convinced\n\t\t\thash = Hash.new()\n\t\t\tpoll.questions.each do |question|\n\t\t\t\tcurrent_array = Array.new()\n\t\t\t\thash.store(question.id, current_array)\n\n\t\t\t\tpoll.participants.each do |participant|\n\t\t\t\t\t# Save current choice in history\n\t\t\t\t\tparticipant.chosen_answer_for_question(question).history_be_chosen_by!(participant)\n\n\t\t\t\t\tunless participant == self\n\t\t\t\t\t\tunless participant.chosen_answer_for_question(question) == self.chosen_answer_for_question(question)\n\t\t\t\t\t\t\tif random_number_is_under(self.influence)\n\t\t\t\t\t\t\t\t# The participant has changed his mind\n\t\t\t\t\t\t\t\tparticipant.chosen_answer_for_question(question).be_not_chosen_by!(participant)\n\t\t\t\t\t\t\t\t# He chooses the answer chosen by the expert\n\t\t\t\t\t\t\t\tself.chosen_answer_for_question(question).be_chosen_by!(participant)\n\t\t\t\t\t\t\t\t# Add the convinced user to the hash\n\t\t\t\t\t\t\t\tcurrent_array.push(participant.first_name + \" \" + participant.name)\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t# Returns hash\n\t\thash\n\tend",
"def vote proposal, values=[], options={}\n return unless proposal\n return unless proposal.is_a?(VoteProposal)\n # return if values.blank?\n values = [values] if values.is_a?(VoteProposalOption)\n status = options[:status]\n action = options[:action] || :add\n\n voting_users = [self]\n voting_users += mandates_from.to_a\n voting_users.map do |user|\n vote = user.vote_in_proposal(proposal) \n if not vote\n user.create_vote proposal, values, status, self\n else\n if user != self and user.has_voted?(proposal)\n # if we are voting for mandate giver but user has already\n # voted by itself do nothing \n else\n # Currently only one option is give at a time.\n option = values.first\n if vote.vote_proposal_options.detect {|opt| opt.id == option.id }\n remove_vote_option vote, [option], self\n else\n add_vote_option vote, [option], self\n end\n end\n end\n end\n end",
"def prefer_that actual, preference = DEFAULT_PREFERENCE, msg = ''\n add_preference\n unless @frame_of_reference.is_true(preference.is_preferred? actual)\n raise DifferingOpinion, \"Preferred #{preference.description}, got <#{actual}>. #{msg}\"\n end\n\t\tend",
"def accepted_proposal\n \n if params[:commit] == \"Accept\"\n @accepted_proposal = UsersJobs.new(:job_id => params[:job_id], :user_id => params[:user_id], :deal => true)\n @acceptance_message = Message.new(:sender_id => current_user.id, :receiver_id => params[:user_id], :job_id => params[:job_id], :reason => \"Your proposal is accepted\")\n\n if @accepted_proposal.save\n @delete_jobs = Appliedjobs.where(:job_id => params[:job_id])\n @acceptance_message.save\n @delete_jobs.each do |delete_job|\n delete_job.apply_status = true if params[:user_id] != delete_job.user_id\n end\n redirect_to :back, notice: 'You accept this proposal.'\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Given another candidate, respond properly based on current state ARG: `other` another Candidate instance
|
def respond_to_proposal_from( other )
case
# Is there a preference for the candidate?
when !prefers?( other )
false
# Are there available positions for more matches?
when free?
match! other
# Is the passed Candidate a better match than any other match?
when better_match?( other )
free!
match! other
else
false
end
end
|
[
"def apply(candidate)\n raise NotImplementedError, \"Not yet?\"\n end",
"def absorb other\n my_voter_ids = self.voter_ids\n other.votes.each { |vote| vote.voter.vote(self, vote.up) unless my_voter_ids.include?(vote.user_id) }\n super if defined? super\n end",
"def == other\n case other\n when true\n accepted?\n when false\n !accepted?\n when State, Symbol\n current_state == other.to_sym\n when Transition\n inspect == other.inspect\n else\n super( other )\n end\n end",
"def receiveInfo(otherPlayer,cardC)\n if otherPlayer != -1 && cardC != nil\n puts(\"Player #{otherPlayer} refuted your suggestion by showing you the #{cardC.value} card\")\n\n else\n puts(\"No one could refute your suggestion\")\n\n end\n end",
"def match(other)\n settings = get_match_settings\n return nil unless settings\n\n potential_prompt_match_attributes = {:offer => other, :request => self}\n full_request_tag_set = self.optional_tag_set ? self.tag_set + self.optional_tag_set : self.tag_set\n full_offer_tag_set = other.optional_tag_set ? (other.tag_set + other.optional_tag_set) : other.tag_set\n\n TagSet::TAG_TYPES.each do |type|\n if self.send(\"any_#{type}\") || other.send(\"any_#{type}\")\n match_count = ALL\n else\n required_count = settings.send(\"num_required_#{type.pluralize}\")\n if settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n else\n # we don't use optional tags to count towards required\n match_count = self.tag_set.match_rank(other.tag_set, type)\n end\n \n # if we have to match all and don't, not a match\n return nil if required_count == ALL && match_count != ALL\n\n # we are a match only if we either match all or at least as many as required\n return nil if match_count != ALL && match_count < required_count\n\n # now get the match rank including optional tags if we didn't before\n if !settings.send(\"include_optional_#{type.pluralize}\")\n match_count = full_request_tag_set.match_rank(full_offer_tag_set, type)\n end\n end\n\n potential_prompt_match_attributes[\"num_#{type.pluralize}_matched\"] = match_count\n end\n return PotentialPromptMatch.new(potential_prompt_match_attributes)\n end",
"def collision(other)\n\t\tif other.is_a?(Torpedo)\n\t\t\tother.collision(self)\n\t\tend\n\tend",
"def on_other(data)\r\n \r\n end",
"def handle_winner(p1,p2)\n winner = winner?(p1,p2)\n if winner == p1\n give_cards_to_winner(p1, p2)\n p1.take_own_hand\n elsif winner == p2\n give_cards_to_winner(p2, p1)\n p2.take_own_hand\n end\n end",
"def candidate?\n !!candidate\n end",
"def propose_to( other )\n proposals << other\n other.respond_to_proposal_from self\n end",
"def other?\n self.name == 'Other'\n end",
"def verify_hand_off_to(other)\n raise ArgumentError, \"cannot hand off to node: #{other} because it is useful\" unless other.useless?\n raise ArgumentError, \"uncompatible handoff between #{self} and #{other}\" unless compatible_handoff?(other)\n end",
"def update_and_send_candidate\n @candidate = @candidates.first\n @models.each { |m| m.tell([:prime?,@candidate],self.getContext) }\n end",
"def connects?(other)\n other &&\n (self == other ||\n (suited? &&\n suit == other.suit &&\n (rank - other.rank).abs <= 2))\n end",
"def respond_to_partnership_request_from(matchable)\r\n if unmatched?\r\n Marry::Me.logger.debug \"#{self} accepts partnership with #{matchable}\"\r\n match_with(matchable)\r\n elsif better_partner? matchable\r\n Marry::Me.logger.debug \"#{self} has left #{@partner} for #{matchable}\"\r\n @partner.free\r\n match_with matchable\r\n else\r\n Marry::Me.logger.debug \"#{self} rejects partnership with #{matchable}\"\r\n end\r\n end",
"def match!( other )\n return false unless prefers?( other ) && !matched?( other )\n matches << other\n other.matches << self\n end",
"def run_candidate\n candidate.call\n end",
"def choose_winner; end",
"def case?(other)\n other === self\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /tcm_patient_infos GET /tcm_patient_infos.json
|
def index
@tcm_patient_infos = TcmPatientInfo.all
end
|
[
"def get_patient_list\n getProfile\n @patientlist = TherapistPatient.get_my_patients @therapist.user_id\n respond_to do |format|\n format.html { render :template => 'therapist/get_patient_list' }\n format.json { render :status => 200, :json => { action: :get_patient_list,\n patient_list: @patientlist}}\n end\n end",
"def show\n @patient = Patient.find(params[:id])\n\n render json: @patient\n end",
"def show\n @patient = Patient.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @patient }\n end\n end",
"def detail\n @patient = Patient.find(params[:patient_id])\n end",
"def show\n @owner_patient = OwnerPatient.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @owner_patient }\n end\n end",
"def show\n @patient_task = PatientTask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @patient_task }\n end\n end",
"def patient\n getProfile\n @patient = Patient.find(params[:patient_id])\n @patient_note = Note.patient_note_for_type(@therapist.therapist_id, @patient.patient_id, 'patient').first\n @patient_note = Note.new if @patient_note.blank?\n ## push @patient, @user to gon for use in javascript\n gon.push({:user => @user, :therapist => @therapist, :patient => @patient, :patient_note => @patient_note })\n respond_to do |format|\n format.html { render :template => 'therapist/patient_profile', :layout => 'main' }\n format.json { render :status => 200, :json => { action: :patient,\n user: @user, therapist: @therapist, patient: @patient, patient_notes: @patient_note}}\n end\n end",
"def show\n @patient_history = PatientHistory.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @patient_history }\n end\n end",
"def show\n @pregnancy_trimester_i_examination = PregnancyTrimesterIExamination.find(params[:id])\n @patient = @pregnancy_trimester_i_examination.patients.first\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pregnancy_trimester_i_examination }\n end\n end",
"def create\n @tcm_patient_info = TcmPatientInfo.new(tcm_patient_info_params)\n\n respond_to do |format|\n if @tcm_patient_info.save\n format.html { redirect_to @tcm_patient_info, notice: 'Tcm patient info was successfully created.' }\n format.json { render :show, status: :created, location: @tcm_patient_info }\n else\n format.html { render :new }\n format.json { render json: @tcm_patient_info.errors, status: :unprocessable_entity }\n end\n end\n end",
"def get_patient_notes\n getProfile\n notes = Note.patient_notes(@therapist.therapist_id, params[:patient_id])\n process_notes(notes, :get_patient_notes, \"Notes not found with the passed patient_id.\")\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patient }\n end\n end",
"def new\n @patient = Patient.new\n\n render json: @patient\n end",
"def index\n @patients = Patient.all\n\n render json: @patients\n end",
"def get_patient\n map_query.get(user.icn)\n end",
"def get_patient\n @get_patient ||= patient_service.get(user.icn)\n end",
"def new\n @owner_patient = OwnerPatient.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @owner_patient }\n end\n end",
"def new\n @pageType = \"new\"\n @patient = Patient.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patient }\n end\n end",
"def index\n @patients = Patient.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @patients }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /tcm_patient_infos POST /tcm_patient_infos.json
|
def create
@tcm_patient_info = TcmPatientInfo.new(tcm_patient_info_params)
respond_to do |format|
if @tcm_patient_info.save
format.html { redirect_to @tcm_patient_info, notice: 'Tcm patient info was successfully created.' }
format.json { render :show, status: :created, location: @tcm_patient_info }
else
format.html { render :new }
format.json { render json: @tcm_patient_info.errors, status: :unprocessable_entity }
end
end
end
|
[
"def create\n @patient_info = PatientInfo.new(patient_info_params)\n\n respond_to do |format|\n if @patient_info.save\n format.html { redirect_to @patient_info, notice: 'Patient info was successfully created.' }\n format.json { render :show, status: :created, location: @patient_info }\n else\n format.html { render :new }\n format.json { render json: @patient_info.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @patient = Patient.new(params[:patient])\n\n if @patient.save\n render json: @patient, status: :created, location: @patient\n else\n render json: @patient.errors, status: :unprocessable_entity\n end\n end",
"def create\n @patientregist = current_dpatient.patientregists.new(patientregist_params)\n\n respond_to do |format|\n if @patientregist.save\n format.html { redirect_to patientregists_path, notice: 'Patientregist was successfully created.' }\n format.json { render :show, status: :created, location: @patientregist }\n else\n format.html { render :new }\n format.json { render json: @patientregist.errors, status: :unprocessable_entity }\n end\n end\n\n end",
"def create\n @diagnosed_patient = DiagnosedPatient.new(diagnosed_patient_params)\n\n respond_to do |format|\n if @diagnosed_patient.save\n format.html { redirect_to @diagnosed_patient, notice: 'Diagnosed patient was successfully created.' }\n format.json { render :show, status: :created, location: @diagnosed_patient }\n else\n format.html { render :new }\n format.json { render json: @diagnosed_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @patient = @client.patients.build(params[:patient])\n \n respond_to do |format|\n if @patient.save\n format.html { redirect_to @patient, notice: 'Patient was successfully created.' }\n format.json { render json: @patient, status: :created, location: @patient }\n else\n format.html { render action: \"new\" }\n format.json { render json: @patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_patient(**params)\n endpoint = \"patients\"\n response = @connection.POST(endpoint, params, common_headers)\n raise \"HTTP error for endpoint #{endpoint} code encountered: #{response.code}\" unless response.code.to_i == 200\n val = JSON.parse(response.body)\n raise \"unexpected patient list len: #{val.length}\" unless val.length == 1\n return val[0][:patientid.to_s].to_i\n end",
"def create\n @medic_patient = MedicPatient.new(medic_patient_params)\n\n respond_to do |format|\n if @medic_patient.save\n format.html { redirect_to @medic_patient, notice: 'Medic patient was successfully created.' }\n format.json { render :show, status: :created, location: @medic_patient }\n else\n format.html { render :new }\n format.json { render json: @medic_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @owner_patient = OwnerPatient.new(params[:owner_patient])\n\n respond_to do |format|\n if @owner_patient.save\n format.html { redirect_to @owner_patient, notice: 'Owner patient was successfully created.' }\n format.json { render json: @owner_patient, status: :created, location: @owner_patient }\n else\n format.html { render action: \"new\" }\n format.json { render json: @owner_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @in_patient = InPatient.new(in_patient_params)\n\n respond_to do |format|\n if @in_patient.save\n format.html { redirect_to @in_patient, notice: 'In patient was successfully created.' }\n format.json { render :show, status: :created, location: @in_patient }\n else\n format.html { render :new }\n format.json { render json: @in_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @patient_infos = PatientInfo.new\n end",
"def create\n @pediatric_patient = PediatricPatient.new(pediatric_patient_params)\n\n respond_to do |format|\n if @pediatric_patient.save\n format.html { redirect_to @pediatric_patient, notice: 'Paciente creado con exito' }\n format.json { render :show, status: :created, location: @pediatric_patient }\n else\n format.html { render :new }\n format.json { render json: @pediatric_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @outpatient = Outpatient.new(outpatient_params)\n\n respond_to do |format|\n if @outpatient.save\n format.html { redirect_to @outpatient, notice: 'Outpatient was successfully created.' }\n format.json { render :show, status: :created, location: @outpatient }\n else\n format.html { render :new }\n format.json { render json: @outpatient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @patient_task = PatientTask.new(params[:patient_task])\n\n respond_to do |format|\n if @patient_task.save\n format.html { redirect_to @patient_task, notice: 'Patient task was successfully created.' }\n format.json { render json: @patient_task, status: :created, location: @patient_task }\n else\n format.html { render action: \"new\" }\n format.json { render json: @patient_task.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @patient = Patient.new\n\n render json: @patient\n end",
"def create\n @inpatient = Inpatient.new(inpatient_params)\n\n respond_to do |format|\n if @inpatient.save\n format.html { redirect_to @inpatient, notice: 'Inpatient was successfully created.' }\n format.json { render :show, status: :created, location: @inpatient }\n else\n format.html { render :new }\n format.json { render json: @inpatient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patient }\n end\n end",
"def patient\n getProfile\n @patient = Patient.find(params[:patient_id])\n @patient_note = Note.patient_note_for_type(@therapist.therapist_id, @patient.patient_id, 'patient').first\n @patient_note = Note.new if @patient_note.blank?\n ## push @patient, @user to gon for use in javascript\n gon.push({:user => @user, :therapist => @therapist, :patient => @patient, :patient_note => @patient_note })\n respond_to do |format|\n format.html { render :template => 'therapist/patient_profile', :layout => 'main' }\n format.json { render :status => 200, :json => { action: :patient,\n user: @user, therapist: @therapist, patient: @patient, patient_notes: @patient_note}}\n end\n end",
"def create\n @provider_patient = ProviderPatient.new(provider_patient_params)\n\n respond_to do |format|\n if @provider_patient.save\n format.html { redirect_to @provider_patient, notice: 'Provider patient was successfully created.' }\n format.json { render :show, status: :created, location: @provider_patient }\n else\n format.html { render :new }\n format.json { render json: @provider_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @doctor_patient = DoctorPatient.new(doctor_patient_params)\n\n respond_to do |format|\n if @doctor_patient.save\n format.html { redirect_to @doctor_patient, notice: 'Doctor patient was successfully created.' }\n format.json { render :show, status: :created, location: @doctor_patient }\n else\n format.html { render :new }\n format.json { render json: @doctor_patient.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PATCH/PUT /tcm_patient_infos/1 PATCH/PUT /tcm_patient_infos/1.json
|
def update
respond_to do |format|
if @tcm_patient_info.update(tcm_patient_info_params)
format.html { redirect_to @tcm_patient_info, notice: 'Tcm patient info was successfully updated.' }
format.json { render :show, status: :ok, location: @tcm_patient_info }
else
format.html { render :edit }
format.json { render json: @tcm_patient_info.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n @patient = @client.patients.find(params[:id])\n\n respond_to do |format|\n if @patient.update_attributes(params[:patient])\n format.html { redirect_to @patient, notice: 'Patient was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @patient_info.update(patient_info_params)\n format.html { redirect_to @patient_info, notice: 'Patient info was successfully updated.' }\n format.json { render :show, status: :ok, location: @patient_info }\n else\n format.html { render :edit }\n format.json { render json: @patient_info.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @patient.update(patient_params)\n head :no_content\n else\n render json: @patient.errors, status: :unprocessable_entity\n end\n end",
"def update\n @patient = Patient.find(params[:id])\n\n if @patient.update(params[:patient])\n head :no_content\n else\n render json: @patient.errors, status: :unprocessable_entity\n end\n end",
"def update\n @patient_task = PatientTask.find(params[:id])\n\n respond_to do |format|\n if @patient_task.update_attributes(params[:patient_task])\n format.html { redirect_to @patient_task, notice: 'Patient task was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @patient_task.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @microrna_patient.update(microrna_patient_params)\n format.html { redirect_to @microrna_patient, notice: 'Patient was successfully updated.' }\n format.json { render :show, status: :ok, location: @microrna_patient }\n else\n format.html { render :edit }\n format.json { render json: @microrna_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @owner_patient = OwnerPatient.find(params[:id])\n\n respond_to do |format|\n if @owner_patient.update_attributes(params[:owner_patient])\n format.html { redirect_to @owner_patient, notice: 'Owner patient was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @owner_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @clinic_patient.update(clinic_patient_params)\n format.html { redirect_to @clinic_patient, notice: 'Patient was successfully updated.' }\n format.json { render action: 'show', status: :ok, location: @clinic_patient }\n else\n format.html { render action: 'edit' }\n format.json { render json: @clinic_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @appointment_patient.update(appointment_patient_params)\n format.html { redirect_to @appointment_patient, notice: 'Appointment patient was successfully updated.' }\n format.json { render :show, status: :ok, location: @appointment_patient }\n else\n format.html { render :edit }\n format.json { render json: @appointment_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @diagnosed_patient.update(diagnosed_patient_params)\n format.html { redirect_to @diagnosed_patient, notice: 'Diagnosed patient was successfully updated.' }\n format.json { render :show, status: :ok, location: @diagnosed_patient }\n else\n format.html { render :edit }\n format.json { render json: @diagnosed_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @patient = Patient.find(params[:id])\n\n respond_to do |format|\n if @patient.update_attributes(params[:patient])\n format.html { redirect_to(@patient, :notice => 'Patient was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @patient.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @patienttest.update(patienttest_params)\n format.html { redirect_to @patienttest, notice: 'Patienttest was successfully updated.' }\n format.json { render :show, status: :ok, location: @patienttest }\n else\n format.html { render :edit }\n format.json { render json: @patienttest.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @in_patient.update(in_patient_params)\n format.html { redirect_to @in_patient, notice: 'In patient was successfully updated.' }\n format.json { render :show, status: :ok, location: @in_patient }\n else\n format.html { render :edit }\n format.json { render json: @in_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @inpatient.update(inpatient_params)\n format.html { redirect_to @inpatient, notice: 'Inpatient was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @inpatient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @admin_patient = Admin::Patient.find(params[:id])\n\n respond_to do |format|\n if @admin_patient.update_attributes(params[:admin_patient])\n format.html { redirect_to(@admin_patient, :notice => 'Patient was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @admin_patient.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_patient\n data = get_data\n data.each do |record|\n patient = Patient.find_by_patient_id(record[\"patient_id\"])\n patient.present? ? patient.update(record) : Patient.create(record)\n end\n end",
"def update\n respond_to do |format|\n if @medic_patient.update(medic_patient_params)\n format.html { redirect_to @medic_patient, notice: 'Medic patient was successfully updated.' }\n format.json { render :show, status: :ok, location: @medic_patient }\n else\n format.html { render :edit }\n format.json { render json: @medic_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @provider_patient.update(provider_patient_params)\n format.html { redirect_to @provider_patient, notice: 'Provider patient was successfully updated.' }\n format.json { render :show, status: :ok, location: @provider_patient }\n else\n format.html { render :edit }\n format.json { render json: @provider_patient.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @patient_identifier.update(patient_identifier_params)\n format.html { redirect_to @patient_identifier, notice: 'Patient identifier was successfully updated.' }\n format.json { render :show, status: :ok, location: @patient_identifier }\n else\n format.html { render :edit }\n format.json { render json: @patient_identifier.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /tcm_patient_infos/1 DELETE /tcm_patient_infos/1.json
|
def destroy
@tcm_patient_info.destroy
respond_to do |format|
format.html { redirect_to tcm_patient_infos_url, notice: 'Tcm patient info was successfully destroyed.' }
format.json { head :no_content }
end
end
|
[
"def destroy\n @patient.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @patient_info.destroy\n respond_to do |format|\n format.html { redirect_to patient_infos_url, notice: 'Patient info was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @patient = Patient.find(params[:id])\n @patient.destroy\n\n respond_to do |format|\n format.html { redirect_to patients_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @microrna_patient.destroy\n respond_to do |format|\n format.html { redirect_to microrna_patients_url, notice: 'Patient was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @diagnosed_patient.destroy\n respond_to do |format|\n format.html { redirect_to diagnosed_patients_url, notice: 'Diagnosed patient was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @clinic_patient.destroy\n respond_to do |format|\n format.html { redirect_to clinic_patients_url }\n format.json { head :no_content }\n end\n end",
"def delete\n @patient = Patient.find(params[:id])\n end",
"def destroy\n @patient_task = PatientTask.find(params[:id])\n @patient_task.destroy\n\n respond_to do |format|\n format.html { redirect_to patient_tasks_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @patientregist.destroy\n respond_to do |format|\n format.html { redirect_to patientregists_url, notice: 'Patientregist was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @admin_patient = Admin::Patient.find(params[:id])\n @admin_patient.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_patients_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @owner_patient = OwnerPatient.find(params[:id])\n @owner_patient.destroy\n\n respond_to do |format|\n format.html { redirect_to owner_patients_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @patienttest.destroy\n respond_to do |format|\n format.html { redirect_to patienttests_url, notice: 'Patienttest was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_patient_by_id(patient_id)\n patient = Patient.find(patient_id)\n patient.destroy\nend",
"def delete_patient_by_id(patient_id)\n \nend",
"def destroy\n @patient = Patient.find(params['patient_id'])\n @patient_record.destroy\n respond_to do |format|\n format.html { redirect_to @patient, notice: 'Patient record was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @inpatient.destroy\n respond_to do |format|\n format.html { redirect_to inpatients_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @medic_patient.destroy\n respond_to do |format|\n format.html { redirect_to medic_patients_url, notice: 'Medic patient was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @patient_log.destroy\n respond_to do |format|\n format.html { redirect_to patient_logs_url, notice: 'Patient log was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @visit = Visit.find(params[:id])\n @visit.destroy\n\n respond_to do |format|\n format.html { redirect_to patient_path (params[:patient_id]) }\n format.json { head :no_content }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Gets three tweets from the passed in user. GET /api/getThreeTweets
|
def getThreeTweets
render json: TwitterAPI.get_top_3_tweets(params[:twitter_id])
end
|
[
"def recent_tweets(user, options = {})\n if @skip_until\n return [] if @skip_until > Time.now\n @skip_until = nil\n end\n\n cache = Ramaze::Cache.plugin\n options = {:count => 5}.merge(options)\n count = options[:count].to_i\n\n count += 10 unless Config.twitter['include_replies']\n count = 200 if count > 200\n\n url = \"http://twitter.com/statuses/user_timeline/#{user}.json?count=\" <<\n count.to_s\n\n if value = cache[url]\n return value\n end\n\n tweets = []\n\n Timeout.timeout(Config.twitter['request_timeout'], StandardError) do\n tweets = JSON.parse(open(url).read)\n end\n\n # Weed out replies if necessary.\n unless Config.twitter['include_replies']\n tweets.delete_if do |tweet|\n !tweet['in_reply_to_status_id'].nil? ||\n !tweet['in_reply_to_user_id'].nil?\n end\n\n tweets = tweets.slice(0, options[:count].to_i)\n end\n\n # Parse the tweets into an easier-to-use format.\n tweets.map! do |tweet|\n {\n :created_at => Time.parse(tweet['created_at']),\n :html => parse_tweet(tweet['text']),\n :id => tweet['id'],\n :source => tweet['source'],\n :text => tweet['text'],\n :truncated => tweet['truncated'],\n :url => \"http://twitter.com/#{user}/statuses/#{tweet['id']}\"\n }\n end\n\n @failures = 0\n\n return cache.store(url, tweets, :ttl => Config.twitter['cache_ttl'])\n\n rescue => e\n Ramaze::Log.error \"Thoth::Plugin::Twitter: #{e.message}\"\n\n @failures ||= 0\n @failures += 1\n\n if @failures >= Config.twitter['failure_threshold']\n @skip_until = Time.now + Config.twitter['failure_timeout']\n Ramaze::Log.error \"Thoth::Plugin::Twitter: Twitter failed to respond #{@failures} times. Will retry after #{@skip_until}.\"\n end\n\n return []\n end",
"def get_all_tweets(user)\n collect_with_max_id do |max_id|\n options = {:count => 200, :include_rts => true}\n options[:max_id] = max_id unless max_id.nil?\n client.user_timeline(user, options)\n end\n end",
"def index\n\t\tuser = User.find_by(id: params[:user_id])\n\t\tif user.present?\n\t\t\tfollower_ids = user.followers.pluck(:id)\n\t\t\ttweets = Tweet.where(\"user_id IN (?)\", follower_ids).order(\"updated_at DESC\")\n\t\t\trender json: {:status=>\"success\", :code=>200, :message=>\"List of tweets from the users you follow.\", data: tweets}\n\t\telse\n\t\t\trender json: {:status=>\"failure\", :message=>\"User is not present.\", data: tweets}\n\t\tend\n\tend",
"def get_user_favorite_words(user, *args)\n http_method = :get\n path = '/user/{user}/favorites/words'\n path.sub!('{user}', user.to_s)\n\n # Ruby turns all key-value arguments at the end into a single hash\n # e.g. Wordnik.word.get_examples('dingo', :limit => 10, :part_of_speech => 'verb')\n # becomes {:limit => 10, :part_of_speech => 'verb'}\n last_arg = args.pop if args.last.is_a?(Hash)\n last_arg = args.pop if args.last.is_a?(Array)\n last_arg ||= {}\n\n # Look for a kwarg called :request_only, whose presence indicates\n # that we want the request itself back, not the response body\n if last_arg.is_a?(Hash) && last_arg[:request_only].present?\n request_only = true\n last_arg.delete(:request_only)\n end\n\n params = last_arg\n body ||= {}\n request = Wordnik::Request.new(http_method, path, :params => params, :body => body)\n request_only ? request : request.response.body\n end",
"def total_tweets(user)\n total_tweets = TwitterAccount.find_by(user_id: user.id).total_num_tweets\n total_tweets\n end",
"def find_tweets\n @topics = Topic.all.limit(5).pluck(:name).join(\" OR \")\n @quantity = Favorite.first.quantity\n @client = create_client\n response = @client.search(@topics, result_type: \"recent\").to_a\n @quantity.times{create_favorite_tweet response[Random.rand(response.length)] }\n check_new_followers\n end",
"def user_tweets(user_id)\n twitter.user_timeline(user_id)\n end",
"def fetch_tweets opts = {}\n opts = {\n trim_user: true,\n tweet_mode: \"extended\",\n count: 200\n }.merge!(opts)\n\n log \"Fetching tweets #{opts.inspect}\"\n\n @twitter.user_timeline @config[:username], opts\n end",
"def favorite_tweets\n logger.debug { \"#{__method__} is called twitter_user_id=#{id}\" }\n tweets = []\n tweets = InMemory::FavoriteTweet.find_by(uid) if InMemory.enabled? && InMemory.cache_alive?(created_at)\n tweets = Efs::FavoriteTweet.where(uid: uid) if tweets.blank? && Efs::Tweet.cache_alive?(created_at)\n tweets = ::S3::FavoriteTweet.where(uid: uid) if tweets.blank?\n tweets.map { |tweet| ::TwitterDB::Favorite.new(uid: uid, screen_name: screen_name, raw_attrs_text: tweet.raw_attrs_text) }\n end",
"def get_sample_user_tweets\r\n [\r\n \"don't ever change\",\r\n \"A long-term goal of mine is to create a water-based horror game. I've done some work on building this in Unity already.\",\r\n \"Many amazing looking animals can be kept in reasonably simple environments, but some require elaborate setups .\",\r\n \"I enjoy creating terrariums but it's a lot of work to keep everything balanced so that all the critters survive .\",\r\n \"Although I haven't had a cat myself, I have had aquariums, terrariums, and rodents at different points .\",\r\n \"i have personally never owned a pet cat, and I'm a bit allergic, but I still enjoy their company .\",\r\n \"carnivorous by nature, cats hunt many other wild animals such as gophers and mice. As a result, some people would prefer less outdoor cats .\",\r\n \"you have now unsubscribed to cat facts. respond with UNSUBSCRIBE to unsubscribe .\",\r\n \"egyption hairless cats are less allergenic than most other cats. they don't have hair and are probably less oily .\",\r\n \"the cat in the hat ate and sat. it got fat and couldn't catch a rat .\"\r\n ]\r\n end",
"def all_user_tweets\n user = self\n user_twitter_id = user.uid\n collect_with_max_id do |max_id|\n options = {count: 200, include_rts: true}\n options[:max_id] = max_id unless max_id.nil?\n user.twitter_api.user_timeline(user_twitter_id, options)\n end\n end",
"def tweets(num)\n begin\n return twitter.user_timeline.take(num)\n rescue\n return nil\n end\n end",
"def fetch_tweets!\n tweets_from_api = $client.user_timeline(username)\n tweets_from_api.each do |tweet|\n tweets.create(text: tweet.text,\n twitter_time: tweet.created_at)\n end\n end",
"def by_user\r\n tweets = Tweet.where(user_id: params[:user_id])\r\n render json: tweets\r\n end",
"def index\n @following_user_ids = @user.following.pluck(:id)\n\n @tweets = Tweet.where(user_id: @following_user_ids).order(created_at: :desc).includes(:user)\n json_response(@tweets)\n end",
"def latest_tweets(k=5)\n\n # Get the tweets\n response = make_response(\"statuses\",\"user_timeline\")\n timeline = JSON.parse(response.body)\n tweets = timeline[0..k-1]\n\nend",
"def get_user_favorite_word_lists(user, *args)\n http_method = :get\n path = '/user/{user}/favorites/wordLists'\n path.sub!('{user}', user.to_s)\n\n # Ruby turns all key-value arguments at the end into a single hash\n # e.g. Wordnik.word.get_examples('dingo', :limit => 10, :part_of_speech => 'verb')\n # becomes {:limit => 10, :part_of_speech => 'verb'}\n last_arg = args.pop if args.last.is_a?(Hash)\n last_arg = args.pop if args.last.is_a?(Array)\n last_arg ||= {}\n\n # Look for a kwarg called :request_only, whose presence indicates\n # that we want the request itself back, not the response body\n if last_arg.is_a?(Hash) && last_arg[:request_only].present?\n request_only = true\n last_arg.delete(:request_only)\n end\n\n params = last_arg\n body ||= {}\n request = Wordnik::Request.new(http_method, path, :params => params, :body => body)\n request_only ? request : request.response.body\n end",
"def fetch_tweets(criteria)\n @client.filter(track: criteria.theme) do |object|\n puts object.text if object.is_a?(Twitter::Tweet)\n end\n end",
"def grab_tweets\n client = twitter_client(self.access_token, self.access_token_secret)\n # Something here is making this array bad to work with.\n # Stores Twitter gem objects before stringification into db table\n tweets_arr = []\n tweets = client.user_timeline(self.uid.to_i, options = {count: 200})\n tweets_arr.push tweets\n # Twitter Ruby API restricts calls to 200 tweets/per request\n # Tweet IDs are (roughly) chronologically sequential, so...\n # ...grab `id` of last tweet, and, next time, grab tweets older than that\n 3.times do\n last_max_id = tweets_arr[0][-1].id\n tweets = client.user_timeline(self.uid.to_i, options = {count: 200, max_id: last_max_id})\n tweets_arr.push tweets\n end\n tweets_string = ''\n tweets_arr[0].each do |tweet|\n tweets_string += tweet.text\n end\n u = self\n u.timeline = tweets_string\n u.save\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /api/getMatchCount Gets the number of matches
|
def getMatchCount
render json: Match.count(:user1 => params[:twitter_id])
end
|
[
"def matched_count\n @results[MATCHED_COUNT]\n end",
"def matched_count\n results.map(&:matched_count).reduce(&:+)\n end",
"def number_match_count\n\t\t\ttotal_match_count - exact_match_count\n\t\tend",
"def count\n hits.count\n end",
"def count_results\n # TODO respond with xml, only if valid session, otherwise return nil\n team = Team.find_by_id( params[:id] )\n if team\n render json: ( team.meeting_individual_results.count + team.meeting_relay_results.count )\n else\n render json: 0\n end\n end",
"def count_results\n team = Team.find_by_id( params[:id] )\n if team\n render( json: ( team.meeting_individual_results.count + team.meeting_relay_results.count ) )\n else\n render( json: 0 )\n end\n end",
"def count( query )\n data = index_request({ \"q\" => query })\n return data[\"response\"][\"numFound\"]\n end",
"def total\n response[:numFound].to_s.to_i\n end",
"def matching_property_count\n inst = self\n inst.adjust_size\n inst.modify_filtered_params\n inst.apply_filters\n inst.modify_query\n count, status = fetch_udprns(true)\n return count, status\n end",
"def name_count\n\t\t@osmatches.size\n\tend",
"def num_hits; @hits.size; end",
"def response_count\n sum = 0\n responses.each do |r|\n sum += 1\n sum += r.response_count\n end\n return sum\n end",
"def count\n search_results.values.collect(&:size).sum\n end",
"def matched_size\n m = @match\n m.to_s.size if (not m.equal?(nil))\n end",
"def count\n url_chunk = \"#{entity_set.name}/$count?#{assemble_criteria}\" # TODO: escape GET params\n entity_set.service.execute(url_chunk).body.to_i\n end",
"def count\n self.at('/RETS/COUNT')['Records'].to_i\n end",
"def total_count #:nodoc:\n total == 1 && !@group.nil? && @group['matches'] > 1 ? @group['matches'] : total\n end",
"def count\n response = call_api method: :get\n json = JSON.parse(response.body)\n if response.code.to_i==200\n ap(\"Found #{json['live_streams'].size} Live Streams total.\", color: {string: :green})\n else\n ap(JSON.parse(response.body))\n end\n return response\n end",
"def counts\n results[\"counts\"]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
The list of rsync server resources in the resource collection
|
def rsync_resources
::ObjectSpace.each_object(::Chef::Resource).select do |resource|
resource.resource_name == :rsync_serve
end
end
|
[
"def rsync_resources\n run_context.resource_collection.select do |resource|\n resource.is_a?(Chef::Resource::RsyncServe)\n end\n end",
"def resources_list(session, is_sync)\n # Get resource type to list\n resource_type = session.gets.chomp.to_sym\n\n # Cache dir name to avoid repeated calls\n dir = Cfg.dir(resource_type)\n\n # Resource dir is scanned and resource directory removed from file name using sub\n # cause we want to keep resources sub directories if any\n result = []\n Find.find(dir).map do |file|\n result << [file.sub(dir, ''), File.mtime(file).to_i] unless File.directory?(file)\n end\n session.puts(result.to_json)\n session.puts(Cfg::MSG_DONE) if is_sync\n end",
"def servers\n @servers\n end",
"def all_servers\n Infrataster::Server.defined_servers.map { |i| server(i.name) }\nend",
"def resources\n @resources ||= []\n end",
"def resource_list\n self.resources\n end",
"def servers\n servers_for\n end",
"def resource_objects\n @body['provision']['resource']\n end",
"def servers\n collect\n end",
"def resources\n return @resources\n end",
"def get_servers\n\t\t\tbegin\n\t\t\t\tresp = @rs_conn.get('/servers')\n\n\t\t\t\t# 200 Success :: anything else is failure\n\t\t\t\tunless resp.code == \"200\"\n\t\t\t\t\traise \"Error requesting server list. Error code #{resp.code}\"\n\t\t\t\tend\n\t\t\t\t# Convert the output to json\n\t\t\t\tserver_list = JSON.parse(resp.body)\n\t\t\t\treturn server_list\n\t\t\trescue Exception => e\n\t\t\t\traise e\n\t\t\tend\n\t\tend",
"def servers\r\n @servers.values\r\n end",
"def servers\n @_servers ||= []\n end",
"def servers\n return @servers.values\n end",
"def servers()\n servers = []\n servers.concat(@servers)\n\n @groups.each do |g|\n servers.concat(g.servers)\n end\n\n return servers\n end",
"def resources\n nodeset = query_root_node(\"gdacs:resources/gdacs:resource\", @@NAMESPACES)\n @items = []\n if !nodeset.nil?\n nodeset.each do |item|\n item_obj = SemanticCrawler::Gdacs::Resource.new(item)\n @items << item_obj\n end\n end\n @items\n end",
"def list_files\n remote_files\n end",
"def servers\n list = []\n Penctl.execute(@pen, \"servers\", 5).each do |l| \n server = Penctl.parse_server_line(l)\n list[server[:slot]] = server\n end\n list.compact\n end",
"def list\n puts local_resources.map { |name, resource| name }.join(\" \")\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PATCH/PUT /http_requests/1 PATCH/PUT /http_requests/1.json
|
def update
respond_to do |format|
if @http_request.update(http_request_params)
format.html { redirect_to @http_request, notice: 'Http request was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @http_request.errors, status: :unprocessable_entity }
end
end
end
|
[
"def patch *args\n make_request :patch, *args\n end",
"def patch(path, params: {}, headers: {})\n request_json :patch, path, params, headers\n end",
"def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end",
"def parallel_patch(requests, options = {})\n base_parallel_call(:patch, requests, options)\n end",
"def update\n @req = Req.find(params[:id])\n\n respond_to do |format|\n if @req.update_attributes(params[:req])\n format.html { redirect_to @req, notice: 'Req was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @req.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, options = {}, &block)\n perform_request Net::HTTP::Patch, path, options, &block\n end",
"def update_other_request_params(request_id, updates = {})\n request_data_file_dir = File.dirname(@params[\"SS_output_dir\"])\n request_data_file_dir.gsub!(\"/#{@params[\"SS_request_number\"]}\",\"/#{request_id}\")\n request_data_file = \"#{request_data_file_dir}/request_data.json\"\n request_params = JSON.parse(File.open(request_data_file).read)\n updates.each do |k,v|\n request_params[k] = v\n end\n fil = File.open(request_data_file,\"w+\")\n fil.write request_params.to_json\n fil.close\n end",
"def patch?; request_method == \"PATCH\" 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_feature_request(folder_id, feature_content, file_name)\n url = URI(\"#{$base_url}/api/projects/#{$project_id}/folders/#{folder_id}/update_from_feature\")\n\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n request = Net::HTTP::Patch.new(url)\n request[\"accept\"] = 'application/vnd.api+json; version=1'\n request[\"access-token\"] = $access_token\n request[\"uid\"] = $uid\n request[\"client\"] = $client\n request[\"Content-Type\"] = 'application/json'\n\n data = {\n data: {\n attributes: {\n \"feature\": feature_content\n }\n }\n }\n\n request.body = JSON.generate(data)\n response = http.request(request)\n\n if response.code == 200.to_s\n update_response = JSON.parse(response.read_body)['data']\n puts \"Feature '#{update_response['attributes']['name']}' with '#{update_response['attributes']['scenarios-count']} scenario(s)' updated.\"\n $success_uploaded_count = $success_uploaded_count + 1\n $uploaded_features_list.push(file_name)\n $updated_count = $updated_count + 1\n else\n $fail_uploaded_count = $fail_uploaded_count + 1\n $not_uploaded_features_list.push(file_name)\n end\n\n response.code\nend",
"def update_request?(http_method = nil)\n http_method = http_method.downcase.to_sym if http_method.is_a?(String)\n %i[put post patch].include?(http_method || @verb)\n end",
"def update_item token, item_id, name, description\n uri = URI.parse \"https://#{get_hostname(token)}/sf/v3/Items(#{item_id})\"\n puts uri\n \n http = Net::HTTP.new uri.host, uri.port\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n \n item = {\"Name\"=>name, \"Description\"=>description}\n \n request = Net::HTTP::Patch.new uri.request_uri \n request[\"Content-Type\"] = \"application/json\"\n request[\"Authorization\"] = get_authorization_header(token)\n request.body = item.to_json\n \n response = http.request request\n puts \"#{response.code} #{response.message}\"\n \n if response.kind_of? Net::HTTPSuccess\n updated_item = JSON.parse response.body\n puts \"Updated Item: #{updated_item['Id']}\"\n end \nend",
"def update\n request = Request.find_by_id(params[:id])\n if request\n request.status = 1\n if request.save\n render json: {\n status: 'success',\n message: 'Request marked as fulfilled',\n },\n status: :ok\n else\n render json: {\n status: 'error',\n message: 'Request failed',\n data: request.errors,\n },\n status: :unprocessable_entity\n end\n else\n render status: :unauthorized\n end\n end",
"def update\n begin\n @job_request = job_requests.find( params[ :id ] )\n rescue ActiveRecord::RecordNotFound\n @job_request = nil\n end\n\n respond_to do |format|\n if @job_request && @job_request.update_attributes( params[ :job_request ] )\n format.html { redirect_to root_path, notice: \"Job Requests Updated Successfully\"}\n format.json { head :no_content }\n else\n format.html { redirect_to root_path, notice: \"Update Failed\" }\n format.json { render json: @job_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @requests_complaints_request = RequestsComplaints::Request.find(params[:id])\n\n respond_to do |format|\n if @requests_complaints_request.update_attributes(params[:requests_complaints_request])\n format.html { redirect_to(@requests_complaints_request, :notice => 'Request was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @requests_complaints_request.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @pending_request = PendingRequest.find(params[:id])\n\n respond_to do |format|\n if @pending_request.update_attributes(params[:pending_request])\n format.html { redirect_to @pending_request, notice: 'Pending request was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @pending_request.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @requestinfo = Requestinfo.find(params[:id])\n\n if @requestinfo.update(requestinfo_params)\n head :no_content\n else\n render json: @requestinfo.errors, status: :unprocessable_entity\n end\n end",
"def put?; request_method == \"PUT\" end",
"def put\n request_method('PUT')\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /http_requests/1 DELETE /http_requests/1.json
|
def destroy
@http_request.destroy
respond_to do |format|
format.html { redirect_to http_requests_url }
format.json { head :no_content }
end
end
|
[
"def delete\n RestClient.delete \"#{@uri}/api/requests/request/#{@data['requestId']||@data['id']}\"\n puts ' Deleted request: '.red + \"#{@data['requestId']||@data['id']}\".light_blue\n end",
"def delete_request\n client.create_request('DELETE', url_path)\n end",
"def destroy\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @request = Request.find(params[:id])\n @request.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :ok }\n end\n end",
"def delete(path, params={}); make_request(:delete, host, port, path, params); end",
"def destroy\n @req = Req.find(params[:id])\n @req.destroy\n\n respond_to do |format|\n format.html { redirect_to reqs_url }\n format.json { head :no_content }\n end\n end",
"def deleteExecution(execution_id)\n uri = URI(RUNDECKSERVER + ':' + RUNDECKPORT + '/api/12/execution/' + execution_id)\n http = Net::HTTP.new(uri.host, uri.port)\n headers = {'Content-Type'=> 'application/jsonr','X-RunDeck-Auth-Token'=> API_KEY }\n r = http.delete(uri.path, headers) \n return r\nend",
"def delete endpoint\n do_request :delete, endpoint\n end",
"def delete_request(item, request)\n option_hash = {accept: :json, cookies: @maint_cookie}\n begin\n res = @api[\"items/#{item[\"id\"]}/requests/#{request[\"id\"]}\"].delete option_hash\n rescue => e\n @logger&.error \"delete_request => exception #{e.class.name} : #{e.message}\"\n if (ej = JSON.parse(e.response)) && (eje = ej[\"errors\"])\n eje.each do |k, v|\n @logger&.error \"#{k}: #{v.first}\"\n end\n end\n return nil\n end\n res\n end",
"def delete_requests\n self.requests.each {|request| request.destroy}\n end",
"def destroy\n @recuest = Recuest.find(params[:id])\n @recuest.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end",
"def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end",
"def http_delete(path, data = nil, content_type = 'application/json')\n http_methods(path, :delete, data, content_type)\n end",
"def delete(url)\n authsub_http_request(Net::HTTP::Delete,url)\n end",
"def destroy\n #@service_request = ServiceRequest.find(params[:id])\n @service_request.destroy\n\n respond_to do |format|\n format.html { redirect_to service_requests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @request.destroy\n respond_to do |format|\n format.html { redirect_to admin_requests_url }\n format.json { head :no_content }\n end\n end",
"def delete(request_opts = {})\n store_result(http(request_opts).delete(resolved_path))\n end",
"def destroy\n @gig_request = GigRequest.find(params[:id])\n @gig_request.destroy\n\n respond_to do |format|\n format.html { redirect_to gig_requests_url }\n format.json { head :no_content }\n end\n end",
"def http_delete(opts={})\n ret=http_delete_low(opts)\n if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then\n\tauthdefault\n\tret=http_delete_low(opts)\n\treturn ret\n else\n\treturn ret\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Obtain a latex representation of the matrix
|
def latex_matrix
if @type == "controlled"
@matrix.map { |value, matrix| [value, latex_matrix_for(matrix)] }
else
latex_matrix_for @matrix
end
end
|
[
"def latex_matrix(matrix)\n output = \"\\\\begin{tabular}{|#{'r|' * matrix.first.length}}\\n\"\n output << \"\\\\hline\\n\"\n output << matrix.map { |line| line.join(' & ') }.join(\"\\\\\\\\\\n\\\\hline\\n\")\n output << \"\\\\\\\\\\n\"\n output << \"\\\\hline\\n\"\n output << \"\\\\end{tabular}\\n\"\n output\nend",
"def to_latex\n \"e^{#{@x.to_latex}}\"\n end",
"def to_s\n @matrix.map{|row| row.join}.join(\"\\n\")\n end",
"def matrixToString(matrix)\n end",
"def to_s\n @matrix.to_s\n end",
"def print_matrix\n width = @rows.flatten.max.to_s.size\n if width > 4 then\n width = width - 0.5\n end\n puts @rows.map { |a|\n \"|#{ a.map { |i|\n outp = \"\"\n num, den = i.to_fraction\n if den == 1 then\n outp += \"#{num}\"\n else\n outp += \"#{num}/#{den}\"\n end\n \"#{outp.rjust(width)} |\"\n }.join }\"\n }\n puts \"↓\"\n end",
"def latex!\n ToLatex::LatexString.new self\n end",
"def to_s \n\t\t\"#{@mat}\"\n\tend",
"def to_s\n matString = \"\"\n (@nFil).times do |i|\n (@mCol).times do |j|\n matString = matString + @matriz[i][j].to_s + \" \"\n end\n matString = matString + \"\\n\"\n end\n matString\n end",
"def to_texTable(cols,col_align=\"c\",math=false)\n hline = '\\\\hline'\n# tex << '$' + cols.each {|col| col.sub(/(.+)_(.+)/,\"\\\\1_\\{\\\\2\\}\")}.join(\"$&$\") + '$' + \"\\\\\\\\\\n\"\n tex = ''\n tab_align = ''\n cols.size.times { tab_align << '|' + col_align }\n tab_align << '|'\n tex << '\\begin{tabular}{' + tab_align + '}' + hline + \"\\n\"\n if math\n tex << '$' + cols.join(\"$&$\").gsub(/(\\w+)_(\\w+)/,\"\\\\1_\\{\\\\2\\}\") + '$' + '\\\\\\\\' + hline + \"\\n\"\n else \n tex << cols.join(\" & \") + '\\\\\\\\' + hline +\"\\n\"\n end\n datasets(cols).each {|dataset|\n tex << dataset.join(\" & \") + '\\\\\\\\' + hline + \"\\n\"\n }\n tex << '\\end{tabular}' + \"\\n\"\n tex\n end",
"def to_s\n \"#{@matriz}\"\n end",
"def latex md\n if md.is_a? String\n md = LatexConvertor.new(md).to_tex\n elsif md.is_a? Enumerable\n render_sublist md\n else\n raise \"Can't deal with a #{md.class}\"\n end\n end",
"def latex(s)\n convert(s, mime: 'text/latex')\n end",
"def latex_table(data, top_headings, left_headings)\n matrix = [[''] + top_headings] +\n left_headings.zip(data).map { |heading, line| [heading] + line }\n latex_matrix matrix\nend",
"def to_markdown\n raise \"expected 2D array\" unless self.first.is_a?(Array)\n\n # Find max widths of data/headers: eg => [10, 25, 18, 21, 6]\n widths = self.transpose.map{ |col| ([col.first.class.to_s.length] + col.map{ |i| i.to_s.length }).max }\n\n # Use the class of each cell in the first row for the table headers.\n out = self.first.map.with_index{|c,i| c.class.to_s.ljust(widths[i])}.join(\" | \") + \"\\n\"\n out << out.gsub(/[^|]/, \"-\") + \"\\n\"\n\n # Left justify each cell\n self.each do |row|\n out << row.map(&:to_s).map.with_index{|c,i| c.ljust(widths[i])}.join(\" | \") + \"\\n\"\n end\n out\n\n rescue => e\n warn \"Unable to generate table: #{e}\"\n nil\n end",
"def to_s\n to_m().to_s.sub(\"Matrix\", \"SparseMatrix\")\n end",
"def print_matrix\n @matrix.each do |m|\n print \"#{m}\\n\"\n end\n end",
"def pretty_print\n puts\n puts \"Matrix:\\n\"\n puts @matrix.to_a.map(&:inspect)\n puts\n end",
"def to_fmt\n m=Matrix.build(self.row_size, self.column_size){nil}\n self.each_with_index do |x, row, col|\n if x.nil? || x.value.nil?\n m[row, col] = nil\n else\n m[row, col] = x.to_fmt\n end\n end\n return m\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /invoice_taxes/new GET /invoice_taxes/new.json
|
def new
@invoice_tax = InvoiceTax.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @invoice_tax }
end
end
|
[
"def new\r\n @tax_invoice = TaxInvoice.new\r\n @products = Product.all\r\n @orders = Order.all\r\n @companies = Company.all\r\n\r\n\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @tax_invoice }\r\n end\r\n end",
"def new\n @breadcrumb = 'create'\n @tax_type = TaxType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tax_type }\n end\n end",
"def new\n @taxon = Taxon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @taxon }\n end\n end",
"def new\n @taxirequest = Taxirequest.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @taxirequest }\n end\n end",
"def new\n @tax_type = TaxType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tax_type }\n end\n end",
"def new\n @breadcrumb = 'create'\n @invoice_type = InvoiceType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invoice_type }\n end\n end",
"def new\n @taxon = @shop.taxonomies.find(params[:taxonomy_id]).taxons.build\n\n respond_to do |format|\n format.html \n format.json { render json: @taxon }\n end\n end",
"def new\n @invoice = Invoice.new\n @invoices = Invoice.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invoice }\n end\n end",
"def new\n @taxinomy = Taxinomy.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @taxinomy }\n end\n end",
"def new\n @invoice = Invoice.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invoice }\n end\n end",
"def new\n @tax_rate = TaxRate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tax_rate }\n end\n end",
"def new\n @taxcode = Taxcode.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @taxcode }\n end\n end",
"def new\n @taxinvoice = Taxinvoice.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @taxinvoice }\n end\n end",
"def new\n @taxdetail = Taxdetail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @taxdetail }\n end\n end",
"def new\n @tax = Tax.new\n end",
"def new\n @taxon_attribute = TaxonAttribute.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @taxon_attribute }\n end\n end",
"def new\n\n @breadcrumb = 'create'\n @invoice_operation = InvoiceOperation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invoice_operation }\n end\n end",
"def create\n @client_tax = ClientTax.new(client_tax_params)\n\n respond_to do |format|\n if @client_tax.save\n format.html { redirect_to @client_tax, notice: 'Client tax was successfully created.' }\n format.json { render :show, status: :created, location: @client_tax }\n else\n format.html { render :new }\n format.json { render json: @client_tax.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_taxes\n country.taxes.each do |tax|\n Tax.create!(tax)\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PUT /invoice_taxes/1 PUT /invoice_taxes/1.json
|
def update
@invoice_tax = InvoiceTax.find(params[:id])
respond_to do |format|
if @invoice_tax.update_attributes(params[:invoice_tax])
format.html { redirect_to @invoice_tax, notice: 'Invoice tax was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @invoice_tax.errors, status: :unprocessable_entity }
end
end
end
|
[
"def send_tax_invoice\n response = JSON.parse(@client.patch(\"items/#{send(:id)}/send_tax_invoice\").body)\n @attributes = response['items']\n true\n end",
"def request_tax_invoice\n response = JSON.parse(@client.patch(\"items/#{send(:id)}/request_tax_invoice\").body)\n @attributes = response['items']\n true\n end",
"def update_item_taxes_with_http_info(body, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: CatalogApi.update_item_taxes ...\"\n end\n # verify the required parameter 'body' is set\n fail ArgumentError, \"Missing the required parameter 'body' when calling CatalogApi.update_item_taxes\" if body.nil?\n # resource path\n local_var_path = \"/v2/catalog/update-item-taxes\".sub('{format}','json')\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n \n header_params['Square-Version'] = \"2018-07-12\"\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(body)\n auth_names = ['oauth2']\n data, status_code, headers = @api_client.call_api(:POST, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'UpdateItemTaxesResponse')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: CatalogApi#update_item_taxes\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def update\n @tax = Tax.find(params[:id])\n\n respond_to do |format|\n if @tax.update_attributes(params[:tax])\n flash[:notice] = 'Tax was successfully updated.'\n format.html { redirect_to(taxes_url) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @tax.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @variable_charge = VariableCharge.find(params[:id])\n\n respond_to do |format|\n if params[:taxes]\n params[:taxes].each do |t|\n\t tax = Taxrate.find_by_name t[0]\n\t # t is the key\n\t if t[1] == '1'\n\t @variable_charge.taxrates << tax unless @variable_charge.taxrates.exists?(tax)\n\t else\n\t @variable_charge.taxrates.delete(tax) if @variable_charge.taxrates.exists?(tax)\n\t end\n\tend\n end\n if @variable_charge.update_attributes(params[:variable_charge]) || params[:taxes]\n format.html { redirect_to(variable_charges_path, :notice => 'VariableCharge was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @variable_charge.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def receive_vend_tax\n vend_taxes = self.vend_sale.taxes\n manual_taxes = self.vend_sale.register_sale_products.find_all do |adj|\n adj.name =~ /tax/i\n end\n\n vend_taxes.each do |tax|\n adjustments.build(\n :amount => tax.tax,\n :source => self,\n :originator_type => \"TaxRate\",\n :label => \"#{tax.name} #{tax.rate * 100}%\",\n :mandatory => true)\n end unless vend_taxes.blank?\n\n manual_taxes.each do |item|\n adjustments.build(\n :amount => item.price,\n :source => self,\n :originator_type => \"TaxRate\",\n :label => \"#{item.name}\",\n :mandatory => true)\n end unless manual_taxes.blank?\n\n save(:validate => false)\n end",
"def create_taxes\n country.taxes.each do |tax|\n Tax.create!(tax)\n end\n end",
"def update\n @quarter_income_tax.update(quarter_income_tax_params) \n @quarter_income_tax = QuarterIncomeTax.new\n @quarter_income_taxes = QuarterIncomeTax.all\n end",
"def update\n respond_to do |format|\n if @client_tax.update(client_tax_params)\n format.html { redirect_to @client_tax, notice: 'Client tax was successfully updated.' }\n format.json { render :show, status: :ok, location: @client_tax }\n else\n format.html { render :edit }\n format.json { render json: @client_tax.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @taxinvoice = Taxinvoice.find(params[:id])\n\n respond_to do |format|\n if @taxinvoice.update_attributes(params[:taxinvoice])\n flash[:notice] = 'Taxinvoice was successfully updated.'\n format.html { redirect_to(@taxinvoice) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @taxinvoice.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def apply(taxes)\n @order.line_items.each do |item|\n taxed_items = taxes.line_item_taxes.select { |i| i.item_id == item.id }\n update_adjustments(item, taxed_items)\n end\n\n @order.shipments.each do |item|\n taxed_items = taxes.shipment_taxes.select { |i| i.item_id == item.id }\n update_adjustments(item, taxed_items)\n end\n end",
"def update\n authorize @incoming_service_tax\n\n respond_to do |format|\n if @incoming_service_tax.update(incoming_service_tax_params)\n format.html { redirect_to @incoming_service_tax, notice: 'Incoming service tax was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @incoming_service_tax.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @product_tax.update(product_tax_params)\n format.html { redirect_to product_taxes_path, notice: 'Product tax was successfully updated.' }\n format.json { render :show, status: :ok, location: @product_tax }\n else\n format.html { render :edit }\n format.json { render json: @product_tax.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @pos_tax.update(pos_tax_params)\n format.html { redirect_to @pos_tax, notice: 'Pos tax was successfully updated.' }\n format.json { render :show, status: :ok, location: @pos_tax }\n else\n format.html { render :edit }\n format.json { render json: @pos_tax.errors, status: :unprocessable_entity }\n end\n end\n end",
"def test_create_invoice_and_edit_taxes_should_copy_taxes_and_mark_edited\n context = \"with taxes enabled in profile and valid\"\n user = tax_user(:basic_user)\n user.enable_profile_taxes\n assert user.profile.tax_enabled\n\n user.login\n# puts \"do click new invoice\"\n user.clicks_create_new_invoice\n \n user.assert_select 'div#tax_container', true, \"new invoice screen was missing tax_container #{context}\"\n \n user.assert_select 'input#invoice_tax_1_enabled', true, \"new invoice failed to show tax_1_enabled #{context}\"\n user.assert_select 'input#invoice_tax_1_rate', true, \"new invoice failed to show tax_1_rate #{context}\"\n\n user.assert_select 'input#invoice_tax_2_enabled', true, \"new invoice failed to show tax_2_enabled #{context}\"\n user.assert_select 'input#invoice_tax_2_rate', true, \"new invoice failed to show tax_2_rate #{context}\"\n \n user.assert user.assigns(:invoice)\n user.deny user.assigns(:invoice).taxes.empty?\n\n user.assert_taxes(user.assigns(:invoice), context)\n# puts \"do save invoice\"\n user.saves_new_invoice(:tax_1_rate => '10.1')\n# puts user.assigns(:invoice).taxes.inspect\n\n user.assert_taxes(user.assigns(:invoice), context, {:tax_1_rate => 10.1, :tax_1_edited => true})\n end",
"def test_edit_invoice_with_edited_enabled_taxes_with_profile_taxes_unchanged\n # show invoice.taxes. Include a link to use profile taxes.\n context = \"when editing invoice with edited taxes with profile taxes unchanged\"\n user = tax_user(:basic_user)\n user.enable_profile_taxes\n assert user.profile.tax_enabled\n\n user.login\n # puts \"do click new invoice\"\n user.clicks_create_new_invoice\n\n user.assert user.assigns(:invoice)\n user.assert_taxes(user.assigns(:invoice), \"after creating new invoice \" + context)\n\n # puts \"do save invoice\"\n user.saves_new_invoice(\n :customer_id => user.scratch.fixture_user.customers.first.id,\n :date => Time.now.to_date.to_s(:MMDDYYYY),\n :due_date => (Time.now + 1.week).to_date.to_s(:MMDDYYYY),\n :description => Babel.random_short.gsub( '&', 'and' ),\n :tax_1_name => 'custom',\n :tax_2_rate => 9\n )\n\n new_invoice = user.assigns(:invoice)\n user.assert_taxes(new_invoice, \"after saving new invoice \" + context, \n {:tax_2_rate => 9, :tax_2_edited => true, :tax_1_name => 'custom', :tax_1_edited => true})\n\n new_invoice.reload\n # puts \"new_invoice: #{new_invoice.inspect}\"\n user.assert_taxes(new_invoice, \"after reloading invoice object \" + context,\n {:tax_2_rate => 9, :tax_2_edited => true, :tax_1_name => 'custom', :tax_1_edited => true})\n\n # puts \"do edit invoice with #{new_invoice.id} user.assigns(:invoice): #{user.assigns(:invoice).inspect}\"\n user.edits_invoice(new_invoice.id)\n\n # puts user.assigns(:invoice).taxes.inspect\n user.deny user.assigns(:invoice).taxes.empty?, \"edited invoice taxes was, empty #{context}\"\n user.assert_taxes(user.assigns(:invoice), \"after editing new invoice \" + context,\n {:tax_2_rate => 9, :tax_2_edited => true, :tax_1_name => 'custom', :tax_1_edited => true}) \n\n end",
"def delete_tax(id)\n @client.raw('delete', \"/ecommerce/taxes/#{id}\")\n end",
"def test_edit_invoice_with_unedited_enabled_taxes_with_profile_taxes_unchanged\n # show invoice.taxes\n context = \"when editing invoice with unedited taxes with profile taxes unchanged\"\n user = tax_user(:basic_user)\n user.enable_profile_taxes\n assert user.profile.tax_enabled\n\n\n user.login\n # puts \"do click new invoice\"\n user.clicks_create_new_invoice\n\n user.assert user.assigns(:invoice)\n user.assert_taxes(user.assigns(:invoice), \"after creating new invoice \" + context)\n\n # puts \"do save invoice\"\n user.saves_new_invoice(\n :customer_id => user.scratch.fixture_user.customers.first.id,\n :date => Time.now.to_date.to_s(:MMDDYYYY),\n :due_date => (Time.now + 1.week).to_date.to_s(:MMDDYYYY),\n :description => Babel.random_short.gsub( '&', 'and' )\n )\n\n new_invoice = user.assigns(:invoice)\n user.assert_taxes(new_invoice, \"after saving new invoice \" + context)\n\n new_invoice.reload\n# puts \"new_invoice: #{new_invoice.inspect}\"\n user.assert_taxes(new_invoice, \"after reloading invoice object \" + context)\n \n # puts \"do edit invoice with #{new_invoice.id} user.assigns(:invoice): #{user.assigns(:invoice).inspect}\"\n user.edits_invoice(new_invoice.id)\n\n # puts user.assigns(:invoice).taxes.inspect\n user.deny user.assigns(:invoice).taxes.empty?, \"edited invoice taxes was, empty #{context}\"\n user.assert_taxes(user.assigns(:invoice), \"after editing new invoice \" + context)\n\n end",
"def update_tax_code(companyId, id, model) path = \"/api/v2/companies/#{companyId}/taxcodes/#{id}\"\n put(path, model, {}, AvaTax::VERSION) end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /invoice_taxes/1 DELETE /invoice_taxes/1.json
|
def destroy
@invoice_tax = InvoiceTax.find(params[:id])
@invoice_tax.destroy
respond_to do |format|
format.html { redirect_to invoice_taxes_url }
format.json { head :no_content }
end
end
|
[
"def delete_tax(id)\n @client.raw('delete', \"/ecommerce/taxes/#{id}\")\n end",
"def destroy\r\n @tax_invoice = TaxInvoice.find(params[:id])\r\n @tax_invoice.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to tax_invoices_url }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @tax.is_active = 0\n @tax.save\n respond_to do |format|\n format.html { redirect_to taxes_url, flash: { notice: 'Налог был удален', type: 'deleted', state: 'ok', rollback_url: \"/taxes/#{params[:id]}/recover\" } }\n format.json { head :no_content }\n end\n end",
"def destroy\n @taxinvoice = Taxinvoice.find(params[:id])\n @taxinvoice.destroy\n\n respond_to do |format|\n format.html { redirect_to(taxinvoices_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n authorize @incoming_service_tax\n\n @incoming_service_tax.destroy\n respond_to do |format|\n format.html { redirect_to incoming_service_taxes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @tax = Tax.find(params[:id])\n @tax.destroy\n\n respond_to do |format|\n format.html { redirect_to(taxes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @client_tax.destroy\n respond_to do |format|\n format.html { redirect_to client_taxes_url, notice: 'Client tax was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @taxirequest = Taxirequest.find(params[:id])\n @taxirequest.destroy\n\n respond_to do |format|\n format.html { redirect_to taxirequests_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @billtaxinvoice = Billtaxinvoice.find(params[:id])\n @billtaxinvoice.destroy\n\n respond_to do |format|\n format.html { redirect_to(billtaxinvoices_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @cal_tax.destroy\n respond_to do |format|\n format.html { redirect_to cal_taxes_url, notice: 'Cal tax was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @itemtax.destroy\n respond_to do |format|\n format.html { redirect_to itemtaxes_url, notice: 'Itemtax was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @transaction_taxis = Transaction::Taxe.find(params[:id])\n @transaction_taxis.destroy\n\n respond_to do |format|\n format.html { redirect_to(transaction_taxes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @transaction_goods_taxis = Transaction::Goods::Taxe.find(params[:id])\n @transaction_goods_taxis.destroy\n\n respond_to do |format|\n format.html { redirect_to(transaction_goods_taxes_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @pos_tax.destroy\n respond_to do |format|\n format.html { redirect_to pos_taxes_url, notice: 'Pos tax was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @invoice = Invoice.find(params[:id])\n @invoice.destroy\n\n respond_to do |format|\n format.html { redirect_to invoices_url }\n format.json { head :no_co}\n end\n end",
"def destroy\n # @invoice = Invoice.find(params[:id])\n @invoice.destroy\n\n respond_to do |format|\n format.html { redirect_to invoices_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @pagto_taxa.destroy\n respond_to do |format|\n format.html { redirect_to pagto_taxas_url }\n format.json { head :no_content }\n end\n end",
"def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def destroy\n record = TaxRule.find(params[:id])\n record.trash\n respond_to do |format|\n format.json { head :no_content }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Notify all connection listeners, that a notice message was received.
|
def handle(context)
# Notify all connection listeners by calling their on_server_response method.
super(context)
# Notify all connection listeners by calling their on_notice method.
notify(context) do |connection_listener|
connection_listener.on_notice(context, context.lookup_user(nick), message)
end
end
|
[
"def notify_on_changes!\n ensure_connection! { register_callback(notifier) }\n end",
"def on_notifications\n self.before_listen if self.respond_to?(:before_listen)\n\n self.class.connection.execute('LISTEN %s' % channel)\n loop do\n handle_notifications do |incoming|\n yield incoming\n end\n end\n ensure\n self.class.connection.execute('UNLISTEN %s' % channel)\n\n self.after_listen if self.respond_to?(:after_listen)\n\n # Make sure we close this connection since its thread will be killed!\n self.class.connection.close()\n end",
"def notify(context)\n \n context.connection_listeners.each do |connection_listener|\n yield connection_listener\n end\n \n end",
"def on_notice(connection, user, message)\n end",
"def notify_peers(event)\n @peers.each do |peer|\n @socket.send(event, 0, peer.address, peer.port)\n end\n end",
"def notify\n @subscribers.each { |ident, (block,obj)| block.call(obj) }\n end",
"def notify(notice)\n if @config.use_dogapi?\n notify_dogapi_event(notice) if @config.send_event\n notify_dogapi_metric(notice) if @config.send_metric\n end\n if @config.use_statsd?\n notify_statsd_event(notice) if @config.send_event\n notify_statsd_metric(notice) if @config.send_metric\n end\n end",
"def inform(msg)\n @observers.each do |o|\n o.notify msg, self\n end\n end",
"def notify_all(notifier_keys)\n Thread.start(notifier_keys) do |keys|\n sleep 1 # let the call to #listen occur\n keys.each do |key|\n DB.run DB[\"NOTIFY #{key.inspect}\"].sql\n end\n end\n end",
"def listen_to_notifications\n listeners = []\n listeners << @interface.on_cycle_end do\n write_packet(\n [\n :cycle_end,\n @interface.execution_engine.cycle_index,\n @interface.execution_engine.cycle_start\n ], defer_exceptions: true)\n end\n listeners << @interface.on_notification do |*args|\n if notifications_enabled?\n queue_packet([:notification, *args])\n elsif Thread.current == @main_thread\n flush_pending_packets\n end\n end\n listeners << @interface.on_ui_event do |*args|\n queue_packet([:ui_event, *args])\n end\n listeners << @interface.on_job_notification do |*args|\n write_packet([:job_progress, *args], defer_exceptions: true)\n end\n listeners << @interface.on_exception do |*args|\n write_packet([:exception, *args], defer_exceptions: true)\n end\n @listeners = Roby.disposable(*listeners)\n end",
"def on_notice(&block)\n @notice_handler = block\n end",
"def notify_message_listeners(message)\n @messageListeners.each_value {|listener| listener.call(message)}\n end",
"def notify_on_change\n @on_change_callbacks.each do |callback|\n begin\n callback.call(self)\n rescue => ex\n logger.error(\"ProcessSettings::Monitor#notify_on_change rescued exception:\\n#{ex.class}: #{ex.message}\")\n end\n end\n end",
"def notify_observers\r\n self.observers.each {|observer| observer.update(self)}\r\n end",
"def notify\n changed(true)\n notify_observers(self)\n end",
"def notify(message)\n client.register(nick)\n client.notify(message)\n client.quit\n\n puts \"New message has been notified on IRC: #{message}\"\n end",
"def notify(players, notice = Notices::Notice.new)\n send @notice_order, players, notice do |player, notice|\n yield player, notice\n end\n end",
"def notify\n changed(true)\n notify_observers(self)\n end",
"def notify_observers\n @observers.each do |observer|\n observer.update(self)\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
execute /bin/sh from vi
|
def send_vi_shell
send_ctrl_escape
data = ":!/bin/sh" + "\n"
session.shell_write(data)
end
|
[
"def vi\n system \"vim ~/.scratchvim.rb\"\nend",
"def execute!\n \tsystem(\"vim #{file} -c 'execute \\\"normal i#{escaped_commands}\\\\<Esc>\\\"' -c 'execute \\\":wq\\\"'\")\n File.read(file)\n end",
"def sh command\n system command\n end",
"def vim(*args)\n\t\tvi *args\n\tend",
"def edit *args\n ::NERV::CLI::ReplHelpers.send :remove_method, :edit\n require 'interactive_editor'\n alias :edit :vim\n vim *args\n end",
"def run_script(content)\n user_switch = \"\"\n\n unless @user == \"root\"\n user_switch = USER_SWITCH_COMMAND\n end\n\n wrapper = <<-EOF\n if [ -e /dev/fd/0 ]\n then\n #{user_switch} /bin/sh /dev/fd/0\n elif [ -e /dev/stdin ]\n then\n #{user_switch} /bin/sh /dev/stdin\n else\n echo \"Cannot find method of communicating with the shell via stdin\"\n exit 1\n fi\n EOF\n\n exec_ssh(wrapper, content)\n end",
"def make_shell_command(source)\n make_executable(\"#!/bin/sh\\n\" + source)\n end",
"def execute_vios_cmd(command)\n hmc.execute_cmd \"viosvrcmd -m #{frame} -p #{name} -c \\\" #{command} \\\"\"\n end",
"def autoscript\n res = []\n self.shell_scripts.executable.each do |s|\n res << s.contents\n end\n self.shell_scripts.replaceable.each do |s|\n res << \"cat <<EOF > #{s.filename}\\n#{s.contents.gsub(/\\r/, '')}\\nEOF\"\n res << \"chown #{s.owner} #{s.filename}\" unless s.owner.to_s.empty?\n res << \"chmod #{s.mode} #{s.filename}\" unless s.mode.to_s.empty?\n end\n \"#!/bin/bash\\n#{res.join(\"\\n\")}\"\n end",
"def edit( filename )\n\t\teditor = ENV['EDITOR'] || ENV['VISUAL'] || DEFAULT_EDITOR\n\t\tsystem editor, filename.to_s\n\t\tunless $?.success? || editor =~ /vim/i\n\t\t\traise \"Editor exited with an error status (%d)\" % [ $?.exitstatus ]\n\t\tend\n\tend",
"def change_shell\n popen('chsh -s zsh')\n end",
"def edit_file( path)\n\t\tVim::command(\"edit #{path}\")\n\tend",
"def edit( filename )\n\t\t\teditor = ENV['EDITOR'] || ENV['VISUAL'] || DEFAULT_EDITOR\n\t\t\tsystem editor, filename\n\t\t\tunless $?.success? || editor =~ /vim/i\n\t\t\t\tfail \"Editor exited uncleanly.\"\n\t\t\tend\n\t\tend",
"def vhome_script script , vm: $vm\n src = vm.fs[:vhome] + '/' + script\n source src\nend",
"def run_sh(cmd)\n begin; sh cmd; rescue; end\nend",
"def shell(*) end",
"def invoke(script, this)\n # Ruby 1.8.7 doesn't let you have empty symbols\n term_mode = :\"#{this.settings.term_mode}\" if this.settings.term_mode\n code = \"#{this.ssh_command} -- #{script}\"\n\n # Certain environments can't do :pretty mode.\n term_mode = :exec if term_mode == :pretty && !pretty_supported?\n\n case term_mode\n when :pretty\n this.pretty_system(code)\n when :exec\n exec code\n else\n system code\n $?.to_i\n end\n end",
"def run_sh(cmd)\n sh cmd\nrescue\nend",
"def shell_exec(cmd, doneStr = nil, _shell = nil, stdin = nil)\n return exec(cmd, doneStr, stdin) if @su_user.nil?\n ret = suexec(cmd, doneStr, stdin)\n # Remove escape character from the end of the line\n ret.sub!(/\\e$/, '')\n ret\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
exit vi without saving
|
def send_vi_exit_nosave
send_ctrl_escape
data = ":q!" + "\n"
session.shell_write(data)
end
|
[
"def send_vi_exit_save\n send_ctrl_escape\n data = \":x!\" + \"\\n\"\n session.shell_write(data)\n end",
"def file_exit\n set_focus\n keystroke(VK_MENU, VK_F, VK_X)\n if message_dialog_confirm(:timeout => 0)\n keystroke(VK_N)\n end\n end",
"def vi\n system \"vim ~/.scratchvim.rb\"\nend",
"def mark_as_exit\n @exit = true\n end",
"def edit( filename )\n\t\t\teditor = ENV['EDITOR'] || ENV['VISUAL'] || DEFAULT_EDITOR\n\t\t\tsystem editor, filename\n\t\t\tunless $?.success? || editor =~ /vim/i\n\t\t\t\tfail \"Editor exited uncleanly.\"\n\t\t\tend\n\t\tend",
"def command_quit\n\t exit(0) \n end",
"def _exit\n exit if go_on? method(:_save)\n # return nil to stop PostQuitMessage()\n end",
"def edit *args\n ::NERV::CLI::ReplHelpers.send :remove_method, :edit\n require 'interactive_editor'\n alias :edit :vim\n vim *args\n end",
"def update_terminate\n return if @@overlay_windows[:exit_confirm].overlayed\n return unless Input.trigger?(:kF4) || Input.press?(:kF4)\n return unless Input.trigger?(:kALT) || Input.press?(:kALT) \n self.heatup_button\n $on_exit = true\n raise_overlay_window(:exit_confirm , nil, :exit)\n end",
"def exit\n\tputs (\"Would you like to continue? (y/n)\")\n end",
"def return_to_edit_command_window\n # activate trigger command window\n @ecommand_window.active = true\n # delete edit trigger window\n @edit_trigger_window.dispose\n # clear variables\n @edit_trigger_window = nil\n # check edit window display\n check_edits\n end",
"def vim(*args)\n\t\tvi *args\n\tend",
"def vi(file=nil, type=:any)\n usage = \"USAGE: vi [name_of_file], [:type]\"\n return usage if file.nil?\n types_to_look_for = %w(controller helper model js rjs css view unit \n functional fixture config layout mailer)\n # determine whether or not we can dissect the file parameter \n if types_to_look_for.include?(file.to_s.split(\"_\").last)\n file_ary = file.to_s.split(\"_\")\n type = file_ary.delete(file_ary.last).to_sym\n file = file_ary.join(\"_\")\n end\n file_path = vi_file_path_for(type, file)\n file.nil? ? puts(usage) : system(\"vi #{file_path}\")\n end",
"def edit( filename )\n\t\teditor = ENV['EDITOR'] || ENV['VISUAL'] || DEFAULT_EDITOR\n\t\tsystem editor, filename.to_s\n\t\tunless $?.success? || editor =~ /vim/i\n\t\t\traise \"Editor exited with an error status (%d)\" % [ $?.exitstatus ]\n\t\tend\n\tend",
"def edit (filename, *data_and_options)\n data, options = *parse_data_and_options(data_and_options)\n editor =\n ENV.has_key?('VISUAL') ? ENV['VISUAL'] :\n ENV.has_key?('EDITOR') ? ENV['EDITOR'] : 'vi'\n\n file_stat = File.stat(filename)\n file_checksum = SHA1.file(filename)\n system(editor, filename, options)\n proc_status = $?\n\n if options[:noop]\n return true\n\n elsif proc_status.success?\n return nil if file_stat == File.stat(filename)\n return false if file_checksum == SHA1.file(filename)\n return true\n\n elsif proc_status.signaled?\n raise AdvFileUtils::CommandError.new(\"editor terminated on signal #{proc_status.termsig}\")\n\n else\n raise AdvFileUtils::CommandError.new(\"editor had non-zero exit code #{proc_status.exitstatus}\")\n end\n end",
"def dont_exit_on_help=(val) #:nodoc:\n @@exit = true\n end",
"def exit_runway\r\n\t\t\"#{model} exits runway.\"\r\n\tend",
"def exit\n clear\n ascii.exit_screen\n sleep(3)\n clear\n end",
"def edit_file( path)\n\t\tVim::command(\"edit #{path}\")\n\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
exit vi with saving
|
def send_vi_exit_save
send_ctrl_escape
data = ":x!" + "\n"
session.shell_write(data)
end
|
[
"def send_vi_exit_nosave\n send_ctrl_escape\n data = \":q!\" + \"\\n\"\n session.shell_write(data)\n end",
"def file_exit\n set_focus\n keystroke(VK_MENU, VK_F, VK_X)\n if message_dialog_confirm(:timeout => 0)\n keystroke(VK_N)\n end\n end",
"def file_save\n set_focus\n keystroke(VK_MENU, VK_F, VK_S)\n end",
"def _exit\n exit if go_on? method(:_save)\n # return nil to stop PostQuitMessage()\n end",
"def vi\n system \"vim ~/.scratchvim.rb\"\nend",
"def save\n system *['djvused', '-s','-e', @command, @file]\n end",
"def update_savefile_selection\n return on_savefile_ok if Input.trigger?(Input::Keys::A)\n return on_savefile_cancel if Input.trigger?(Input::Keys::B)\n update_cursor if @savefile_windows[@index].selected == true\n end",
"def mark_as_exit\n @exit = true\n end",
"def buffer_close\n if buffer.scratch? and buffer.modified?\n file = buffer.short_filename\n\n VER.choice(\"Save changes to #{file}? \", Y_N_C) do |choice|\n case choice\n when 'yes'\n save_as_ask(close = true)\n when 'no'\n view.buffer_close\n view.open\n when 'cancel'\n view.open\n end\n end\n elsif buffer.modified?\n file = buffer.short_filename\n\n VER.choice(\"Save changes to #{file}? \", Y_N_C) do |choice|\n case choice\n when 'yes'\n buffer.save_file\n view.buffer_close\n view.open\n when 'no'\n view.buffer_close\n view.open\n when 'cancel'\n view.open\n end\n end\n else\n view.buffer_close\n end\n end",
"def return_to_edit_command_window\n # activate trigger command window\n @ecommand_window.active = true\n # delete edit trigger window\n @edit_trigger_window.dispose\n # clear variables\n @edit_trigger_window = nil\n # check edit window display\n check_edits\n end",
"def edit( filename )\n\t\t\teditor = ENV['EDITOR'] || ENV['VISUAL'] || DEFAULT_EDITOR\n\t\t\tsystem editor, filename\n\t\t\tunless $?.success? || editor =~ /vim/i\n\t\t\t\tfail \"Editor exited uncleanly.\"\n\t\t\tend\n\t\tend",
"def edit_file( path)\n\t\tVim::command(\"edit #{path}\")\n\tend",
"def save_or_view_or_back?\n prompt = TTY::Prompt.new\n prompt.select(\"Would you like to save a spell, view your current spell slots, delete a spell, or exit this menu?\", %w(Save View Delete Back))\nend",
"def prompt_save_deletion\r\n pbMessage(_INTL('The save file is corrupt, or is incompatible with this game.'))\r\n exit unless pbConfirmMessageSerious(\r\n _INTL('Do you want to delete the save file and start anew?')\r\n )\r\n self.delete_save_data\r\n $game_system = Game_System.new\r\n $PokemonSystem = PokemonSystem.new\r\n end",
"def prompt_save_deletion\n pbMessage(_INTL('The save file is corrupt, or is incompatible with this game.'))\n exit unless pbConfirmMessageSerious(\n _INTL('Do you want to delete the save file and start anew?')\n )\n self.delete_save_data\n $game_system = Game_System.new\n $PokemonSystem = PokemonSystem.new\n end",
"def save_and_exit\n begin\n Menu.data_handler.persist_data\n Menu.exit_script\n rescue IOError => e\n raise IOError, \"Error while saving data: \".concat(e.message).red\n end\n end",
"def exit_runway\r\n\t\t\"#{model} exits runway.\"\r\n\tend",
"def save_to_vim!\n save!(File.expand_path(\"~/.vim/colors/#{@name.to_s}.vim\"))\n end",
"def command_exit\n # Play decision SE\n $game_system.se_play($data_system.cancel_se)\n # Exit to menu\n $scene = Scene_Menu.new(5)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
for assigning teacher to a course
|
def teacher_assign
@course_allocation = CourseAllocation.find_by_course_id(params[:id])
@course = Course.find(params[:id])
@teachers = get_teachers_for_institute
end
|
[
"def teacher=(value)\n @teacher = value\n end",
"def teacher\n self.course_person.first(:type => \"teacher\").person\n end",
"def assignment_by_teacher(student_user)\n self.line_break\n puts \"Please select a teacher by typing out their full name below:\".colorize(:light_blue)\n self.all_teachers(student_user)\n self.line_break\n student_input = gets.chomp.titleize\n self.line_break\n if Teacher.find_by(name: student_input)\n puts \"Here are your assignments for Professor #{student_input}:\".colorize(:magenta)\n s = Student.find_by(name: student_user)\n t = Teacher.find_by(name: student_input)\n list = s.assignments.select do |assignment|\n assignment.teacher_id == t.id\n end\n list.each do |assignment|\n puts assignment.task\n end\n self.student_main_menu(student_user)\n else \n puts \"Invalid response!\".colorize(:yellow)\n self.assignment_by_teacher(student_user)\n end\n end",
"def teacher= name\n set_teacher(name, Term.current)\n end",
"def add_teacher(person)\n c = CoursePerson.new type: \"teacher\"\n c.person = person\n self.course_person << c\n end",
"def register_teacher(user_id, course)\n current_course = course\n current_course.teachers.push(user_id)\n current_course\n end",
"def apply_for_tutor\n set_course\n end",
"def run\n return invalid_course unless teacher_valid? && course_params\n\n TeacherCourse.create(teacher: teacher, course: course) if course.valid?\n\n course\n end",
"def tutor\n\t\tif course_convenor?(@current_user, @course)\n\t\t\t@user = Lecturer.find_by(params[:lecturer_id]).user_id\n\t\t\t@lecturer = Lecturer.find_by(params[:lecturer_id])\n\t\t\t@lecturer.destroy\n\t\t\tTutor.create!(user_id: @user, course_id: @course.id)\n\t\t\tflash[:success] = \"Changed course member to tutor role\"\n\t\t\tredirect_to course_members_path(@course)\n\t\tend\n\tend",
"def assign\n # Must be POST request to create course\n return unless request.post?\n\n # Retrieves current user\n user = get_logged_user()\n return unless user\n return unless user.is? \"supervisor\"\n\n # Receives parameters from the course creation page\n course_id = params[:course_id]\n\n # Get course\n course = Course.find(course_id)\n\n # Assign\n user.courses << course\n\n redirect_back fallback_location: \"/\"\n end",
"def change_teacher\n member = Member.find(params[:member_id])\n user = User.find(params[:teacher_to_change_to])\n \n User.change_teacher(user.id, member)\n\n redirect_to users_teachers_path, notice: \"#{user.first_name} #{user.last_name} is now a teacher of section #{member.section_number}.\"\n end",
"def pick_teacher\n @activity = @course.activities.find params[:id]\n @teachers = User.teachers\n @indexes = TimetablesOnRails::FirstLetterIndex.build_from_name @teachers\n end",
"def create_teacher(type, id, grade)\n subjects = DataUtility.get_random_academic_subjects_for_type(@prng, type)\n # name is intentionally left nil here\n # -> signal for Teacher.new (when invoked via teacher work order) to randomly create name for this teacher\n {\"id\"=>id, \"name\"=>nil, \"grades\"=>[grade], \"subjects\"=>subjects, \"num_sections\"=>sections_for_this_teacher(type)}\n end",
"def create\n authorize Course\n @user = current_user\n @course = Course.new(course_params)\n @course.teacher = current_user.id\n @course.uni_id = current_user.university_id\n if @course.save\n redirect_to '/teacherportal'\n else\n render 'courses/new'\n end\n end",
"def teacher_required\n unless current_user.is_teacher == true\n redirect_to education_path\n end\n end",
"def assign_elective\n @subject = Subject.shod(params[:student_subject][:subject_id])\n @subject.assign_subject(params[:students])\n flash[:notice] = t('assign_elective')\n redirect_to elective_student_path(@subject)\n authorize! :create, @student\n end",
"def create_teacher\n\t\t@teacher = Teacher.new\n\t\t@teacher.user = self\n\t\t@teacher.save!\n\tend",
"def run\n return teacher unless teacher.save\n\n authenticate_teacher\n\n teacher\n end",
"def set_teacher\n @teacher = Teacher.joins(:account).select(\"teachers.*, teachers.id,\n\t accounts.id AS account_id\").where(\"accounts.id\": params[:id]).first\n\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
creates a button and form with a hidden field in order to pass ids across to new objects
|
def my_button_to(text, path, objs)
s = "<form method=\"get\" action=\"#{path}\" class=\"button_to\">
<div><input type=\"submit\" value=\"#{text}\"/></div>"
for obj in objs
if(!obj.nil?)
s+= "<input type=\"hidden\" name=\"#{obj.class.to_s.downcase}_id\" value=\"#{obj.id}\" />"
end
end
s+= "</form>"
return s.html_safe
end
|
[
"def button_set_form_vars\n @sb[:buttons_node] = true\n @edit = {}\n if session[:resolve] && session[:resolve][:instance_name]\n @resolve = session[:resolve]\n else\n build_resolve_screen\n end\n @resolve[:target_class] = if x_active_tree == :sandt_tree\n \"ServiceTemplate\"\n elsif x_node.starts_with?(\"-ub-\")\n x_node.sub(/-ub-([^_]+)(_.*)?/, '\\1')\n else\n x_node.sub(/xx-ab_([^_]+)_.*/, '\\1')\n end\n @record = @edit[:custom_button] = @custom_button\n @edit[:instance_names] = Array(@resolve[:instance_names])\n @edit[:new] = {}\n @edit[:current] = {}\n @edit[:new][:attrs] ||= []\n @edit[:rec_id] = @custom_button.try(:id)\n if @custom_button.uri_attributes\n instance_name = @custom_button.uri_object_name\n if @edit[:instance_names].include?(instance_name)\n @edit[:new][:instance_name] = instance_name\n else\n @edit[:new][:other_name] = instance_name\n end\n @edit[:new][:object_request] = @custom_button.uri_attributes[\"request\"]\n\n button_type = @custom_button.options.try(:[], :button_type) ? @custom_button.options[:button_type] : 'default'\n default_attributes = %w[request]\n default_attributes = %w[request service_template_name hosts] if button_type == 'ansible_playbook'\n\n @custom_button.uri_attributes.each do |attr|\n if attr[0] != \"object_name\" && !default_attributes.include?(attr[0].to_s)\n @edit[:new][:attrs].push(attr) unless @edit[:new][:attrs].include?(attr)\n end\n end\n end\n (ApplicationController::AE_MAX_RESOLUTION_FIELDS - @edit[:new][:attrs].length).times { @edit[:new][:attrs].push([]) }\n @edit[:new][:starting_object] ||= \"SYSTEM/PROCESS\"\n @edit[:new][:instance_name] ||= \"Request\"\n\n @edit[:new].update(\n :target_class => @resolve[:target_class],\n :name => @custom_button.name,\n :description => @custom_button.description,\n :button_icon => @custom_button.options.try(:[], :button_icon),\n :button_color => @custom_button.options.try(:[], :button_color),\n :disabled_text => @custom_button.disabled_text,\n :display => @custom_button.options.try(:[], :display).nil? ? true : @custom_button.options[:display],\n :open_url => @custom_button.options.try(:[], :open_url) ? @custom_button.options[:open_url] : false,\n :display_for => @custom_button.options.try(:[], :display_for) ? @custom_button.options[:display_for] : 'single',\n :submit_how => @custom_button.options.try(:[], :submit_how) ? @custom_button.options[:submit_how] : 'one',\n :button_type => button_type,\n :object_message => @custom_button.uri_message || \"create\"\n )\n button_set_expression_vars(:enablement_expression, :enablement_expression_table)\n button_set_expression_vars(:visibility_expression, :visibility_expression_table)\n\n @edit[:new][:disabled_open_url] = !(MODEL_WITH_OPEN_URL.include?(@resolve[:target_class]) && @edit[:new][:display_for] == 'single')\n\n @edit[:current] = copy_hash(@edit[:new])\n\n @edit[:visibility_types] = [[\"<#{_('To All')}>\", \"all\"], [\"<#{_('By Role')}>\", \"role\"]]\n # Visibility Box\n if @custom_button.visibility && @custom_button.visibility[:roles]\n @edit[:new][:visibility_typ] = @custom_button.visibility[:roles][0] == \"_ALL_\" ? \"all\" : \"role\"\n if @custom_button.visibility[:roles][0] == \"_ALL_\"\n @edit[:new][:roles] = [\"_ALL_\"]\n else\n @edit[:new][:roles] ||= []\n @custom_button.visibility[:roles].each do |r|\n role = MiqUserRole.find_by(:name => r)\n @edit[:new][:roles].push(role.id) if role\n end\n end\n @edit[:new][:roles].sort! if @edit[:new][:roles].present?\n end\n\n @edit[:sorted_user_roles] = []\n MiqUserRole.all.sort_by { |ur| ur.name.downcase }.each do |r|\n @edit[:sorted_user_roles].push(r.name => r.id)\n end\n @edit[:new][:dialog_id] = @custom_button.resource_action.dialog_id\n load_available_dialogs\n\n button_set_playbook_form_vars\n\n @edit[:current] = copy_hash(@edit[:new])\n session[:edit] = @edit\n @changed = session[:changed] = (@edit[:new] != @edit[:current])\n end",
"def button_id(value)\n @submit_id = value\n end",
"def form_button_for(obj, name = nil)\n name ||= obj.object.new_record? ? 'Create' : 'Update'\n\n obj.button name, class: 'btn btn-theme', data: { disable_with: raw(\"<i class='fa fa-circle-o-notch fa-spin'></i> Saving...\") }\n end",
"def edit\n obj_retry(\"button\") do; det.button(:id, 'editButton'); end\n end",
"def save\n obj_retry(\"button\") do; det.button(:name, 'Submit'); end\n end",
"def button(...)\n tag.button(...)\n end",
"def create_button(name, title)\n return '<input type=\"button\" name=\"' + name + '\" value=\"' + name + '\" title=\"' + title + '\">'\n end",
"def link_to_add_piece(name, f)\n new_piece = Piece.new\n fields = f.fields_for(:pieces, new_piece, :child_index => \"new_pieces\") do |builder|\n render(\"piece_fields\", :f => builder)\n end\n button_to_function(name, \"Application.add_fields(this, \\\"piece\\\", \\\"#{escape_javascript(fields)}\\\")\", :class => \"btn\")\n end",
"def add_button_to_query(button); end",
"def submit_button \n\t\t@browser.button(id: @submit)\n\tend",
"def generate_btn(memo)\n message = {\n \"type\": \"template\",\n \"altText\": \"#{memo.title}\",\n \"template\": {\n \"type\": \"buttons\",\n \"title\": \"#{memo.title}\",\n \"text\": \"#{memo.body}\",\n \"actions\": [\n {\n \"type\": \"postback\",\n \"label\": \"削除\",\n \"data\": \"#{memo.id}\",\n }\n ]\n }\n }\n message\n end",
"def new_button\n begin\n $results.log_action(\"button(#{@params[0..-1].join(' ')})\")\n if @params[1].nil?\n @driver.find_element(:link_text, 'New').click\n else\n # If the New Button has multiple options, choose the right one from the dropdown menu.\n buttons = @driver.find_elements(:class, 'caret')\n buttons[2].click\n @driver.find_element(:link_text, @params[1].capitalize).click\n end\n $session.wait_for_stale\n $results.success\n rescue => ex\n $results.fail(\"button(#{@params.join(' ')})\", ex)\n end\n end",
"def scaffold_button_to_remote(text, action, options) \n \"#{scaffold_form_remote_tag(action, options)}\\n<input type='submit' value=#{text} />\\n</form>\"\n end",
"def sp_button(name, show, wrapper_tag, options = {})\n if show && name\n button = submit_tag(\"#{name}\", options)\n button = \"<#{wrapper_tag}> #{button} </#{wrapper_tag.split(' ').first}>\" if wrapper_tag\n end\n button.html_safe if !button.blank?\n end",
"def linkwizard_confirm_button\n $tracer.trace(__method__)\n return ToolTag.new(button.id(\"/btnSubmit/\") ,__method__)\n end",
"def create\n self.done_add_button\n wait_for_ajax\n end",
"def delete_button(object_or_url, contents=\"Delete\", attrs = {})\n url = object_or_url.is_a?(String) ? object_or_url : resource(object_or_url)\n button_text = (contents || 'Delete')\n tag :form, :class => 'delete-btn', :action => url, :method => :post do\n tag(:input, :type => :hidden, :name => \"_method\", :value => \"DELETE\") <<\n tag(:input, attrs.merge(:value => button_text, :type => :submit))\n end\n end",
"def generate_submit\n\n'<input type=\"submit\" class=\"submit-button\"></ul></form>'\n\n end",
"def add_link_to_document\n frm.div(:id=>\"PostForm:tab2\").button(:value=>\"Add to document\").click\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Function to build a radio button list
|
def radio_list(items)
rl = "<ul>"
if(!items.empty?)
for item in items
if(item.is_a?(Category)) #not currently used
rl += "#{radio_button_tag "category_ids[]", item.id, @items_to_select.include?(item), :id=>"a#{item.id}"}" + "<label for=\"a#{item.id}\">#{item.name}</label><br />"
elsif(item.is_a?(Product))
rl += "#{radio_button_tag "product_ids[]", item.id, @items_to_select.include?(item), :id=>"p#{item.id}"}" + "<label for=\"p#{item.id}\">#{item.name}</label><br />"
#{item.name}</label>"
elsif(item.is_a?(Component))
rl += "#{radio_button_tag "component_ids[]", item.id, @items_to_select.include?(item), :id=>"c#{item.id}"}" + "<label for=\"c#{item.id}\">#{item.name}</label><br />"
elsif(item.is_a?(Valuefield))
rl += "#{radio_button_tag "valuefield_ids[]", item.id, @items_to_select.include?(item), :id=>"v#{item.id}"}" + "<label for=\"v#{item.id}\">#{item.name}</label><br />"
elsif(item.is_a?(Group)) #not currently used
rl += "#{radio_button_tag "group_ids[]", item.id, @items_to_select.include?(item), :id=>"g#{item.id}"}" + "<label for=\"g#{item.id}\">#{item.name}</label><br />"
elsif(item.is_a?(Property))
rl += "#{radio_button_tag "property_ids[]", item.id, @items_to_select.include?(item), :id=>"o#{item.id}"}" + "<label for=\"o#{item.id}\">#{item.name}</label><br />"
end
end
rl += "</ul>"
end
return rl
end
|
[
"def radiobuttons; end",
"def radio_buttons(model, method, values, options = {})\n values = values.is_a?(Hash) ? values.to_a : values.map{|v| [v,v]}\n radios = values.map do |value|\n html = radio_button(model, method, value[0].to_s)\n html << ' ' << value[1].to_s\n content_tag('label', html)\n end\n radios.join(' ')\n end",
"def collection_radio_buttons(method, collection, value_method, text_method, options = T.unsafe(nil), html_options = T.unsafe(nil), &block); end",
"def radio_buttons(method, choices, options = {})\n choices.map!{ |i| i.is_a?(Array) ? i : [i] }\n build_shell(method, options, \"radio_buttons_field\") do\n choices.map{ |c| radio_button method, c[1], :label => c[0],\n :label_for => [object_name, method, c[1].to_s.downcase].join('_') }\n end\n end",
"def create_multiple_choice_fields(question)\n choices = question.possible_choices\n radio_name = \"questions[]#{question.question_type}[]#{question.id}\"\n\n html = \"\"\n html << \"<ul class='no-list'>\"\n choices.each do |choice|\n radio_id = \"questions[]#{question.question_type}[]#{question.id}_#{choice}\"\n radio_name = \"questions[]#{question.question_type}[]#{question.id}\"\n html << \"<li> #{radio_button_tag(radio_name, choice)} #{label_tag radio_id, choice }</li>\"\n end\n html << \"<li class='hidden'>#{radio_button_tag(radio_name, \"\", :check => true)} </li>\"\n html << \"</ul>\"\n raw(html)\n end",
"def radio_group(name = \"\", *values)\n if name.kind_of?(Hash)\n values = name[\"VALUES\"]\n name = name[\"NAME\"]\n end\n values.collect{|value|\n if value.kind_of?(String)\n radio_button(name, value) + value\n else\n if value[-1] == true || value[-1] == false\n radio_button(name, value[0], value[-1]) +\n value[-2]\n else\n radio_button(name, value[0]) +\n value[-1]\n end\n end\n }.join\n end",
"def radio_group(name = \"\", *values)\n if name.kind_of?(Hash)\n values = name[\"VALUES\"]\n name = name[\"NAME\"]\n end\n values.collect{|value|\n if value.kind_of?(String)\n radio_button(name, value) + value\n else\n if value[value.size - 1] == true\n radio_button(name, value[0], true) +\n value[value.size - 2]\n else\n radio_button(name, value[0]) +\n value[value.size - 1]\n end\n end\n }.to_s\n end",
"def collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {})\n ('<div data-role=\"fieldcontain\"><fieldset data-role=\"controlgroup\" data-type=\"horizontal\" data-mini=\"true\">' + super + '</fieldset></div>').html_safe\n end",
"def radio_button_group(method, values, options = {})\n selections = []\n values.each do |value|\n if value.is_a?(Hash)\n tag_value = value[:value]\n label = value[:label]\n help = value.delete(:help)\n else\n tag_value = value\n value_text = value\n end\n radio_button = @template.radio_button(@object_name, method, tag_value, options.merge(:object => @object, :help => help))\n selections << boolean_field_wrapper(radio_button, \"#{@object_name}_#{method.to_s}\", tag_value, value_text)\n end\n selections\n field_name, label_text, error_text, options = field_settings(method, options)\n semantic_group('radio', field_name, label_text, selections, options)\n end",
"def boolean_radio_input(method, options)\n options[:true] ||= \"Yes\"\n options[:false] ||= \"No\"\n\n choices = [ {:label => options[:true], :value => true}, {:label => options[:false], :value => false} ]\n\n @template.content_tag(:fieldset, \n %{<legend><span>#{label_text(method, options)}</span></legend>} + \n @template.content_tag(:ol, \n choices.map { |c| \n @template.content_tag(:li,\n @template.label_tag(\"#{@object_name}_#{method}_#{c[:value]}\", \n \"#{@template.radio_button_tag(\"#{@object_name}[#{method}]\", c[:value], @template.instance_eval(\"@#{@object_name}\").send(method) == c[:value], :id => \"#{@object_name}_#{method}_#{c[:value]}\")} #{c[:label]}\" # TODO checked is always false, which ain't always right ;)\n )\n )\n }\n )\n )\n end",
"def radio_collection(object, method, instance, collection, options = {})\n ret = \"\"\n columns = options[:columns] || 1\n\n label_class ||= options.delete(:label_class)\n label_class ||= \"radio_collection_label\"\n options[:class] ||= \"input_radio radio_collection_input\"\n collection.each do |element| \n ret << radio_button(object, method, element[1], options)\n ret << content_tag(:label, element.first, {:for => \"#{object}_#{method}_#{element[1]}\", :class => label_class})\n str = []\n columns.to_i.times do |x|\n str << \" \"\n end unless columns == 1\n str << tag(:br)\n unless columns == 1\n ret << cycle(\"\", str) \n else\n ret << tag(:br)\n end\n end\n ret << tag(:br)\n ret\n end",
"def radio_button_tag(name, value, checked = T.unsafe(nil), options = T.unsafe(nil)); end",
"def enum_radio_group(method, value_array, checked_value)\n rg_array = value_array.collect do |sym|\n options = {:value=>sym, :label=>sym.to_s}\n if checked_value.to_s == sym.to_s\n options[:checked] = 'checked'\n end\n options\n end\n radio_group method, rg_array\n end",
"def quick_radio_set(name, values, selected=nil, html_options={})\n html_options[:class] ||= ''\n html_options[:class] << ' ujs-quick-buttonset ui-buttonset'\n html_options[:autocomplete] = 'off'\n content = ''\n last_key = values.keys.length - 1\n values.each_with_index do |(value, label), i|\n content << radio_button_tag(name, value, selected == value,\n :class => 'ui-helper-hidden-accessible')\n label_class = 'ui-button ui-widget ui-state-default ui-button-text-only'\n label_class << ' ui-state-active' if selected == value\n label_class << ' ui-corner-left' if i == 0\n label_class << ' ui-corner-right' if i == last_key\n content << label_tag(\"#{name}_#{value}\", :class => label_class,\n :role => 'button',\n :'aria-disabled' => 'false') do\n content_tag :span, label, :class => 'ui-button-text'\n end\n end\n content_tag(:div, raw(content), html_options)\n\n end",
"def radio_button(object_name, method, tag_value, options = T.unsafe(nil)); end",
"def element\n HTML.ul(:class => :radio_options) { \n option_elements().map { |o| HTML.li() { o } } \n }\n end",
"def radio_buttons(object, method, choices, options = {}, html_options = {})\n ActionView::Helpers::InstanceTag.new(object, method, self, options.delete(:object)).to_radio_buttons_tag(choices, options, html_options)\n end",
"def makeButton(radio, item)\n if radio\n NSButton.radioButtonWithTitle('', target: self, action: 'buttonAction:')\n else\n NSButton.checkboxWithTitle('', target: self, action: 'buttonAction:')\n end.tap do |button|\n button.lineBreakMode = 5 # NSLineBreakByTruncatingMiddle\n button.state = NSOnState if item.end_with?(\"\\n\") # NSControlStateValueOn\n button.title = item.chomp\n end\n end",
"def printChoicesOnScreen()\n $strAnswer = ($arrCorrectAnswers[$intQuestionOnScreen - 1].strip)\n # Based on the number of correct answers, the program decides to use radio or check buttons\n if $strAnswer.length == 1\n $radioChoice = TkVariable.new\n $radioA = Tk::Tile::RadioButton.new($frmChoiceA) {text ''; variable $radioChoice; value 'A'; command {yourAnswer}}\n $radioB = Tk::Tile::RadioButton.new($frmChoiceB) {text ''; variable $radioChoice; value 'B'; command {yourAnswer}}\n $radioC = Tk::Tile::RadioButton.new($frmChoiceC) {text ''; variable $radioChoice; value 'C'; command {yourAnswer}}\n $radioD = Tk::Tile::RadioButton.new($frmChoiceD) {text ''; variable $radioChoice; value 'D'; command {yourAnswer}}\n $radioA.grid :column => 0, :row => 0\n $radioB.grid :column => 0, :row => 0\n $radioC.grid :column => 0, :row => 0\n $radioD.grid :column => 0, :row => 0\n else\n $option_one = TkVariable.new( 0 )\n $checkA = Tk::Tile::CheckButton.new($frmChoiceA) {text \"\"; variable $option_one; onvalue 'A'; command {yourAnswer}}\n $option_two = TkVariable.new( 0 )\n $checkB = Tk::Tile::CheckButton.new($frmChoiceB) {text \"\"; variable $option_two; onvalue 'B'; command {yourAnswer}}\n $option_three = TkVariable.new( 0 )\n $checkC = Tk::Tile::CheckButton.new($frmChoiceC) {text \"\"; variable $option_three; onvalue 'C'; command {yourAnswer}}\n $option_four = TkVariable.new( 0 )\n $checkD = Tk::Tile::CheckButton.new($frmChoiceD) {text \"\"; variable $option_four; onvalue 'D'; command {yourAnswer}}\n $checkA.grid :column => 0, :row => 0\n $checkB.grid :column => 0, :row => 0\n $checkC.grid :column => 0, :row => 0\n $checkD.grid :column => 0, :row => 0\n end\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Function to build a checkbox list only usable for an array of the same class
|
def checkbox_list(items)
cl = "<ul>"
if(!items.empty?)
item_class = items[0].class.to_s
item_class_sub = item_class[0..0].to_s
for item in items
cl += "<li>#{check_box_tag(item_class +"_ids[]", item.id, @items_to_select.include?(item), :id=>"#{item_class_sub + "" + item.id.to_s}")}"
cl += "<label for=\"#{item_class_sub + "" + item.id.to_s}\">#{item.name}</label></li>"
end
cl += "</ul>"
end
return cl
end
|
[
"def checkboxes_for coll, &blok\n \n @checkbox ||= Class.new do \n \n def initialize &blok\n instance_eval(&blok)\n end\n \n def text txt\n @text = txt\n end\n \n def value txt\n @value = txt\n end\n \n def name txt\n @name = txt\n end\n \n def props\n [ \n @text, \n { :name => @name, \n :type => 'checkbox', \n :value => @value \n } \n ]\n end\n \n end\n \n span_txt, attrs = @checkbox.new(&blok).props\n ele_id = \"checkbox_#{rand(1000)}_#{attrs[:value]}\"\n s_ele_id = \"selected_checkbox_#{rand(1000)}_#{attrs[:value]}\"\n \n text(capture {\n loop coll do\n \n show_if 'selected?' do\n div.box.selected {\n input( {:checked=>'checked', :id=>s_ele_id}.update attrs )\n label span_txt, :for=>s_ele_id\n }\n end\n \n if_not 'selected?' do\n div.box {\n input( {:id=>ele_id}.update attrs )\n label span_txt, :for=>ele_id\n }\n end\n \n end # === loop\n })\n\n end",
"def checkboxes_from_list(var, param, conf, object, horizontal=false)\n\t\tres = []\n key = ([param.split('_').last.singularize] & ['item', 'language', 'layout', 'type', 'category', 'profile', 'container']).first\n\t\tvar.each do |l|\n\t\t if horizontal\n\t\t content = '<div class=\"checkboxListHorizontal\">'\n\t\t else\n content = '<div>'\n end\n content += check_box_tag(object+'['+param+']'+\"[]\", \"#{l}\", ((ref=conf[param]) ? ref.include?(l) : false), :class => \"checkboxes\")\n content += ' '+I18n.t('general.'+key+'.'+l)\n content += \"</div>\"\n\t\t\tres << content\n end\n\t\treturn res\n\tend",
"def checkbox_collection(object, method, instance, collection, opts = {})\n css_class = opts[:css_class] || \"inplace_checkbox\"\n columns = opts[:columns] || 1\n\n m2m = instance.send(\"#{method}\") \n name_string = \"#{object}[#{method}][]\"\n\n htm_class = opts.delete(:label_class)\n htm_class ||= \"checkbox_collection_label\"\n collection.map do |k, v|\n id_string = \"#{object}_#{method}_#{k}\"\n tag_options = {\n :type => \"checkbox\", \n :name => name_string,\n :id => id_string,\n :value => k,\n :class => css_class\n }\n title = opts[:title] || v rescue \"No Title\"\n tag_options[:checked] = \"checked\" if m2m.respond_to?(:collect) && m2m.include?(k)\n final_out = tag(:input, tag_options) + content_tag(:label, title, :for => id_string, :class => htm_class )\n str = []\n\n columns.to_i.times do |x|\n str << \" \"\n end unless columns == 1\n str << tag(:br)\n unless columns == 1\n final_out << cycle(\"\", str) \n else\n final_out << tag(:br)\n end\n final_out\n end.join(\"\\n\") + tag(:br)\n end",
"def collection_check_boxes(method, collection, value_method, text_method, options = T.unsafe(nil), html_options = T.unsafe(nil), &block); end",
"def checkboxes_for_multiple_select(name, container, selected_items = [], options = {})\n container = container.to_a if Hash === container\n position = (options[:position] or :right)\n inner_class = options[:inner_class]\n alternate = (options[:alternate] or false)\n alternate_class = (options[:alternate_class] or 'alt') if alternate\n alt = (options[:initial_alternate] or false) if alternate\n \n checkboxes_for_multiple_select = container.map do |item|\n if !item.is_a?(String) and item.respond_to?(:first) and item.respond_to?(:last)\n is_selected = selected_items.include?(item.last)\n item_id = html_escape(\"#{name}#{item.last}\")\n cbt = check_box_tag(\"#{name}[]\", html_escape(item.last.to_s), is_selected, :id => item_id)\n lbt = content_tag('label', html_escape(item.first.to_s), :for => item_id)\n else\n \tis_selected = selected_items.include?(item)\n item_id = html_escape(\"#{name}#{item.to_s}\")\n cbt = check_box_tag(\"#{name}[]\", html_escape(item.to_s), is_selected, :id => item_id)\n lbt = content_tag('label', html_escape(item.to_s), :for => item_id)\n end\n \n if alternate\n item_class = alt ? \"#{inner_class} #{alternate_class}\".strip : inner_class\n alt = !alt\n else\n item_class = inner_class\n end\n \n content_tag('div', position == :left ? lbt + cbt : cbt + lbt, :class => item_class)\n end\n \n checkboxes_for_multiple_select.join(\"\\n\")\n end",
"def render_checkboxes_new\n return_string = ''\n alternate = 0 \n Referral.referral_types.each do |referral| \n if alternate.even? \n return_string += '<tr><td style=\"font-size: .95em\"><input type=\"checkbox\" name=\"referrals[]\" value=\"' + referral[1].to_s + '\"> ' + referral[0].to_s + '</td>'\n else\n return_string += '<td style=\"font-size: .95em\"><input type=\"checkbox\" name=\"referrals[]\" value=\"' + referral[1].to_s + '\"> ' + referral[0].to_s + '</td></tr>'\n end \n alternate += 1 \n end\n return return_string.html_safe \n end",
"def parse_checkboxes(input_header, options)\n\n input_header[2] = input_header[2]+\"[]\"\n concat \"<div class='checkboxes'>\".html_safe\n\n @collection = input_header[3][:options][\"collection\"][0]\n\n\n @collection.each_with_index do |item, index|\n\n concat send(:label, item, item.to_s)\n concat send(input_header[0], input_header[2], item, false, id:(item+'_'+item))\n\n end\n\n concat \"</div>\".html_safe\n end",
"def checkbox(item)\n name_li(item).checkbox\n end",
"def check_box_tag_for_array(object_name, field_name, checked_value)\n checked = nil\n if params[object_name] and params[object_name][field_name]\n checked = params[object_name][field_name].include?(checked_value)\n end\n return check_box_tag(\"#{object_name}[#{field_name}][]\",\"#{checked_value}\",checked)\n end",
"def build_check_box_without_hidden_field\n build_check_box(nil)\n end",
"def build_check_box(unchecked_value = unchecked_value())\n @builder.check_box(attribute_name, input_html_options, checked_value, unchecked_value)\n end",
"def description\n 'Choose multiple values using checkbox'\n end",
"def checkbox_for_multiple_select(\n name, item, selected_items = [], is_alternate = false, options = {}\n )\n position = (options[:position] or\n FormMultipleSelectHelperConfiguration.position)\n inner_class = (options[:inner_class] or\n FormMultipleSelectHelperConfiguration.inner_class)\n alternate_class = (options[:alternate_class] or\n FormMultipleSelectHelperConfiguration.alternate_class)\n is_disabled = (options[:disabled] or false)\n \n if !item.is_a?(String) and item.respond_to?(:first) and item.respond_to?(:last)\n is_selected = selected_items.include?(item.last)\n is_disabled = is_disabled.include?(item.last) if is_disabled.respond_to?(:include?)\n item_id = idfy(\"#{name}#{item.last}\")\n cbt = check_box_tag(\"#{name}[]\", html_escape(item.last.to_s), is_selected, :id => item_id, :disabled => is_disabled)\n lbt = content_tag('label', html_escape(item.first.to_s), :for => item_id)\n else\n is_selected = selected_items.include?(item)\n is_disabled = is_disabled.include?(item) if is_disabled.respond_to?(:include?)\n item_id = idfy(\"#{name}#{item.to_s}\")\n cbt = check_box_tag(\"#{name}[]\", html_escape(item.to_s), is_selected, :id => item_id, :disabled => is_disabled)\n lbt = content_tag('label', html_escape(item.to_s), :for => item_id)\n end\n \n item_class = is_alternate ? \"#{inner_class} #{alternate_class}\".strip : inner_class\n \n extra = block_given? ? yield : ''\n \n content_tag(\n FormMultipleSelectHelperConfiguration.list_tags[1],\n position == :left ? lbt + cbt + extra : cbt + lbt + extra,\n :class => item_class\n )\n end",
"def checkbox_elements(identifier)\n platform.checkboxes_for(identifier.clone)\n end",
"def item_containers_checkboxes(form, item, container)\n\t\tstrg = \"\"\n\t\titem_class_name = item.class.to_s.underscore\n\t\tcheck_box_tag_name = \"#{item_class_name}[#{container}_ids][]\"\n\t\tres=[]\n\t\t# Workspace list allowing user to add new item and accepting items of that type\n\t\tlist = (res + container.classify.constantize.allowed_to_user_with_permission(@current_user, item_class_name+\"_new\")).uniq.delete_if{ |w| !w.available_items.to_s.split(',').include?(item_class_name) }\n\t\tif (list.size > 1 || @current_user.has_system_role('admin'))\n\t\t\t#form.field(:workspaces, :label => I18n.t('general.object.workspace').camelize+'(s) :', :ajax => false)\n\t\t\tlist.collect do |w|\n\t\t\t\t# Setting the checked status form that workspace\n\t\t\t\tif params[item.class.to_s.downcase] && params[item.class.to_s.downcase][\"#{container}_ids\".to_sym]\n checked = params[item.class.to_s.downcase][\"#{container}_ids\".to_sym].include?(w.id.to_s)\n\t\t\t\telse\n checked = \"items_#{container}\".classify.constantize.exists?(\"#{container}_id\".to_sym => w.id, :itemable_id => item.id, :itemable_type => item.class.to_s)\n\t\t\t\tend\n\t\t\t\t# Creating the checkboxes\n\t\t\t\tif (w == @current_user.private_workspace) || (w == current_container)# && (item.new_record?))\n\t\t\t\t\tstrg += check_box_tag(check_box_tag_name, w.id, true, :disabled => true, :class => 'checkboxes') + ' ' + w.title + '<br />'\n\t\t\t\t\tstrg += hidden_field_tag(check_box_tag_name, w.id.to_s)\n\t\t\t\telse\n\t\t\t\t\tstrg += check_box_tag(check_box_tag_name, w.id, checked, :class => 'checkboxes') + ' ' + w.title + '<br />'\n\t\t\t\tend\n\t\t\tend\n\t\t\tstrg += ajax_error_message_on(item, \"items_#{container.pluralize}\")\n\t\telsif (list.size > 0)\n\t\t\tlist.each do |ws|\n\t\t\t\tstrg += hidden_field_tag(check_box_tag_name, ws.id.to_s)\n\t\t\tend\n\t\tend\n\t\t(item.send(container.pluralize) - list).each do |ws|\n\t\t\tstrg += hidden_field_tag(check_box_tag_name, ws.id.to_s)\n\t\tend\n\t\treturn strg\n\tend",
"def check_box_field_template(l = {})\n \"#{l[:element]} #{l[:label]} #{l[:decoration]}\"\n end",
"def checkboxes_for_multiple_select(\n name, container, selected_items = [], options = {}\n )\n container = container.to_a if Hash === container\n ialternate = options[:alternate].nil? ?\n FormMultipleSelectHelperConfiguration.alternate :\n options[:alternate]\n alt = (options[:initial_alternate] or false)\n \n checkboxes = container.map do |item|\n cbfms = checkbox_for_multiple_select(\n name, item, selected_items, alt, options\n )\n alt = !alt if ialternate\n cbfms\n end\n \n checkboxes.join(\"\\n\")\n end",
"def checkbox(obj, field, values, options={})\n join = options.delete(:join) || ' '\n labs = options.delete(:label)\n vals = param_or_default(obj, field, [])\n ary = values.is_a?(Array) && values.length > 1 ? '[]' : ''\n Array(values).collect do |val|\n id, text = id_and_text_from_value(val)\n single_tag(:input, options.merge(:type => \"checkbox\", :id => css_id(obj, field, id),\n :name => \"#{obj}[#{field}]#{ary}\", :value => id,\n :checked => vals.include?(id) ? 'checked' : nil)) +\n (labs.nil? || labs == true ? label(obj, \"#{field}_#{id.to_s.downcase}\", text) : '')\n end.join(join)\n end",
"def show_check_options(options, checkboxes)\r\n\tpara \"\\n\"\r\n\tfor i in 0..options.length - 1\r\n\t\tcheckboxes[i] = check()\r\n\t\tpara \"#{options[i]} \\n\"\r\n\tend\r\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a hash for all groups
|
def all_group_hash
hash = {}
for group in @all_groups
hash[group] = {}
end
return hash
end
|
[
"def create_group_hash(group_names, groups)\n group_hash = Hash.new\n for i in 0..group_names.length-1\n group_hash[group_names[i]] = groups[i]\n end\n group_hash\nend",
"def group_list\n @group_list = {}\n @group.each { |m| @group_list[m] = 0 }\n @group_list\n end",
"def group\n @_group ||= Hash.new { |h, k| h[k] = Group.new(k) }\n end",
"def generate_each_group\n all_groups = {}\n all_attributes.each do |attr_name|\n attr_values(attr_name).each do |attr_value|\n hosts_matched = hosts_per(attr_name, attr_value)\n all_groups.merge!({attr_value => hosts_matched})\n end\n end\n return all_groups\n end",
"def list_group_as_hash(group=nil, state=nil, inst_ids=[], &each_inst)\n instances = list_as_hash(state, inst_ids)\n # Remove instances that are not in the specified group\n if instances\n instances = instances.reject { |id,inst| !inst.groups.member?(group) } if group\n instances.each_value { |inst| each_inst.call(inst) } if each_inst\n end\n instances = nil if instances && instances.empty? # Don't return an empty hash\n instances\n end",
"def list_hash_groups\n print_message( \"[%s] Listing groups...\" % self.name )\n imp_hashes = {}\n\n @relyze.library.archives do | archive |\n archive.hashes do | hash_name, hash_value |\n if( hash_name == 'IMPHASH' )\n if( imp_hashes[hash_value].nil? )\n imp_hashes[hash_value] = [ archive ]\n else\n imp_hashes[hash_value] << archive\n end\n break\n end\n end\n end\n\n imp_hashes.each do | hash_value, archives |\n next if archives.length <= 1\n print_message( \"\\tIMPHASH '%s' has %d matches\" % [ hash_value, archives.length ] )\n archives.each do | archive |\n print_message( \"\\t\\t%-40s (%s)\" % [ archive.name, archive.path ] )\n end\n end\n print_message( \"[%s] Finished.\" % self.name )\n end",
"def cache_all_group_ids(trace: false)\n @group_id_map = {}\n @dbx_info.groups_list(trace: trace) do |gf|\n @group_id_map[gf['group_name']] = gf['group_id']\n end\nend",
"def create_groups(cohort)\n if cohort.length % 5 == 0\n hash = {} \t\n \tcounter = 1\n group_count = cohort.length / 5\n remainder = cohort.length % 5 \t\n # Set to groups(keys) to members(values)\n group_count.times do\n hash[counter] = cohort.slice!(0..4)\n counter += 1\n end\n else\n \thash = {}\n counter = 1 \n group_count = cohort.length / 4\n remainder = cohort.length % 4\n # Set to groups(keys) to members(values)\n group_count.times do\n hash[counter] = cohort.slice!(0..3)\n counter += 1\n end\n end\n # Add remainders\n counter = 1\n cohort.each do |string|\n hash[counter] << string\n counter += 1\n end\nreturn hash\nend",
"def group_data\n data_hash = {color: @color, bling: @bling, age: @age, functional: @functional}\n end",
"def group_by\n self.inject(Hash.new { |h, k| h[k] = [] }) { |h, v| h[yield v] << v ; h }\n end",
"def group_by\n {}.tap do |hash|\n array = []\n each do |element| \n array << element if yield element\n hash[yield element] = array\n end\n end\n end",
"def group_instances\n @group_instance_map = {} if @group_instance_map.nil?\n values = @group_instance_map.values.uniq\n keys = @group_instance_map.keys\n \n values.each do |group_inst|\n group_inst.reused_by = keys.clone.delete_if{ |k| @group_instance_map[k] != group_inst }\n end\n \n values\n end",
"def to_hash\n ad_group_hash = {\n :id => self[:id],\n :name => self[:name],\n :status => self[:status]\n }\n end",
"def to_jaxb_json_hash\n _h = {}\n if !groupIds.nil?\n _ha = Array.new\n groupIds.each { | _item | _ha.push _item.to_jaxb_json_hash }\n _h['groupIds'] = _ha\n end\n return _h\n end",
"def user_group_list_hashes\n user_groups_list_table.rows_text.map{ |row| Hash[*user_groups_list_table.headers_text.zip(row).flatten] }\n end",
"def acct_groups(names)\r\n\r\n\tnum_groups = names.size / 4\r\n\r\n\tgroups_ary = Array.new(num_groups) { Array.new }\r\n\r\n\tnames.each_with_index do |name, index|\r\n\t\tgroups_ary[index % num_groups] << name\r\n\tend\r\n\r\n\tgroups_hash = Hash.new\r\n\tgroups_ary.each_with_index do |group_ary, index|\r\n\t\tgroups_hash[\"Accountability Group \" + (index+1).to_s] = group_ary\r\n\tend\r\n\r\n\treturn groups_hash\r\n\r\nend",
"def add_groups(host, groups=[])\n for group in groups\n if !GROUPS.key?(group) then\n GROUPS[group] = []\n end\n GROUPS[group].push(host)\n end\nend",
"def all_chunk_hashes\n\t\t\n\t\tbegin\n\t\t\t@all_chunk_map = \"\"\n\t\t\t0.upto(num_chunks-1) { |i|\n\t\t\t\t@all_chunk_map += sha1_chunk(i)\n\t\t\t}\n\n\t\tend unless @all_chunk_map\n\t\t@all_chunk_map\n\tend",
"def group_by\n return enum_for(:each) unless block_given?\n hash = Hash.new([])\n each do |e|\n res = yield e\n hash[res] = Array.new unless hash.key?(res)\n hash[res] << e\n end\n hash\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a hash for all properties
|
def all_property_hash
hash = {}
items = @all_properties
for prop in items
hash[prop] = {}
end
return hash
end
|
[
"def to_hash()\n hash = {}\n @properties.each{ |key, property|\n hash[key.to_s] = property.get_value()\n }\n return hash\n end",
"def property_objects\n hash = {}\n self.class.properties.each { |prop| hash[prop] = @properties[prop] }\n hash\n end",
"def properties_hash(properties, special_properties)\n properties.inject({}) do |props, (key, value)|\n key = \"$#{key}\" if special_properties.include?(key.to_s)\n props[key.to_sym] = value\n props\n end\n end",
"def object_properties_hash\n h = {}\n File.readlines(File.join(@path, CONFIG.dig('bag', 'item', 'object_properties_file'))).each do |line|\n key, *rest = line.split(' ')\n h[key] = rest.map { |e| e.split(',') }.flatten\n end\n h\n end",
"def property_digest(properties)\n normalize_object = lambda do |obj|\n case obj\n when Hash\n {}.tap { |result| obj.sort.each { |k, v| result[k] = normalize_object.call(v) } }\n when Enumerable\n obj.map(&normalize_object)\n else\n obj\n end\n end\n \"sha1:#{Digest::SHA1.hexdigest(normalize_object.call(properties).to_json)}\"\nend",
"def product_properties_hash\n product_properties.pluck(:property_id, :value).to_h\n end",
"def props\n ret = {\"_neo_id\" => getId()}\n iter = getPropertyKeys.iterator\n while (iter.hasNext) do\n key = iter.next\n ret[key] = getProperty(key)\n end\n ret\n end",
"def wb_create_properties(props)\n properties = Hash.new\n\n props.each do |prop|\n handle = prop[0]\n type = prop[1]\n data = '{\"labels\":{\"en\":{\"language\":\"en\",\"value\":\"' + generate_random_string(8) +\n '\"}},\"descriptions\":{\"en\":{\"language\":\"en\",\"value\":\"' + generate_random_string(20) +\n '\"}},\"datatype\":\"' + type + '\"}'\n property = wb_create_entity(data, \"property\")\n properties[handle] = property\n end\n\n properties\n end",
"def to_hash\n JSON.parse(properties).to_h\n end",
"def hash\n { hash: @hash, hashType: @hash_type }\n end",
"def to_hash\n\t\t\th = {}\n\t\t\tself.class::PublicProperties.each { |p|\n\t\t\t\th[p] = send(p)\n\t\t\t\tif h[p].kind_of? Sequel::Model\n\t\t\t\t\th[p] = h[p].to_hash\n\t\t\t\tend\n\t\t\t}\n\t\t\th\n\t\tend",
"def build_formatted_property_hash(property)\n property_hash = Hash.new\n property_hash = \n {\n \"address\"=> property[\"property_adress\"], \n \"apartment_number\"=> property[\"apartment_no\"],\n \"postal_code\"=> property[\"zip_code\"],\n \"city\"=> property[\"town\"],\n \"country\"=> property[\"country\"],\n \"description\"=> property[\"property_description\"],\n \"number_of_bedrooms\"=> property[\"bedrooms_no\"],\n \"max_guests\"=> property[\"max_people\"],\n \"internal_id\"=> property[\"source_id\"]\n }\n end",
"def property_map\n properties.reject { |p| p.external_name.blank? }\n .map { |p| [p.external_name.to_sym, p] }\n .to_h\n end",
"def to_hash(prop_headings)\n h = {\n manufacturer_part_no: @manufacturer_part_no,\n supplier_part_no: @supplier_part_no,\n brand_name: @brand_name,\n description: @description,\n weblink: @weblink\n }\n h[:properties] = properties_to_hash_array(prop_headings)\n h[:prices] = prices_to_hash_array\n h\n end",
"def initialization_hash\n h = {}\n meta_attributes.each do |attribute|\n h.merge!(attribute => self.send(attribute))\n end\n h\n end",
"def add_properties(hsh)\n hsh.each do |key, val|\n add_property(key, val)\n end\n end",
"def hash\n strs = FIELDS.collect {|f| \"#{f}:#{send(f).inspect}\"}\n Digest::SHA256.hexdigest(strs.join(' '))\n end",
"def hash\n attributes.hash\n end",
"def to_hash\n hsh = {}\n instance_variables.each do |var|\n name = var.to_s.gsub('@','').to_sym\n obj = instance_variable_get(var)\n hsh[name] = obj.is_a?(Base) ? obj.to_hash : obj\n end\n\n hsh\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a hash for all products
|
def all_product_hash
hash = {}
items = @all_products
for prod in items
hash[prod] = {}
end
return hash
end
|
[
"def cart_hash\n return Digest::MD5.hexdigest(items_to_buy.collect { |i| i.product.id.to_s }.join(':'))\n end",
"def products_hash\n return {} if @products.nil?\n products_hash = {}\n @products.map { |p| products_hash[p.code] = p.price }\n products_hash\n end",
"def all_prod_comp_hash(item=nil)\n\n hash = {}\n\n if(!item.nil?)\n items = item.components\n else\n items = @all_products\n end\n\n for comp in items\n\n hash[comp] = all_prod_comp_hash(comp)\n\n end\n\n return hash\n\n end",
"def get_product_name_hash\n\t\tproduct_id_name_hash = Hash.new\n\t\tself.order_product_histories.each do |order_product_history| \n\t\t\tproduct_id = order_product_history.product.id\n\t\t\tproduct_name = order_product_history.product.name\n\t\t\tproduct_id_name_hash[product_id] = product_name\n\t\tend\n\t\treturn product_id_name_hash\n\tend",
"def hash\n strs = FIELDS.collect {|f| \"#{f}:#{send(f).inspect}\"}\n Digest::SHA256.hexdigest(strs.join(' '))\n end",
"def cart_hash\n end",
"def hash_transaction\n dig = Digest::SHA256.new\n [user_id, merchant, currency, amount, created_at, image_hash ].each do |thing|\n dig << thing.to_s\n end\n \n self.transaction_hash = dig.to_s\n save\n end",
"def uniqueness_hash\n @uniqueness_hash ||= begin\n sum = Digest::MD5.new\n sum << SPRITE_VERSION\n sum << path\n sum << layout\n images.each do |image|\n [:relative_file, :height, :width, :repeat, :spacing, :position, :digest].each do |attr|\n sum << image.send(attr).to_s\n end\n end\n sum.hexdigest[0...10]\n end\n @uniqueness_hash\n end",
"def create_products(hash)\n prod_reports = {}\n hash[\"items\"].each do |item|\n report = ProductReport.new\n report.title = item[\"title\"]\n report.description = item[\"description\"]\n report.brand = item[\"brand\"]\n report.stock = item[\"stock\"]\n report.full_price = item[\"full-price\"]\n if item[\"purchases\"] && item[\"purchases\"].length > 0\n item[\"purchases\"].each do |purchase|\n purch = Purchase.new\n purch.channel = purchase[\"channel\"]\n purch.date = purchase[\"date\"]\n purch.price = purchase[\"price\"]\n purch.shipping = purchase[\"shipping\"]\n purch.currency = purchase[\"currency\"]\n purch.user = User.new\n purch.user.name = purchase['user']['name']\n purch.user.state = purchase['user']['state']\n report.add_purchase(purch)\n end\n end\n prod_reports[report.title] = report\n end\n prod_reports\nend",
"def merchanthash\n if version.to_i == 1 \n return HashGenerator::generate(merchant_hash_key, merchant_id, order_id);\n else\n return Digest::SHA512.hexdigest(\"#{merchant_hash_key},#{merchant_id},01,#{order_id},#{gross_amount}\")\n end\n end",
"def generate_hash\n block_contents = timestamp_string + @transactions.to_json.gsub(\"\\\"\", \"'\").gsub(\",\", \", \") + @previous_hash.to_s + @nonce.to_s\n Digest::SHA256.hexdigest block_contents\n end",
"def generated_hash\n items = [order_id, amount, response]\n items += [transaction_id, avs_response, cvv_response]\n items << customer_vault_id if customer_vault_id\n items += [time, BraintreeTransparentRedirectSlice.config[:key]]\n Digest::MD5.hexdigest(items.join('|'))\n end",
"def enterable_products\n ids = get_enterable_products\n Hash[*get(ids)['products'].map { |x| [x['name'], x] }.flatten]\n end",
"def product_properties_hash\n product_properties.pluck(:property_id, :value).to_h\n end",
"def hash(*) end",
"def build_hash_for(body)\n hasher = OpenSSL::Digest.new('sha256')\n hasher.hexdigest(body)\n end",
"def create_variants_of_products(users)\n idx = -1\n products_query = ::Spree::Product.where(user_id: users.collect(&:id) ).where('master_product_id IS NULL')\n puts \" These users have #{products_query.count} products; making duplicates for 1/3 of them\"\n products_query.all.each do|product|\n idx += 1\n puts \" #{idx}\" if idx % 20 == 1\n next unless idx % 3 == 2\n users_to_get_count = rand(3) + 2 - product.slave_products.count\n duplicates = []\n 1.upto(users_to_get_count) do\n p2 = product.build_clone\n p2.view_count = rand(900) + 100\n p2.created_at = product.created_at + rand(365).days\n p2.user_id = product.user_id\n p2.save\n\n p2.copy_variants_from!(product)\n p2.variants.each do|v2|\n diff = rand(product.price / 2) - (product.price / 4) # from -1/4 to 1/4\n v2.update(price: product.price + diff)\n end\n duplicates << p2\n end\n duplicates[ (users_to_get_count / 2.0).floor, 2 ].each do|p|\n p.txn_count = rand(100)\n p.engagement_count = p.txn_count + rand(500)\n p.gms = p.txn_count * p.price\n p.save\n end\n end\n end",
"def hash\n hash = 17\n hash = 37 * hash + @prob.hash\n hash = 37 * hash + @alias.hash\n hash = 37 * hash + @values.hash\n hash\n end",
"def products\n @products ||= begin\n items = []\n\n for i in (1..params[\"NumItens\"].to_i)\n items << {\n :id => params[\"ProdID_#{i}\"],\n :description => params[\"ProdDescricao_#{i}\"],\n :quantity => params[\"ProdQuantidade_#{i}\"].to_i,\n :price => to_price(params[\"ProdValor_#{i}\"]),\n :shipping => to_price(params[\"ProdFrete_#{i}\"]),\n :fees => to_price(params[\"ProdExtras_#{i}\"])\n }\n end\n\n items\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a hash for all valuefields
|
def all_valuefield_hash
hash = {}
items = @all_valuefields
for vf in items
hash[vf] = {}
end
return hash
end
|
[
"def values_hash\n hashify(:value)\n end",
"def fields_hash\n each_pair.to_h\n end",
"def field_hash\n\n self.yattributes || fields.inject({}) { |r, f| r[f.fkey] = f.value; r }\n end",
"def hash\n strs = FIELDS.collect {|f| \"#{f}:#{send(f).inspect}\"}\n Digest::SHA256.hexdigest(strs.join(' '))\n end",
"def hash\n value_id.hash\n end",
"def to_hash() end",
"def recalculate_values_hashes\n vh = {}\n @values.each do |k,v|\n vh[k] = v.hash\n end\n @values_hashes = vh.freeze\n end",
"def hash\n { hash: @hash, hashType: @hash_type }\n end",
"def to_hash\n result = {}\n filled_params.each{ |x| result[ x.name ] = x.value }\n result\n end",
"def attr_hash\n md5 = Digest::MD5.new\n @ruby_types.each do |k,typ|\n md5.update typ.attr_hash\n end\n md5.hexdigest\n end",
"def calculate_values_hashes\n @values_hashes || recalculate_values_hashes\n end",
"def extended_fields\n @hash ||= {}\n @hash\n end",
"def to_h\n h = {}\n self._attribute_keys.each do |attr_key|\n attr_val = self.send attr_key\n if attr_val.is_a? Array\n h[attr_key] = []\n\n attr_val.each do |_attr_val|\n h[attr_key] << (_attr_val.is_a?(FieldSet) ? _attr_val.to_h : _attr_val.value )\n end\n else\n if !attr_val.is_a?(FieldSet) && attr_val.nil?\n puts \"#{@_full_name} expected value for #{attr_key} in hash, but none found\"\n next\n end\n h[attr_key] = (attr_val.is_a?(FieldSet) ? attr_val.to_h : attr_val.value )\n end\n end\n h\n end",
"def fields_hash\n @fields_hash ||=\n begin\n field_sets_hash = Hash.new { |h, k| h[k] = Set.new }\n @types.each do |type|\n Setup.for(type).fields.each do |field|\n field_sets_hash[field.name.to_sym] << field\n end\n end\n fields_hash = {}\n field_sets_hash.each_pair do |field_name, set|\n if set.length == 1\n fields_hash[field_name] = set.to_a.first\n end\n end\n fields_hash\n end\n end",
"def attr_hash\n Digest::MD5.hexdigest(\"#{@name}:#{@ruby_type}\")\n end",
"def to_hash\n fattrs.inject({}){|h,a| h.update a => send(a)}\n end",
"def hash\n attributes.hash\n end",
"def vals(fieldname, val_hash)\n fieldname = fieldname.to_sym\n if(fieldname == :_)\n val_hash.each {|valname, val| @register[:vals][valname.to_sym] = val}\n else\n field(fieldname, val_hash)\n end\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"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a hash for all images
|
def all_image_hash
hash = {}
items = @all_images
for img in items
hash[img] = {}
end
return hash
end
|
[
"def uniqueness_hash\n @uniqueness_hash ||= begin\n sum = Digest::MD5.new\n sum << SPRITE_VERSION\n sum << path\n sum << layout\n images.each do |image|\n [:relative_file, :height, :width, :repeat, :spacing, :position, :digest].each do |attr|\n sum << image.send(attr).to_s\n end\n end\n sum.hexdigest[0...10]\n end\n @uniqueness_hash\n end",
"def generate_image_layers_hash\n @generated_image_layers_hash ||=\n Digest::MD5.hexdigest(image_layers.map(&:id).join(',')).first(8)\n end",
"def populate_hash\n self.orig_image_url_hash = Digest::SHA1.hexdigest orig_image_url\n end",
"def image_hashes\n @iostream.each_line.flat_map { |line| line_hash(line) }.compact\n end",
"def images\n @images ||= Hash.new\n end",
"def create_images\n imgNames = Hash[\n \tFile.join(Dir.home, 'Desktop/image1.png') => 0,\n \tFile.join(Dir.home, 'Desktop/image2.png') => 1,\n \tFile.join(Dir.home, 'Desktop/image3.png') => 2,\n \tFile.join(Dir.home, 'Desktop/image4.png') => 3,\n \tFile.join(Dir.home, 'Desktop/image5.png') => 4,\n \tFile.join(Dir.home, 'Desktop/image6.png') => 0,\n \tFile.join(Dir.home, 'Desktop/image7.png') => 1,\n \tFile.join(Dir.home, 'Desktop/image8.png') => 2,\n \tFile.join(Dir.home, 'Desktop/image9.png') => 3,\n \tFile.join(Dir.home, 'Desktop/image10.png') => 4 ]\n \t\n i = 0\n imgNames.each_key do |imgN|\n open(imgN, 'wb', 0666) do |file|\n puts \"Loading...\"\n file << open(@imageArray[i%5]).read\n end\n i += 1\n end\n end",
"def hash\n Digest::SHA256.hexdigest(@icons.join(\"|\"))\n end",
"def image_hash\n @image_hash ||= begin\n image_meta = page[\"image\"]\n\n case image_meta\n when Hash\n { \"path\" => nil }.merge!(image_meta)\n when String\n { \"path\" => image_meta }\n else\n { \"path\" => nil }\n end\n end\n end",
"def compute_image_md5s_json(test_image_folder)\n image_md5s = {}\n traverse_directories(test_image_folder) do |ancestry, file|\n md5 = Digest::MD5.file(file).hexdigest\n image_md5s[ancestry] = md5\n end\n { count: image_md5s.size, json: image_md5s.to_json }\nend",
"def digests\n @map.map { |sha1, path| sha1 }\n end",
"def create_image_metadata\n {}\n end",
"def create_image_metadata\n {}\n end",
"def calculate_fileset_hash(database)\n hash_files(database, collect_fileset_for_hash(database))\n end",
"def get_filehash_rcimg(target)\n f_imghash = Hash[]\n\n f_list = Dir.glob(%Q[#{@recent_image_dir}/**/#{target}].untaint)\n f_list = f_list + Dir.glob(%Q[#{@recent_image_dir}/**/s#{target}].untaint) if target != \"*\"\n f_list.each do |f_name|\n b_name = File.basename(f_name)\n next unless b_name.match(\"^([0-9]{8}_[0-9]+)\\..+\")\n tmb_name = %Q[#{File.dirname(f_name)}/s#{b_name}]\n file = (f_list.include?(tmb_name) ? tmb_name : f_name)\n f_imghash[$1] = (@recent_imageex_yearlydir == 1 ? %Q[#{$1[0,4]}/#{File.basename(file)}] : File.basename(file))\n end\n\n return f_imghash\nend",
"def hash\n [width, height].hash\n end",
"def store_images\n self.images.each_key do |k|\n if self.send(\"store_#{k}\") == \"1\"\n if self.send(\"#{k}?\")\n image = Image.new\n image.image = self.send(k).to_file\n image.save\n end\n end\n end\n end",
"def generate_histogram_hash(image)\n return {} if image.type == :pbm\n original = image.pixels.dup.flatten \n\n #counting number of pixels per frequency\n freq = Hash.new 0\n original.map { |pixel| freq[pixel] += 1}\n \n freq\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 hash(*) end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Creates a hash for all products and components
|
def all_prod_comp_hash(item=nil)
hash = {}
if(!item.nil?)
items = item.components
else
items = @all_products
end
for comp in items
hash[comp] = all_prod_comp_hash(comp)
end
return hash
end
|
[
"def all_product_hash\n hash = {}\n items = @all_products\n for prod in items\n hash[prod] = {}\n end\n return hash\n end",
"def products_hash\n return {} if @products.nil?\n products_hash = {}\n @products.map { |p| products_hash[p.code] = p.price }\n products_hash\n end",
"def get_product_name_hash\n\t\tproduct_id_name_hash = Hash.new\n\t\tself.order_product_histories.each do |order_product_history| \n\t\t\tproduct_id = order_product_history.product.id\n\t\t\tproduct_name = order_product_history.product.name\n\t\t\tproduct_id_name_hash[product_id] = product_name\n\t\tend\n\t\treturn product_id_name_hash\n\tend",
"def cart_hash\n end",
"def cart_hash\n return Digest::MD5.hexdigest(items_to_buy.collect { |i| i.product.id.to_s }.join(':'))\n end",
"def uniqueness_hash\n @uniqueness_hash ||= begin\n sum = Digest::MD5.new\n sum << SPRITE_VERSION\n sum << path\n sum << layout\n images.each do |image|\n [:relative_file, :height, :width, :repeat, :spacing, :position, :digest].each do |attr|\n sum << image.send(attr).to_s\n end\n end\n sum.hexdigest[0...10]\n end\n @uniqueness_hash\n end",
"def product_info\n {\n product_name: {\n default_value: 'similarity detection reference tool'\n },\n product_version: '1.0',\n description: {\n default_value: 'LTI 2.1 tool provider reference implementation'\n },\n product_family: {\n code: 'similarity detection reference tool',\n vendor: {\n code: 'Instructure.com',\n vendor_name: {\n default_value: 'Instructure'\n },\n description: {\n default_value: 'Canvas Learning Management System'\n }\n }\n }\n }\n end",
"def hash\n strs = FIELDS.collect {|f| \"#{f}:#{send(f).inspect}\"}\n Digest::SHA256.hexdigest(strs.join(' '))\n end",
"def enterable_products\n ids = get_enterable_products\n Hash[*get(ids)['products'].map { |x| [x['name'], x] }.flatten]\n end",
"def product_properties_hash\n product_properties.pluck(:property_id, :value).to_h\n end",
"def catalog_data_hash\n catalog.to_data_hash\n end",
"def auctions_hash_for_product_help()\n a_hash = {\"\" => \"(空白)\"}\n # auction except those product registed\n Auction.select(\"auctions.auction_id, auctions.auction_name\") \\\n .joins(\"LEFT OUTER JOIN pa_maps ON auctions.auction_id = pa_maps.auction_id\") \\\n .where(ope_flg: 1).where(\"pa_maps.auction_id is null\").each do |auction|\n akey = auction.auction_id\n avalue = auction.auction_name\n new_hash = { akey => avalue}\n a_hash.merge! new_hash\n end\n return a_hash\n end",
"def build_initial_hash\n new_hash = {}\n\n # Release context\n release_context = Util::NonNilHashBuilder.build do |h|\n h.add(:commit_hash, ENV['RELEASE_COMMIT'] || ENV['HEROKU_SLUG_COMMIT'])\n h.add(:created_at, ENV['RELEASE_CREATED_AT'] || ENV['HEROKU_RELEASE_CREATED_AT'])\n h.add(:version, ENV['RELEASE_VERSION'] || ENV['HEROKU_RELEASE_VERSION'])\n end\n\n if release_context != {}\n new_hash.merge!({release: release_context})\n end\n\n # System context\n hostname = Socket.gethostname\n pid = Process.pid\n system_context = Contexts::System.new(hostname: hostname, pid: pid)\n new_hash.merge!(system_context.to_hash)\n\n # Runtime context\n thread_object_id = Thread.current.object_id\n runtime_context = {thread_id: thread_object_id}\n new_hash.merge!({runtime: runtime_context})\n\n new_hash\n end",
"def create_products(hash)\n prod_reports = {}\n hash[\"items\"].each do |item|\n report = ProductReport.new\n report.title = item[\"title\"]\n report.description = item[\"description\"]\n report.brand = item[\"brand\"]\n report.stock = item[\"stock\"]\n report.full_price = item[\"full-price\"]\n if item[\"purchases\"] && item[\"purchases\"].length > 0\n item[\"purchases\"].each do |purchase|\n purch = Purchase.new\n purch.channel = purchase[\"channel\"]\n purch.date = purchase[\"date\"]\n purch.price = purchase[\"price\"]\n purch.shipping = purchase[\"shipping\"]\n purch.currency = purchase[\"currency\"]\n purch.user = User.new\n purch.user.name = purchase['user']['name']\n purch.user.state = purchase['user']['state']\n report.add_purchase(purch)\n end\n end\n prod_reports[report.title] = report\n end\n prod_reports\nend",
"def generate_dependencies_info\n components.each_with_object({}) do |component, hsh|\n hsh.merge!(component.get_dependency_hash)\n end\n end",
"def generated_hash\n items = [order_id, amount, response]\n items += [transaction_id, avs_response, cvv_response]\n items << customer_vault_id if customer_vault_id\n items += [time, BraintreeTransparentRedirectSlice.config[:key]]\n Digest::MD5.hexdigest(items.join('|'))\n end",
"def build_initial_hash\n new_hash = {}\n\n # Release context\n release_context = Contexts::Release.from_env\n if release_context\n add_to!(new_hash, release_context)\n end\n\n # System context\n hostname = Socket.gethostname\n pid = Process.pid\n system_context = Contexts::System.new(hostname: hostname, pid: pid)\n add_to!(new_hash, system_context)\n\n # Runtime context\n thread_object_id = Thread.current.object_id\n runtime_context = Contexts::Runtime.new(vm_pid: thread_object_id)\n add_to!(new_hash, runtime_context)\n\n new_hash\n end",
"def generate_hash\n block_contents = timestamp_string + @transactions.to_json.gsub(\"\\\"\", \"'\").gsub(\",\", \", \") + @previous_hash.to_s + @nonce.to_s\n Digest::SHA256.hexdigest block_contents\n end",
"def product_mapping\n return { } unless self.has_split_product_listings?\n if self.name =~ /(RHEL-[0-9].?)(-.+)/\n prefix = $1\n suffix = $2\n else\n prefix = self.name\n suffix = ''\n end\n self.rhel_release.name =~ /(RHEL-[0-9])/\n rhel_pv = ProductVersion.find_by_name $1\n\n variants = Variant.find(:all,\n :conditions =>\n ['product_version_id = ? and id = rhel_variant_id',\n rhel_pv])\n\n names = variants.collect {|v| v.name}.collect {|n| n[1..-1]}\n products = { }\n names.each do |n|\n products[n] = prefix + \"-#{n}\"\n end\n suffix = '-RHX' if suffix == '-RHX-Centric'\n\n if self.is_server_only?\n products.delete_if {|k,v| k != 'Server'}\n end\n\n products.each_pair { |k,v| products[k] = v + suffix}\n return products\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
checks if move is on the board or if the position is taken
|
def valid_move?(board, position)
position.between?(0, 8) && !position_taken?(board, position)
end
|
[
"def valid_move?(board, origin, destination)\n\n end",
"def valid_move?(to_row, to_col, board, color)\r\n return false if super == false\r\n return legal_move?(to_row, to_col, board) && move_not_in_check?(@row, @col, to_row, to_col, board)\r\n\tend",
"def valid_move?\n\t\t@table.stays_on_table?(@robot_direction, @x, @y)\n\tend",
"def position_taken?(board, index)\n board[index] === \"X\" || board[index] ===\"O\" ? true : false\nend",
"def position_taken?(position)\n !@board[position].include?(\" \")\n end",
"def legal_move?(move)\n captured_piece = @board.data[move[0]][move[1]]\n move_current_piece(move)\n king = @king_location || move\n result = safe_king?(king)\n @board.data[move[0]][move[1]] = captured_piece\n result\n end",
"def on_board?(pos)\n pos.all? {|coord| coord.between?(0, SIZE - 1)}\n end",
"def taken?(move)\n x = move.to_i - 1\n @cells[x] == \"X\" || @cells[x] == \"O\"\n end",
"def valid_move?(from_row, from_column, to_row, to_column)\n piece = @state[from_row][from_column]\n return false if piece == nil\n\n new_location = [to_row, to_column]\n return false unless piece.moves.include? new_location\n\n return pawn_valid_move?(piece, new_location, to_column, from_column) if\n piece.class == Pawn\n\n return false unless empty_location?([to_row, to_column]) || \n enemy_piece_at_location?(piece.color, new_location)\n\n unless piece.class == Knight || piece.class == King\n return no_pieces_in_between?(from_row, from_column, to_row, to_column)\n end\n\n true\n end",
"def can_move_to?(position, color)\n @grid.each do |row|\n row.each do |square|\n if (square != nil && square.color == color &&\n square.moves.include?(position))\n return true\n end\n end\n end\n return false\n end",
"def position_taken?(board, position)\n move = position.to_i\n if board[move] == \" \"\n false\n elsif board[move] == \"\"\n false\n elsif board[move] == nil\n false\n else\n true\n end\nend",
"def valid_pawn_move?(start_pos, board, move)\n board.diagonal?(start_pos, move) ||\n (first_move(start_pos) && board.two_ahead?(start_pos, move)) ||\n board.one_ahead?(start_pos, move)\n end",
"def on_board?(position)\n position.all? { |coordinate| coordinate > -1 && coordinate < 8 }\n end",
"def castling_move?(start_x, start_y, end_x, end_y)\n starting_piece = @game_board[start_x][start_y]\n return false if starting_piece.class != King\n #has to be on the same row, column seperated by two\n (start_x == end_x) && (end_y - start_y).abs == 2\n end",
"def valid_piece_movement?(coordinates)\n row = coordinates[:row]\n column = coordinates[:column]\n @active_piece.moves.any?([row, column]) || @active_piece.captures.any?([row, column])\n end",
"def valid_move?\n \n x = @robot.position[0]\n y = @robot.position[1]\n \n # check for direction and the next position\n case @robot.direction\n when \"NORTH\" then (y += 1)\n when \"SOUTH\" then (y -= 1)\n when \"EAST\" then (x += 1)\n when \"WEST\" then (x -= 1)\n end\n\n # check for valid position\n \n if not @table.valid_location?(x, y)\n # don't do anything if invalid\n else \n @robot.move\n end\n\n end",
"def can_move?(start_row, start_col, dest_row, dest_col, color)\n piece = get_piece(start_row, start_col)\n if piece.nil? or piece.is_blank_space? then return false end\n\n moves = piece.get_moves\n piece.color == color and\n moves.include?({ row: dest_row, col: dest_col })\n end",
"def valid_move?(position)\n return false if (position < 0 || position > 8)\n !position_taken?(position)\n end",
"def valid_move_command?(x,y)\n @tb_event && @tb_event.tb_unit.tb_valid_move?(x,y) && $game_map.tbu_id_xy(x,y) == 0\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Generate the video tag +options+ you can specify height/width/allowfullscreen for an individual video here
|
def video_tag(options = {})
options = ActiveRecord::Acts::Cinema::DEFAULT_OPTIONS.merge(options)
video_url = read_attribute(ActiveRecord::Acts::Cinema::SOURCE_PARAM)
width = options[:width]
height = options[:height]
allow_full_screen = options[:allow_full_screen] ? "true" : "false"
# Check the tag option, if a method is assigned,
# call it to get the template string
if options[:tag_template].is_a?(Symbol)
tag_template = self.send options[:tag_template]
else
tag_template = options[:tag_template]
end
ERB.new(tag_template).result(binding)
end
|
[
"def video(*sources)\n options = sources.extract_options!.symbolize_keys\n sources = sources.shift if sources.size == 1\n\n if options[:poster]\n options[:poster] = asset_path(options[:poster])\n end\n\n if size = options.delete(:size)\n options[:width], options[:height] = size =~ /^\\d+x\\d+$/ ? size.split('x') : size\n end\n\n if sources.is_a?(Array)\n content_tag(:video, options) do\n sources.collect { |source| tag(:source, src: asset_path(source)) }.join(\"\\n\")\n end\n else\n tag(:video, options.reverse_merge(src: asset_path(sources)))\n end\n end",
"def render_video_csid options={}\n # render video player\n content_tag(:div) do\n options[:value].collect do |video_csid|\n content_tag(:video,\n content_tag(:source, \"I'm sorry; your browser doesn't support HTML5 video in MP4 with H.264.\",\n src: \"https://webapps.cspace.berkeley.edu/#TENANT#/imageserver/blobs/#{video_csid}/content\",\n id: 'video_csid',\n type: 'video/mp4'),\n controls: 'controls',\n style: 'width: 640px;')\n end.join.html_safe\n end\n end",
"def render_video_csid options = {}\n # render video player\n content_tag(:div) do\n options[:value].collect do |video_csid|\n content_tag(:video,\n content_tag(:source, \"I'm sorry; your browser doesn't support HTML5 video in MP4 with H.264.\",\n src: \"https://webapps.cspace.berkeley.edu/bampfa/imageserver/blobs/#{video_csid}/content\",\n id: 'video_csid',\n type: 'video/mp4'),\n controls: 'controls',\n style: 'width: 640px;')\n end.join.html_safe\n end\n end",
"def embed_video(object, tracks, options={})\n options.symbolize_keys!\n tracks.symbolize_keys!\n\n if options[:class]\n options[:class] = \"video-js vjs-default-skin\"\n else\n options[:class] = options[:class] + \"video-js vjs-default-skin\"\n end\n\n options[:id] = object.teaching.name if options[:id]\n\n controls = 'controls' if options[:controls] == 'true'\n\n options[:preload] = 'none' if options[:preload]\n\n if size = options.delete(:size)\n options[:width], options[:height] = size.split(\"x\") if size =~ %{^\\d+x\\d+$}\n end\n\n puts \"<video \" + controls + options + \" data-setup='{}'>\"\n\n if object.is_a?(Array)\n object.map { |source, type| tag(\"source\", :src => source, :type => type ) }.join.html_safe\n else\n options[:src] = path_to_video(object.teaching.url)\n puts \"<source \" + options[:src] + options[:type] + \" />\"\n end\n\n if false #tracks\n tracks.each do |track|\n \"<track kind='captions' \" + track + \" />\"\n end\n end\n\n puts \"</video>\"\n end",
"def local_video_player(video_id, opts = {})\n ogv = \"/videos/#{video_id}.ogv\"\n mp4 = \"/videos/#{video_id}.m4v\"\n return unless local_video_exists?(ogv) && local_video_exists?(mp4)\n defaults = {\n id: 'js_video_player',\n width: 510,\n height: 290,\n class: 'video-js vsj-default-skin',\n controls: true,\n preload: false,\n poster: '/assets/video_poster_image.png'\n }\n include_video_js_files\n content_tag :video, defaults.merge(opts) do\n \"<source src='#{mp4}' type='video/mp4'/>\n <source src='#{ogv}' type='video/ogg'/>\".html_safe\n end\n end",
"def video_background_with_features(slides, options={})\n default_options = { hide_for_small: true, hide_arrow: false, pattern_overlay: true }\n options = default_options.merge options\n\n hide_for_small = (options[:hide_for_small]) ? \"hide-for-small\" : \"\"\n ret = \"\"\n\n if slides.size > 0\n if slides.pluck(:slide_file_name).find{|f| /^(.*)\\.webm|mp4$/ =~ f}\n fname = $1\n\n video_sources = \"\"\n if webm = slides.find{|f| /webm/i =~ f.slide_content_type && /^#{fname}\\./ =~ f.slide_file_name }\n video_sources += \"<source src='#{ webm.slide.url }' type='#{ webm.slide_content_type }'/>\"\n end\n\n if ogv = slides.find{|f| /ogv/i =~ f.slide_content_type && /^#{fname}\\./ =~ f.slide_file_name }\n video_sources += \"<source src='#{ ogv.slide.url }' type='video/ogg ogv' codecs='theora, vorbis'/>\"\n end\n\n if mp4 = slides.find{|f| /mp4/i =~ f.slide_content_type && /^#{fname}\\./ =~ f.slide_file_name }\n video_sources += \"<source src='#{ mp4.slide.url }' type='#{ mp4.slide_content_type }'/>\"\n end\n poster = slides.find{|f| /jpg|jpeg|png/i =~ f.slide_content_type && /^#{fname}\\./ =~ f.slide_file_name }\n\n ret += content_tag(:video, video_sources.html_safe,\n poster: (poster) ? poster.slide.url : '',\n id: \"video_background\",\n preload: \"auto\",\n autoplay: \"true\",\n loop: \"loop\",\n muted: \"true\",\n volume: 0)\n\n if options[:pattern_overlay]\n ret += content_tag(:div, \"\", id: \"video_pattern\")\n end\n\n if anim = slides.find{|f| /gif/i =~ f.slide_content_type && /^#{fname}\\./ =~ f.slide_file_name }\n ret += content_tag(:div, class: \"bg-gif\") do\n image_tag( anim.slide.url, lazy: false )\n end\n elsif poster\n ret += content_tag(:div, class: \"bg-gif\") do\n image_tag( poster.slide.url, lazy: false )\n end\n end\n\n if website.homepage_headline\n if website.homepage_headline_product_id\n headline_slide = content_tag(:h1, website.homepage_headline)\n product = Product.find(website.homepage_headline_product_id)\n if product.name.match(/^\\d*$/)\n headline_slide += content_tag(:p, \"#{product.name} #{product.short_description_1}\")\n else\n headline_slide += content_tag(:p, product.name)\n end\n headline_slide += link_to(\"Learn More\", product, class: \"secondary button\")\n if product.in_production?\n headline_slide += buy_it_now_link(product, html_button: true)\n end\n elsif website.homepage_headline_product_family_id\n product_family = ProductFamily.find(website.homepage_headline_product_family_id)\n headline_slide = content_tag(:h1, product_family.name.titleize)\n headline_slide += content_tag(:p, website.homepage_headline)\n headline_slide += link_to(\"Learn More\", product_family, class: \"button\")\n else\n headline_slide = content_tag(:h1, website.homepage_headline)\n end\n headline_class = website.homepage_headline_overlay_class || \"large-6 small-12 columns\"\n ret += content_tag(:div, class: 'row headline_slide') do\n content_tag(:div, headline_slide, class: headline_class )\n end\n else\n ret += content_tag(:div, class: \"container\", id: \"feature_spacer\") do\n if options[:tagline]\n content_tag(:h1, website.tagline, id: \"tagline\")\n end\n end\n end\n\n ret = content_tag(:div, ret.html_safe, id: \"video-container\", class: hide_for_small)\n ret += content_tag(:div, \"\", class: \"bouncing-arrow\") unless options[:hide_arrow]\n @leftover_slides = slides.reject{|f| /^#{fname}\\./ =~ f.slide_file_name }\n\n else\n\n ret += content_tag(:div, class: \"row\") do\n content_tag(:div, class: \"large-12 #{ hide_for_small } columns\") do\n orbit_slideshow(slides: slides, duration: 6000, navigation_arrows: false, transition: \"fade\")\n end\n end\n\n end\n end\n\n raw(ret)\n end",
"def process_video(options = {})\n vzaar_video_id = nil\n request_xml = %{\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <vzaar-api>\n <video>\n <guid>#{options[:guid]}</guid>\n <title>#{options[:title]}</title>\n <description>#{options[:description]}</description>\n <profile>#{options[:profile]}</profile>\n }\n if !options[:transcoding].nil?\n request_xml += %{\n <transcoding>#{options[:transcoding]}</transcoding>\n }\n end\n request_xml += %{ \n </video>\n </vzaar-api>\n }\n auth_connection HTTP_POST, '/api/videos', request_xml do |response_body|\n vzaar_video_id = get_video_id_from_response_body(response_body)\n end\n vzaar_video_id\n end",
"def oembed_options\n { :maxwidth => \"560\", :maxheight => \"315\" }.merge(options[:oembed]||{})\n end",
"def render_video(url, size=:medium)\n\n\t\tif (size == :small)\n\t\t\twidth = 450\n\t\t\theight = 300\n\t\telsif (size == :medium)\n\t\t\twidth = 720\n\t\t\theight = 480\n\t\telsif (size == :large)\n\t\t\twidth = 800\n\t\t\theight = 450\n\t\tend\n\t\tiframe_string = \"<iframe src='#{url}\"\n\t\tiframe_string += \"?color=#{$player_color}&portrait=0&title=0&byline=0%api=1&player_id=' \" # some paramaters for the player\n\t\tiframe_string += \"width='#{width}' height='#{height}' \"\n\t\tiframe_string += \"frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>\"\n\n\t\treturn iframe_string.html_safe\n\n\tend",
"def video_url(source, options = T.unsafe(nil)); end",
"def create_video_object(obj)\n return content_tag(:div, content_tag(:iframe, \"\", :src => obj.link, :width => \"100%\"), :style => \"position:absolute; top: #{obj.y}px; left: #{obj.x}px;\")\n end",
"def new_video\n FFMpegCommand << \"-newvideo\"\n end",
"def video_gen(slide)\n term = slide['term']\n kind = slide['kind']\n index = slide['index']\n audio = slide['audio']\n image = slide['image']\n raise \"audio is required fof #{term}\" unless audio\n raise \"image is required fof #{term}\" unless image\n file_name = file_name_gen(slide, \".mpg\")\n audio = command_arg(slide['audio'])\n image = command_arg(slide['image'])\n video = command_arg(file_name)\n `ffmpeg -loop 1 -y -i #{image} -i #{audio} -acodec libmp3lame -vcodec mpeg4 -shortest -qscale:v 1 #{video}`\n slide['video'] = file_name\nend",
"def extra_video_options_for_format(format)\n case format.to_s\n when 'flv'\n '-ar 44100 -qmax 30'\n else\n '' \n end\n end",
"def video=(value)\n @video = value\n end",
"def video(filename, opts = {})\n n = input(filename, opts)\n @videos << n\n n\n end",
"def guided_tour_video\n video_path = params[:video_path]\n render :partial => 'shared/flvplayer', :locals => { :video_path => video_path, :width => nil, :height => nil, :padding => nil }\n end",
"def video_url(opts={})\n if original_file_name\n file = opts[:format].nil? ? original_file_name : original_file_name.sub(/\\.[^.]+$/, \".#{opts[:format].to_s}\")\n \"#{media_host}/video/#{file}\"\n end\n end",
"def set_movie_common_options\n set_parameter :MovieFileFormat, options[:format]\n set_parameter :MovieQuality, options[:quality]\n set_parameter :SteadyMode, options[:steady]\n set_parameter :ColorSetting, options[:color]\n set_parameter :WindNoiseReduction, options[:noise]\n set_parameter :AudioRecording, options[:audio]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Public: Prints the elements inside tree nodes in a PARENT LEFT RIGHT manner x Node, Preferably a root node Examples NOTE: Based on the mock tree structure at LINE:61 preoder_tree_walk(F) => F B A D C E G I H
|
def preoder_tree_walk(x)
unless x.nil?
p x.key
preoder_tree_walk(x.left)
preoder_tree_walk(x.right)
end
end
|
[
"def print_tree(tree)\n return \"-\" if tree.nil?\n puts \"#{tree.value}: \"\n print \"Left: \"\n puts \"#{print_tree(tree.children[0])}\"\n print \"Right: \"\n puts \"#{print_tree(tree.children[1])}\"\nend",
"def print_tree\n space = 0\n print_tree_helper(@root, space)\n end",
"def left_side_of_tree(root, current_level)\n return if root.nil?\n if (current_level > @max_level)\n puts root.val\n @max_level = current_level\n end\n left_side_of_tree(root.left, current_level + 1)\n left_side_of_tree(root.right, current_level + 1)\nend",
"def pre_order_traversal(tree_node)\n # visit root node\n p tree_node\n\n if tree_node.left\n pre_order_traversal(tree_node.left)\n end\n\n if tree_node.right\n pre_order_traversal(tree_node.right)\n end\nend",
"def print_preorder\n return \"Empty BST\" if is_empty\n\n stack = [@root]\n\n until stack.empty?\n current = stack.pop\n\n puts current.value\n\n stack << current.right unless current.right.nil?\n stack << current.left unless current.left.nil?\n end\n end",
"def print_tree\n if root.children\n puts \" - root : #{root.children.length} - \"\n root.children.each(&:print_node)\n puts ''\n end\n end",
"def preorder(node)\n p node.value if node.value \n preorder(node.left) if node.left\n preorder(node.right) if node.right\nend",
"def print_tree\n @tree.print_tree\n end",
"def print_tree(lines)\n width = 1\n curr_line = 1\n while curr_line < lines - 1 do\n width += 2\n curr_line += 1\n end\n\n xout = 0\n lines.times do\n startx = ((width - 1) / 2) \n printx = 0\n width.times do\n if printx >= startx - xout && printx <= startx + xout\n print('X')\n else\n print('-')\n end\n printx += 1\n end\n xout += 1\n print(\"\\n\")\n end\nend",
"def level_order_print(tree)\n unless tree\n return\n end\n\n nodes = [tree]\n current_line_count = 1\n next_line_count = 0\n\n while nodes.length != 0\n current_node = nodes.shift\n current_line_count -= 1\n print current_node.key.to_s + ' '\n if current_node.left_child\n nodes.push(current_node.left_child)\n next_line_count += 1\n end\n if current_node.right_child\n nodes.push(current_node.right_child)\n next_line_count += 1\n end\n if current_line_count == 0\n # finished printing current level\n puts ''\n current_line_count = next_line_count\n next_line_count = current_line_count\n end\n end\nend",
"def print_tree(node)\r\n return CATEGORY_NOT_FOUND unless node\r\n \r\n result, = print_rec(node) # grab the ASCII string from the array\r\n result.shift # remove the extra vertical bar\r\n puts result.join(\"\\n\") # print the result\r\n end",
"def test_print_tree\n setup_test_tree\n #puts\n #@root.print_tree\n end",
"def print_prefix(node)\n return if node == nil\n print node.value + \" \" #print contents of this node\n print_prefix(node.left) #starts recursion -- go left\n print_prefix(node.right) #go right\nend",
"def draw_left(node, parent_x, parent_y, block)\n if node.right != nil\n count = 1 + children_count(node.right)\n else\n count = 0\n end\n x = parent_x - @x_distance - (count*@x_distance)\n y = parent_y + @y_distance\n block.call(node.value, x, y, parent_x, parent_y)\n \n draw_left(node.left, x, y, block) if node.left != nil\n draw_right(node.right, x, y, block) if node.right != nil\n end",
"def print_tree(tree)\n\t\t\tif tree.is_leaf? and tree.depth > 0\n\t\t\t\tprint_line((\"|\\t\"*(tree.depth-1))+\"+------\"+tree.name)\n\t\t\telse\n\t\t\t\tprint_line((\"|\\t\"*tree.depth)+tree.name)\n\t\t\tend\n\t\t\ttree.children.each_pair do |name,child|\n\t\t\t\t\tprint_tree(child)\n\t\t\tend\n\t\tend",
"def preorder_traversal_to_file(root=@root,f)\n f.write root.data\n f.write \",\"\n if root.left!=nil\n preorder_traversal_to_file(root.left,f)\n end\n if root.right!=nil\n preorder_traversal_to_file(root.right,f)\n end\n end",
"def preorder\n if @root == nil\n return\n end\n\n stack1 = Stack.new()\n stack1.push(@root)\n while stack1.empty? == false # while stack is not empty\n current = stack1.pop() # pop from stack\n print \" #{current.data}\" # print its value\n stack1.push(current.right) if current.right != nil\n stack1.push(current.left) if current.left != nil\n end\n print \"\\n\"\n end",
"def print_level_order\n return \"Empty BST\" if is_empty\n\n queue = [@root]\n\n until queue.empty?\n current = queue.pop\n puts current.value\n\n queue << current.left unless current.left.nil?\n queue << current.right unless current.right.nil?\n end\n end",
"def print_level_order(root)\n return if !root\n queue = Queue.new()\n queue.enqueue(root)\n total_nodes_in_current_level = 1\n total_nodes_in_next_level = 0\n\n while (!queue.is_empty?) # as long as the queue is not empty\n current_node = queue.dequeue\n\n # we print current_node's value and decrement total_nodes_in_current_level by 1. We then add its children (if any) to the queue and increment total_nodes_in_next_level by 2.\n print current_node.value, \" \"\n total_nodes_in_current_level -= 1\n\n queue.enqueue(current_node.left_child) if current_node.left_child\n queue.enqueue(current_node.right_child) if current_node.right_child\n total_nodes_in_next_level += 2\n\n if total_nodes_in_current_level == 0 # this means we finished printing the node values in the current node\n print \"\\n\"\n # swap total_nodes_in_current_level and total_nodes_in_next_level\n total_nodes_in_current_level = total_nodes_in_next_level\n total_nodes_in_next_level = total_nodes_in_current_level\n end\n end\n print \"\\n\"\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Calculates the minimum element in a row
|
def min (row_num)
row = @rows[row_num]
min = row[0]
row.each do |num|
if min == 0 then
min = num
end
if (num < min) && (num != 0) then
min = num
end
end
return min
end
|
[
"def min\n encontrado = false\n value = 0\n i = -1\n # Se revisan todos los elementos de la matriz.\n while encontrado == false\n i += 1\n j = 0\n while j < self.cols\n if self[i][j] != nil and value == 0\n value = self[i][j]\n encontrado = true\n break\n else\n j += 1\n end\n end\n end\n # Se recorre la matriz y se asigna un valor menor en caso de encontrarlo a la variable value.\n @rows.times do |i|\n @cols.times do |j|\n if self[i][j] != nil && self[i][j] < value\n value = self[i][j]\n end\n end\n end\n # Se retorna el minimo de los elementos de la matriz.\n value\n end",
"def min\n # Establecemos valor del primer elemento\n min = @matrix[0][0]\n i = 0\n \n # Fila a fila actualizando el valor minimo\n while (i < @fil)\n j = 0\n while (j < @col)\n if (@matrix[i][j] < min)\n min = @matrix[i][j]\n end\n j += 1\n end\n i += 1\n end\n min\n end",
"def minimum(column_name)\n calculate(:minimum, column_name)\n end",
"def find_smallest(d)\n\tmin = d[1][0]\n\tmin_row = 1\n\tmin_col = 0\n\t(0...(d.size-1)).each do |col|\n\t\t((col+1)...d.size).each do |row|\n\t\t\tif (d[row][col] < min)\n\t\t\t\tmin_row = row\n\t\t\t\tmin_col = col\n\t\t\t\tmin = d[row][col]\n\t\t\tend\n\t\tend\n\tend\n\treturn min,min_row,min_col\nend",
"def step_one\n matrix.map_rows! do |row|\n min = row.min\n row.map { |cell| cell - min }\n end\n end",
"def min(column)\n run.min(column)\n end",
"def min() end",
"def min(column_name)\n calculate(:min, column_name)\n end",
"def minimum(arr)\n m = arr.min\n m\n end",
"def min(&block)\n flag = true # 1st element?\n result = nil\n self.each{|*val|\n val = val.__svalue\n if flag\n # 1st element\n result = val\n flag = false\n else\n if block\n result = val if block.call(val, result) < 0\n else\n result = val if (val <=> result) < 0\n end\n end\n }\n result\n end",
"def min(column)\n get(:min[column])\n end",
"def min_on_left(arr, x, y)\n raise ArgumentError, \"x coordinate cannot exceed number of rows\" unless x < arr.length\n if x == 0\n 0\n else\n raise ArgumentError, \"y coordinate cannot exceed length of column (x - 1)\" unless y < arr[x-1].length\n if y == 0\n [arr[x-1][y], arr[x-1][y+1]].min\n elsif y == (arr[x-1].length - 1)\n [arr[x-1][y-1], arr[x-1][y]].min\n else\n [arr[x-1][y-1], arr[x-1][y], arr[x-1][y+1]].min\n end\n end\n end",
"def min(column)\n _all_with_present_column(column).min\n end",
"def minimum(column_name, options = {})\n calculate(:minimum, column_name, options)\n end",
"def min(attr)\n column(attr).min\n end",
"def minimum_value(table, expr)\n min_or_max_value(table, expr, false)\n end",
"def find_min_in_nested_arrays(src)\n results_array = []\n \n row_index = 0 \n while row_index < src.count do \n row = src[row_index]\n column_index = 0 \n smallest_element = row[column_index]\n \n while column_index < row.count do\n if row[column_index] < smallest_element\n smallest_element = row[column_index]\n end\n column_index += 1 \n end\n \n results_array << smallest_element\n row_index += 1\n end\n results_array\nend",
"def find_min_value(array)\n x = array[0]\n array.length.times { |i| x = array[i] if array[i] < x}\n x\nend",
"def find_min\r\n return nil if !@head\r\n cursor = @head\r\n min = cursor.data\r\n while cursor\r\n if cursor.data < min\r\n min = cursor.data\r\n end\r\n cursor = cursor.next\r\n end\r\n return min\r\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Calculates the common factor of a row
|
def has_common (row_num, row_min)
row = @rows[row_num]
result = false
if row_min != 0 then
result = true
row.each do |num|
if result == true then
if (num != 0) && ((num.abs).modulo(row_min.abs) != 0) then
result = false
end
end
end
end
return result
end
|
[
"def common_x\n ah, bh, ch = [a,b,c].map {|arr| arr.each_with_object(Hash.new(0)) {|e,h| h[e] += 1}}\n (a & b & c).inject(0) {|sum, e| sum += e * [ah[e], bh[e], ch[e]].min}\nend",
"def getCommonClass(rows)\n return rows.inject(rows[0].class) { |klass, el| break if klass != el.class ; klass }\nend",
"def greatest_common_factor(arr)\n gcf = nil\n sorted = arr.sort\n factor_sets = sorted.map { |n| find_all_factors(n) }\n\n common_factors = factor_sets.shift\n factor_sets.each do |set|\n common_factors &= set\n end\n\n common_factors.max\n end",
"def is_strong_intersection?(row, column)\n return((row+column).even?)\n end",
"def greatest_common_factor(first_number, second_number)\n \nend",
"def row_checksum(row)\n row = row.split\n row = row.map(&:to_i)\n row = row.sort\n\n row.length.times do\n numerator = row.pop\n\n row.each do |denominator|\n return numerator / denominator if numerator % denominator == 0\n end\n end\nend",
"def greatest_common_factor(first_number, second_number)\nend",
"def least_common_multiple(num_1, num_2)\n num_1, num_2 = [num_1, num_2].sort\n\n (1..num_2).each do |i|\n mutiple_1 = num_1 * i\n\n return mutiple_1 if mutiple_1 % num_2 == 0\n end\nend",
"def most_common_value\n class_var = @tree.class_var\n class_values = @tree.dataset.column_values(class_var)\n count = class_values.each.with_object({}) do |val, o|\n o[val] = 0\n end\n self.subset.each.with_object(count) do |row, o|\n count[row[class_var]] += 1\n end\n count.max_by{|v, c| c}[0]\n end",
"def smallest_common_multiple(n)\n\n\treturn 0\nend",
"def least_common_multiple(num_1, num_2) # Important\n num_1_prime = find_prime_factors(num_1)\n num_2_prime = find_prime_factors(num_2)\n lcm = 1\n num_1_prime.each do |k, v|\n greater_power = v > num_2_prime[k] ? v : num_2_prime[k]\n num_2_prime.delete(k) # delete key-val pair from num_2_prime\n lcm = lcm * (k ** greater_power)\n end\n\n # if num_2_prime is not empty, add their key-value in lcm\n if !num_2_prime.empty?\n num_2_prime.each do |k, v|\n lcm = lcm * (k ** v)\n end\n end\n lcm\nend",
"def same_prime_factors_v2(max)\n (2...max).find_all do |num|\n num_r = num.digits.join.to_i\n num_r != num && num.prime_division.map(&:first) == num_r.prime_division.map(&:first)\n end\nend",
"def check(sheet)\n cells = sheet.map {|row| row.split.map {|cell| cell.to_i} }\n\n total = 0\n\n cells.each do |row|\n row.each do |cell|\n row.each do |divisor|\n dividend, modulo = cell.divmod(divisor)\n total += dividend if modulo == 0 && dividend != 1\n end\n end\n end\n\n total\nend",
"def calculateFactors()\n @factorHash = getCachedResult(@sourceArray)\n if !@factorHash.nil?\n return @factorHash\n end\n @factorHash = {}\n for i in 0...@sourceArray.length do\n tempArray = []\n for j in 0...@sourceArray.length do\n # don't compare the same number and don't modulus a zero\n if (i == j ||\n @sourceArray[j] == 0)\n next\n end\n # if i modulus j is 0, then j is a factor of i\n if (@sourceArray[i] % @sourceArray[j] == 0)\n tempArray.append(@sourceArray[j])\n end\n end\n # add entry to the hash, i is the key and the array of factors is the value\n @factorHash[@sourceArray[i]] = tempArray\n end\n storeCalculation(@sourceArray, @factorHash)\n return @factorHash\n end",
"def find_common_letter(rucksack)\n (rucksack[0] & rucksack[1])[0]\n end",
"def contingency_coefficient\n c_s = chi_square\n Math.sqrt(c_s / (table_sum_all + c_s) )\n end",
"def same_row?(row)\n end",
"def mutual_factors(*args)\n div_hash = Hash.new\n args.each do |num|\n div_hash[num] = divisors(num)\n end\n common_divisors(div_hash.values)\nend",
"def common_divisor(int1, int2)\n smallest_possible = [int1, int2].min\n possibilities = smallest_possible.downto(1).to_a\n\n possibilities.each do |i|\n return i if int1 % i == 0 && int2 % i == 0\n end\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Divides a whole row by its common factor (Row , Common Factor)
|
def reduce (row_num, row_min)
row = @rows[row_num]
for i in 0..(row.length - 1) do
@rows[row_num][i] = (@rows[row_num][i])/row_min
if @rows[row_num][i] == -0.0 then
@rows[row_num][i] = 0.0
end
end
num, den = row_min.to_fraction
if den == 1 then
puts "R#{row_num + 1} -> R#{row_num + 1}/#{num}"
else
puts "R#{row_num + 1} -> R#{row_num + 1}/(#{num}/#{den})"
end
end
|
[
"def div_row_vector!(s); divi_row_vector(s); end",
"def divide_constant(matrix, constant)\n mat = clone_matrix(matrix)\n constant = constant.to_f\n mat.each do |row|\n row.map! do |element|\n element / constant\n end\n end\n return mat\nend",
"def row_checksum(row)\n row = row.split\n row = row.map(&:to_i)\n row = row.sort\n\n row.length.times do\n numerator = row.pop\n\n row.each do |denominator|\n return numerator / denominator if numerator % denominator == 0\n end\n end\nend",
"def divide_by(iFactor)\n case @Function[:FunctionType]\n when FCTTYPE_PIECEWISE_LINEAR\n @Function[:Points].each do |ioPoint|\n ioPoint[1] /= iFactor\n end\n else\n log_err \"Unknown function type: #{@Function[:FunctionType]}\"\n end\n end",
"def divide_line_by(i,pivot, m)\n for j in 1..m[0].size-1\n m[i][j] /= pivot.to_f\n end\n print \"Dividir L#{i} por #{pivot}\".italic.blue \n m\nend",
"def fdiv(other)\n if other.is_a? Array\n raise \"Incorrect Dimensions\" unless self.size == other.size\n other = other.dup\n self.class.new(map { |i| i.fdiv other.shift })\n elsif other.is_a?(Integer) or other.is_a?(Float)\n self.class.new(map { |i| i.fdiv other })\n else\n super\n end\n end",
"def factors\n 1.upto(Math.sqrt(self)).select { |i| (self % i).zero? }.inject([]) do |f, i|\n f << self / i unless i == self / i\n f << i\n end.sort\n end",
"def calculate_proper_divisors\n return [] if self == 1\n result = [1]\n 2.upto(Math.sqrt(self).floor) do |candidate|\n # add both candidate and quotient, since they are both divisors\n result << candidate << (self / candidate) if self % candidate == 0\n end\n result.sort.uniq # uniq is needed for perfect squares\n end",
"def check(sheet)\n cells = sheet.map {|row| row.split.map {|cell| cell.to_i} }\n\n total = 0\n\n cells.each do |row|\n row.each do |cell|\n row.each do |divisor|\n dividend, modulo = cell.divmod(divisor)\n total += dividend if modulo == 0 && dividend != 1\n end\n end\n end\n\n total\nend",
"def div(other)\n if other.is_a? Array\n raise \"Incorrect Dimensions\" unless self.size == other.size\n other = other.dup\n self.class.new(map { |i| i.div other.shift })\n elsif other.is_a?(Integer) or other.is_a?(Float)\n self.class.new(map { |i| i.div other })\n else\n super\n end\n end",
"def divide_hash ( h, divisor )\n Hash[h.map { |k,v| [k, v = v.to_f/divisor.to_f] }]\n end",
"def divide_set(column, divider_value, data_set=data)\n\t\t\ttrue_set = []\n\t\t\tfalse_set = []\n\n\t\t\tdata_set.each do |row|\n\t\t\t\tif compare?(row[column], divider_value)\n\t\t\t\t\ttrue_set << row\n\t\t\t\telse\n\t\t\t\t\tfalse_set << row\n\t\t\t\tend\n\t\t\tend\n\t\t\t[true_set, false_set]\t\n\t\tend",
"def pre_divide; end",
"def meanColumns(rows)\n sums = Array.new(rows[0].size(), 0)\n\n rows.each{|row|\n row.each_index{|i|\n sums[i] += row[i]\n }\n }\n\n return sums.map{|sum| sum / rows.size().to_f()}\nend",
"def divide(arr)\n do_math(arr) do |a, b|\n if 0 == a || 0 == b\n 0\n else\n a.to_f / b rescue 0\n end\n end\n end",
"def fdiv(numeric)\n #This is a stub, used for indexing\n end",
"def prime_rows(row)\n size = row.length\n size.times.collect {|i|\n interval = row[i]<row[0] ? (row[i]-row[0]) : (row[i]-row[0]-size)\n size.times.collect {|j|\n (row[j]-interval) % size\n }\n }\n end",
"def div(numeric)\n #This is a stub, used for indexing\n end",
"def call_div(reg_key, addr, i_reg, m_spec)\n mem_addr = get_mem_addr(addr, i_reg)\n\n adder = @computer.memory.read(mem_addr, m_spec[:l], m_spec[:r])\n num1 = @registers['A'].word.to_i\n num2 = adder.to_i\n @registers['A'].word.from_int(num1 / num2)\n @registers['X'].word.from_int(num1 % num2)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Swaps two rows with each other (Index 's)
|
def swap (row1, row2)
row1_copy = @rows[row1]
row2_copy = @rows[row2]
new_row1 = row2_copy
new_row2 = row1_copy
@rows[row1] = new_row1
@rows[row2] = new_row2
puts "R#{row1 + 1} <-> R#{row2 + 1}"
end
|
[
"def swap_rows ( r1, r2 )\r\n new_matrix = [] \r\n @matrix.each do |r|\r\n case\r\n when r == row(r1)\r\n new_matrix << row(r2)\r\n when r == row(r2)\r\n new_matrix << row(r1)\r\n else\r\n new_matrix << r\r\n end\r\n end \r\n Matrix.new( new_matrix )\r\n end",
"def swap_line!(matrix, i, j)\n matrix[i], matrix[j] = matrix[j], matrix[i]\n matrix.each { |array| array[i], array[j] = array[j], array[i] }\nend",
"def exchange_rows(p, q)\n tmp = self.row(p)\n replace_row(p, self.row(q))\n replace_row(q, tmp)\n end",
"def swap_indexes(i,j)\n\t\tnew_array = self.dup\n\t\tnew_array[i],new_array[j] = self[j],self[i]\n\t\tnew_array\n\tend",
"def swap_with_index(i1, i2)\n v1 = self[i1]\n v2 = self[i2]\n self[i1] = v2\n self[i2] = v1\n self\n end",
"def swap_locations(row, col, length, layer)\n # [\n # [row, col],\n # [col, length - 1 + layer],\n # [length - 1 + layer, length - 1 - col],\n # [length - 1 - col, row]\n # ]\n\nend",
"def swap_line!(matrix, i, j)\n\tmatrix[i], matrix[j] = matrix[j], matrix[i]\n\tmatrix.each { |array| array[i], array[j] = array[j], array[i] }\nend",
"def swap(idx1, idx2)\n raise \"index out of range: #{idx1}\" if idx1 >= size()\n raise \"index out of range: #{idx2}\" if idx2 >= size()\n @cards[idx2], @cards[idx1] = [@cards[idx1], @cards[idx2]]\n end",
"def swap_gene_positions(index_1, index_2)\n tmp_gene = @genes.at(index_1)\n @genes[index_1] = @genes[index_2]\n @genes[index_2] = tmp_gene\n end",
"def swap\n @store[-1], @store[-2] = @store[-2], @store[-1] if size > 1\n end",
"def swapper(arr, idx_1, idx_2)\n temp = arr[idx_1]\n arr[idx_1] = arr[idx_2] # as soon as I execute this line, it will be [\"c\", \"b\", \"c\", \"d\"]\n arr[idx_2] = temp # then, I excute this line, then it will be [\"c\", \"b\", \"c\", \"d\"], which is wrong!\n arr\n\nend",
"def swap(seq, x, y)\n tmp = seq[x]\n seq[x] = seq[y]\n seq[y] = tmp\nend",
"def weave2 other\n zip( other ).map { |row1, row2| row1.weave row2 }\n end",
"def swap swap_index\n new_cells = cells.clone\n new_cells[zero_position] = new_cells[swap_index]\n new_cells[swap_index] = 0\n Puzzle.new new_cells\n end",
"def mergerows(row1,row2)\n\t\tif row2 >= @text.length\n\t\t\treturn\n\t\tend\n\t\tcol = @text[row1].length\n\t\t@text[row1] = @text[row1].dup\n\t\t@text[row1] += @text[row2]\n\t\t@text.delete_at(row2)\n\tend",
"def swap(word, index1, index2)\n temp_word = word.dup\n temp_word[index1], temp_word[index2] = temp_word[index2], temp_word[index1]\n return temp_word\nend",
"def swap(index_1, index_2)\n if valid_index?(index_1) && valid_index?(index_2)\n @items[index_1], @items[index_2] = @items[index_2], @items[index_1]\n true\n else\n false\n end\n end",
"def two_swap(path, i, j)\n path[0..i] + path[(i + 1)..j].reverse + path[(j + 1)..-1]\n end",
"def swap_skills_index(index1, index2)\n @skills_set[index1], @skills_set[index2] = @skills_set[index2], @skills_set[index1]\n @skills_set.compact!\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Substitutes Pivot Row (Array Index) with the row you are performing a row operation on (Array Index). Applies cancel_val (See cancel_val above) as the multiplier
|
def substitute (pivot_row_num, cancel_row_num, cancel_val)
for i in 0..(((@rows[pivot_row_num]).length) - 1)
@rows[cancel_row_num][i] = @rows[cancel_row_num][i] - (cancel_val)*(@rows[pivot_row_num][i])
if @rows[cancel_row_num][i] == -0.0 then
@rows[cancel_row_num][i] = 0.0
end
end
num, den = cancel_val.to_fraction
outp = ""
if den == 1 then
outp += "#{num}"
else
outp += "#{num}/#{den}"
end
if (cancel_val < 0) then
puts "R#{cancel_row_num + 1} -> R#{cancel_row_num + 1} - (#{outp})R#{pivot_row_num + 1}"
else
puts "R#{cancel_row_num + 1} -> R#{cancel_row_num + 1} - (#{outp})R#{pivot_row_num + 1}"
end
end
|
[
"def inverted_rows(options = {})\n rows = voucher_rows\n rows.reject!(&:canceled?) unless options[:canceled]\n rows.map do |old|\n vr = old.dup\n vr.sum *= -1\n vr\n end\n end",
"def calculate_table_row(value)\n @row_values.collect {|x| x * value}\n end",
"def replace_row idx, *cells\n if(row = @rows[idx]) && cells.size < row.size\n cells.concat Array.new(row.size - cells.size)\n end\n update_row idx, *cells\n end",
"def call_transform(tform, row)\n if source_cardinality == 0 && target_cardinality == 1\n tform.call\n elsif source_cardinality == 1 && target_cardinality == 1\n tform.call(row[*@source_vectors])\n else\n tform.call(row)\n end\n end",
"def choose_supplier_value(current_cell, value)\n update_result(current_cell, value)\n data.b[current_cell.column] -= value\n increase_row(current_cell)\n end",
"def scalar_subtract!(i)\n to_sparse!(to_matrix.scalar_subtract(i))\n end",
"def subtract_value_from_row_in_array(row_id, value_to_subtract)\n\t\traise 'Row does not exist in array' if row_id >= self.length || row_id < 0\n\t\traise 'Would result in negative value' if self[row_id].dup.map {|x| x.zero? ? value_to_subtract : x}.min < value_to_subtract\n\t\tself[row_id].map! {|x| !x.zero? ? x-value_to_subtract : x }\n\t\treturn self\n\tend",
"def shift(index, pivot, collection)\n index.upto(pivot) do |i|\n collection[i] = collection[i + 1]\n end\n collection\nend",
"def pre_multiply(trans)\n dup.tap { |t| t.pre_multiply!(trans) }\n end",
"def transform_row!(row)\n @row_transform.call(row) unless @row_transform.nil?\n @col_transforms.each do |name, func|\n next unless row.has_key?(name)\n if func.respond_to?(:transform)\n row[name] = func.transform(row[name])\n else\n row[name] = func.call(row[name])\n end\n end\n end",
"def translateAnswerRow( valArr )\n valStr = \"\"\n index = 0\n valArr.each { |value|\n valStr += ( translateFromFillValue( value, index ) + \",\" )\n index = index + 1\n }\n valStr\n end",
"def multiplier(board, row, column, direction, index)\n if direction == VERTICAL\n board[row + index][column]\n else\n board[row][column + index]\n end\n end",
"def subtract_value(index)\n val = @puzzle[index]\n if val != \".\"\n row = @rows[calculate_row(index)]\n row.delete_at(row.index(val) || row.length)\n\n column = @columns[calculate_column(index)]\n column.delete_at(column.index(val) || column.length)\n\n box = @boxes[calculate_box(index)]\n box.delete_at(box.index(val) || box.length)\n end\n end",
"def multiply_row(matrix, index, number)\n matrix = matrix.row(index).map{ |n| n * number }\n end",
"def calculate_row(index)\n index/9\n end",
"def subtract_row(linear_task, from, which)\n which_col = restriction_to_var(which)\n from_col = restriction_to_var(from)\n\n linear_task.b[from] = linear_task.b[from] - linear_task.a[from, which_col] * linear_task.b[which] / linear_task.a[which, which_col]\n log(\"b[#{from}] = #{linear_task.b[from]}\")\n\n 0.upto(from_col - 1) do |j| # upto from_col, not which_col becase we can subtract not only neighbour rows\n log(\"a[#{from}, #{j}] = a[#{from}, #{j}] - a[#{from}, #{which_col}] * a[#{which}, #{j}]\")\n log(\"= #{linear_task.a[from, j]} - #{ linear_task.a[from, which_col]} * #{linear_task.a[which, j]}\")\n linear_task.a[from, j] = linear_task.a[from, j] - linear_task.a[from, which_col] * linear_task.a[which, j] / linear_task.a[which, which_col] # linear_task.a[which, which_col] = 1 or -1\n log(\"= #{linear_task.a[from, j]}\")\n end\n # values in columns more than from_col should be zero anyway\n end",
"def transformed_rows\n work_rows.map do |row|\n @transform_procs.each do |tform|\n result = call_transform(tform, row)\n row[*@target_vectors] = result if target_cardinality == 1\n row[*@source_vectors] = result if source_cardinality == 1 && target_cardinality == 1\n end\n\n row\n end\n end",
"def rotate_row(canvas, row, shift)\n # Pop the value of the end, and move it to the front.\n shift.times { canvas[row].unshift(canvas[row].pop) }\nend",
"def add_a_to_plan(cell)\n a = data.a[cell.row]\n result[cell] = a\n data.remove_row!(cell.row)\n data.b[cell.column] -= a\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Prints matrix to Standard Output
|
def print_matrix
width = @rows.flatten.max.to_s.size
if width > 4 then
width = width - 0.5
end
puts @rows.map { |a|
"|#{ a.map { |i|
outp = ""
num, den = i.to_fraction
if den == 1 then
outp += "#{num}"
else
outp += "#{num}/#{den}"
end
"#{outp.rjust(width)} |"
}.join }"
}
puts "↓"
end
|
[
"def print_matrix\n @matrix.each do |m|\n print \"#{m}\\n\"\n end\n end",
"def print_matrix\n $matrix.each do |rows|\n rows.each do |col|\n puts col\n end\n end\n end",
"def pretty_print\n puts\n puts \"Matrix:\\n\"\n puts @matrix.to_a.map(&:inspect)\n puts\n end",
"def print\n @maze[:matrix].each do |line|\n puts line.join\n end\n end",
"def disp_matrix(m)\n for i in 0...m.length\n print '| '\n for j in 0...m[0].length\n print m[i][j].to_s + ' '\n end\n puts '|'\n end\n end",
"def print_annotated_matrix matrix, io=$stdout\n labels = self.stations.map {|s| s.label}\n\n # clear diagonal\n (0...(matrix.size)).each do |i| matrix[i][i] = \"\"; end\n\n io.puts <<OD\n\\t#{labels.join(\"\\t\")}\n#{labels.zip(matrix).map {|row| row.flatten.join(\"\\t\")}.join(\"\\n\")}\nOD\n end",
"def show_board\n @matrix.each do |row|\n print row.to_s\n print \"\\n\"\n end\n end",
"def dump_matrix(*arg)\n matrix = self.to_matrix(*arg)\n sorted = @index.sort {|a,b| a[1] <=> b[1]}\n \"[# \" + sorted.collect{|x| x[0]}.join(\", \") + \"\\n\" +\n matrix.to_a.collect{|row| ' ' + row.inspect}.join(\",\\n\") + \"\\n]\"\n end",
"def printmatrixTofile(inputmatrix,outfilePath)\n outfile=File.open(outfilePath,\"w\")\n for ii in 0...inputmatrix.row_size \n line=\"\"\n for jj in 0...inputmatrix.column_size\n line=\"#{line}\\t#{inputmatrix.[](ii,jj)}\" \n end\n outfile.puts line.strip!\n end\n outfile.close()\n end",
"def print_mat(matrix, delim=nil)\n puts matrix.map{|x| delim ? x.join(delim) : x.inspect}\nend",
"def display\n\t\t@adj_matrix.each do |sublist|\n\t\t\tsublist.each do |item|\n\t\t\t\tprint \"%s \" % item\n\t\t\tend\n\t\t\tputs \"\\n\"\n\t\tend\n\t\tputs @nmap\n\tend",
"def display\n\t\tdisplay_maze = @maze_matrix.map { |row| row.map {|e| e == \"*\" ? \"*\" : e == 1 ? \"|\" : \"o\" }}\n\t\tdisplay_maze.each {|row| print \"#{row.join}\\n\"}\n\t\tputs\n\tend",
"def print\n $stdout.sync = true ; $stderr.sync = true\n each do |row|\n row.each_with_index do |entry, field|\n $stdout.write entry\n max_width = column_widths[field] + spacer\n unless entry.size >= max_width\n num_spaces = max_width - entry.size\n pad = \" \" * num_spaces\n $stderr.write(pad)\n end\n end\n $stdout.write \"\\n\"\n end\n end",
"def print\n displayBoard = []\n @board.each_with_index { |elem, index|\n if index % @columns == 0\n displayBoard.push(\"\\n\")\n end\n displayBoard.push(elem)\n }\n puts displayBoard.join\n end",
"def matrixToString(matrix)\n end",
"def print_annotated_od_matrix matrix, station_names, io=STDOUT, no_diag=true\n raise \"station names do not match matrix\" if\n station_names.size != matrix.size\n\n io.puts \"\\t\" + station_names.join(\"\\t\")\n matrix.each_with_index do |row, i| \n row = row.dup\n row[i] = '' if no_diag\n io.puts station_names[i] + \"\\t\" + row.join(\"\\t\")\n end\n\n nil\n end",
"def form(matrix, io = $stdout, indent = 0)\n #Obtain max length for each column.\n\n matrix = matrix.transpose if @transpose\n\n max_lengths = []\n matrix.each do |row|\n row.each_with_index do |item, index|\n item = item.to_s\n max_lengths[index] ||= 0\n size = print_size(item)\n max_lengths[index] = size if max_lengths[index] < size\n end\n end\n\n #Output\n matrix.each do |row|\n new_items = []\n row.each_with_index do |item, index|\n item = item.to_s\n method = (@just.to_s + \"_just\").to_sym\n new_items[index] = item.send(method, max_lengths[index])\n end\n io.print(\" \" * indent)\n io.puts new_items.join(@separator).sub(/ +$/, \"\")\n end\n end",
"def print_board\n print to_s\n # @board.each do |row|\n # row.each do |square|\n # print \" #{square.number} \"\n # end\n # puts \"\"\n # end\n end",
"def paintMatrix(a)\n\t\n\tputs \" | 1 | 2 | 3 | 4 | 5 | 6\".green\n\tputs \"\"\n\tfor i in 0..5\n\t\tif ( i != 0 )\n\t\tputs \" \"\n\t\tend\n\t\tfor j in 0..5\n\t\t\t\tprint \" | \".blue\n\t\t\t\tprint \"#{a[i][j]}\"\n\t\tend\n\t\tputs \"\"\n\tend\n\tputs\"\"\n\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get process information by command 'ps auxw | grep serverId | grep pid'
|
def get_ps_info args={}, &block
return if OS.windows?
pid = args[:pid]
EM.system('sh', proc{ |process|
process.send_data "ps auxw | grep " + pid.to_s + " | grep -v 'grep'\n"
process.send_data "exit\n"
}) { |output, status|
if status.exitstatus == 0
format args, output, &block
else
block.call status, nil if block
end
}
end
|
[
"def ps\n `ps haxo pid,ppid,cmd`\n end",
"def mon_pid\n shell = systemu(\"ps auxw | grep -v grep | grep bixby-monitoring-daemon\")\n lines = shell.stdout.split(/\\n/).reject{ |s| s.empty? }\n return nil if lines.empty?\n lines = lines.map{ |s| s.split(/\\s+/) }\n lines.reject!{ |l| l.first != \"bixby\" || l.last != \"bixby-monitoring-daemon\" }\n if lines.size > 1 then\n raise Micron::Assertion, \"Found #{lines.size} monitoring daemons running!\", caller\n end\n ps = lines.first\n return ps[1].to_i\n end",
"def ps\n `ps auxwww | grep -v grep | grep 'puma: server'`.split(/\\n/)\n end",
"def linux_worker_pids\n `ps -A -o pid,command | grep -E \"[r]esque:work|[r]esque:\\sStarting|[r]esque-[0-9]\" | grep -v \"resque-web\"`.split(\"\\n\").map do |line|\n line.split(' ')[0]\n end\n end",
"def get_pid\n @pid = `pidof #{process_name}`.delete(\"\\n\")\n end",
"def processes()\n\t\t\t\tprocesses = ProcessList.new()\n\t\t\t\tprocesslist = `ps auxww`\n\t\t\t\tprocessregex = /^(\\S+)\\s+([0-9]+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(.*)$/\n\t\t\t\tprocesslist.each() { |line|\n\t\t\t\t\tline.strip!()\n\t\t\t\t\tmatch = processregex.match(line)\n\t\t\t\t\tif(match != nil)\n\t\t\t\t\t\tinfo = ProcessInfo.new()\n\t\t\t\t\t\tinfo.username = match[1]\n\t\t\t\t\t\tinfo.pid = match[2].to_i()\n\t\t\t\t\t\tinfo.flags = match[8]\n\t\t\t\t\t\tinfo.starttime = match[9]\n\t\t\t\t\t\tinfo.runtime = match[10]\n\t\t\t\t\t\tinfo.program = match[11]\n\t\t\t\t\t\tinfo.cpu = match[3].to_f()\n\t\t\t\t\t\tinfo.mem = match[4].to_f()\n\t\t\t\t\t\tif(processes.has_key?(info.pid))\n\t\t\t\t\t\t\traise(DuplicateProcessError, \"Process #{info.pid} appeared twice in the process listing\")\n\t\t\t\t\t\tend\n\t\t\t\t\t\tprocesses[info.pid] = info\n\t\t\t\t\tend\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn(processes)\n\t\t\tend",
"def collect_process_info\n process = {}\n cmdline_file = \"/proc/#{Process.pid}/cmdline\"\n\n # If there is a /proc filesystem, we read this manually so\n # we can split on embedded null bytes. Otherwise (e.g. OSX, Windows)\n # use ProcTable.\n if File.exist?(cmdline_file)\n cmdline = IO.read(cmdline_file).split(?\\x00)\n else\n cmdline = ProcTable.ps(Process.pid).cmdline.split(' ')\n end\n\n if RUBY_PLATFORM =~ /darwin/i\n cmdline.delete_if{ |e| e.include?('=') }\n process[:name] = cmdline.join(' ')\n else\n process[:name] = cmdline.shift\n process[:arguments] = cmdline\n end\n\n process[:pid] = Process.pid\n # This is usually Process.pid but in the case of containers, the host agent\n # will return to us the true host pid in which we use to report data.\n process[:report_pid] = nil\n process\n end",
"def pid\n ['PID:', OSX::NSProcessInfo.processInfo.processIdentifier.to_s]\n end",
"def list_pids\n access_processes do |processes|\n processes.keys\n end\n end",
"def server_pid\n\t\treturn @pid\n\tend",
"def parse_process_list\n array = `ps -eo pid,comm | grep tnnl`.split(/\\n/)\n array.map { |string| string.strip.split(\" \") }\n end",
"def daemon_process\n pid = nil\n Sys::ProcTable.ps do |process|\n if process.cmdline =~ /#{__FILE__}/ and process.pid != Process.pid\n pid = process.pid\n break\n end\n end\n pid\nend",
"def getpid\n @resource.fail \"Either stop/status commands or a pattern must be specified\" unless @resource[:pattern]\n ps = Facter[\"ps\"].value\n @resource.fail \"You must upgrade Facter to a version that includes 'ps'\" unless ps and ps != \"\"\n regex = Regexp.new(@resource[:pattern])\n self.debug \"Executing '#{ps}'\"\n IO.popen(ps) { |table|\n table.each_line { |line|\n if regex.match(line)\n ary = line.sub(/^\\s+/, '').split(/\\s+/)\n return ary[1]\n end\n }\n }\n\n nil\n end",
"def pid\n @process.pid\n end",
"def pidof(program)\n pids = []\n full = cmd_exec('ps aux').to_s\n full.split(\"\\n\").each do |pid|\n pids << pid.split(' ')[1].to_i if pid.include? program\n end\n pids\n end",
"def workers_pids\n pgrep_result = `pgrep -f '#{WORKER_CMDLINE_PATTERN}'`.split(\"\\n\")\n return unless $CHILD_STATUS.success?\n\n pgrep_result\n end",
"def find_runserver_child(parent_pid)\n `ps -o pid,ppid ax | awk \"{ if ( \\\\$2 == #{parent_pid} ) { print \\\\$1 }}\"`.chomp\n end",
"def solaris_worker_pids\n get_worker_pids('ps -A -o pid,args')\n end",
"def windows_worker_pids\n lines = `tasklist /FI \"IMAGENAME eq ruby.exe\" /FO list`.encode(\"UTF-8\", Encoding.locale_charmap).split($/)\n\n lines.select! { |line| line =~ /^PID:/}\n lines.collect!{ |line| line.gsub(/PID:\\s+/, '') }\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Example For n = 29, the output should be addTwoDigits(n) = 11.
|
def addTwoDigits(n)
result = 0
n.to_s.split("").each {|number| result += number.to_i }
result
end
|
[
"def add_digits(num)\n return num if num.to_s.length == 1\n int_array = split_digits(num)\n sum = add_array_ints(int_array)\n return add_digits(sum)\n end",
"def sum_digits(number)\n number = number.to_i * 2\n right_digit(number) + left_digit(number)\nend",
"def two_digit_sum(int)\n digit1 = (int / 10).round\n digit2 = int % 10\n sum = digit1 + digit2\nend",
"def sumDigits(n)\n\tn.abs.to_s.split(//).map(&:to_i).reduce(:+)\nend",
"def two_to_sum(n)\n result = 2 ** n\n \n result.to_s.split('').map {|x| x.to_i }.reduce(:+)\nend",
"def sum_digits\n number = 2 ** 1000\n number.to_s.split(\"\").inject{|x,y| x.to_i + y.to_i}\nend",
"def mystery2(n)\n if n < 10\n return n\n else\n return (n%10) + mystery2(n/10)\n end\nend",
"def sumDigits(number)\n number.abs.to_s.chars.map(&:to_i).inject(:+)\nend",
"def compute_number(digits)\n digits.length == 1 ? (digits.to_i) : (digits[-1].to_i + 10*compute_number(digits[0..-2]))\nend",
"def super_digit(n)\n\n # return n for all one digit n values \n if n < 10\n return n\n end\n\n # add each digit, peeling of last one in place each time\n return super_digit(n % 10 + super_digit(n/10))\n\nend",
"def two_digits_number(x)\n x < 10 ? \"0#{x}\" : x.to_s\n end",
"def two_digit_sum(nums)\n if nums.integer?\n string = nums.to_s.split(//)\n return string[0].to_i + string[1].to_i\n else\n print \"Please pass a valid two-digit argument\"\n end\n return\n\nend",
"def sum_digit_power(number, n)\n digits = number.to_s.split(\"\")\n sum = 0\n digits.each {|i| sum += i.to_i ** n}\n sum\nend",
"def super_digit(n)\n while n > 9\n n = n % 10 + super_digit(n / 10)\n end\n return n\nend",
"def sum_of_digits(number)\n split_to_array(number).inject(:+)\n end",
"def sum(number)\n number.to_s.chars.map(&:to_i).reduce(:+)\n \nend",
"def add_two(number)\n p number += 2\n end",
"def sum(number)\r\n number.digits.sum\r\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"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /session_replicas GET /session_replicas.json
|
def index
@session_replicas = SessionReplica.all
end
|
[
"def replicas\n data[:replicas]\n end",
"def get_all_replicas(id, options = GetAllReplicasOptions.new) end",
"def replicas; end",
"def destroy\n @session_replica.destroy\n respond_to do |format|\n format.html { redirect_to session_replicas_url }\n format.json { head :no_content }\n end\n end",
"def index\n @image_replicas = ImageReplica.all\n end",
"def create\n @session_replica = SessionReplica.new(session_replica_params)\n\n respond_to do |format|\n if @session_replica.save\n format.html { redirect_to @session_replica}\n format.json { render :show, status: :created, location: @session_replica }\n else\n format.html { render :new }\n format.json { render json: @session_replica.errors, status: :unprocessable_entity }\n end\n end\n end",
"def get_replicas_by_shard(host, port, collection, shard)\n params = {:action => \"CLUSTERSTATUS\"}\n cluster_status_resp = solr_collection_api(host, port, params)\n Chef::Log.info(\"cluster_status_resp in get_replicas_by_shard = #{cluster_status_resp.to_json}\")\n cluster_status_collections = cluster_status_resp[\"cluster\"][\"collections\"]\n shards = cluster_status_collections[collection][\"shards\"]\n replicas = shards[shard][\"replicas\"]\n return replicas\n end",
"def update\n respond_to do |format|\n if @session_replica.update(session_replica_params)\n format.html { redirect_to @session_replica}\n format.json { render :show, status: :ok, location: @session_replica }\n else\n format.html { render :edit }\n format.json { render json: @session_replica.errors, status: :unprocessable_entity }\n end\n end\n end",
"def get_any_replica(id, options = GetAnyReplicaOptions.new) end",
"def index\n @text_replicas = TextReplica.all\n end",
"def read_replica_identifiers\n data[:read_replica_identifiers]\n end",
"def read_replica_db_cluster_identifiers\n data[:read_replica_db_cluster_identifiers]\n end",
"def default_backend_replicas\n r = (worker_node_count / 10.to_f).ceil\n\n return 1 if worker_node_count <= 1 # covers also single node cluster case where master is un-tainted\n return 2 if r < 2 && worker_node_count > 1 # Always min 2 replicas if 2 or more nodes\n\n r\n end",
"def increment_replica_count\n self.original['spec']['replicas'] += 1\n end",
"def replica_count\n @replica_count\n end",
"def count_ideal_replicas_not_ready\n get_ideal_replicas_not_ready().size\n end",
"def read_replica_db_instance_identifiers\n data[:read_replica_db_instance_identifiers]\n end",
"def getNodeSessions(node)\n sessions = Jiocloud::Utils.get(sessionurl + '/node/' + node)\n return sessions\n end",
"def decrement_replica_count\n self.original['spec']['replicas'] -= 1\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /session_replicas POST /session_replicas.json
|
def create
@session_replica = SessionReplica.new(session_replica_params)
respond_to do |format|
if @session_replica.save
format.html { redirect_to @session_replica}
format.json { render :show, status: :created, location: @session_replica }
else
format.html { render :new }
format.json { render json: @session_replica.errors, status: :unprocessable_entity }
end
end
end
|
[
"def index\n @session_replicas = SessionReplica.all\n end",
"def replicas\n data[:replicas]\n end",
"def destroy\n @session_replica.destroy\n respond_to do |format|\n format.html { redirect_to session_replicas_url }\n format.json { head :no_content }\n end\n end",
"def increment_replica_count\n self.original['spec']['replicas'] += 1\n end",
"def replicas; end",
"def create\n step = Step.find(params[:step_id])\n @image_replica = step.image_replicas.create(image_replica_params)\n\n respond_to do |format|\n if @image_replica.save\n format.html { redirect_to step_path(step), notice: 'ImageReplica was successfully created.' }\n format.json { render :show, status: :created, location: @image_replica }\n else\n format.html { render :new }\n format.json { render json: @image_replica.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @session_replica.update(session_replica_params)\n format.html { redirect_to @session_replica}\n format.json { render :show, status: :ok, location: @session_replica }\n else\n format.html { render :edit }\n format.json { render json: @session_replica.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n step = Step.find(params[:step_id])\n @text_replica = step.text_replicas.create(text_replica_params)\n\n respond_to do |format|\n if @text_replica.save\n format.html { redirect_to step_path(step), notice: 'TextReplica was successfully created.' }\n format.json { render :show, status: :created, location: @text_replica }\n else\n format.html { render :new }\n format.json { render json: @text_replica.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_replica (collection_name, shard_num, ip, port_num)\n shard_name = \"shard\"+\"#{shard_num}\"\n node_name = \"#{ip}:#{port_num}_solr\"\n Chef::Log.info(\"Adding replica for #{shard_name} to #{node_name}\")\n params = {\n :action => \"ADDREPLICA\",\n :collection => collection_name,\n :shard => shard_name,\n :node => node_name\n }\n response = collection_api(ip, port_num.to_s, params)\n Chef::Log.info(\"#{response.to_json}\")\n return true\nend",
"def decrement_replica_count\n self.original['spec']['replicas'] -= 1\n end",
"def get_all_replicas(id, options = GetAllReplicasOptions.new) end",
"def index\n @image_replicas = ImageReplica.all\n end",
"def default_backend_replicas\n r = (worker_node_count / 10.to_f).ceil\n\n return 1 if worker_node_count <= 1 # covers also single node cluster case where master is un-tainted\n return 2 if r < 2 && worker_node_count > 1 # Always min 2 replicas if 2 or more nodes\n\n r\n end",
"def add_replica (shard_num, ip)\n shard_name = \"shard\"+\"#{shard_num}\"\n node_name = \"#{ip}:#{@port_num}_solr\"\n Chef::Log.info(\"Adding replica for #{shard_name} to #{node_name}\")\n params = {\n :action => \"ADDREPLICA\",\n :collection => @collection_name,\n :shard => shard_name,\n :node => node_name\n }\n response = collection_api(ip, @port_num.to_s, params)\n Chef::Log.info(\"#{response.to_json}\")\n return true\n end",
"def replica_count=(value)\n @replica_count = value\n end",
"def add_tenant_to_specified_shard(args = {}) \n post(\"/tenants.json/shard/#{args[:shardId]}\", args)\nend",
"def assign_suspended_tenant_to_shard(args = {}) \n put(\"/shards.json/#{args[:shardId]}/tenant/#{args[:tenantId]}\", args)\nend",
"def replication(path, replnum, options = {})\n WebHDFS.check_options(options, OPT_TABLE['SETREPLICATION'])\n res = operate_requests('PUT', path, 'SETREPLICATION',\n options.merge('replication' => replnum.to_s))\n WebHDFS.check_success_json(res, 'boolean')\n end",
"def count_ideal_replicas_not_ready\n get_ideal_replicas_not_ready().size\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PATCH/PUT /session_replicas/1 PATCH/PUT /session_replicas/1.json
|
def update
respond_to do |format|
if @session_replica.update(session_replica_params)
format.html { redirect_to @session_replica}
format.json { render :show, status: :ok, location: @session_replica }
else
format.html { render :edit }
format.json { render json: @session_replica.errors, status: :unprocessable_entity }
end
end
end
|
[
"def increment_replica_count\n self.original['spec']['replicas'] += 1\n end",
"def index\n @session_replicas = SessionReplica.all\n end",
"def replication(path, replnum, options = {})\n WebHDFS.check_options(options, OPT_TABLE['SETREPLICATION'])\n res = operate_requests('PUT', path, 'SETREPLICATION',\n options.merge('replication' => replnum.to_s))\n WebHDFS.check_success_json(res, 'boolean')\n end",
"def destroy\n @session_replica.destroy\n respond_to do |format|\n format.html { redirect_to session_replicas_url }\n format.json { head :no_content }\n end\n end",
"def replication(path, replnum, options={})\n check_options(options, OPT_TABLE['SETREPLICATION'])\n res = operate_requests('PUT', path, 'SETREPLICATION', options.merge({'replication' => replnum.to_s}))\n check_success_json(res, 'boolean')\n end",
"def update_replication(request, &block)\n put \"/replicate/#{request[:replication_id]}/\", request, &block\n end",
"def update\n #@session = @client.sessions.update!(session_params)\n\n respond_to do |format|\n if @session.update(session_params)\n format.html { redirect_to client_url(@client), notice: 'Session was successfully updated.' }\n format.json { render :show, status: :ok, location: @session }\n else\n format.html { render :edit }\n format.json { render json: @session.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @session_replica = SessionReplica.new(session_replica_params)\n\n respond_to do |format|\n if @session_replica.save\n format.html { redirect_to @session_replica}\n format.json { render :show, status: :created, location: @session_replica }\n else\n format.html { render :new }\n format.json { render json: @session_replica.errors, status: :unprocessable_entity }\n end\n end\n end",
"def assign_suspended_tenant_to_shard(args = {}) \n put(\"/shards.json/#{args[:shardId]}/tenant/#{args[:tenantId]}\", args)\nend",
"def decrement_replica_count\n self.original['spec']['replicas'] -= 1\n end",
"def update\n @session_resource = SessionResource.find(params[:id])\n\n if @session_resource.update(session_resource_params)\n head :no_content\n else\n render json: @session_resource.errors, status: :unprocessable_entity\n end\n end",
"def update\n authorize! :update, @db_replication\n respond_to do |format|\n if @db_replication.update(db_replication_params)\n format.html { redirect_to @db_replication, notice: 'Database replication was successfully updated.' }\n format.json { render :show, status: :ok, location: @db_replication }\n else\n format.html { render :edit }\n format.json { render json: @db_replication.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @image_replica.update(image_replica_params)\n if @image_replica.type == \"TextReplica\"\n redirect_path = text_replica_path(@image_replica)\n elsif @image_replica.type == \"ImageReplica\"\n redirect_path = image_replica_path(@image_replica)\n end\n\n format.html { redirect_to redirect_path, notice: 'ImageReplica was successfully updated.' }\n format.json { render :show, status: :ok, location: @image_replica }\n else\n format.html { render :edit }\n format.json { render json: @image_replica.errors, status: :unprocessable_entity }\n end\n end\n end",
"def replicas; end",
"def update_replication\n replication.stored = true\n replication.update_admin\n replication.update_local\n end",
"def update\n respond_to do |format|\n if @text_replica.update(text_replica_params)\n if @text_replica.type == \"TextReplica\"\n redirect_path = admin_step_text_replica_path(@text_replica.step, @text_replica)\n elsif @text_replica.type == \"ImageReplica\"\n redirect_path = image_replica_path(@text_replica)\n end\n\n format.html { redirect_to redirect_path, notice: 'TextReplica was successfully updated.' }\n format.json { render :show, status: :ok, location: @text_replica }\n else\n format.html { render :edit }\n format.json { render json: @text_replica.errors, status: :unprocessable_entity }\n end\n end\n end",
"def restart_all_node\n put '/cluster/restart'\n end",
"def replicas\n data[:replicas]\n end",
"def modify_server(server_uuid, params)\n data = { \"server\" => params }\n json = JSON.generate data\n response = put \"server/#{server_uuid}\", json\n\n response\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /session_replicas/1 DELETE /session_replicas/1.json
|
def destroy
@session_replica.destroy
respond_to do |format|
format.html { redirect_to session_replicas_url }
format.json { head :no_content }
end
end
|
[
"def destroy\n @image_replica.destroy\n respond_to do |format|\n format.html { redirect_to replicas_url, notice: 'ImageReplica was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n replication_agent = client(resource).replication_agent(resource[:run_mode], resource[:name])\n result = replication_agent.delete\n handle(result)\n end",
"def destroy\n @text_replica.destroy\n respond_to do |format|\n format.html { redirect_to replicas_url, notice: 'TextReplica was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n authorize! :destroy, @db_replication\n @db_replication.destroy\n respond_to do |format|\n format.html { redirect_to db_replications_url, notice: 'Database replication was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def decrement_replica_count\n self.original['spec']['replicas'] -= 1\n end",
"def deleteSession(name,node=nil)\n Jiocloud::Utils.put(sessionurl + '/destroy/' + getSessionID({:name => name,:node => node}),'')\n end",
"def destroy\n @session = @client.sessions.find(params[:id])\n @session.destroy\n respond_to do |format|\n format.html { redirect_to client_url(@client), notice: 'Session was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @shard.destroy\n respond_to do |format|\n format.html { redirect_to shards_url, notice: 'Shard was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @shard = Shard.find(params[:id])\n @shard.destroy\n\n respond_to do |format|\n format.html { redirect_to shards_url }\n format.json { head :no_content }\n end\n end",
"def deleteReplica(shard_name,collection_name,replica)\n params = {:action => \"DELETEREPLICA\",\n :collection => collection_name,:shard => shard_name,:replica => replica}\n\n jsonresponse = solr_collection_api(node['ipaddress'],node['port_no'],params)\n issuccess = jsonresponse.fetch('success', '')\n\n if issuccess.empty?\n iserror = jsonresponse.fetch('error', '')\n errormessage = iserror.fetch('msg','')\n raise errormessage\n else\n Chef::Log.info(issuccess)\n end\n end",
"def remove(node)\n @replicas.times do |i|\n key = hash(\"#{node.to_s}:#{i}\")\n @ring.delete(key)\n @nodesort.delete(key)\n end\n end",
"def delete\n @server.delete_run uuid\n end",
"def destroy\n @cluster = Cluster.find(params[:id])\n @cluster.destroy\n @cluster.virtual_machines.destroy\n\n respond_to do |format|\n format.html { redirect_to clusters_url }\n format.json { head :no_content }\n end\n end",
"def delete_ingress(namespace, ingress_name)\n if namespace_exists?(namespace) && object_exists?(namespace, \"ingress\", ingress_name)\n execute(\"kubectl delete ingress #{ingress_name} -n #{namespace}\")\n end\nend",
"def destroy\n @f5_cluster = F5Cluster.find(params[:id])\n @f5_cluster.destroy\n\n respond_to do |format|\n format.html { redirect_to f5_clusters_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n authorize! :destroy, @db_cluster\n @db_cluster.destroy\n respond_to do |format|\n format.html { redirect_to db_clusters_url, notice: 'Database cluster was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cluster = Cluster.find(params[:id])\n @cluster.destroy\n\n respond_to do |format|\n format.html { redirect_to clusters_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @discovery_session = DiscoverySession.find(params[:id])\n @discovery_session.destroy\n\n respond_to do |format|\n format.html { redirect_to discovery_sessions_url }\n format.json { head :no_content }\n end\n end",
"def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Delete participant by ID.
|
def delete_participant(account_id,
participant_id)
# Prepare query url.
_query_builder = config.get_base_uri(Server::WEBRTCDEFAULT)
_query_builder << '/accounts/{accountId}/participants/{participantId}'
_query_builder = APIHelper.append_url_with_template_parameters(
_query_builder,
'accountId' => { 'value' => account_id, 'encode' => false },
'participantId' => { 'value' => participant_id, 'encode' => false }
)
_query_url = APIHelper.clean_url _query_builder
# Prepare and execute HttpRequest.
_request = config.http_client.delete(
_query_url
)
WebRtcBasicAuth.apply(config, _request)
_response = execute_request(_request)
# Validate response against endpoint and global error codes.
case _response.status_code
when 401
raise APIException.new(
'Unauthorized',
_response
)
when 403
raise APIException.new(
'Access Denied',
_response
)
when 404
raise APIException.new(
'Not Found',
_response
)
end
unless _response.status_code.between?(200, 208)
raise ErrorException.new(
'Unexpected Error',
_response
)
end
validate_response(_response)
# Return appropriate response type.
ApiResponse.new(_response)
end
|
[
"def destroy\n @participant = Participant__c.find(params[:id])\n @participant.delete\n\n respond_to do |format|\n format.html { redirect_to participants_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @participant = Participant.find(params[:id])\n @participant.destroy\n\n respond_to do |format|\n format.html { redirect_to participants_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @participant = Participant.find(params[:id])\n @participant.destroy\n\n respond_to do |format|\n format.html { redirect_to(participants_url) }\n format.xml { head :ok }\n end\n end",
"def delete_by_id(id)\n delete(id)\n end",
"def destroy\n # Only participants which can edit the trip are able to remove a participant (except for the owner)\n authorize @participant\n\n user_email = @participant.user.email\n @participant.destroy\n flash[:notice] = I18n.t 'trip_participant_removed', :email => user_email\n\n redirect_to trip_participants_path(@trip)\n end",
"def delete\n user = self.load_user(params)\n meeting = self.load_meeting(params)\n\n if user != nil and meeting != nil\n participants = meeting.participants\n meeting.participants.delete(participants)\n meeting.delete\n self.send_ok\n else\n self.send_error 401\n end\n end",
"def delete(id)\n raise ArgumentError, 'You must pass an ID to delete' unless id\n\n send_message( verb_for(:delete), \n param_string(:delete, nil, id), \n false )\n\n self\n end",
"def delete(id)\n self.find(id).delete_\n end",
"def destroy\n @participant_person = Participant::Person.find(params[:id])\n @participant_person.destroy\n\n respond_to do |format|\n format.html { redirect_to(participant_people_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @az_participant = AzParticipant.find(params[:id])\n @az_participant.destroy\n\n respond_to do |format|\n format.html { redirect_to(az_participants_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @participant_registration = ParticipantRegistration.find(params[:id])\n if params[:user_id]\n @user = User.find(params[:user_id])\n else\n # if we aren't an admin we shouldn't be here\n record_not_found and return if !admin?\n end\n\n # destroy the participant registration\n @participant_registration.destroy\n\n flash[:notice] = 'Participant Registration deleted successfully.'\n\n respond_to do |format|\n format.html {\n if params[:user_id]\n redirect_to(user_participant_registrations_url(@user))\n else\n redirect_to(participant_registrations_url)\n end\n }\n end\n end",
"def destroy\n @backend_participant = Backend::Participant.find(params[:id])\n @backend_participant.destroy\n\n respond_to do |format|\n format.html { redirect_to(backend_participants_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n get_event\n @event_participant = @event.participants.find(params[:id])\n @event_participant.destroy\n end",
"def delete_deal_participants(id:, deal_participant_id:, **args)\n params = parameters(args) do\n optional_params\n end\n request(:delete, \"deals/#{id}/participants/#{deal_participant_id}\", params)\n end",
"def destroy\n @activity_participant = ActivityParticipant.find(params[:id])\n @activity_participant.destroy\n\n respond_to do |format|\n format.html { redirect_to(activity_participants_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @participant = Participant.find(params[:id])\n @participant.destroy\n\n respond_to do |format|\n format.html { redirect_to :back }\n format.xml { head :ok }\n end\n end",
"def delete\n contributor = AssignmentParticipant.find(params[:id])\n name = contributor.name\n assignment_id = contributor.assignment\n begin\n contributor.destroy\n flash[:note] = \"\\\"#{name}\\\" is no longer a participant in this assignment.\"\n rescue StandardError\n flash[:error] = \"\\\"#{name}\\\" was not removed from this assignment. Please ensure that \\\"#{name}\\\" is not a reviewer or metareviewer and try again.\"\n end\n redirect_to controller: 'review_mapping', action: 'list_mappings', id: assignment_id\n end",
"def destroy\n @participant = Participant__c.find(request[:participant_id])\n @participant_profile = ParticipantProfile__c.find(params[:id])\n @participant_profile.delete\n\n respond_to do |format|\n format.html { redirect_to participant_participant_profiles_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @event_participant = EventParticipant.find(params[:id])\n @event_participant.destroy\n\n respond_to do |format|\n format.html { redirect_to(event_participants_url) }\n format.xml { head :ok }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
List participants in a session.
|
def list_session_participants(account_id,
session_id)
# Prepare query url.
_query_builder = config.get_base_uri(Server::WEBRTCDEFAULT)
_query_builder << '/accounts/{accountId}/sessions/{sessionId}/participants'
_query_builder = APIHelper.append_url_with_template_parameters(
_query_builder,
'accountId' => { 'value' => account_id, 'encode' => false },
'sessionId' => { 'value' => session_id, 'encode' => false }
)
_query_url = APIHelper.clean_url _query_builder
# Prepare headers.
_headers = {
'accept' => 'application/json'
}
# Prepare and execute HttpRequest.
_request = config.http_client.get(
_query_url,
headers: _headers
)
WebRtcBasicAuth.apply(config, _request)
_response = execute_request(_request)
# Validate response against endpoint and global error codes.
case _response.status_code
when 401
raise APIException.new(
'Unauthorized',
_response
)
when 403
raise APIException.new(
'Access Denied',
_response
)
when 404
raise APIException.new(
'Not Found',
_response
)
end
unless _response.status_code.between?(200, 208)
raise ErrorException.new(
'Unexpected Error',
_response
)
end
validate_response(_response)
# Return appropriate response type.
decoded = APIHelper.json_deserialize(_response.raw_body)
ApiResponse.new(
_response,
data: decoded.map { |element| Participant.from_hash(element) }
)
end
|
[
"def get_participants\n user = self.load_user(params)\n meeting = self.load_meeting(params)\n\n if user != nil and meeting != nil\n users = meeting.participants\n send_json(users)\n else\n send_error 401\n end\n end",
"def participants\n\n get_participant_map.participants\n end",
"def participants\n expose Challenge.participants(@oauth_token, params[:challenge_id].strip)\n end",
"def listerParticipants\n puts \"\"\n puts \"\"\n puts \"---------------| PARTICIPANTS |----------------------\"\n puts \"\"\n @participants.each do |participant|\n puts \" #{participant.nom.upcase}[#{participant.initiative}] - PV(#{participant.pv} / #{participant.pv_max}) >> #{participant.etat}\"\n end\n puts \"\"\n puts \"---------------| PARTICIPANTS |----------------------\"\n puts \"\"\n puts \"\"\n end",
"def getParticipants\r\n\t\t\t\t\treturn @participants\r\n\t\t\t\tend",
"def participants\n return @participants\n end",
"def participants\n return @participants\n end",
"def list\n\n get_list['list'].collect { |e| ParticipantEntry.new(e) }\n end",
"def conference_list_members(params)\n path = @version + '/Conference/Member/List/'\n method = 'POST'\n return request(path, method, params)\n end",
"def members\n participants\n end",
"def get_conversation_participants(id)\n @client.raw('get', \"/content/conversations/#{id}/participants\")\n end",
"def get_all_participants(params = {})\n room_id = self.room_id || params.delete(:room_id)\n raise ArgumentError.new(\"room_id required\") unless room_id\n res = call_api(:method => :get, :uri => @api_base.merge(\"room/#{room_id}/participant\"), :query_params => params)\n return unless res.successful?\n Users.new(res.data)\n end",
"def index\n if @talk.user_ids.include?(current_user.id) || current_user.is_admin?\n @participants = @talk.workshop_participants.collect {|p| p.user }\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @participants }\n end\n else\n flash[:error] = \"Access Denied\"\n redirect_to new_user_path\n end\n end",
"def list\n @participants = Participant__c.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @participants }\n end\n end",
"def participants=(value)\n @participants = value\n end",
"def find_participants(discussion_id, params={}, headers=default_jwt_headers)\n @logger.info(\"Finding Participants in the #{discussion_id} Discussion\")\n get(\"#{@api_url}/discussions/#{discussion_id}/participants\", params, headers)\n end",
"def participants=(value)\n @participants = value\n end",
"def fetchParticipants\n participants = @conv.participants \n if participants.count >= 2 \n blacklist = [current_user] \n participants = participants - blacklist\n end\n return participants\n end",
"def participants #igger loudin\n participating_users.includes(:user).map(&:user)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Add a participant to a session. Subscriptions can optionally be provided as part of this call.
|
def add_participant_to_session(account_id,
session_id,
participant_id,
body: nil)
# Prepare query url.
_query_builder = config.get_base_uri(Server::WEBRTCDEFAULT)
_query_builder << '/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}'
_query_builder = APIHelper.append_url_with_template_parameters(
_query_builder,
'accountId' => { 'value' => account_id, 'encode' => false },
'sessionId' => { 'value' => session_id, 'encode' => false },
'participantId' => { 'value' => participant_id, 'encode' => false }
)
_query_url = APIHelper.clean_url _query_builder
# Prepare headers.
_headers = {
'content-type' => 'application/json; charset=utf-8'
}
# Prepare and execute HttpRequest.
_request = config.http_client.put(
_query_url,
headers: _headers,
parameters: body.to_json
)
WebRtcBasicAuth.apply(config, _request)
_response = execute_request(_request)
# Validate response against endpoint and global error codes.
case _response.status_code
when 401
raise APIException.new(
'Unauthorized',
_response
)
when 403
raise APIException.new(
'Access Denied',
_response
)
when 404
raise APIException.new(
'Not Found',
_response
)
end
unless _response.status_code.between?(200, 208)
raise ErrorException.new(
'Unexpected Error',
_response
)
end
validate_response(_response)
# Return appropriate response type.
ApiResponse.new(_response)
end
|
[
"def add_participant_to_session(account_id, session_id, participant_id, opts = {})\n add_participant_to_session_with_http_info(account_id, session_id, participant_id, opts)\n nil\n end",
"def add_participant(participant_id)\n #TODO\n end",
"def add_participant\n user = self.load_user(params)\n meeting = self.load_meeting(params)\n participant_ids = params[\"participant_ids\"]\n comment = params[\"comment\"].nil? ? \"\" : params[\"comment\"]\n\n if user != nil and meeting != nil and participant_ids.length > 0\n participant_ids.each do |participant_id|\n unless meeting.participants.exists?(participant_id)\n new_participant = User.find(participant_id)\n meeting.participants << new_participant\n # add default vote for the new added participant to each suggestion\n meeting.suggestions.each do |suggestion|\n suggestion.votes << Vote.new(:voter => new_participant, :decision => \"?\")\n end\n\n NotificationService.send_meeting_invitation(user, new_participant, meeting, comment)\n end\n end\n self.send_ok\n else\n self.send_error 401\n end\n end",
"def create_conferences_add_participant(options = {})\r\n # Prepare query url.\r\n _query_builder = Configuration.base_uri.dup\r\n _query_builder << '/conferences/addParticipant.json'\r\n _query_url = APIHelper.clean_url _query_builder\r\n\r\n # Prepare form parameters.\r\n _parameters = {\r\n 'ConferenceSid' => options['conference_sid'],\r\n 'ParticipantNumber' => options['participant_number'],\r\n 'Muted' => options['muted'],\r\n 'Deaf' => options['deaf']\r\n }\r\n _parameters = APIHelper.form_encode_parameters(_parameters)\r\n\r\n # Prepare and execute HttpRequest.\r\n _request = @http_client.post(\r\n _query_url,\r\n parameters: _parameters\r\n )\r\n BasicAuth.apply(_request)\r\n _context = execute_request(_request)\r\n validate_response(_context)\r\n\r\n # Return appropriate response type.\r\n _context.response.raw_body\r\n end",
"def ab_add_participant(experiment, alternative, identity)\n VanityParticipant.retrieve(experiment, identity, true, seen: alternative)\n end",
"def ab_add_participant(_experiment, _alternative, _identity)\n raise \"Not implemented\"\n end",
"def add_participant(user) # :nodoc:\n id = user.to_s.downcase\n if @participant_ids.include?(id)\n logger.warning(\"Attempted to add a participant who was already in the wavelet(#{@id}): #{id}\")\n return nil\n end\n\n # Allow string names to be used as participant.\n user = if @context.users[id]\n @context.users[id]\n else\n @context.add_user(:id => id)\n end\n\n @context.add_operation(:type => Operation::WAVELET_ADD_PARTICIPANT,\n :wave_id => @wave_id, :wavelet_id => @id, :property => user)\n @participant_ids << id\n \n user\n end",
"def add(participant)\n participants.add(participant)\n participant.order = self\n\n participant\n end",
"def update_participant_subscriptions(account_id,\r\n session_id,\r\n participant_id,\r\n body: nil)\r\n # Prepare query url.\r\n _query_builder = config.get_base_uri(Server::WEBRTCDEFAULT)\r\n _query_builder << '/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}/subscriptions'\r\n _query_builder = APIHelper.append_url_with_template_parameters(\r\n _query_builder,\r\n 'accountId' => { 'value' => account_id, 'encode' => false },\r\n 'sessionId' => { 'value' => session_id, 'encode' => false },\r\n 'participantId' => { 'value' => participant_id, 'encode' => false }\r\n )\r\n _query_url = APIHelper.clean_url _query_builder\r\n\r\n # Prepare headers.\r\n _headers = {\r\n 'content-type' => 'application/json; charset=utf-8'\r\n }\r\n\r\n # Prepare and execute HttpRequest.\r\n _request = config.http_client.put(\r\n _query_url,\r\n headers: _headers,\r\n parameters: body.to_json\r\n )\r\n WebRtcBasicAuth.apply(config, _request)\r\n _response = execute_request(_request)\r\n\r\n # Validate response against endpoint and global error codes.\r\n case _response.status_code\r\n when 400\r\n raise APIException.new(\r\n 'Bad Request',\r\n _response\r\n )\r\n when 401\r\n raise APIException.new(\r\n 'Unauthorized',\r\n _response\r\n )\r\n when 403\r\n raise APIException.new(\r\n 'Access Denied',\r\n _response\r\n )\r\n when 404\r\n raise APIException.new(\r\n 'Not Found',\r\n _response\r\n )\r\n end\r\n unless _response.status_code.between?(200, 208)\r\n raise ErrorException.new(\r\n 'Unexpected Error',\r\n _response\r\n )\r\n end\r\n validate_response(_response)\r\n\r\n # Return appropriate response type.\r\n ApiResponse.new(_response)\r\n end",
"def add(subscription)\n @subscriptions << subscription\n end",
"def add_participant_to_deal(id:, **args)\n params = parameters(args) do\n required_params :person_id\n optional_params :person_id\n end\n request(:post, \"deals/#{id}/participants\", params)\n end",
"def update_participant_subscriptions(account_id, session_id, participant_id, opts = {})\n update_participant_subscriptions_with_http_info(account_id, session_id, participant_id, opts)\n nil\n end",
"def create_participant_subscription\n if self.participant.is_a?(Organization) && self.survey.sponsor != self.participant then\n s = SurveySubscription.create!(\n :organization => self.participant,\n :survey => self.survey,\n :relationship => 'participant'\n )\n end\n end",
"def add_subscription(entity)\r\n subscriptions << entity\r\n end",
"def register (*args, &block)\n\n if args.size > 0\n register_participant(*args, &block)\n else\n proxy = ParticipantRegistrationProxy.new(self)\n block.arity < 1 ? proxy.instance_eval(&block) : block.call(proxy)\n end\n end",
"def add_session_subscriber(subscriber)\n add_event_subscriber(session_event_subscribers, subscriber)\n end",
"def add_participant(assignment_id, user)\n AssignmentParticipant.create(parent_id: assignment_id, user_id: user.id, permission_granted: user.master_permission_granted) if AssignmentParticipant.where(parent_id: assignment_id, user_id: user.id).first.nil?\n end",
"def register(name, participant, options, block)\n\n entry = to_entry(name, participant, options, block)\n\n key = entry.first\n options = entry.last.last\n\n list = get_list\n\n position = options['position'] || options['pos'] || 'last'\n\n if position == 'before'\n\n position = list['list'].index { |e| e.first == key } || -1\n\n elsif position == 'after'\n\n position = (list['list'].rindex { |e| e.first == key } || -2) + 1\n\n elsif position == 'over'\n\n position = list['list'].index { |e| e.first == key } || -1\n list['list'].delete_at(position) unless position == -1\n\n elsif options.delete('override') != false\n\n list['list'].delete_if { |e| e.first == key }\n # enforces only one instance of a participant per key/regex\n end\n\n case position\n when 'last' then list['list'] << entry\n when 'first' then list['list'].unshift(entry)\n when Fixnum then list['list'].insert(position, entry)\n else raise \"cannot insert participant at position '#{position}'\"\n end\n\n if r = @context.storage.put(list)\n #\n # if put returns something it means the put failed, have to redo the\n # work...\n #\n return register(name, participant, options, block)\n end\n\n if entry.last.first == 'Ruote::StorageParticipant'\n Ruote::StorageParticipant.new(@context)\n else\n nil\n end\n end",
"def add_participant(user_name, can_submit, can_review, can_take_quiz)\n user = User.find_by(name: user_name)\n if user.nil?\n raise \"The user account with the name #{user_name} does not exist. Please <a href='\" +\n url_for(controller: 'users', action: 'new') + \"'>create</a> the user first.\"\n end\n participant = AssignmentParticipant.find_by(parent_id: id, user_id: user.id)\n raise \"The user #{user.name} is already a participant.\" if participant\n\n new_part = AssignmentParticipant.create(parent_id: id,\n user_id: user.id,\n permission_granted: user.master_permission_granted,\n can_submit: can_submit,\n can_review: can_review,\n can_take_quiz: can_take_quiz)\n new_part.set_handle\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Remove a participant from a session. This will automatically remove any subscriptions the participant has associated with this session.
|
def remove_participant_from_session(account_id,
session_id,
participant_id)
# Prepare query url.
_query_builder = config.get_base_uri(Server::WEBRTCDEFAULT)
_query_builder << '/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}'
_query_builder = APIHelper.append_url_with_template_parameters(
_query_builder,
'accountId' => { 'value' => account_id, 'encode' => false },
'sessionId' => { 'value' => session_id, 'encode' => false },
'participantId' => { 'value' => participant_id, 'encode' => false }
)
_query_url = APIHelper.clean_url _query_builder
# Prepare and execute HttpRequest.
_request = config.http_client.delete(
_query_url
)
WebRtcBasicAuth.apply(config, _request)
_response = execute_request(_request)
# Validate response against endpoint and global error codes.
case _response.status_code
when 401
raise APIException.new(
'Unauthorized',
_response
)
when 403
raise APIException.new(
'Access Denied',
_response
)
when 404
raise APIException.new(
'Not Found',
_response
)
end
unless _response.status_code.between?(200, 208)
raise ErrorException.new(
'Unexpected Error',
_response
)
end
validate_response(_response)
# Return appropriate response type.
ApiResponse.new(_response)
end
|
[
"def remove_participant_from_session(account_id, session_id, participant_id, opts = {})\n remove_participant_from_session_with_http_info(account_id, session_id, participant_id, opts)\n nil\n end",
"def unsubscribe\n participant = SportSessionParticipant.where(:user_id => params[:user_id], :sport_session_id => params[:sport_session_id]).first!\n if participant.destroy\n redirect_to sport_sessions_url, :notice => \"Successfully unsubscribed from the session\"\n else\n redirect_to sport_sessions_url, :alert => \"Unable to unsubscribe from event\"\n end\n\n end",
"def remove_session_subscriber(subscriber)\n remove_event_subscriber(session_event_subscribers, subscriber)\n end",
"def remove_participant(remover, participant)\n return if remover.nil? or participant.nil?\n \n remover = participant_event_class.find_by_event_id_and_schedule_id(self.id, remover.schedule.id)\n participant_event = participant_event_class.find_by_event_id_and_schedule_id(\n self.id, participant.schedule.id)\n\n return if remover.nil? or participant_event.nil?\n\n permission = \"remove_#{participant_event.role}\".to_sym\n\n if execute_action?(permission, remover, participant_event, \"remove\")\n self.route.users.delete(participant) unless self.route.nil?\n participant_event.destroy\n end\n end",
"def remove_session_subscriber(subscriber)\n\t\tremove_event_subscriber(session_event_subscribers, subscriber)\n\tend",
"def removeSubscription\n require 'json'\n\n if (@role.nil? or !(@role.subscriptions_permissions)) and !current_actor.superadmin\n json_response({ message: \"You don't have permission to remove subscriptions in this project\" }, :unauthorized)\n return\n end\n\n sub_id = @subscription.subscription_id\n service_id = @subscription.service_id\n service = Service.find(service_id)\n\n # Send it to context broker endpoint for Subscriptions\n # TODO: Move path in configuration elsewhere\n serviceURI = service.endpoint+\":1026/v2/subscriptions/\"+sub_id\n\n begin\n response = RestClient.delete(serviceURI)\n # Set sub as unregistered and remove ID if successful\n @subscription.update(status: \"unregistered\", subscription_id: \"pending\")\n json_response({message: \"Subscription removed\"})\n rescue RestClient::ExceptionWithResponse => e\n # If errored, report to client\n json_response({message: e.response}, :unprocessable_entity)\n end\n end",
"def remove_participant\n user = self.load_user(params)\n meeting = self.load_meeting(params)\n participant_ids = params[\"participant_ids\"]\n\n if user != nil and meeting != nil and participant_ids.length > 0\n participant_ids.each do |participant_id|\n if meeting.participants.exists?(participant_id)\n # remove all the participant's votes from each suggestion\n meeting.suggestions.each do |suggestion|\n vote = Vote.where(:voter_id => participant_id, :suggestion_id => suggestion.id)\n if vote != nil\n suggestion.votes.delete(vote)\n end\n end\n meeting.participants.delete(User.find(participant_id))\n end\n end\n self.send_ok\n else\n self.send_error 401\n end\n end",
"def unregister_participant (name_or_participant)\n\n re = @context.plist.unregister(name_or_participant)\n\n raise(ArgumentError.new('participant not found')) unless re\n\n @context.storage.put_msg(\n 'participant_unregistered',\n 'regex' => re.to_s)\n end",
"def destroy\n # Only participants which can edit the trip are able to remove a participant (except for the owner)\n authorize @participant\n\n user_email = @participant.user.email\n @participant.destroy\n flash[:notice] = I18n.t 'trip_participant_removed', :email => user_email\n\n redirect_to trip_participants_path(@trip)\n end",
"def destroy_participant\n @catalogs_participant.destroy\n end",
"def unsubscribe(subscriber)\n @subscribers.delete(subscriber)\n end",
"def unregister_participant (participant_name)\n\n get_participant_map.unregister_participant(participant_name)\n end",
"def delete_subscription subscription\n subscriber.delete_subscription subscription: subscription_path(subscription)\n end",
"def delete_room_subscriber(room_id, user_id)\n Rooms.delete_room_subscriber(@base_url, @headers, room_id, user_id)\n end",
"def unsubscribed\n x = Chatroom.find(params[:id])\n x.unsubscribe()\n end",
"def delete_participant(account_id,\r\n participant_id)\r\n # Prepare query url.\r\n _query_builder = config.get_base_uri(Server::WEBRTCDEFAULT)\r\n _query_builder << '/accounts/{accountId}/participants/{participantId}'\r\n _query_builder = APIHelper.append_url_with_template_parameters(\r\n _query_builder,\r\n 'accountId' => { 'value' => account_id, 'encode' => false },\r\n 'participantId' => { 'value' => participant_id, 'encode' => false }\r\n )\r\n _query_url = APIHelper.clean_url _query_builder\r\n\r\n # Prepare and execute HttpRequest.\r\n _request = config.http_client.delete(\r\n _query_url\r\n )\r\n WebRtcBasicAuth.apply(config, _request)\r\n _response = execute_request(_request)\r\n\r\n # Validate response against endpoint and global error codes.\r\n case _response.status_code\r\n when 401\r\n raise APIException.new(\r\n 'Unauthorized',\r\n _response\r\n )\r\n when 403\r\n raise APIException.new(\r\n 'Access Denied',\r\n _response\r\n )\r\n when 404\r\n raise APIException.new(\r\n 'Not Found',\r\n _response\r\n )\r\n end\r\n unless _response.status_code.between?(200, 208)\r\n raise ErrorException.new(\r\n 'Unexpected Error',\r\n _response\r\n )\r\n end\r\n validate_response(_response)\r\n\r\n # Return appropriate response type.\r\n ApiResponse.new(_response)\r\n end",
"def remove_event(event)\n participant_event = get_participant_event(event)\n\n if not participant_event.nil? and participant_event.role == \"creator\"\n event.route.destroy unless event.route.nil?\n event.destroy\n end\n end",
"def remove_participant(user) # :nodoc:\n id = user.to_s.downcase\n unless @participant_ids.include?(id)\n logger.warning(\"Attempted to remove a participant who was not in the wavelet(#{@id}): #{id}\")\n return nil\n end\n\n # Allow string names to be used as participant.\n user = @context.users[id]\n\n unless user.robot?\n logger.warning(\"Attempted to remove a non-robot from wavelet(#{@id}): #{id}\")\n return nil\n end\n\n if user == @context.robot\n return remove_robot\n end\n\n @context.add_operation(:type => Operation::WAVELET_REMOVE_PARTICIPANT,\n :wave_id => @wave_id, :wavelet_id => @id, :property => user)\n @participant_ids.delete id\n \n user\n end",
"def unsubscribe(course)\n subscribeds.delete(course)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get a participant's subscriptions.
|
def get_participant_subscriptions(account_id,
session_id,
participant_id)
# Prepare query url.
_query_builder = config.get_base_uri(Server::WEBRTCDEFAULT)
_query_builder << '/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}/subscriptions'
_query_builder = APIHelper.append_url_with_template_parameters(
_query_builder,
'accountId' => { 'value' => account_id, 'encode' => false },
'sessionId' => { 'value' => session_id, 'encode' => false },
'participantId' => { 'value' => participant_id, 'encode' => false }
)
_query_url = APIHelper.clean_url _query_builder
# Prepare headers.
_headers = {
'accept' => 'application/json'
}
# Prepare and execute HttpRequest.
_request = config.http_client.get(
_query_url,
headers: _headers
)
WebRtcBasicAuth.apply(config, _request)
_response = execute_request(_request)
# Validate response against endpoint and global error codes.
case _response.status_code
when 401
raise APIException.new(
'Unauthorized',
_response
)
when 403
raise APIException.new(
'Access Denied',
_response
)
when 404
raise APIException.new(
'Not Found',
_response
)
end
unless _response.status_code.between?(200, 208)
raise ErrorException.new(
'Unexpected Error',
_response
)
end
validate_response(_response)
# Return appropriate response type.
decoded = APIHelper.json_deserialize(_response.raw_body)
ApiResponse.new(
_response, data: Subscriptions.from_hash(decoded)
)
end
|
[
"def get_subscriptions\n get_subscriptions_from(@nodename)\n end",
"def get_subscriptions_from_node\n iq = basic_pubsub_active_calls_query(:get)\n\n entities = iq.pubsub.add(REXML::Element.new('subscriptions'))\n entities.attributes['node'] = \"/me/#{@jid}\"\n\n res = []\n @stream.send_with_id(iq) { |reply|\n if reply.pubsub.first_element('subscriptions')\n reply.pubsub.first_element('subscriptions').each_element('subscription') { |subscription|\n res << Jabber::PubSub::Subscription.import(subscription)\n }\n end\n }\n res\n end",
"def get_subscribers(subscription_id)\r\n Subscription.new(subscription_id).getSubscriber.list\r\n end",
"def all_subscriptions\n get(url_(\"subscription\"))\n end",
"def get_participant_subscriptions(account_id, session_id, participant_id, opts = {})\n data, _status_code, _headers = get_participant_subscriptions_with_http_info(account_id, session_id, participant_id, opts)\n data\n end",
"def subscribers\n subscriptions.map(&:subscriber)\n end",
"def get_subscribers\n @subscriptions = subscribers(@nodename)\n end",
"def subscriptions\n Subscription.all( {:customer_id => id} )\n end",
"def subscriptions\n return @subscriptions\n end",
"def get_subscription_list(options = {})\n options = argument_cleaner(required_params: %i( subscriberid ), optional_params: %i( entityid ), options: options )\n authenticated_get cmd: \"getsubscriptionlist\", **options\n end",
"def subscriptions\n \t# Data from GET request\n query = params[\"query\"]\n page = params[\"page\"].to_i\n\n if page < 1 || !page\n page = 1\n end\n\n return search_subscriptions(query, page)\n end",
"def subscriptions\n # subscriber entries are embedded in subscriptions inside of an\n # org. We'll flip this, so that we only return subscriber entries\n # for the account\n orgs = Org.all(:conditions=>{ \"subscriptions.subscribers.account_id\"=> self.id})\n subscribers = []\n orgs.each do |org|\n org.subscriptions.each do |subscription|\n subscribers += subscription.subscribers.select { |subscriber| subscriber.account_id.to_s == self.id.to_s }\n end\n end\n subscribers.flatten!\n subs = []\n subscribers.each do |subscriber|\n subscript = subscriber.subscription\n org = subscript.org\n subs << AccountSubscription.new(org.id.to_s, org.name, subscript.product, subscript.billing_level, subscriber.role)\n end\n subs\n end",
"def subscriptions\n @subscriptions ||= SubscriptionsApi.new config\n end",
"def all\n response = api_request(:get, \"/subscribers.xml\")\n return [] unless response.has_key?(\"subscribers\")\n response[\"subscribers\"].collect{|data| Subscriber.new(data)}\n end",
"def list_subscriptions options = {}\n paged_enum = subscriber.list_subscriptions project: project_path(options),\n page_size: options[:max],\n page_token: options[:token]\n\n paged_enum.response\n end",
"def subscriptions(options = nil)\n request = Request.new(@client)\n path = \"/customers/\" + CGI.escape(@id) + \"/subscriptions\"\n data = {\n\n }\n\n response = Response.new(request.get(path, data, options))\n return_values = Array.new\n \n a = Array.new\n body = response.body\n for v in body['subscriptions']\n tmp = Subscription(@client)\n tmp.fill_with_data(v)\n a.push(tmp)\n end\n\n return_values.push(a)\n \n\n \n return_values[0]\n end",
"def subscriptions\n @subscriptions ||= Services::SubscriptionsService.new(@api_service)\n end",
"def list_subscriptions\n Azure::Armrest::SubscriptionService.new(configuration).list\n end",
"def subscribers\n subscriptions = Joyce::StreamSubscriber\n .joins(\"JOIN joyce_activities_streams AS jas ON joyce_streams_subscribers.stream_id = jas.stream_id\")\n .includes(:subscriber)\n .where(\"jas.activity_id = ?\", self.id)\n .where(\"joyce_streams_subscribers.ended_at IS NULL OR joyce_streams_subscribers.ended_at >= ?\", self.created_at)\n .where(\"joyce_streams_subscribers.started_at <= ?\", self.created_at)\n subscriptions.collect{ |s| s.subscriber }.uniq\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Update a participant's subscriptions. This is a full update that will replace the participant's subscriptions. First call `getParticipantSubscriptions` if you need the current subscriptions. Call this function with no `Subscriptions` object to remove all subscriptions.
|
def update_participant_subscriptions(account_id,
session_id,
participant_id,
body: nil)
# Prepare query url.
_query_builder = config.get_base_uri(Server::WEBRTCDEFAULT)
_query_builder << '/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}/subscriptions'
_query_builder = APIHelper.append_url_with_template_parameters(
_query_builder,
'accountId' => { 'value' => account_id, 'encode' => false },
'sessionId' => { 'value' => session_id, 'encode' => false },
'participantId' => { 'value' => participant_id, 'encode' => false }
)
_query_url = APIHelper.clean_url _query_builder
# Prepare headers.
_headers = {
'content-type' => 'application/json; charset=utf-8'
}
# Prepare and execute HttpRequest.
_request = config.http_client.put(
_query_url,
headers: _headers,
parameters: body.to_json
)
WebRtcBasicAuth.apply(config, _request)
_response = execute_request(_request)
# Validate response against endpoint and global error codes.
case _response.status_code
when 400
raise APIException.new(
'Bad Request',
_response
)
when 401
raise APIException.new(
'Unauthorized',
_response
)
when 403
raise APIException.new(
'Access Denied',
_response
)
when 404
raise APIException.new(
'Not Found',
_response
)
end
unless _response.status_code.between?(200, 208)
raise ErrorException.new(
'Unexpected Error',
_response
)
end
validate_response(_response)
# Return appropriate response type.
ApiResponse.new(_response)
end
|
[
"def update_participant_subscriptions(account_id, session_id, participant_id, opts = {})\n update_participant_subscriptions_with_http_info(account_id, session_id, participant_id, opts)\n nil\n end",
"def update_subscriptions(opts = {})\n data, _status_code, _headers = update_subscriptions_with_http_info(opts)\n data\n end",
"def bulk_update_subscriptions(subscriptions = [])\n attrs = { updateSubscriptionsRequests: subscriptions }\n Iterable.request(conf, '/users/bulkUpdateSubscriptions').post(attrs)\n end",
"def update_subscriptions\n @subscription = @customer.subscription\n @options[:prorate] ||= ChargebeeRails.configuration.proration\n @result = ChargeBee::Subscription.update(@subscription.chargebee_id, @options)\n @plan = Plan.find_by(plan_id: @result.subscription.plan_id)\n @subscription.update(subscription_attrs)\n end",
"def get_participant_subscriptions(account_id,\r\n session_id,\r\n participant_id)\r\n # Prepare query url.\r\n _query_builder = config.get_base_uri(Server::WEBRTCDEFAULT)\r\n _query_builder << '/accounts/{accountId}/sessions/{sessionId}/participants/{participantId}/subscriptions'\r\n _query_builder = APIHelper.append_url_with_template_parameters(\r\n _query_builder,\r\n 'accountId' => { 'value' => account_id, 'encode' => false },\r\n 'sessionId' => { 'value' => session_id, 'encode' => false },\r\n 'participantId' => { 'value' => participant_id, 'encode' => false }\r\n )\r\n _query_url = APIHelper.clean_url _query_builder\r\n\r\n # Prepare headers.\r\n _headers = {\r\n 'accept' => 'application/json'\r\n }\r\n\r\n # Prepare and execute HttpRequest.\r\n _request = config.http_client.get(\r\n _query_url,\r\n headers: _headers\r\n )\r\n WebRtcBasicAuth.apply(config, _request)\r\n _response = execute_request(_request)\r\n\r\n # Validate response against endpoint and global error codes.\r\n case _response.status_code\r\n when 401\r\n raise APIException.new(\r\n 'Unauthorized',\r\n _response\r\n )\r\n when 403\r\n raise APIException.new(\r\n 'Access Denied',\r\n _response\r\n )\r\n when 404\r\n raise APIException.new(\r\n 'Not Found',\r\n _response\r\n )\r\n end\r\n unless _response.status_code.between?(200, 208)\r\n raise ErrorException.new(\r\n 'Unexpected Error',\r\n _response\r\n )\r\n end\r\n validate_response(_response)\r\n\r\n # Return appropriate response type.\r\n decoded = APIHelper.json_deserialize(_response.raw_body)\r\n ApiResponse.new(\r\n _response, data: Subscriptions.from_hash(decoded)\r\n )\r\n end",
"def update_contact_account_subscriptions\n accounts = params[:accounts]\n accounts_subscribing = params[:account_subscriptions].is_a?(Hash) ? params[:account_subscriptions].keys : []\n accounts_unsubscribing = accounts - accounts_subscribing\n accounts_unsubscribing.each do |a_id|\n Case_Watcher.remove_subscription!(current_contact.synced_record, \n :account => Sfaccount.find(a_id).synced_record )\n end\n redirect_to :controller => 'contact', :action => 'settings', \n :notice => \"Account subscriptions updated.\"\n end",
"def update_subscription(options = {})\n query = set_query(options)\n query[:recurring] = 'update_subscription'\n query[:type] = 'recurring'\n require_fields(:subscription_id)\n response = post query\n end",
"def subscriptions\n @subscriptions ||= Services::SubscriptionsService.new(@api_service)\n end",
"def subscriptions=(value)\n @subscriptions = value\n end",
"def modify_subscriptions(subs)\n iq = connection.iq_stanza({'to'=>jid.bare,'type'=>'set'},\n x('pubsub',{:xmlns => EM::Xmpp::Namespaces::PubSubOwner},\n x('subscriptions',{:node => node_id},\n subs.map do |s|\n x('subscription',:jid => s.jid, :subscription => s.subscription, :subid => s.sub_id)\n end\n )\n )\n )\n send_iq_stanza_fibered iq\n end",
"def update_subscribers\n Spotify.playlist_update_subscribers(session.pointer, pointer)\n end",
"def subscriptions\n iq = connection.iq_stanza({'to'=>jid.bare},\n x('pubsub',{:xmlns => EM::Xmpp::Namespaces::PubSubOwner},\n x('subscriptions',:node => node_id)\n )\n )\n send_iq_stanza_fibered iq\n end",
"def update_subscription(subscription_id, params)\n request :patch,\n \"/v3/subscriptions/#{subscription_id}.json\",\n params\n end",
"def get_participant_subscriptions(account_id, session_id, participant_id, opts = {})\n data, _status_code, _headers = get_participant_subscriptions_with_http_info(account_id, session_id, participant_id, opts)\n data\n end",
"def subscriptions\n @subscriptions ||= SubscriptionsApi.new config\n end",
"def update_subscriptions_from_account \n contacts = params[:contacts]\n contacts_subscribing = params[:subscribers].is_a?(Hash) ? params[:subscribers].keys : []\n contacts_unsubscribing = params[:contacts] - contacts_subscribing\n \n # subscribe these contacts\n contacts_subscribing.each do |c_id|\n begin\n Case_Watcher.create_subscription!(Contact.find(c_id), \n :account => Sfaccount.find(params[:id]).synced_record )\n rescue ActiveRecord::RecordNotFound\n logger.info(\"Couldn't create subscription for contact w/id: #{c_id}. Contact doesn't exist.\")\n end\n end\n\n # unsubscribe these contacts\n contacts_unsubscribing.each do |c_id|\n begin\n Case_Watcher.remove_subscription!(Contact.find(c_id), \n :account => Sfaccount.find(params[:id]).synced_record )\n rescue ActiveRecord::RecordNotFound\n logger.info(\"Couldn't remove subscription for contact w/id: #{c_id}. Contact doesn't exist.\")\n end\n end\n \n redirect_to :action => 'account', :id => @account, :notice => \"Account subscriptions updated.\"\n end",
"def update(prorate, options = nil)\n request = Request.new(@client)\n path = \"/subscriptions/\" + CGI.escape(@id) + \"\"\n data = {\n \"trial_end_at\"=> @trial_end_at, \n 'prorate'=> prorate\n }\n\n response = Response.new(request.put(path, data, options))\n return_values = Array.new\n \n body = response.body\n body = body[\"subscription\"]\n \n \n return_values.push(self.fill_with_data(body))\n \n\n \n return_values[0]\n end",
"def update\n @subscription = Subscription.get(params[:id])\n @subscription.update(params[:subscription])\n respond_with(@subscription.reload)\n end",
"def unsubscribe\n currentSubscriptions = nil\n\n @gate.synchronize do\n unless @unsubscribed\n @unsubscribed = true\n currentSubscriptions = @subscriptions\n @subscriptions = []\n @length = 0\n end\n end\n\n currentSubscriptions.each {|subscription| subscription.unsubscribe} if currentSubscriptions\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
other sport name actions are scoped to venue; we need all possible sport names for all venues
|
def sport_name_options
authorize :report
sport_names = company.venues.
flat_map { |venue| venue.supported_sports_options }.
uniq { |hash| hash[:value] }
render json: sport_names
end
|
[
"def unusual_sport; end",
"def national_sport; end",
"def unusual_sport\n fetch('sport.unusual')\n end",
"def venue_name\n venue ? venue.name : \"\"\n end",
"def national_sport\n fetch('team.sport')\n end",
"def winter_olympics_sport; end",
"def summer_olympics_sport; end",
"def sport_name_generator sport\n (sport.name.gsub /' /, \"\") + \".html\"\n end",
"def winter_paralympics_sport; end",
"def sport\n fetch('team.sport')\n end",
"def summer_paralympics_sport; end",
"def show_teams\n puts \"\\nWhat sport would you like to see the teams for? (Enter a sport please)\"\n sport_name = gets.chomp\n\n @sport = Sport.find_by(name: sport_name)\n\n puts \"\\nHere is a list of the teams for #{sport_name}\"\n @sport.teams.each do |x|\n puts \"\\n#{x.name} - #{x.city.name}\\n\"\n # puts x.info\n end\n end",
"def rules_regional_er_csi\n @title = I18n.t('championships.rules') + ' ' + @season.get_full_name\n end",
"def change_team_name(old_name, old_short_name, new_name, new_short_name)\n @teams.each do |t|\n if t.name == old_name && t.short_name == old_short_name\n t.name = new_name\n t.short_name = new_short_name\n break\n end\n end\n @winners.each do |round|\n round.each do |t|\n next if t == UNKNOWN_TEAM\n if t.name == old_name && t.short_name == old_short_name\n t.name = new_name\n t.short_name = new_short_name\n break\n end\n end\n end\n end",
"def sport(sport_id, **options) = get(\"/sports/#{sport_id}\", **options)",
"def college_sport?\n\t\t['college-football','college-basketball'].include?(sport_name)\n\tend",
"def name_all_players()\n set_name()\n set_other_name()\n end",
"def team_names\n game = Game.find(self.game_id)\n type = self.bet_type\n if over_under?\n return \"#{game.away_team} vs #{game.home_team}\"\n elsif type == \"lay\"\n if game.spread <= 0\n return game.home_team\n else\n return game.away_team\n end\n else\n if game.spread <= 0\n return game.away_team\n else\n return game.home_team\n end\n end\n end",
"def get_champion_names\n Static.get_champion_list.keys\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Adds an HTTP header to the request
|
def add_http_header(key, value)
@http_headers[key] = value
end
|
[
"def add_headers\n @headers.each do |field, value|\n @request_header << \"#{field}: #{value}\"\n end\n end",
"def add_headers value\n API.add_headers value\n end",
"def http_header(k, v)\r\n @message_headers[\"http_header_#{k}\".to_sym] = v\r\n end",
"def set_http_header(args={})\n @response[:http_header] = {} unless @response[:http_header]\n @response[:http_header].update(args)\n end",
"def http_header(env)\n env[:request_headers][\"Authorization\"] = \"token #{@auth[:http_header]}\"\n\n return env\n end",
"def set_additional_header(key, value)\n if value.nil? and @http_header.has_key? key\n @http_header[key] = nil\n end\n\n @http_header[key] = value\n end",
"def add_custom_headers headers\n @service.request_options.header.merge! headers\n end",
"def set_header name, value\n response_object.header name, value\n end",
"def set_header(name, value)\n if !@headers[name].nil?\n @headers[name] = @headers[name] + value\n else\n @headers[name] = value \n end\n return self\n end",
"def add_header key, v\n if v.nil?\n get_header key\n elsif has_header? key\n set_header key, \"#{get_header key},#{v}\"\n else\n set_header key, v\n end\n end",
"def set_header key, value\n headers.update(key => value)\n end",
"def add_generic_headers(http_method, uri, request_headers, context = nil)\n request_headers.concat(@session.meta_data_provider.meta_data_headers)\n request_headers.push(RequestHeader.new('Date', get_header_date_string))\n if !context.nil? && !context.idempotence_key.nil?\n request_headers.push(RequestHeader.new('X-GCS-Idempotence-Key', context.idempotence_key))\n end\n authenticator = @session.authenticator\n authentication_signature = authenticator.create_simple_authentication_signature(http_method, uri, request_headers)\n request_headers.push(RequestHeader.new('Authorization', authentication_signature))\n end",
"def perform\n add_request_if_new do |request|\n request.header_set(*arguments)\n end\n end",
"def new_header\n SimpleOAuth::Header.new(\n request_method,\n API_URL,\n params,\n client.oauth_options\n )\n end",
"def set_request_headers(request, headers)\n headers.each { |key, val| request.add_field key, val }\n end",
"def add_header_line h\n raise 'can not modify sent header' if request.response_header.frozen?\n h = h.sub /(?<![\\r\\n])\\z/, \"\\r\\n\"\n request.response_header_extra_lines << h\n end",
"def update_header(name, value)\n end",
"def sign_header(header)\n @request.set_auth_header header\n end",
"def header header, data\n @headers[header] = data\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
load the workflow view
|
def show
name = params[:name]
action = params[:id] ? "show" : "index"
action = params[:view] if params[:view].present?
@page = ("Workflows::#{name.to_s.capitalize}::#{action.capitalize}").constantize.new(params, { user: current_user, cookies: cookies })
render(html: @page.item.display) and return if params[:view].present?
render :template => "#{name}/#{action}"
end
|
[
"def load_view\r\n @view = XamlReader.load_from_path view_path if File.exists? view_path\r\n @view ||= view_name.to_s.gsub(/(.*::)+/, '').classify.new \r\n @view\r\n end",
"def load_view(path, parent, loader)\n sheet = Qt::File.new(path)\n sheet.open(Qt::File::ReadOnly)\n view = loader.load(sheet, parent)\n sheet.close\n \n view\n end",
"def show\n @workflow_task = WorkflowTask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @workflow_task }\n end\n end",
"def show\n @workflow = Workflow.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @workflow }\n end\n end",
"def show\n @workflow = Workflow.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @workflow }\n end\n end",
"def setup_for_showing_view\n #log_on_error do\n objs = ModelCollection.generate_for refresh_objects\n cmds = @command_builder.generate_for commands\n cmds.each do |cmd|\n cmd.add_observer(:reading_input) do\n synchronise_with_view_model\n end\n end\n nails_engine.initialize_with cmds, objs\n logger.debug \"initialized the view manager\", IRONNAILS_FRAMEWORKNAME\n #end\n end",
"def new\n @workflow_task = WorkflowTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @workflow_task }\n end\n end",
"def load_workflow_state\n @workflow_state if instance_variable_defined? :@workflow_state\n end",
"def show\n @workflow_task_type = WorkflowTaskType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @workflow_task_type }\n end\n end",
"def view\n return @view unless @view.nil?\n file = File.join VIEWS, self.template\n @view = Haml::Engine.new File.read(file), HAML_CONFIG\n end",
"def load(mode = :complete)\n unless @loaded || mode == :reload\n self.proxy = XamlProxy.load(name)\n proxy.instance.name = element_name.to_s.to_clr_string if has_parent?\n @loaded = true\n #notify_observers :loaded, self\n end\n if has_container? && has_parent? && mode == :complete && !added?\n parent.add_control(container, proxy)\n @added = true\n end\n children.each { |cv| cv.load }\n logger.debug(\"loaded view #{name}\", IRONNAILS_FRAMEWORKNAME)\n self\n end",
"def new\n @workflow = Workflow.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @workflow }\n end\n end",
"def view_workflow_wdl\n analysis_configuration = AnalysisConfiguration.find_by(namespace: params[:namespace], name: params[:workflow],\n snapshot: params[:snapshot].to_i)\n @workflow_name = analysis_configuration.name\n @workflow_wdl = analysis_configuration.wdl_payload\n end",
"def load!\n load_layout\n refresh!\n adopt_existing_volumes!\n adopt_existing_instances!\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 new\n @workflow = Workflow.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @workflow }\n end\n end",
"def show\n @workflow_log = WorkflowLog.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @workflow_log }\n end\n end",
"def view\n\n @defurl = params[:defurl]\n url = LaunchPermission.to_real_url(@defurl)\n\n @launch = params[:launch]\n\n unless LaunchPermission.may_view(url)\n #\n # preventing rogue urls\n\n flash[:notice] = \"off limits\"\n redirect_to :controller => \"stores\"\n return\n end\n\n begin\n #\n # reading the process definition, if possible...\n\n @process_definition, @json_process_definition = \\\n load_process_definition(url)\n\n rescue Exception => e\n\n m = \"couldn't parse process definition at #{@defurl}<br/>\"\n m += \"because of #{e}\"\n\n flash[:notice] = m\n\n redirect_to :controller => \"launch\"\n return\n end\n\n #\n # the process definition as XML or Ruby code\n\n xml = @process_definition.strip[0, 1] == \"<\"\n\n @wrapped_process_definition = if xml\n\n '<iframe id=\"xml_process_definition\" src=\"' + @defurl + '\"></iframe>'\n else\n\n \"<pre class='rb_process_definition'>\\n\" + @process_definition + \"\\n</pre>\"\n end\n end",
"def new\n @workflow_task_type = WorkflowTaskType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @workflow_task_type }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /evolutions/1 GET /evolutions/1.json
|
def show
@evolution = Evolution.find(params[:id])
end
|
[
"def show\n @evolution = Evolution.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @evolution }\n end\n end",
"def index\n @character_class_evolutions = CharacterClassEvolution.all\n\n render json: @character_class_evolutions\n end",
"def new\n @evolution = Evolution.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @evolution }\n end\n end",
"def index\n @devolutions = Devolution.all\n end",
"def evolution_request(species, name)\n\t\tevolution_request = HTTParty.get(\"http://pokeapi.co/api/v2/evolution-chain/#{species.evolution_id}\")\n\t\tevolutions = PokeapiEvolutions.new(evolution_request, name)\n\t\treturn evolutions\n\tend",
"def show\n @experiment_visual = ExperimentVisual.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @experiment_visual }\n end\n end",
"def index\n @digital_editions = DigitalEdition.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @digital_editions }\n end\n end",
"def show\n @version = Version.find(params[:id])\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: version }\n end\n end",
"def show\n @involve = Involve.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @involve }\n end\n end",
"def index\n @pokemon_evolutions = PokemonEvolution.all\n end",
"def index\n @editions = Edition.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @editions }\n end\n end",
"def index\n @engines = Engine.all\n\n render json: @engines\n end",
"def index\n @electors = Elector.all\n\n render json: @electors\n end",
"def show\n @redcarpet = Redcarpet.find(params[:id])\n @photos = @redcarpet.photos\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @redcarpet }\n end\n end",
"def destroy\n @evolution = Evolution.find(params[:id])\n @evolution.destroy\n\n respond_to do |format|\n format.html { redirect_to evolutions_url }\n format.json { head :no_content }\n end\n end",
"def show\n @vision = Vision.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @vision }\n end\n end",
"def index\n @visualisations = Visualisation.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @visualisations }\n end\n end",
"def show\n @especy = Especie.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @especy }\n end\n end",
"def show\n @vocalium = Vocalium.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @vocalium }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
configures the target page (using a Dynarex document) for a new day
|
def new_day()
puts 'inside new_day' if @debug
@archive_path = Time.now.strftime("%Y/%b/%-d").downcase
@indexpath = File.join(@filepath, @archive_path, 'index.xml')
FileX.mkdir_p File.dirname(@indexpath)
if FileX.exists? @indexpath then
@dx = Dynarex.new @indexpath
else
puts 'creating a new dx file' if @debug
@dx = Dynarex.new @schema, debug: @debug
@dx.order = 'descending'
@dx.default_key = @default_key
@dx.xslt = @dx_xslt
@dx.title = @title
@dx.identifier = @identifier
end
end
|
[
"def setup_launching_soon_page\n @css_file = LAUNCHING_SOON_CONFIG[:css_file_name]\n @launching_date = Time.zone.parse(LAUNCHING_SOON_CONFIG[:launching_date]).utc\n render :template => File.join('launching_soon', LAUNCHING_SOON_CONFIG[:html_file_name]), :layout => \"launching_soon\"\n end",
"def twenty_pct_release_date=(rd=Time.now)\n update_values([:twenty_pct_release_date] => rd.beginning_of_day.utc.xmlschema)\n content_will_change!\n end",
"def on_new_day(filepath, urlpath)\n\n px = create_tags_seealso(@todays_filepath) \n \n return unless File.exists? filepath\n\n # opens the master file for all the liveblog tags\n # e.g. jamesrobertson.eu/liveblog/dxtags.xml\n dxt = DynarexTags.new(@parent_filepath, tagfile_xslt: @tag_xsltpath)\n \n dxt.generate(filepath) do |section|\n\n title = section.x.lines.first\n\n title.scan(/\\B#(\\w+)(?=\\s|$)/).map do |x|\n \n hashtag = x.first\n [hashtag, title.sub(/#\\s+/,''), @urlbase + urlpath + '#' + hashtag]\n end\n\n end \n \n return unless @todays_filepath\n \n end",
"def test04_EventPDF\n\t\tlogin $user_1_email, $master_password\n\t\t$browser.goto($patch_new_event)\n\n \t\t$post_event_title.when_present.set(\"hiking extravaganza #{random}\")\n \t\t$post_event_calendar_start_text.when_present.set(\"#{next_year}-04-01\") \n \t\tsleep 1\n \t\t$post_event_time_start_field.when_present.click\n \t\t$post_event_select_time.when_present.select(\"8:00 AM\")\n \t\t$post_event_location.when_present.set(\"olympic national park #{random}\")\n \t\t$browser.execute_script(\"jQuery('iframe.wysihtml5-sandbox').contents().find('body').prepend('wolf creek trail is unavailable')\")\n \t\t$post_add_media_article.when_present.click\n\t\tfile_upload \"PDFDocument.pdf\"\n\t\tif $environment == 'staging'\n\t\t sleep 10\n\t\tend\n\t\t$post_now_event.fire_event(\"onclick\")\n\t\tsleep 2\n\t\tassert $post_new_post.exists?\n\t\t#verify details?\n\tend",
"def go_to_today\n frm.button(:value=>\"Go to Today\").click\n Calendar.new(@browser)\n end",
"def req_design_doc_refresh\n @design_doc_fresh = { }\n end",
"def remote_link_for_new_schedule_article(text, date, options = {}, html_options = {})\n options[:controller] = \"schedules\"\n options[:params] = {:start_date => date, \n :display_mode => \"schedules\"} \n remote_link_to_new(text, options )\n end",
"def interaction_add_date_navigation(view, page = 1, pages = 1, date = 0, label = \"\")\n interaction_add_navigation(\n view,\n labels: [\"❙❮\", \"❮\", label, \"❯\", \"❯❙\"],\n disabled: [page == 1, page == 1, true, page == pages, page == pages],\n ids: [\"button:date:-1000000000\", \"button:date:-1\", \"button:date:#{date}\", \"button:date:1\", \"button:date:1000000000\"]\n )\nend",
"def place_ad_for_today\n copy_image\n update_page_heading\n end",
"def goto_date_time\n return if authorise_for_web(program_name?,'read') == false\n \n @error_types =[\"palletizing\",\"bintipping\",\"carton labeling\",\"rebin labeling\",\"pdt\",\"all midware errors\",\"bad scans\"]\n \n render :template=> '/diagnostics/midware/goto_date_time.rhtml', :layout=>'content'\n \nend",
"def scrape(options = nil)\n @max_blog_entries = options[:max_blog_entries] if options != nil\n @completed = false\n \n #TODO: pw should be optional\n page = login #if @pw != nil #only do the login thing if you have pw\n page =goto_weblog(page)\n \n #create new xml document from template\n #at some point in future, you want to pass in non-default options here\n create_new_xml_document\n \n scrape_1_page(page)\n next_link = page.links.reject{|i| i.to_s != \"Next 5 >>\" }\n while next_link.size == 1 and @completed != true do\n sleep(1)\n p \"clicking on next link: #{next_link[0].uri.to_s}\"\n page = @agent.click(next_link[0])\n scrape_1_page(page)\n \n #now update the next_link\n next_link = page.links.reject{|i| i.to_s != \"Next 5 >>\" }\n end\n \n #dump @doc out as the output\n file = File.new(\"wordpress.#{Time.now.strftime(\"%Y-%m-%d\")}.xml\", \"w+\")\n file.puts( @doc.inner_html )\n file.close\n \n @doc\n end",
"def set_page_view\n @page_view = 1\n end",
"def make_official\n on EditAcademicCalendar do |page|\n page.make_official\n end\n end",
"def create_new_xml_blog( body, time )\n p \"new xml doc created for time=#{time}\"\n \n #this is our template for a an individual entry in the blog import file\n item_template = <<-eos\n<item>\n<title>xxx</title>\n<link>xxx</link>\n<pubDate>xxx</pubDate>\n<dc:creator><![CDATA[xxx]]></dc:creator>\n\n\t\t<category><![CDATA[Uncategorized]]></category>\n\n\t\t<category domain=\"category\" nicename=\"uncategorized\"><![CDATA[Uncategorized]]></category>\n\n<guid isPermaLink=\"false\">xxx</guid>\n<description></description>\n<content:encoded><![CDATA[xxx]]></content:encoded>\n<excerpt:encoded><![CDATA[]]></excerpt:encoded>\n<wp:post_id>xxx</wp:post_id>\n<wp:post_date>xxx</wp:post_date>\n<wp:post_date_gmt>xxx</wp:post_date_gmt>\n<wp:comment_status>closed</wp:comment_status>\n<wp:ping_status>closed</wp:ping_status>\n<wp:post_name>xxx</wp:post_name>\n<wp:status>publish</wp:status>\n<wp:post_parent>0</wp:post_parent>\n<wp:menu_order>0</wp:menu_order>\n<wp:post_type>post</wp:post_type>\n<wp:post_password></wp:post_password>\n</item>\n\n eos\n \n doc = Hpricot.XML(item_template)\n \n #xanga names entries on date, so we will do same\n doc.search(\"title\")[0].inner_html = \"#{time.gsub(\" +0000\",\"\")}\"\n #link is constructed as follows: [base_blog_url]/[YYYY]/[MM]/[DD]/[title.downcase]\n #for dates, this looks like: [base_blog_url]/[YYYY]/[MM]/[DD]/tue-10-mar-2009-001259-0000/, for example\n doc.search(\"link\")[0].inner_html = \"#{@options[:base_blog_url]}/#{Time.now.strftime(\"%Y\")}/#{Time.now.strftime(\"%m\")}/#{Time.now.strftime(\"%d\")}/#{time.downcase.gsub(\",\", \"\").gsub(\":\",\"\").gsub(\" +\",\"-\").gsub(\" \",\"-\")}/\"\n \n #pubDate is 'time' passed in\n doc.search(\"pubDate\")[0].inner_html = \"#{time}\"\n #the creator is the username that gets credit for the posting i guess\n doc.search(\"dc:creator\")[0].inner_html = \"<![CDATA[#{@options[:creator]}]]>\"\n #guid is, as far as i can tell follows base_blog_url/?p=N format, where N=sequence of blog \n doc.search(\"guid\")[0].inner_html = \"#{@options[:base_blog_url]}/?p=#{@curr_blog_entries}\"\n #content:encoded is the blog body passed here\n doc.search(\"content:encoded\")[0].inner_html = \"<![CDATA[#{body}]]>\"\n #wp:post_id is as far as i can tell, just the sequential ordering of imported entries \n doc.search(\"wp:post_id\")[0].inner_html = \"#{@curr_blog_entries}\"\n\n #I've a conflict with my Time class; so I have to hack around, so sorry\n #input: time formatted as Tue, 10 Mar 2009 00:12:59 +0000\n #output: 2009-03-10 00:12:59, for example\n def convert_to_wp_post_date(time)\n ret = time.split(\" \")\n month_value = { 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12 }\n ret[2] = month_value[ ret[2].upcase ] \n ret[2] = \"0\" + ret[2].to_s if ret[2].to_s.size == 1 #we want month padded to 2 digits\n ret[1] = \"0\" + ret[1].to_s if ret[1].to_s.size == 1 #we want day padded to 2 digits\n \n \"#{ret[3]}-#{ret[2]}-#{ret[1]} #{ret[4]}\"\n end\n \n #wp:post_date /wp:post_date_gmt is yet another format for the time field passed in\n #it looks like: 2009-03-10 00:12:59, for example\n doc.search(\"wp:post_date\")[0].inner_html = \"#{convert_to_wp_post_date(time)}\"\n doc.search(\"wp:post_date_gmt\")[0].inner_html = \"#{convert_to_wp_post_date(time)}\"\n #wp:post_name with xanga, it is same asthe last part of the link tag\n doc.search(\"wp:post_name\")[0].inner_html = \"#{time.downcase.gsub(\",\", \"\").gsub(\":\",\"\").gsub(\" +\",\"-\").gsub(\" \",\"-\")}\"\n\n doc\n end",
"def set_show_time_setting\n change_show_time\n home_change_template = @simulation_mode ? \"home/change_simulation_mode\" : \"home/change_show_time\"\n render :update do |page|\n page[:show_time_setting].replace_html :partial => \"layouts/show_time_setting\"\n page[:page_jp_title].replace_html \"ホーム\"\n# page[:layout_calendar].replace_html :partial => \"layouts/calendar_menu\"\n page[:menu_clusters].replace_html :partial => \"menu_clusters\"\n page[:contents_i].replace_html :partial => home_change_template\n end\n end",
"def release_date=(rd=Time.now)\n\t\tupdate_values([:release_date] => rd.beginning_of_day.utc.xmlschema)\n self.content=self.ng_xml.to_s\n end",
"def auto\n redirect_to report_url(Report.key_for_area(Current.setting.area))\n end",
"def after_new_document(document)\n\n end",
"def adjust_current_date\n session[:date] = Date.today\n return true\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
guesses random word of appropriate length
|
def guess_word(word_length)
self.sample(dict.select { |word| word.length == word_length } )
end
|
[
"def random_word(difficulty)\n map = word_map()\n words = map[difficulty]\n words[rand(words.length)]\nend",
"def ramdon_word(words_array)\n random_number = rand(0..words_array.length)\n word = words_array[random_number].gsub!(/\\r/, \"\")\n if word.length >= 5 && word.length <= 12\n return word.downcase\n else\n ramdon_word(words_array)\n end\nend",
"def word_rand\n o = [('a'..'z')].map{|r| r.to_a}.flatten\n word = (0..8).map{ o[rand(o.length)] }.join\n return word\n end",
"def get_random_word\n word = File.read(\"dic/5desk.txt\").split.find_all { |word| word.length > 4 && word.length < 13 }\n return word.sample(1).join\n end",
"def choose_word(word_list)\n acceptable_words = word_list.select{ |word| word.length > 4 && word.length < 13 }\n word = acceptable_words[Random.rand(acceptable_words.length)].strip\n end",
"def pick_random_word(dictionary)\n random_num = rand(dictionary.length)\n dictionary[random_num]\n end",
"def random_word\n\t\tnumber = rand(@modified_dictionary.length)\n\t\t@modified_dictionary[number]\n\tend",
"def random_word(msg)\n word = LiterateRandomizer.word\n @last_words = [] if @last_words.nil?\n word = LiterateRandomizer.word while @last_words.include?(word)\n @last_words.prepend_capped(word, 5)\n msg.reply(word)\n end",
"def makes_secret\n length = @word.length\n @guessed = @guessed.push('_') * length\n end",
"def new_word\n\t\tdictionary = File.open(\"5desk.txt\", \"r\").readlines\n\t\tbegin \n\t\t\t@the_word = dictionary[rand(0..dictionary.length)]\n\t\tend while @the_word.length >= 12 || @the_word.length <=5\n\t\t@the_word\n\tend",
"def random_word()\n \t WORDS_WITHOUT_PUNCTUATION[rand(WORDS_WITHOUT_PUNCTUATION.length)]\n end",
"def long_word\n keys = @dictionary.keys.sort\n @dictionary[keys.partition{|v| v >= keys[keys.size/2] }.first.sample].sample # Magic! It actually just randomly picks from the larger words..\n end",
"def random_word_of_size(size)\n words = find_words(size, (('a'..'z').to_a * 3).join)\n words[rand(words.size)]\n end",
"def word(length=nil)\n length = @dictionary.keys.sample if !length || length > @dictionary.keys.max\n @dictionary[length].sample if @dictionary.has_key?(length)\n end",
"def pick_dictionary_word(options={})\n min_length = (options[:exact] || options[:min] || 1).to_i\n max_length = (options[:exact] || options[:max] || 5).to_i\n \n language = (options[:language] || @@default_language).to_s\n validate_language(language)\n \n dictionary = options[:dictionary] || @@dictionaries[language] ||= load_dictionary(language)\n validate_dictionary(dictionary)\n \n sized_words = dictionary.select do |word|\n min_length <= word.length && word.length <= max_length\n end\n if !sized_words.empty?\n return sized_words[rand(sized_words.length)] \n else\n # TODO: How should an empty sized_words be handled?\n return \"\"\n end\n end",
"def chosen_random_word()\n word_found = false\n while !word_found\n word = File.readlines(@filename).sample\n word.gsub!(\"\\n\", \"\")\n if word.length.between?(5,12)\n @chosen_word = word\n word_found = true\n end\n end\n end",
"def random_word\n words = @dictionary.dictionary.keys\n words[rand(words.length)]\n end",
"def random_word\n @dict[rand(@dict.count)]\n end",
"def random_word\n keys = @dictionary.dictionary.keys\n keys[rand(keys.length)]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Finds Single match via the supplied ID Usage: match = PUBG::Match(1337) Arguments: id: (Integer)
|
def match(id)
self.get("/matches/#{id}")
end
|
[
"def match(id_or_hash, hash={})\n url = Base + 'match'\n if id_or_hash.kind_of? String\n id = id_or_hash\n url += \"/#{id}\"\n params_hash = hash\n elsif id_or_hash.kind_of? Hash\n id = nil\n params_hash = id_or_hash\n else\n raise ArgumentError, \"first parameter must be a kind of String or Hash\"\n end\n url += add_querystring(params_hash) #\"?\" + FsUtils.querystring_from_hash(params_hash) unless params_hash.empty?\n response = @fs_communicator.get(url)\n familytree = Org::Familysearch::Ws::Familytree::V2::Schema::FamilyTree.from_json JSON.parse(response.body)\n # require 'pp'\n # pp familytree\n familytree.matches[0]\n end",
"def determineMatchID\n @matchid = @value.get_attribute('id').split('_')[2]\n end",
"def find(id)\r\n find_one do |record|\r\n record.id == id\r\n end\r\n end",
"def current_match_obj\n return matches.find_by(id: current_match) if current_match.present?\n end",
"def find_one(id, params={})\n find_with_endpoint([:one, :default], {id: id}.merge(params))\n end",
"def match ident\n case ident\n when Match\n ident\n when Fixnum, Symbol\n if ident == :new\n Match.create!(:white => Player.find(:first), :black => Player.find(:first) )\n else\n Match.find(ident)\n end\n when String\n Match.find_by_name(ident)\n end\n end",
"def find_one(id, params={})\n find_with_endpoint([\"one\", \"default\"], {\"id\" => id}.merge(params))\n end",
"def find_by_id(id)\n self.select { |record| record.id == id.to_s }.first\n end",
"def get(id)\n # \"ID\" is an internal search field for Summon, not listed in our\n # own search_field_definitions, but it works.\n results = search(id, :search_field => \"ID\")\n\n raise BentoSearch::NotFound.new(\"ID: #{id}\") if results.length == 0\n raise BentoSearch::TooManyFound.new(\"ID: #{id}\") if results.length == 0\n raise (results.error[:exception] || Exception.new(error.inspect)) if results.failed?\n\n return results.first\n end",
"def find_match\n user_match = User.find_by(id: self.id)\n end",
"def find_match(match_request)\n account = self.session[:account]\n\n enqueue(account)\n \n if accounts = dequeue(2)\n logger.debug \"Starting a match between #{accounts.first} and #{accounts.second}\"\n start_match(accounts)\n else\n logger.debug \"Not enough alive accounts to start a match - waiting\"\n end\n end",
"def matches_by_id\n Hash[*matches.collect{|match| [match.id, match]}.flatten]\n end",
"def find_first(match)\n entry = Lib::ErrlogEntry.new\n status = Lib.errlog_find_first(@handle, match.to_struct, entry)\n return if status == :done\n Errors.throw(status, \"handle: #{@handle}, match: #{match}\") unless status == :ok\n\n Entry.new(entry)\n end",
"def match_with_seed(seed)\n self.matches.order(:id).where(seed: seed).first\n end",
"def get_match(id, matches, p1, p2)\n outputmatch = nil\n matches.each do |match|\n outputmatch = match['match'] if ((match['match']['player1_id'].to_s.eql?(p1) && match['match']['player2_id'].to_s.eql?(p2))||(match['match']['player1_id'].to_s.eql?(p2) && match['match']['player2_id'].to_s.eql?(p1)))\n end\n return outputmatch\nend",
"def find_by_tournament match_id, tournament_code\n DynamicModel.new perform_request api_url \"matches/#{match_id}/by-tournament-code/#{tournament_code}\"\n end",
"def full_match\n @match_data[0]\n end",
"def get_current_match\n\t\t@current_match ||= if params[:match_id].present?\n\t\t\tMatch.find(params[:match_id])\n\t\tend\n\tend",
"def find(id)\n @records.find { |record| record.id == id }\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Builds the query that will be passed to the matches request, based on what options are supplied (if any)
|
def query_builder(options)
parsed_options = []
options.each do |key,value|
case key
when :offset
parsed_options << "page[offset]=#{value}"
when :limit
parsed_options << "page[limit]=#{value}"
when :sort
parsed_options << "sort=#{value}"
when :created_at_start
parsed_options << "filter[createdAt-start]=#{value}"
when :created_at_end
parsed_options << "filter[createdAt-end]=#{value}"
when :player_ids
parsed_options << "filter[playerIds]=#{value.join(',')}"
when :game_mode
parsed_options << "filter[gameMode]=#{value}"
end
end
if options.empty?
"/matches"
else
queries = parsed_options.join("&")
"/matches?#{queries}"
end
end
|
[
"def build_query\n query = '?'\n query_hash = @entity.query\n return if query_hash.empty?\n query += \"$select=#{query_hash[:select]}&\" unless query_hash[:select].nil?\n query += \"$filter=#{query_hash[:filters]}&\" unless query_hash[:filters].nil?\n query += \"$orderby=#{query_hash[:order_by]}&\" unless query_hash[:order_by].nil?\n query += \"$top=#{query_hash[:top]}&\" unless query_hash[:top].nil?\n query += \"$expand=#{query_hash[:expand]}&\" unless query_hash[:expand].nil?\n query += \"$skip=#{query_hash[:skip]}&\" unless query_hash[:skip].nil?\n query += \"#{query_hash[:custom_param]}&\" unless query_hash[:custom_param].nil?\n query\n end",
"def custom_query(options)\n form_data = {}\n options.each {|k,v| form_data[k.to_s] = v.to_s }\n form_data['action'] = 'query'\n make_api_request(form_data).first.elements['query']\n end",
"def get_search_query_string(options)\n query = \"\"\n\n if options[:scope].include?(\"/\")\n query += \"repo:#{options[:scope]} \"\n else\n query += \"user:#{options[:scope]} \"\n end\n\n if options[:label] == \"issues\"\n query += \"is:issue \"\n elsif options[:label] == \"pulls\"\n query += \"is:pr \"\n else\n query += \"label:\\\"#{options[:label]}\\\" \"\n end\n\n if !options[:state].nil?\n query += \"is:#{options[:state]} \"\n end\n\n if !options[:created_at].nil?\n query += \"created:#{options[:created_at][:from].iso8601()}..#{options[:created_at][:until].iso8601()} \"\n end\n\n if !options[:closed_at].nil?\n query += \"closed:#{options[:closed_at][:from].iso8601()}..#{options[:closed_at][:until].iso8601()} \"\n end\n\n return query.strip\n end",
"def build_query_from_options(api_method, options = {})\n # normalize options to a hash\n unless options.respond_to?(:merge!)\n options = CGI.parse(options)\n end\n\n options.merge!({:command => api_method, :token => @token})\n options.merge!({:format => :xml}) if options.key?(:output) && 'mrss'.eql?(options[:output])\n { :query => options }\n end",
"def build_json_query(additional_param_items=[], options={})\n options[:any_or_all_sections] ||= []\n \n query = {:phenotype => []}\n additional_param_items.each do |item_name|\n query[item_name.to_s.singularize.to_sym] = []\n query[:gene_class] = [] if item_name.to_s.singularize.to_sym == :gene\n end\n query[:include_inferred] = (params[:filter][:include_inferred] == 'true') if options[:inferred]\n options[:any_or_all_sections].each do |section| \n query[\"match_all_#{section}\".to_sym] = (params[:filter][\"#{section}_match_type\"] == 'all')\n end\n \n params[:filter][:phenotypes].each do |index, ph|\n phenotype = {}\n [:entity, :quality, :related_entity].each do |phenotype_component|\n phenotype[phenotype_component] = {:id => ph[phenotype_component]} unless ph[phenotype_component].blank?\n end\n phenotype[:entity][:including_parts] = (ph[:including_parts] == 'true') if phenotype[:entity]\n query[:phenotype] << phenotype\n end\n additional_param_items.each do |item_name|\n params[:filter][item_name].each do |index, id|\n if item_name.to_s == 'genes'\n query_section_name = Gene.gene_class?(@filter_term_names[id]) ? :gene_class : :gene\n query[query_section_name] << {:id => id}\n else\n query[item_name.to_s.singularize.to_sym] << {:id => id}\n end\n end\n end\n return URI.encode(JSON.generate(query))\n end",
"def build_queries(text, build_opts, norm_opts)\n\t\ttrier = TEXT_TO_TRIE.new( build_opts[:min_tokens],\n\t\t\t\t\t\t\t\t build_opts[:max_tokens],\n\t\t\t\t\t\t\t\t )\n\t\t\n\t\t# Queries are normalized.\n\t\tqueries = trier.to_trie( text, \n\t\t \t\t\t\t norm_opts[:lowercased], \n\t\t \t norm_opts[:hyphen_replaced], \n\t\t \t norm_opts[:stemmed], \n\t\t \t)\n\t\t# queries - A hash of key (the normalized query string) and value (the array of \n\t\t# offsets (range values)) pairs.\n\t\tqueries\n\tend",
"def query\n ([query_for_one_keyword] * split_query_string.size).join(' AND ')\n end",
"def construct_cql_query(args)\n if args[:query].kind_of?(Hash)\n # multi-field\n args[:query].collect {|field, query| fielded_cql_query(query, field)}.join(\" AND \")\n else\n fielded_cql_query(args[:query], args[:search_field] || \"srw.kw\")\n end\n end",
"def build_query_for(options={})\n \n condition = ''\n order = ''\n \n # We specify different quries based on wheter we are getting a single\n # instance or all instances of an entity.\n condition = \"i.id = #{options[:instance]}\" if options[:instance]\n condition = \"i.entity_id = #{options[:entity]}\" if options[:entity]\n \n # These are the instance ids sorted and filtered \n instance_ids = []\n \n # if the instances are to be fetched for entity, we need to \n # modify the conditions in order to support the pagination and others things\n if options[:entity]\n records_info = get_filtered_instance_ids( \n :entity => options[:entity],\n :order_by => options[:order_by],\n :direction => options[:direction],\n :conditions => options[:conditions],\n :start_index => options[:start_index],\n :max_results => options[:max_results]\n )\n \n instance_ids = records_info[:instance_ids]\n \n # If no instance is found, raise an exception\n if instance_ids.nil? or instance_ids.length == 0\n msg = \"No instances found\"\n msg += \" based on #{options[:conditions]}\" if options[:conditions]\n raise msg\n end\n \n condition += \" AND i.id IN (#{instance_ids.join(',')})\"\n# if options[:offset] or options[:limit]\n# condition += \" AND i.id IN (SELECT id FROM instances WHERE instances.entity_id =#{options[:entity]} ORDER BY id\"\n# condition += \" OFFSET #{options[:offset]}\" if options[:offset]\n# condition += \" LIMIT #{options[:limit]}\" if options[:limit]\n# condition += ')'\n# end\n end\n \n # Ordering clause of the \n order = 'display_order' if options[:instance]\n order = 'id, display_order' if options[:entity]\n \n \n # These are the tables that we query for the values because:\n # Simple text values are stored in detail_values\n # Integer values are in integer_detail_values\n # Date values are in date_detail_values\n dt = [ \"detail_values\", \"integer_detail_values\", \"date_detail_values\"]\n columns = 'i.id, i.lock_version as instance_version, d.id as detail_id, d.name, dt.name as data_type, v.id as detail_value_id, v.lock_version as value_version, v.value::text, e2d.display_order'\n # Here we list the columns that we want to have.\n \n\n #FIXME: Soem tables can be take out of join:\n # * entities2details. currently needed because need the display order.\n # * entities\n # * data_types?? (not possible due to integer, date and ddl value types)\n query = dt.inject(\"\") do |q, t|\n q += %Q~SELECT #{columns} \n FROM #{t} v \n JOIN details d ON (v.detail_id = d.id) \n JOIN instances i ON (i.id=v.instance_id) \n JOIN entities e ON (e.id=i.entity_id) \n JOIN entities2details e2d ON (e2d.detail_id=d.id and e2d.entity_id = e.id) \n JOIN data_types dt ON (d.data_type_id=dt.id)\n WHERE #{condition} UNION ~\n end\n\n # And this is for \n query += %Q~SELECT i.id, i.lock_version as instance_version, d.id as detail_id, d.name, dt.name as data_type, v.id as detail_value_id, v.lock_version as value_version, p.value::text, e2d.display_order \n FROM ddl_detail_values v \n JOIN details d ON (v.detail_id = d.id) \n JOIN detail_value_propositions p ON (p.id=v.detail_value_proposition_id) \n JOIN instances i ON (i.id=v.instance_id) \n JOIN entities e ON (e.id=i.entity_id) \n JOIN entities2details e2d ON (e2d.detail_id=d.id and e2d.entity_id = e.id) \n JOIN data_types dt ON (d.data_type_id=dt.id)\n WHERE #{condition} ORDER BY #{order}~\n\n return [query, records_info]\n \n \n end",
"def generate_query\n \n # set up for the loop\n @query_string = @base\n @query_string += @wrapped_values[:format] + @wrapped_values[:query_string] + @wrapped_values[:rank] + @wrapped_values[:api_key]\n \n end",
"def query_params\n {\n name:,\n q: query,\n api_key:\n }\n end",
"def build_query(builder)\n builder.OPTION {\n @option.each do |k, v|\n builder.PARAMETER k.to_s.upcase\n value = case v\n when Array then v.join(',')\n when Hash then v.map { |a| a.join(':') }.join(',')\n else\n v.to_s\n end\n\n # I don't know this is correct or not, but I think we should not\n # touch third party ID.\n value.upcase! unless k == :prefer_xid\n\n builder.VALUE value\n end\n }\n end",
"def create_dsl_query\n # Added q_param so we only permit certain params on search and be able to use them as a hash\n {\n query: {\n bool: { must: parse_dls_query_params }\n }\n }\n end",
"def build_search_url(options = {})\n url = APP_CONFIG['ac']['api_url']\n search_path = APP_CONFIG['ac']['api_search_path']\n search_url = \"#{url}#{search_path}\"\n\n api_params = {}\n\n # basic query params\n basics = %w(q page per_page sort order)\n basics.each do |key|\n api_params[key] = options[key] if options[key].present?\n end\n\n # If we get non-AC sort params, either fix or ignore\n sort_key = options['sort']\n order_key = options['order']\n\n # combined, e.g.: sort=pub_date_sort+desc\n if sort_key.present? && sort_key.match(/\\w+ \\w+sc/)\n sort_key, order_key = sort_key.match(/(\\w+) (\\w+sc)/).captures\n end\n sort_key = 'date' if sort_key == 'pub_date_sort'\n if %w(best_match date title).include? sort_key\n api_params['sort'] = sort_key\n api_params['order'] = order_key if %w(asc desc).include? order_key\n end\n\n # *** remap params ***\n # \"SEARCH FIELD\" V.S. \"SEARCH TYPE\"\n key_remaps = {\n 'search_field' => 'search_type'\n }\n value_remaps = {\n 'all_fields' => 'keyword',\n 'all' => 'keyword'\n }\n key_remaps.each do |clio_key, api_key|\n # We have a key that needs to be remapped\n next unless options[clio_key].present?\n # if the value is in our remap table, remap value also\n clio_value = options[clio_key]\n api_value = value_remaps[clio_value] || clio_value\n api_params[api_key] = api_value\n end\n\n # facet filter params\n filters = %w(author date department subject type columbia_series)\n filters.each do |key|\n api_params[key] = options[key] if options[key].present?\n end\n\n # DISSERTATIONS\n # hardcode filter to show only dissertations if we're in that datasource\n api_params['type[]'] = 'Theses' if options['datasource'] == 'ac_dissertations'\n\n search_url = \"#{search_url}?#{api_params.to_query}\" if api_params.present?\n Rails.logger.debug \"Spectrum::SearchEngines::Ac build_search_url(options)\\n #{search_url}\"\n search_url\n end",
"def query_options(options)\n options.each_with_object({}) do |(key, val), hash|\n case key\n when :date\n hash[:ShowDate] = val.to_ShowDate\n when :movie_id\n hash[:movie_id] = val\n when :movie_source\n # Set both movie_id and ShowDate.\n movie_source = val\n hash.merge! query_options(movie_id: movie_source.external_id)\n hash.merge! query_options(date: movie_source.released_on) if movie_source.released_on\n when :postal_code\n hash[:SearchZip] = val.to_s.gsub(' ', '')\n else\n raise \"unknown option: #{key}\"\n end\n end\n end",
"def build_param_string(query_string, options = {})\n query = build_query(query_string, options)\n param = \"?q=#{escape(query[:q])}\"\n param += \"&sort=#{escape(query[:sort])}\" if query[:sort]\n param += \"&start=#{escape(query[:start])}\" if query[:start]\n param += \"&rows=#{escape(query[:rows])}\" if query[:rows]\n param\n end",
"def build_search_conditions(query)\n return nil\n end",
"def build_search_query\n doc_query = self\n\n search.query do\n function_score do\n functions doc_query.functions\n\n query do\n bool do\n if doc_query.query.present?\n must do\n bool do\n # prefer bigram matches\n should { match bigrams: { operator: 'and', query: doc_query.query } }\n should { term promote: true }\n\n # prefer_word_form_matches\n must do\n bool do\n should do\n bool do\n must do\n simple_query_string do\n query doc_query.query\n fields doc_query.boosted_fields\n end\n end\n\n unless doc_query.query.match(/\".*\"/)\n must do\n bool do\n doc_query.full_text_fields.values.each do |field|\n should { common({ field => doc_query.common_terms_hash }) }\n end\n end\n end\n end\n end\n end\n\n should { match(audience: { operator: 'and', query: doc_query.query }) }\n should { match(basename: { operator: 'and', query: doc_query.query }) }\n should { match(searchgov_custom1: { operator: 'and', query: doc_query.query.downcase }) }\n should { match(searchgov_custom2: { operator: 'and', query: doc_query.query.downcase }) }\n should { match(searchgov_custom3: { operator: 'and', query: doc_query.query.downcase }) }\n should { match(tags: { operator: 'and', query: doc_query.query.downcase }) }\n end\n end\n end\n end\n end\n\n filter do\n bool do\n must { term language: doc_query.language } if doc_query.language.present?\n\n minimum_should_match '100%'\n should do\n bool do\n if doc_query.included_sites.any?\n minimum_should_match 1\n\n doc_query.included_sites.each do |site_filter|\n should do\n bool do\n must { term domain_name: site_filter.domain_name }\n must { term url_path: site_filter.url_path } if site_filter.url_path.present?\n end\n end\n end\n end\n end\n end\n\n FILTERABLE_TEXT_FIELDS.each do |field|\n next if doc_query.send(field).blank?\n\n should do\n bool do\n doc_query.send(field).each do |field_value|\n minimum_should_match 1\n should { term \"#{field}\": field_value.downcase }\n end\n end\n end\n end\n\n must { range changed: doc_query.date_range } if doc_query.timestamp_filters_present?\n must { range created: doc_query.date_range_created } if doc_query.created_timestamp_filters_present?\n\n if doc_query.ignore_tags.present?\n must_not do\n terms tags: doc_query.ignore_tags\n end\n end\n\n doc_query.excluded_sites.each do |site_filter|\n if site_filter.url_path.present?\n must_not { regexp path: { value: \"https?:\\/\\/#{site_filter.domain_name}#{site_filter.url_path}/.*\" } }\n else\n must_not { term domain_name: site_filter.domain_name }\n end\n end\n end\n end\n end\n end\n end\n end\n end",
"def make_query_string\n\t\t\tif(self.non_query_fields != nil)\n\t\t\t\tfields = self.fields - self.non_query_fields\n\t\t\telse\n\t\t\t\tfields = self.fields\n\t\t\tend\n\t\t\tqstr = 'SELECT ' + fields.join(', ') + ' FROM ' + self.object_name\n\t\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Makes a Web Scrapper to get the twitter description
|
def fetch_twitter_informations
unparsed_html = Nokogiri::HTML(open(twitter_profile_address))
self.twitter_username = fetch_twitter_username(unparsed_html)
self.twitter_description = fetch_twitter_description(unparsed_html)
end
|
[
"def scraper\n url = 'https://twitter.com/DataScienceCtrl' # This gets the url to scrape\n\n raw_page = HTTParty.get(url) # This is just used to get the page itself Nokogiri will do the rest\n\n parsed_page = Nokogiri::HTML(raw_page) # This puts it it into Nokogiri::XML::NodeSet\n # puts parsed_page # Prints the parsed page as a Nokogiri Nodelist\n\n\n # Now that we have the pages lets tarted the elements by CSS class( we cant by html since....well Front end code)\n\n ds_tweets = parsed_page.css('p.tweet-text') # Sets a variable to all of the tweets we have\n\n # puts ds_tweets.class # This should be the type Nokogiri::XML::NodeSet\n\n # ds_tweets.each do |tweet| # This will loop over the nodeSet like and array and we can access the text via the .text mehod\n # puts tweet.text\n # end\n\n # Now that we can see the tweets, lets put them into a data structure in this case a hash/dictionary\n tweet_array = Array.new\n ds_tweets.each do |dsTweet|\n tweet_hash = {\n tweet: dsTweet.text\n }\n tweet_array.push(tweet_hash)\n end\n\n tweet_array.each do |key, value|\n puts key\n puts value\n\n end\n\n # byebug # using bye bug to test variables\nend",
"def fetch_details_from_twitter\n\n\tend",
"def getTwitters(searchTerm)\n # url encoding the searchterm\n searchTerm = CGI::escape(searchTerm)\n \n # grabbing the search results for the given searchTerm from summize as a REXML document\n doc = REXML::Document.new open(\"http://summize.com/search.atom?lang=en&rpp=100&q=#{searchTerm}\").read\n \n # this part swaps the current @content stack with the search result\n @content.clear {\n doc.elements.each(\"feed/entry\") do |element|\n stack(:width => 500, :height => 80) do\n fill \"#282828\"..\"#141414\", :angle => 180\n rect 0, 0, 500, 80, 5\n flow(:margin_left => 5, :margin_top => 5) do\n flow(:width => 50) do\n #clicking on avatar => visit the person's twitter profile in a webbrowser\n click do\n visit(element.elements['author'].elements['uri'].text)\n end\n \n element.each_element_with_attribute('rel', 'image', 1) do |pic|\n image pic.attributes['href'] # downloads and displays avatar\n end\n end\n flow(:width => 440) do\n # clicking on message => visit the message on twitter in a webbrowser\n click do\n element.each_element_with_attribute('rel', 'alternate', 1) do |profile|\n visit(profile.attributes['href'])\n end\n end\n \n inscription getFormattedTime(element.elements[\"published\"].text), :stroke => orange\n para element.elements[\"title\"].text, :stroke => white\n end\n end\n end\n end\n }\n end",
"def extract\n if summary.blank? || title.blank?\n # http = RubyTubesday.new\n # raw = http.get(link)\n c = Curl::Easy.perform(self.link) do |curl|\n curl.follow_location = true\n end\n data = Nokogiri::HTML(c.body_str)\n no_body = false\n end\n if extended_body.blank?\n self.extended_body = Sanitize.clean(SemanticExtraction::AdHoc.extract_text(link))\n end\n if summary.blank?\n if meta_desc = data.css(\"meta[name='description']\").first \n content = meta_desc['content']\n elsif no_body\n content = \"No summary available\"\n else\n content = Nokogiri::HTML(extended_body)\n content = content.css(\"p\").first.text\n end\n self.summary = content\n end\n if title.blank?\n self.title = data.css(\"title\").first.children.first.to_s\n end\n end",
"def downloadTwitterWebPage\n twitterURL = 'https://twitter.com/' + @screen_name\n\n uri = ::URI.parse(twitterURL)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n # Make the HTTP request to Twitter.\n response = http.request(Net::HTTP::Get.new(uri.request_uri))\n\n # If it's not accepted, throw an exception.\n @web_page = response.body\n end",
"def scrape_basic_content(t)\n\t\t\tbegin\n\t\t\t\ttweet_id = t.xpath(\"@data-item-id\").text().to_s.strip\n\t\t\t\tposter_name = t.xpath(\"//strong/text()\").to_s.strip\n\t\t\t\t#check if the poster is the current user!!\n\t\t\t\tputs \"NAME#{@name}\"\n\t\t\t\t@max_tweet_id = tweet_id\n\t\t\t\tset_id(tweet_id)\n\t\t\t\t#puts tweet_id\n\t\t\t\ttweet_content = t.xpath(\"./div/div/p/text()\").to_s.strip\n\t\t\t\t#puts tweet_content\n\t\t\t\tset_content(tweet_content)\n\n\n\t\t\trescue Exception => e\n\t\t\t\tLogWriter.error(e)\n\t\t\t\treturn self\t\n\t\t\tend\n\tend",
"def parse_tweet(tweet)\n oembeds = []\n # link urls:\n re = Regexp.new('(^|[\\n ])([\\w]+?://[\\w]+[^ \\\"\\n\\r\\t<]*)')\n # find urls through redirects\n urls = []\n tweet.scan(re) do |s|\n # find final url\n url = fetch(s[1])\n # replace url with found url\n urls << [s[1], url]\n end\n # do url link replacements\n urls.each do |url|\n # test each url for oembed data\n oohembed_url = \"http://oohembed.com/oohembed/?url=#{url[1]}\"\n resp = Net::HTTP.get_response(URI.parse(oohembed_url))\n if resp.code == '200' && resp.body.length > 0\n oembeds << resp.body\n end\n # replace urls with links\n tweet.gsub!(url[0], \"<a href=\\\"#{url[0]}\\\" title=\\\"#{CGI.escapeHTML(url[1])}\\\">#{shorten_url(url[1])}</a>\")\n end\n # link usernames\n re = Regexp.new('(\\@)([\\w]+)')\n tweet.gsub!(re, '<a href=\"http://twitter.com/\\2\">@\\2</a>')\n # link hashtags (needs to start the string or have a space before so we don't link #s in urls)\n re = Regexp.new('(\\s|^)(\\#)([\\w]+)')\n tweet.gsub!(re, '\\1<a href=\"http://twitter.com/search/%23\\3\">#\\3</a>')\n # return tweet and any oembed data\n [tweet, oembeds]\nend",
"def tweetfetch\n @array = []\n TweetStream::Client.new.sample(language: 'en') do |status, client|\n link = status.text.match(/http:\\/\\/t\\.co\\/[a-zA-Z0-9]+/)\n #continue if tweet has a link in it\n if link\n @array.push(link[0])\n\n #use this if we need to get hashtags later on\n # status.text.scan(/#\\w+/).each do |h|\n# Hashtag.create(tag: h.sub!(\"#\", \"\"), url_id: Url.last.id)\n# end\n end\n #continue streaming until we have 50 links\n client.stop if @array.length >= 50\n end\n\n @array.each do |link|\n until link.nil?\n final_link = link\n isSSL = link.match(/https:\\/\\//)\n #for https links\n if isSSL\n uri = URI.parse(link)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl =true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Get.new(uri.request_uri)\n response = http.request(request)\n link = response['location']\n #for http links\n else\n link = Net::HTTP.get_response(URI.parse(link))['location']\n end\n end\n \n #gets rid of ask.fm, twitter, and facebook links\n isAskFM = final_link.match(/.*ask\\.fm/)\n isTwitter = final_link.match(/.*twitter\\.com/)\n isFacebook = final_link.match(/.*facebook\\.com/)\n \n if isAskFM || isTwitter || isFacebook\n next\n end\n \n \n #doesn't work\n l = Url.find_or_create_by_link(final_link) do |c|\n c.frequency += 1\n end\n l.frequency += 1\n end\n\n #uses readability to get article and meta data\n Url.all.each do |u|\n url = 'https://readability.com/api/content/v1/parser?url=' + \"#{u.link}\" + '&token=b9a8aa67a490c643bd12efd3d861c05a2a665927'\n uri = URI.parse(url)\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl =true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Get.new(uri.request_uri)\n response = http.request(request)\n \n response = JSON.parse(response.body)\n u.update_attributes(article: response['content'], \n author: response['author'],\n title: response['title'],\n word_count: response['word_count'],\n date_published: response['date_published'])\n end\n end",
"def extract\n if extended_body.blank? || body.blank? || title.blank?\n http = RubyTubesday.new\n raw = http.get(link)\n data = Nokogiri::HTML(raw)\n no_body = false\n end\n if extended_body.blank?\n containers = (data/\"div div\")\n if containers.blank?\n text = raw\n no_body = true\n else\n possibles = []\n containers.each_with_index do |c, index|\n possibles << {:index => index, :count => ((c/\"p\").length - (c/\"div\").sum{|u| (u/\"p\").length})}\n end\n text_index = possibles.max{|a,b| a[:count] <=> b[:count]}[:index]\n text = containers[text_index]\n no_body = false\n end\n self.extended_body = Sanitize.clean(text.text)\n end\n if body.blank?\n if meta_desc = data.css(\"meta[name='description']\").first \n content = meta_desc['content']\n elsif no_body\n content = \"No summary available\"\n else\n content = Nokogiri::HTML(extended_body)\n content = content.css(\"p\").first.text\n end\n self.body = content\n end\n if title.blank?\n self.title = data.css(\"title\").first.children.first.to_s\n end\n end",
"def get_tweets(screen_name, num_tweets)\n\t\n\tresult = \"\"\n #Query num_tweets tweets from screen_name and create the HTML\n Twitter.user_timeline(screen_name, {\"count\" => num_tweets}).each do |tweet|\n \tlinkified = linkifyTweet(tweet.text)\n \tresult = result + \"<li class=\\\"tweet\\\">\n <span class=\\\"gentle\\\">#{linkified}</span>\n </li>\"\n end\n return result\nend",
"def fetch_tweet\n client = Twitter::Client.new.configure do |config|\n config.consumer_key = ENV['CONSUMER_KEY']\n config.consumer_secret = ENV['CONSUMER_SECRET']\n config.oauth_token = ENV['OAUTH_TOKEN']\n config.oauth_token_secret = ENV['OAUTH_TOKEN_SECRET']\n end\n\n # From https://github.com/sferik/twitter#configuration\n # \n # searches through Twitter client to find the word from html form. Will only return the first tweet.\n @tweet = client.search(@word, :lang => \"en\", :count => 1).results.first.text\n\n end",
"def parse_tweet_content (t)\n\t\tbegin\n\t\ttweet_id = t.xpath(\"@data-item-id\").text().to_s.strip\n\t\txpath = '//*[@id=\"stream-item-tweet-'+tweet_id+'\"]/div/div/div[1]/a/strong/text()'\n\t\tposter_name = t.xpath(xpath)\n\t\t#poster_name = t.xpath('//*[@id=\"stream-item-tweet-371766472051138560\"]/div/div/div[1]/a/strong/text()')\n\t\t#check if the poster is the current user!!\n\t\t#test_name = poster_name.partition(\" \").first\n\t\t#puts \"is of page owner real name:#{@real_name} poster name: #{poster_name}\"\n\t\tif @real_name.include?(poster_name.to_s)\t\t\n\t\t\t@is_of_page_owner = true\n\t\tend\n\t\t@max_tweet_id = tweet_id\n\t\tset_id(tweet_id)\n\t\t#puts tweet_id\n\t\ttweet_content = t.xpath(\"./div/div/p/text()\").to_s.strip\n\t\t#puts tweet_content\n\t\tset_content(tweet_content)\n\t\t#fetching retweets and favourites gets complicated\n\t\tif @is_of_page_owner\n\t\t\tfetch_retweet_favourites(t)\t\n\t\tend\n\trescue Exception => e\n\t\tLogWriter.error(e)\n\t\treturn self\n\tend\n\tend",
"def second_scrape(string) #Format output nd improvement\n comb_str = @base_url + string\n html = open(comb_str)\n trail_parsed_to_html = Nokogiri::HTML(html)\n trail_parsed_to_html.css('p').text #returns summary & parking paragraphs\n end",
"def description\n @description = @description || BeerMe::Scraper.scrape_description(self.url)\n end",
"def get_twitter(npo)\n\t\trequire 'net/http'\n\t\trequire 'rexml/document'\n\n begin\n\n res = Net::HTTP.get(URI.parse(\"http://api.twitter.com/1/users/show.xml?screen_name=#{npo.twitter}\"))\n document = REXML::Document.new(res)\n\n if document.root.elements[2]\n document.root.elements[2].expanded_name == 'error' ? nil : npo.twitter\n end\n rescue\n nil\n end\n\tend",
"def scrape_description\n if self.checkURL\n mechanize = Mechanize.new\n page = mechanize.get(self.url)\n \n if page.at(\"head meta[name='description']\")\n page.at(\"head meta[name='description']\").attributes[\"content\"].value \n elsif page.at(\"head meta[name='Description']\")\n page.at(\"head meta[name='Description']\").attributes[\"content\"].value\n else\n \"No Description\"\n end\n else\n \"No Description\"\n end\n end",
"def generate_description\n html = Nokogiri::HTML(overview)\n lines = html.search('//text()').map(&:text)\n self[:description] = lines.join(\"\\n\")\n end",
"def tube_get(url)\n begin\n data = Nokogiri::HTML(open(url))\n title = data.at_css('#eow-title').text.strip if data.at_css('#eow-title').text.strip\n views = data.at_css('.watch-view-count').text.strip if data.at_css('.watch-view-count').text.strip\n likes = data.at_css('.likes-count').text.strip if data.at_css('.likes-count').text.strip\n dislikes = data.at_css('.dislikes-count').text.strip if data.at_css('.dislikes-count').text.strip\n say_to_chan(\"\\2Youtube - #{title}\\2 - #{views} views - likes up/down at #{likes}/#{dislikes}\")\n rescue\n tell_chan_title(url)\n end\n end",
"def tweet\n return \"tweet tweet\"\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return all the elements containing currency input text field
|
def get_currency_input_field_elements
elements(xpath: './/label[contains(text(),"Limit") or contains(text(), "Accounts Receivable") or contains(text(), "On Premises") or contains(text(), "Off Premises")]//following-sibling::app-currency-input/input[1]')
end
|
[
"def get_sum_of_all_elements\n @logger.info(\"Searching element #{[value1, value2, value3, value4, value5]}\")\n allelements = @driver.find_elements(By.xpath(\"//*[contains(@id, 'txt_val_')]\"))\n\n if allelements.all? { |elem| elem.value.start_with?(\"$\") }\n elements = allelements.map { |elem| elem.value.tr('$', '').to_i }\n elements.reduce(:+)\n else \n raise \"Field value should have currency format\"\n end\n end",
"def all_text_fields_values_formatted_as_currency?(currency)\r\n # encoding: utf-8\r\n value_text_box_fields.all? { |text_box| Monetize.parse(tb.value).currency == currency }\r\n end",
"def getCurrencyEntries()\r\n ids = [ \"txt_val_1\", \"txt_val_2\", \"txt_val_4\", \"txt_val_5\", \"txt_val_6\"]\r\n return getTextsOfLIs(ids)\r\n end",
"def clear_currency_input_field_elements\n get_currency_input_field_elements.each do |ele|\n # This is a temporary work around for clearing the currency input field as '.clear' on element is not working\n ele.send_keys(:control, a)\n end\n end",
"def extract_text_field_elements\n extract_elements 'text'\n end",
"def getAllCurrencies\n {\n \"EUR\" => preorpost(\"\\\\€\"),\n \"USD\" => preorpost(\"\\\\$\"),\n \"GBP\" => preorpost(\"\\\\£\"),\n \"CHF\" => preorpost(\"CHF\"),\n \"TWD\" => preorpost(\"NT\\\\$\"),\n \"SGD\" => preorpost(\"S\\\\$\"),\n \"HKD\" => preorpost(\"HK\\\\$\"),\n \"CNY\" => preorpost(\"(\\\\¥|RNB)\")\n }\nend",
"def currency_fields\n CURRENCY_FIELDS\n end",
"def extract_base_currency result\n result.css('basecurrency').children[0].to_s.downcase.to_sym\n end",
"def currency\n params['currency']\n end",
"def essai\n\npage = Nokogiri::HTML(open('https://coinmarketcap.com'))\nresult = page.css('tbody tr').each do |tr|\n id = tr.css(\"currency-name\").text\n price = tr.css(\"price\").text \n puts id + \"vaut aujourd'hui\" + price\nend\nend",
"def posted_currency\n params['currency']\n end",
"def buy_rate\n regexp = Regexp.new(currency_code)\n page.search('//tr[@valign=\"middle\"]').each do |tr|\n tr.search('td').each do |td|\n if regexp.match(td.content)\n return td.next_element.content.sub(',','.').to_f\n end\n end\n end\n end",
"def currency_field(f, method, options = {})\n # get the symbol for the field.\n sym = '$'\n if options[:currency_symbol]\n sym = options[:currency_symbol]\n options.except! :currency_symbol\n end\n\n # get the value\n if (val = f.object.send(method))\n options[:value] = number_with_precision val, precision: 2, delimiter: ','\n end\n\n # build the field\n fld = f.text_field(method, options)\n\n # return the value.\n \"<div class=\\\"input-symbol\\\"><span>#{h sym}</span>#{fld}</div>\".html_safe\n end",
"def total_balance_text_field\r\n @browser.text_field(:id, 'txt_ttl_val')\r\n end",
"def get_charges\n #fill in the remaining claim info\n # box 28\n text_box sprintf(\"%.2f\", @charges_for_service.to_s), :at => [370, 82]\n # box 29\n text_box sprintf(\"%.2f\", @copay_amount.to_s), :at => [450, 82]\n # box 30\n text_box sprintf(\"%.2f\", @balance_owed.to_s), :at => [520, 82]\n end",
"def parse_price\n price = [\n page.at('#priceblock_ourprice'),\n page.at('#priceblock_dealprice')\n ].compact.first\n\n price.text.match(/(\\d+[,.]\\d+)/)[0]\n end",
"def currencies\n @currencies || []\n end",
"def sell_rate\n regexp = Regexp.new(currency_code)\n page.search('//tr[@valign=\"middle\"]').each do |tr|\n tr.search('td').each do |td|\n if regexp.match(td.content)\n return td.next_element.next_element.content.sub(',','.').to_f\n end\n end\n end\n end",
"def currency_types\n collection(\"currency_types\")\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Clear input field of all the elements containing currency input text field
|
def clear_currency_input_field_elements
get_currency_input_field_elements.each do |ele|
# This is a temporary work around for clearing the currency input field as '.clear' on element is not working
ele.send_keys(:control, a)
end
end
|
[
"def clear_input\n @input_values.clear\n end",
"def clear_input\n begin\n $results.log_action(\"#{@action}(#{@params[0]})\")\n @driver.find_element(:id, $session.form + @params[0]).clear\n $results.success\n rescue => ex\n $results.fail(\"#{@action}(#{@params[0]})\", ex)\n end\n end",
"def clear\n wait_until_exists\n @text_field.clear\n end",
"def clear_amounts\n %w(amount_usd amount_wmr amount_wme).each{|m| self.send(\"#{m}=\", nil) }\n end",
"def textfield_by_class_clear_text(textfield_class)\n textfield_by_class(textfield_class).clear\nend",
"def clear_text(element_name)\n $LOG.info \"clear value of text field or text area : #{element_name}\"\n wait_and_find_element(element_name)\n begin\n wait_and_find_element element_name\n clear_value = el element_name\n clear_value.clear\n rescue Exception => e\n $LOG.error \"Unable to clear value of text field or text area : #{element_name} \"+e.message\n $driver.save_screenshot(\"log/webscreenshot/webScreenshot_#{$webscreenshot}.png\")\n $webscreenshot = $webscreenshot+1\n raise \"Unable to clear value of text field or text area : #{element_name} \"+e.message\n end\n end",
"def do_clear\n @editor.value = ''\n @editor.focus\n end",
"def clear_input!\n current = params[:Body] || params[:Digits]\n\n params[:Body] = nil\n params[:Digits] = nil\n\n @session.clear_session_input!\n end",
"def clear_textfield(loc)\n @browser.text_field(parse_location(loc)).clear\n end",
"def price=(input)\n input.delete!(\"$\")\n super\n end",
"def reset_basic_currency\n self.class.where(\"id != ?\", self.id).update_all(:basic => false) if self.basic?\n end",
"def clear_choices\n\t\t@order.clear\n\t\t@balance = 20.00\n\n\tend",
"def clear\n\t\t\t@store.transaction { @store.delete(:custom_numerals); @store.commit}\n\t\t\tputs \"User defined Roman Numerals cleared.\"\n\t\t\tconfig(true)\t\t\t\n\t\tend",
"def clear\n @field.each_index { |i| @field[i] = 0 }\n end",
"def clearFilter\n\t\t@ctrl['date_min'].text=''\n\t\t@ctrl['date_max'].text=''\n\t\t@ctrl['count_min'].text=''\n\t\t@ctrl['count_max'].text=''\n\t\t@ctrl['value_min'].text=''\n\t\t@ctrl['value_max'].text=''\n\t\t@ctrl['category'].categoryID=0\n\t\t@ctrl['description'].text=''\n\t\t@filter=nil\n\tend",
"def reset_basic_currency\n if basic?\n self.class.where(\"id != ?\", id).update_all(basic: false)\n end\n end",
"def clear\n @element.clear\n end",
"def backspace_clear(element_name)\n field_element = find_element(element_name)\n if field_element\n field_text = field_element.value\n (0..field_text.size).each do\n send_keys(element_name, :backspace)\n end\n else\n return false\n end\n true\n end",
"def clear_standard_fields()\n\t\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DNA to RNA Conversion Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T'). Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structure and contains no Thymine. In RNA Thymine is replaced by another nucleic acid Uracil ('U'). Create a funciton which translates a given DNA string into RNA. For example: DNAtoRNA("GCAT") returns ("GCAU") The input string can be of arbitrary length in particular, it may be empty. All input is guaranteed to be valid, i.e. each input string will only ever consist of 'G', 'C', 'A' and/or 'T'.
|
def DNAtoRNA(dna)
dna.gsub("T", "U")
end
|
[
"def DNAtoRNA(dna)\n rna = dna.gsub('T', 'U')\n\n rna \nend",
"def dna_to_rna(string)\n index = 0\n rna_strand = \"\"\n while index < string.length\n if string[index] == \"G\"\n rna_strand << \"C\"\n elsif string[index] == \"C\"\n rna_strand << \"G\"\n elsif string[index] == \"T\"\n rna_strand << \"A\"\n elsif string[index] == \"A\"\n rna_strand << \"U\"\n end\n index += 1\n end\n return rna_strand\nend",
"def parse_dna(str)\n dna = String::new \n str.upcase.each_char do |chr|\n if chr.match(\"A\") || chr.match(\"C\") || chr.match(\"T\") || chr.match(\"G\")\n dna = dna + chr\n end\n end\n dna \nend",
"def DNA_strand(dna)\n n = dna.split(\"\")\n mapping = {'T' => 'A', 'A' => 'T', 'C' => 'G', 'G' => 'C'}\n # n = n.map {|e| mapping[e] || e}\n n.map! {|e| mapping[e] || e}\n n = n.join(\"\")\n return n\nend",
"def DNA_strand(dna)\n dna.tr('ATCG', 'TAGC')\n new_strand = []\n dna.split('').each do |letter|\n if letter === 'A'\n new_strand.push('T')\n elsif letter === 'T'\n new_strand.push('A')\n elsif letter === 'C'\n new_strand.push('G')\n elsif letter === 'G'\n new_strand.push('C')\n end\n end\n return new_strand.join('')\nend",
"def reverse_complement(dna)\n return \"Invalid sequence\" if dna.count(\"ACGTacgt\") != dna.size\n dna.gsub!(/[ACGT]/, 'A' => 'T', 'C' => 'G', 'T' => 'A', 'G' => 'C', 'a' => 't', 'c' => 'g', 't' => 'a', 'g' => 'c')\n dna.reverse!\nend",
"def transcription(strand)\n rna = []\n dna_arr = strand.split(\"\")\n dna_arr.each do |nucleotide|\n if nucleotide == \"G\"\n rna << \"C\"\n elsif nucleotide == \"C\"\n rna << \"G\"\n elsif nucleotide == \"T\"\n rna << \"A\"\n elsif nucleotide == \"A\"\n rna << \"U\"\n end\n end\n rna.join\nend",
"def get_rna_transcript(dna_seq)\r\n nts_array = dna_seq.upcase.split(\"\")\r\n transcribed = []\r\n nts_array.each do |nt|\r\n if nt == \"T\" \r\n transcribed.concat([\"U\"])\r\n else\r\n transcribed.concat([nt])\r\n end\r\n end\r\n transcribed = transcribed.join(\"\")\r\n return transcribed\r\nend",
"def get_reverse_complement(dna_seq)\r\n complement_nt = {\"A\"=> \"T\", \"T\"=> \"A\", \"C\"=> \"G\", \"G\"=> \"C\", \"N\"=> \"N\"}\r\n reverse_complement = \"\"\r\n dna_seq.each_char do |nt|\r\n reverse_complement = complement_nt[nt] + reverse_complement\r\n end\r\n return reverse_complement \r\nend",
"def translate(sequence, gencode)\n protein = ''\n sequence.scan(/[ACGT]{3}/i).each do |codon|\n protein += gencode[codon.upcase]\n end\n return protein\nend",
"def DNA_strand(dna)\n arr = dna.split(//)\n another_arr = Array.new\n arr.each do |chr|\n case chr\n when \"A\"\n another_arr << \"T\"\n when \"T\"\n another_arr << \"A\"\n when \"C\"\n another_arr << \"G\"\n else\n another_arr << \"C\"\n end\n end\n \"String #{dna} is #{another_arr.join}\"\nend",
"def DNA_strand(dna)\n complementary_str = ''\n dna.chars.each do |char|\n case char\n when 'A'\n complementary_str += 'T'\n when 'T'\n complementary_str += 'A'\n when 'C'\n complementary_str += 'G'\n when 'G'\n complementary_str += 'C'\n end\n end\n\n complementary_str\nend",
"def translate_nucseq (nuc_str, frame=1)\n\t\tnuc_seq = Bio::Sequence::NA.new(nuc_str)\n\t\treturn nuc_seq.translate(frame).to_str()\n\tend",
"def rna_to_protein(string)\n\t\tprotein = []\n\t\ttriplets = string.split(\"\").each_slice(3).to_a.map { |a| a.join }\n\t\t\n\t\t(0...triplets.length).each do |a|\n\t\t \tif (Codon_table[triplets[a-1]] != 'Stop') or (a ==0) \n\t\t \t\tprotein << Codon_table[triplets[a]] \n\t\t \telse\n\t\t \t\tbreak\n\t\t \tend\n\t\t end\n\n\t\tif protein.include?('Stop') \n\t\t\tprotein -= ['Stop']\n\t\t\tprotein.join(\"\") \n\t\tend\n\tend",
"def getDna (cds, seq)\n loc = cds.locations\n sbeg = loc[0].from.to_i\n send = loc[0].to.to_i\n fasta = Bio::Sequence::NA.new(seq.subseq(sbeg,send))\n position = \"#{sbeg}..#{send}\"\n if loc[0].strand == -1\n fasta.reverse_complement!\n end\n dna = Bio::Sequence.auto(fasta)\n return dna\nend",
"def getDna (cds, seq)\n loc = cds.locations\n sbeg = loc[0].from.to_i\n send = loc[0].to.to_i\n fasta = Bio::Sequence::NA.new(seq.subseq(sbeg,send))\n # position = \"#{sbeg}..#{send}\"\n if loc[0].strand == -1\n fasta.reverse_complement!\n end\n dna = Bio::Sequence.auto(fasta)\n return dna\n end",
"def reverse_complement(dna)\n\t\tcomplement = []\n\t\tdna.each_char do |s|\n\t\t\tif s == 'A'\n\t\t\t\tcomplement << 'T'\n\t\t\telsif s == 'T'\n\t\t\t\tcomplement << 'A'\n\t\t\telsif s == 'G'\n\t\t\t\tcomplement << 'C'\n\t\t\telsif s == 'C'\n\t\t\t\tcomplement << 'G'\n\t\t\telsif s == 'N'\n\t\t\t\tcomplement << 'N'\n\t\t\tend\t\n\t\tend\n\t\tcomplement.join('').reverse\n\tend",
"def get_reverse_complement(dna_seq)\r\n nts_array = dna_seq.upcase.split(\"\")\r\n reverse = nts_array.reverse\r\n complement = []\r\n reverse.each do |nt|\r\n if nt == \"T\"\r\n complement.concat([\"A\"])\r\n elsif nt == \"A\"\r\n complement.concat([\"T\"])\r\n elsif nt == \"C\"\r\n complement.concat([\"G\"])\r\n elsif nt == \"G\"\r\n complement.concat([\"C\"])\r\n end\r\n end\r\n complement = complement.join(\"\")\r\n return complement \r\nend",
"def reverse_strand #(genome)\n reverse = String.new\n @genome.each_char do |a|\n if a == \"A\"\n a = \"T\"\n elsif a ==\"T\"\n a = \"A\"\n elsif a == \"G\"\n a=\"C\"\n elsif a== \"C\"\n a=\"G\"\n else\n return \"Invalid nucleotide: ${a}\"\n end\n reverse = \"#{a}#{reverse}\"\n end\n return reverse\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Do a shelllike path lookup for prog_script and return the results. If we can't find anything return prog_script.
|
def whence_file(prog_script)
if prog_script.index(File::SEPARATOR)
# Don't search since this name has path separator components
return prog_script
end
for dirname in ENV['PATH'].split(File::PATH_SEPARATOR) do
prog_script_try = File.join(dirname, prog_script)
return prog_script_try if File.exist?(prog_script_try)
end
# Failure
return prog_script
end
|
[
"def whence_file(prog_script)\n if prog_script.index(File::SEPARATOR)\n # Don't search since this name has path separator components\n return prog_script\n end\n\n ENV['PATH'].split(File::PATH_SEPARATOR).each do |dirname|\n prog_script_try = File.join(dirname, prog_script)\n return prog_script_try if File.exist?(prog_script_try)\n end\n\n # Failure\n prog_script\n end",
"def whence_file(prog_script)\n if prog_script.index(File::SEPARATOR)\n # Don't search since this name has path separator components\n return prog_script\n end\n for dirname in ENV['PATH'].split(File::PATH_SEPARATOR) do\n prog_script_try = File.join(dirname, prog_script)\n return prog_script_try if File.readable?(prog_script_try)\n end\n # Failure\n return prog_script\n end",
"def findProgram( progname )\n\t\tENV['PATH'].split(File::PATH_SEPARATOR).each {|d|\n\t\t\tfile = File.join( d, progname )\n\t\t\treturn file if File.executable?( file )\n\t\t}\n\t\treturn nil\n\tend",
"def which(prog, path = ENV['PATH'])\n path.split(File::PATH_SEPARATOR).each do |dir|\n if File::ALT_SEPARATOR\n ext = Win32Exts.find do |ext|\n if prog.include?('.')\n f = File.join(dir, prog)\n else\n f = File.join(dir, prog+ext)\n end\n File.executable?(f) && !File.directory?(f)\n end\n if ext\n if prog.include?('.')\n f = File.join(dir, prog).gsub(/\\//,'\\\\')\n else\n f = File.join(dir, prog + ext).gsub(/\\//,'\\\\')\n end\n return f\n end\n else\n f = File.join(dir, prog)\n if File.executable?(f) && !File.directory?(f)\n return File::join(dir, prog)\n end\n end\n end\n\n nil\n end",
"def find_shell_wrapper_or_executable prog\n @bindir.each do |dir|\n fname = File.join(dir, \"#{prog}.sh\")\n\n# $stderr.print \"Checking '#{fname}'\\n\"\n\n return fname if File.executable_real? fname\n end\n\n return find_executable(prog)\n end",
"def find_program( progname )\n\t\tunless Programs.key?( progname )\n\t\t\tENV['PATH'].split(File::PATH_SEPARATOR).\n\t\t\t\tcollect {|dir| Pathnanme.new(dir) }.each do |dir|\n\t\t\t\t\tfile = dir + progname\n\t\t\t\t\tif file.executable?\n\t\t\t\t\t\tPrograms[ progname ] = file\n\t\t\t\t\t\tbreak\n\t\t\t\t\tend\n\t\t\t\tend\n\t\tend\n\n\t\treturn Programs[ progname ].to_s\n\tend",
"def find_script(script)\n return nil if script.nil? or script.empty?\n return script if File.exists? script\n\n # try relative path\n s = File.expand_path(File.join(@root, script))\n return s if File.exists? s\n\n # try searching\n matches = find_all_files(@root).\n find_all { |f| f.include?(\"/bin/\") && f.include?(script) }.\n sort { |a,b| ld(script, File.basename(a)) <=> ld(script, File.basename(b)) }\n\n return matches if matches.size == 1 # only one result, just return it\n\n # fuzzy search\n fuzzy_matches = FuzzyFileFinder.new(@root).find(script.dup).\n sort_by { |m| -m[:score] }.\n map{ |f| f[:path] }.\n find_all{ |f| keep?(f, @root) }\n\n # return the union of all unique matches\n return fuzzy_matches + (matches - fuzzy_matches)\n end",
"def path!\n return @path unless @path.nil?\n rel = relative_path or abort( usage )\n find_in_load_path(rel) or abort(\"no script found: file #{rel.to_s.inspect} is not in path.\")\n end",
"def exe_lookup(bin)\n if @system_path || @env['PATH']\n @system_path ||= @env['PATH'].encode(\n 'UTF-8', 'binary',\n invalid: :replace,\n undef: :replace,\n replace: ''\n ).split(File::PATH_SEPARATOR)\n\n @system_path.each do |path|\n file_path = \"#{path}#{File::SEPARATOR}#{bin}\"\n return file_path if File.executable? file_path\n end\n\n nil\n end\n end",
"def find\n # PATHEXT on Windows defines the valid executable extensions.\n exts = ENV.fetch('PATHEXT', '').split(';')\n # On other systems we'll work with no extensions.\n exts << '' if exts.empty?\n\n ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|\n path = unescape_path(path)\n exts.each do |ext|\n file = File.join(path, bin + ext)\n return file if executable?(file)\n end\n end\n\n nil\n end",
"def find_script(default_script, override_script_path = nil)\n script = find_script_from_override_path(default_script, override_script_path) ||\n File.expand_path(\"../../../scripts/#{default_script}\", File.dirname(__FILE__))\n raise Errno::ENOENT, \"Unable to locate script '#{script}'\" unless File.file?(script)\n script\n end",
"def find_executable(executable, advance_from = nil)\n search_paths = Executioner::SEARCH_PATHS\n search_paths = search_paths[(search_paths.index(advance_from) + 1)..-1] if advance_from\n \n if executable_in_path = search_paths.find { |path| File.exist?(File.join(path, executable)) }\n File.join(executable_in_path, executable)\n end\n end",
"def find_executable(bin, path = nil, exts: nil)\n\t\t\texecutable_file = lambda do |name|\n\t\t\t\tname=Pathname.new(name)\n\t\t\t\treturn name if name.file? and name.executable?\n\t\t\tend\n\t\t\t#we use Proc so that 'return' escapes the block\n\t\t\ttry_executable = Proc.new do |file|\n\t\t\t\treturn file if executable_file.call(file)\n\t\t\t\texts && exts.each {|ext| executable_file.call(ext = file.append_name(ext)) and return ext}\n\t\t\t\tnil\n\t\t\tend\n\n\t\t\tbin=Pathname.new(bin)\n\t\t\tif bin.absolute?\n\t\t\t\ttry_executable.call(bin)\n\t\t\telse\n\t\t\t\tpath ||= ENV['PATH'] || %w[/usr/local/bin /usr/bin /bin]\n\t\t\t\tpath = path.split(File::PATH_SEPARATOR) unless path.kind_of?(Array)\n\t\t\t\tpath.each do |dir|\n\t\t\t\t\tdir=Pathname.new(dir)\n\t\t\t\t\ttry_executable.call(dir+bin)\n\t\t\t\tend\n\t\t\tend\n\t\t\tnil\n\t\tend",
"def find_executable( bin, *paths )\n paths = Launchy.path.split( File::PATH_SEPARATOR ) if paths.empty?\n paths.each do |path|\n file = File.join( path, bin )\n if File.executable?( file ) then\n Launchy.log \"#{self.name} : found executable #{file}\"\n return file\n end\n end\n Launchy.log \"#{self.name} : Unable to find `#{bin}' in #{paths.join(\", \")}\"\n return nil\n end",
"def script\n @script ||= (Dir.glob(root+'/**/parts.js').first || Dir.glob(root+'/**/parts.js.coffee').first)\n end",
"def find_program( *names )\n system_path = ENV.read( 'PATH', Array )\n [ names ].flatten!.find do | prog |\n system_path.find { | d | File.executable?( d / prog ) }\n end\n end",
"def find_executable_in_path(command_name)\n ENV['PATH'].split(/;|:/).each do |dir|\n path = File.join(dir, command_name)\n return path if File.executable?(path)\n end\n return nil\n end",
"def which(*bins)\n bins.flatten.each do |bin|\n ENV[\"PATH\"].split(\":\").each do |dir|\n full_path = File.join(dir, bin)\n return full_path if File.exist? full_path\n end\n end\n nil\nend",
"def script_alias_path(path)\n \t@config_map[\"ScriptAlias\"].each do |k,v|\n \t\tif path==\"#{k}\"\n \t\t return v[0]\n \t\tend\n \tend\n \treturn nil\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
A method to convert an openlayersformat bbox string into an rgeo bbox object
|
def bbox_from_string(string, factory)
return unless string
minlon, minlat, maxlon, maxlat = string.split(',').collect { |i| i.to_f }
bbox = RGeo::Cartesian::BoundingBox.new(factory)
bbox.add(factory.point(minlon, minlat)).add(factory.point(maxlon, maxlat))
end
|
[
"def bbox_from_string(string, factory)\n return unless string\n minlon, minlat, maxlon, maxlat = string.split(',').collect(&:to_f)\n bbox = RGeo::Cartesian::BoundingBox.new(factory)\n bbox.add(factory.point(minlon, minlat)).add(factory.point(maxlon, maxlat))\n end",
"def bbox_from_string(string, factory)\n return unless string\n\n minlon, minlat, maxlon, maxlat = string.split(\",\").collect(&:to_f)\n bbox = RGeo::Cartesian::BoundingBox.new(factory)\n bbox.add(factory.point(minlon, minlat)).add(factory.point(maxlon, maxlat))\n end",
"def decode_bbox(geohash)\n decode_bbox_base(geohash)\n end",
"def convert_bbox(box)\n\tfactory = RGeo::Geographic.simple_mercator_factory(:srid => 4326)\n\tring = []\n\tfor item in box\n\t\tring << factory.point(item[0], item[1])\n\tend\n\tlinear_ring = factory.linear_ring(ring)\n\tpolygon = factory.polygon(linear_ring)\n\tpolygon\nend",
"def bounding_box\n Geoblacklight::BoundingBox.from_rectangle(blacklight_params[:bbox])\n end",
"def box2d_to_bbox(box2d)\n box2d.gsub(',', ' ').gsub('BOX(', '').gsub(')', '').split(' ').map(&:to_f)\nend",
"def get_bbox(left, bottom, right, top)\n raise TypeError.new('\"left\" value needs to be a number between -180 and 180') unless(left.kind_of?(Float) && left >= -180 && left <= 180)\n raise TypeError.new('\"bottom\" value needs to be a number between -90 and 90') unless(bottom.kind_of?(Float) && bottom >= -90 && bottom <= 90)\n raise TypeError.new('\"right\" value needs to be a number between -180 and 180') unless(right.kind_of?(Float) && right >= -180 && right <= 180)\n raise TypeError.new('\"top\" value needs to be a number between -90 and 90') unless(top.kind_of?(Float) && top >= -90 && top <= 90)\n response = get(\"map?bbox=#{left},#{bottom},#{right},#{top}\")\n check_response_codes(response)\n db = OSM::Database.new\n parser = OSM::StreamParser.new(:string => response.body, :db => db)\n parser.parse\n db\n end",
"def bounding_box\n obj = factory.parse_wkt(geometry_as_wkt)\n\n # Get the minimum bounding box for the geometry as a Polygon\n bbox = obj.envelope\n\n # Return as wsen string\n minx = bbox.coordinates[0][0][0]\n miny = bbox.coordinates[0][0][1]\n maxx = bbox.coordinates[0][1][0]\n maxy = bbox.coordinates[0][2][1]\n \"#{minx}, #{miny}, #{maxx}, #{maxy}\"\n rescue RGeo::Error::ParseError\n Geoblacklight.logger.warn \"Error parsing geometry: #{geom}\"\n default_extent\n end",
"def getBBoxInLonLat() ;\n bbox = nil ;\n @roadList.each{|road|\n roadBBox = road.getBBoxInLonLat() ;\n if(bbox.nil?) then\n bbox = roadBBox ;\n else\n bbox.insert(roadBBox) ;\n end\n }\n return bbox ;\n end",
"def get_bbox(left, bottom, right, top)\n raise TypeError.new('\"left\" value needs to be a number between -180 and 180') unless(left.kind_of?(Float) && left >= -180 && left <= 180)\n raise TypeError.new('\"bottom\" value needs to be a number between -90 and 90') unless(bottom.kind_of?(Float) && bottom >= -90 && bottom <= 90)\n raise TypeError.new('\"right\" value needs to be a number between -180 and 180') unless(right.kind_of?(Float) && right >= -180 && right <= 180)\n raise TypeError.new('\"top\" value needs to be a number between -90 and 90') unless(top.kind_of?(Float) && top >= -90 && top <= 90)\n response = get(\"map?bbox=#{left},#{bottom},#{right},#{top}\")\n check_response_codes(response)\n db = OSMLib::Database.new\n parser = OSMLib::Stream::Parser.new(:string => response.body, :db => db)\n parser.parse\n db\n end",
"def bbox_as_range\n \"[\\\"#{bbox[0]} #{bbox[1]}\\\" TO \\\"#{bbox[2]} #{bbox[3]}\\\"]\"\n end",
"def simple_bbox\n\t\t\tutm = self.to_utm\n\t\t\tsize = 10**(5-@precision)\n\n\t\t\tminx = utm.easting\n\t\t\tminy = utm.northing\n\n\t\t\tmaxx = minx + size\n\t\t\tmaxy = miny + size\n\n\t\t\tsrid=26900 + @utm_zone\n\t\t\t# ex. POLYGON((654000 5191000,654000 5192000,655000 5192000,655000 5191000,654000 5191000))\n\t\t\t\"SRID=#{srid};POLYGON((#{minx} #{miny}, #{minx} #{maxy}, #{maxx} #{maxy}, #{maxx} #{miny}, #{minx} #{miny}))\"\n\t\tend",
"def bbox\n @bbox ||= @attributes['fontbbox'].split(/\\s+/).map { |e| Integer(e) }\n end",
"def to_flickr_bbox(options = {})\n options = {\n :precision => 1\n }.merge(options)\n precision = 10.0 ** options[:precision]\n\n [\n (self.west * precision).floor / precision,\n (self.south * precision).floor / precision,\n (self.east * precision).ceil / precision,\n (self.north * precision).ceil / precision\n ].join(',')\n end",
"def bbox(args = {})\n name = args.delete(:name) || nil\n if args[:reload]\n @bbox = BBox.new(self, name)\n else\n @bbox ||= BBox.new(self, name)\n end\n end",
"def bbox_geojson_geometry\n \t\taw.bounding_box.geojson_geometry\n \tend",
"def bbox=(bbox)\n Validator.validate_bbox(bbox)\n @parameters[:bbox] = bbox\n end",
"def bounding_box_str\n return nil unless longitude && latitude\n\n \"#{longitude} #{latitude} #{longitude} #{latitude}\"\n end",
"def by_bounding_box(name, lat1, lng1, lat2, lng2)\n JSON.parse(RestClient.get(\"#{ design_document_uri(database, model_name) }/_spatial/#{name}?bbox=#{ [lat1,lng1,lat2,lng2].join(',') }\", default_headers))['rows'].map do |row|\n find(row['id'])\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Method: walk_automation_objects Purpose: Recursively walk and record the automation object hierarchy from $evm.root downwards Arguments: service_object Returns: A completed Struct::ServiceObject data structure
|
def walk_automation_objects(service_object)
automation_object = Struct::ServiceObject.new(service_object.to_s, "", Array.new)
if service_object.to_s == $evm.root.to_s
automation_object.position = 'root'
elsif service_object.to_s == $evm.parent.to_s
automation_object.position = 'parent'
elsif service_object.to_s == $evm.object.to_s
automation_object.position = 'object'
end
offspring = service_object.children
unless offspring.nil? || (offspring.kind_of?(Array) and offspring.length.zero?)
Array.wrap(offspring).each do |child|
automation_object.children << walk_automation_objects(child)
end
end
return automation_object
end
|
[
"def print_automation_objects(indent_level, hierarchy)\n case hierarchy.position\n when 'root'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.root)\")\n when 'parent'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.parent)\")\n when 'object'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.object)\")\n else\n print_line(indent_level, \"#{hierarchy.obj_name}\")\n end\n indent_level += 1\n hierarchy.children.each do |child|\n print_automation_objects(indent_level, child)\n end\nend",
"def walk_object(object_string, this_object)\n begin\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n $recursion_level += 1\n if $recursion_level > $max_recursion_level\n print_line($recursion_level, \"*** exceeded maximum recursion level ***\")\n $recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n print_line($recursion_level,\n \"Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if $debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n print_line($recursion_level, \"Debug: this_object_class = #{this_object_class}\") if $debug\n if $object_recorder.key?(this_object_class)\n if $object_recorder[this_object_class].include?(this_object_id)\n print_line($recursion_level,\n \"Object #{this_object_class} with ID #{this_object_id} has already been printed...\")\n $recursion_level -= 1\n return\n else\n $object_recorder[this_object_class] << this_object_id\n end\n else\n $object_recorder[this_object_class] = []\n $object_recorder[this_object_class] << this_object_id\n end\n #\n # Dump out the things of interest\n #\n print_attributes(object_string, this_object)\n print_virtual_columns(object_string, this_object, this_object_class)\n print_associations(object_string, this_object, this_object_class)\n print_methods(object_string, this_object) if $print_methods\n print_tags(this_object, this_object_class) if $service_model_base_supports_taggable\n print_custom_attributes(object_string, this_object)\n \n $recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{$method} (walk_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n $recursion_level -= 1\n end\nend",
"def iterate_services(service, server, depth)\n obj = get_service(server, service)\n depth = depth - 1\n\n if depth > 0 # If the max depth has not been reached\n if service['dependencies'] # and the service has dependencies\n service['dependencies'].each do |dep| # parse the dependencies\n begin\n child = server.run {\n Zabby::Service.get(\n 'output'=> 'extend',\n 'selectDependencies' => 'extend',\n 'selectTimes' => 'extend',\n 'sortfield' => 'name',\n 'sortOrder' => 'ASC',\n 'serviceids' => dep['serviceid']\n )}\n rescue Exception => e\n puts e.message\n raise \"Impossible to query a dependency of the service %s\" % service['name']\n end\n \n if !child[0]['dependencies'].empty? or !$opts.present?(:parentsonly)\n # adds the dependencies to the object\n # if needed\n obj['children'] << iterate_services(child[0], server, depth)\n end\n end\n end\n end\n \n # updates the maxdepth\n $maxdepth = ($opts[:depth] - depth) if (($opts[:depth] - depth) > $maxdepth) \n return obj\nend",
"def dump_object(object_string, this_object, indent_string)\n begin\n if @recursion_level == 0\n indent_string += \" \"\n else\n indent_string += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n log(:info, \"#{indent_string}#{@method}: *** exceeded maximum recursion level ***\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n log(:info, \"#{indent_string}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n log(:info, \"#{indent_string}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n\n #log(:info, \"#{indent_string}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, indent_string)\n dump_virtual_columns(object_string, this_object, this_object_class, indent_string)\n dump_associations(object_string, this_object, this_object_class, indent_string)\n dump_methods(object_string, this_object, indent_string) if @dump_methods\n\n @recursion_level -= 1\n rescue => err\n log(:error, \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end",
"def each_service(xrds_tree, &block); end",
"def dump_object(object_string, this_object, spaces)\n begin\n if @recursion_level == 0\n spaces += \" \"\n else\n spaces += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n $evm.log(\"info\", \"#{spaces}#{@method}: Exceeded maximum recursion level\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n $evm.log(\"info\", \"#{spaces}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n \n $evm.log(\"info\", \"#{spaces}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, spaces)\n dump_virtual_columns(object_string, this_object, spaces)\n dump_associations(object_string, this_object, this_object_class, spaces)\n \n @recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend",
"def walk_association(object_string, association, associated_objects)\n begin\n #\n # Assemble some fake code to make it look like we're iterating though associations (plural)\n #\n number_of_associated_objects = associated_objects.length\n if is_plural?(association)\n assignment_string = \"#{object_string}.#{association}.each do |#{association.singularize}|\"\n else\n assignment_string = \"#{association} = #{object_string}.#{association}\"\n end\n print_line($recursion_level, \"#{assignment_string}\")\n associated_objects.each do |associated_object|\n associated_object_class = \"#{associated_object.method_missing(:class)}\".demodulize\n associated_object_id = associated_object.id rescue associated_object.object_id\n print_line($recursion_level, \"(object type: #{associated_object_class}, object ID: #{associated_object_id})\")\n if is_plural?(association)\n walk_object(\"#{association.singularize}\", associated_object)\n if number_of_associated_objects > 1\n print_line($recursion_level,\n \"--- next #{association.singularize} ---\")\n number_of_associated_objects -= 1\n else\n print_line($recursion_level,\n \"--- end of #{object_string}.#{association}.each do |#{association.singularize}| ---\")\n end\n else\n walk_object(\"#{association}\", associated_object)\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (walk_association) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend",
"def each_systemT_deep_ref(&ruby_block)\n # No ruby block? Return an enumerator.\n return to_enum(:each_systemT_deep_ref) unless ruby_block\n # A ruby block? \n # Recurse on the systemT accessible through the instances.\n self.scope.each_scope_deep do |scope|\n scope.each_systemI do |systemI|\n # systemI.systemT.each_systemT_deep(&ruby_block)\n systemI.each_systemT do |systemT|\n systemT.each_systemT_deep_ref(&ruby_block)\n end\n end\n end\n # Finally apply it to current.\n ruby_block.call(self)\n end",
"def print_associations(object_string, this_object, this_object_class)\n begin\n #\n # Only dump the associations of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n #\n # Print the associations of this object according to the\n # $walk_associations_whitelist & $walk_associations_blacklist hashes\n #\n associations = []\n associated_objects = []\n duplicates = []\n if this_object.respond_to?(:associations)\n associations = Array.wrap(this_object.associations)\n if associations.length.zero?\n print_line($recursion_level, \"--- no associations ---\")\n else\n print_line($recursion_level, \"--- associations follow ---\")\n duplicates = associations.select{|item| associations.count(item) > 1}\n if duplicates.length > 0\n print_line($recursion_level,\n \"*** De-duplicating the following associations: #{duplicates.inspect} ***\")\n end\n associations.uniq.sort.each do |association|\n begin\n associated_objects = Array.wrap(this_object.method_missing(:send, association))\n if associated_objects.length == 0\n print_line($recursion_level,\n \"#{object_string}.#{association} (type: Association (empty))\")\n else\n print_line($recursion_level, \"#{object_string}.#{association} (type: Association)\")\n #\n # See if we need to walk this association according to the walk_association_policy\n # variable, and the walk_association_{whitelist,blacklist} hashes\n #\n if $walk_association_policy == 'whitelist'\n if $walk_association_whitelist.has_key?(this_object_class) &&\n ($walk_association_whitelist[this_object_class].include?('ALL') ||\n $walk_association_whitelist[this_object_class].include?(association.to_s))\n walk_association(object_string, association, associated_objects)\n else\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' isn't in the walk_association_whitelist \" \\\n \"hash for #{this_object_class} ***\")\n end\n elsif $walk_association_policy == 'blacklist'\n if $walk_association_blacklist.has_key?(this_object_class) &&\n ($walk_association_blacklist[this_object_class].include?('ALL') ||\n $walk_association_blacklist[this_object_class].include?(association.to_s))\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' is in the walk_association_blacklist \" \\\n \"hash for #{this_object_class} ***\")\n else\n walk_association(object_string, association, associated_objects)\n end\n else\n print_line($recursion_level,\n \"*** Invalid $walk_association_policy: #{$walk_association_policy} ***\")\n exit MIQ_ABORT\n end\n end\n rescue NoMethodError\n print_line($recursion_level,\n \"*** #{this_object_class} association: \\'#{association}\\', gives a \" \\\n \"NoMethodError when accessed (product bug?) ***\")\n next\n end\n end\n print_line($recursion_level, \"--- end of associations ---\")\n end\n else\n print_line($recursion_level, \"--- no associations ---\")\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_associations) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend",
"def enumerate_snapshots(vm)\n snapshot_info = vm.snapshot\n\n if snapshot_info.nil?\n snapshot_root = []\n else\n snapshot_root = snapshot_info.rootSnapshotList\n end\n\n recursor = lambda do |snapshot_list|\n Enumerator.new do |yielder|\n snapshot_list.each do |s|\n # Yield the current VirtualMachineSnapshotTree object\n yielder.yield s\n\n # Recurse into child VirtualMachineSnapshotTree objects\n children = recursor.call(s.childSnapshotList)\n loop do\n yielder.yield children.next\n end\n end\n end\n end\n\n recursor.call(snapshot_root)\n end",
"def inspect_hierarchy(object_to_inspect, object_to_inspect_class)\n puts \"#{object_to_inspect} instance of \\\"#{object_to_inspect_class.name}\\\"\"\n\n print \"Hierarchy : \"\n object_to_inspect_class.ancestors.each do |ancestor|\n print \"#{ancestor} -> \"\n end\n puts\n puts \"#{Util::get_line_separator}\"\n end",
"def services_walk\n\t\tprint_status('Enumerating Running Services.....')\n\t\tservices=[['Running Services']]\n\t\t@manager.walk('enterprises.77.1.2.3.1.1') { |x| services << [\"#{x.value}\"] }\n\t\tif services.empty?\n\t\t\tprint_error(\"No Values Found!\")\n\t\telse\n\t\t\ttable = services.to_table(:first_row_is_head => true)\n\t\t\tputs table.to_s\n\t\tend\n\tend",
"def find_path_objects\n target_obj = self.find_target_obj()\n path_objects = [target_obj]\n\n until target_obj.nil? \n target_obj = target_obj.parent\n path_objects << target_obj\n end\n\n path_objects[0..-2].reverse\n end",
"def find_target_obj\n #initialize the first root node by generating its children family\n self.generate_family(self.root_node)\n #This returns the object that includes the ending position\n self.search_through(self.root_node)\n\n end",
"def walk(node)\n return unless componentizable?(node)\n @component_xpaths.push(node.path)\n node.children.each { |c| walk(c) }\n end",
"def list_vms(folder)\n children = folder.children.find_all\n children.each do |child|\n if child.class == VIM::VirtualMachine\n puts child.name\n elsif child.class == VIM::Folder\n list_vms(child)\n end\n end\nend",
"def dumpVM(vm)\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Attributes [vm.attributes]\")\n vm.attributes.sort.each { |k, v| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Attributes - #{k}: #{v.inspect}\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Attributes [vm.attributes]\")\n $evm.log(\"info\",\"\")\n\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Associations [vm.associations]\")\n vm.associations.sort.each { |assc| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Associations - #{assc}\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Associations [vm.associations]\")\n $evm.log(\"info\",\"\")\n\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Hardware Attributes [vm.hardware]\")\n vm.hardware.attributes.each { |k,v| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Hardware - #{k}: #{v.inspect}\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Hardware Attributes [vm.hardware]\")\n $evm.log(\"info\",\"\")\n\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Hardware Associations [vm.hardware.associations]\")\n vm.hardware.associations.sort.each { |assc| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> hardware Associations - #{assc}\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End hardware Associations [vm.hardware.associations]\")\n $evm.log(\"info\",\"\")\n\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Neworks [vm.hardware.nics]\")\n vm.hardware.nics.each { |nic| nic.attributes.sort.each { |k,v| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> VLAN:<#{nic.device_name}> - #{k}: #{v.inspect}\")}}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Networks [vm.hardware.nics]\")\n $evm.log(\"info\",\"\")\n\n unless vm.ext_management_system.nil?\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin EMS [vm.ext_management_system]\")\n vm.ext_management_system.attributes.sort.each { |ems_k, ems_v| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> EMS:<#{vm.ext_management_system.name}> #{ems_k} - #{ems_v.inspect}\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End EMS [vm.ext_management_system]\")\n $evm.log(\"info\",\"\")\n end\n\n unless vm.owner.nil?\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Owner [vm.owner]\")\n vm.owner.attributes.each { |k,v| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Owner - #{k}: #{v.inspect}\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Owner [vm.owner]\")\n $evm.log(\"info\",\"\")\n end\n\n unless vm.operating_system.nil?\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Operating System [vm.operating_system]\")\n vm.operating_system.attributes.sort.each { |k, v| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Operating System - #{k}: #{v.inspect}\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Operating System [vm.operating_system]\")\n $evm.log(\"info\",\"\")\n end\n\n unless vm.guest_applications.nil?\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Guest Applications [vm.guest_applications]\")\n vm.guest_applications.each { |guest_app| guest_app.attributes.sort.each { |k, v| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Guest Application:<#{guest_app.name}> - #{k}: #{v.inspect}\")}} unless vm.guest_applications.nil?\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Guest Applications [vm.guest_applications]\")\n $evm.log(\"info\",\"\")\n end\n\n unless vm.snapshots.nil?\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Snapshots [vm.snapshots]\")\n vm.snapshots.each { |ss| ss.attributes.sort.each { |k, v| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Snapshot:<#{ss.name}> - #{k}: #{v.inspect}\")}} unless vm.snapshots.nil?\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Snapshots [vm.snapshots]\")\n $evm.log(\"info\",\"\")\n end\n\n unless vm.storage.nil?\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin VM Storage [vm.storage]\")\n vm.storage.attributes.sort.each { |stor_k, stor_v| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Storage:<#{vm.storage.name}> #{stor_k} - #{stor_v.inspect}\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End VM Storage [vm.storage]\")\n $evm.log(\"info\",\"\")\n end\n\n unless vm.tags.nil?\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Tags [vm.tags]\")\n vm.tags.sort.each { |tag_element| tag_text = tag_element.split('/'); $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Category:<#{tag_text.first.inspect}> Tag:<#{tag_text.last.inspect}>\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Tags [vm.tags]\")\n $evm.log(\"info\",\"\")\n end\n\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> Begin Virtual Columns [vm.virtual_column_names]\")\n vm.virtual_column_names.sort.each { |vcn| $evm.log(\"info\", \"#{@method} - VM:<#{vm.name}> Virtual Columns - #{vcn}: #{vm.send(vcn).inspect}\")}\n $evm.log(\"info\",\"#{@method} - VM:<#{vm.name}> End Virtual Columns [vm.virtual_column_names]\")\n $evm.log(\"info\",\"\")\n end",
"def each_with_ancestors(objects)\n ancestors = nil\n last_parent = nil\n objects.each do |o|\n if ancestors == nil\n ancestors = o.root? ? [] : o.ancestors.entries\n end\n if ancestors.empty? || o.parent_id != ancestors.last.id\n # we are on a new level, did we descend or ascend?\n if ancestors.any? {|a| a.id == o.parent_id}\n # ascend\n ancestors.pop while (!ancestors.empty? && ancestors.last.id != o.parent_id)\n elsif !o.root?\n # descend\n ancestors << last_parent\n end\n end\n yield(o, ancestors)\n last_parent = o\n end\n end",
"def recursiveTreeTraversal(element)\n if StereotypesHelper.hasStereotype(element, $veStereotype)\n findRefinedParameters(element)\n end\n for child in element.getOwnedElement()\n recursiveTreeTraversal(child)\n end\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
End of walk_object_hierarchy Method: print_automation_objects Purpose: recursively walk & dump the service object hierarchy discovered by walk_automation_objects Arguments: hierarchy: the service object hierarchy indent_level: the indentation string Returns: Nothing
|
def print_automation_objects(indent_level, hierarchy)
case hierarchy.position
when 'root'
print_line(indent_level, "#{hierarchy.obj_name} ($evm.root)")
when 'parent'
print_line(indent_level, "#{hierarchy.obj_name} ($evm.parent)")
when 'object'
print_line(indent_level, "#{hierarchy.obj_name} ($evm.object)")
else
print_line(indent_level, "#{hierarchy.obj_name}")
end
indent_level += 1
hierarchy.children.each do |child|
print_automation_objects(indent_level, child)
end
end
|
[
"def inspect_hierarchy(object_to_inspect, object_to_inspect_class)\n puts \"#{object_to_inspect} instance of \\\"#{object_to_inspect_class.name}\\\"\"\n\n print \"Hierarchy : \"\n object_to_inspect_class.ancestors.each do |ancestor|\n print \"#{ancestor} -> \"\n end\n puts\n puts \"#{Util::get_line_separator}\"\n end",
"def output_hierarchy(output=$stdout)\n hierarchy.print_tree(output)\n end",
"def walk_automation_objects(service_object)\n automation_object = Struct::ServiceObject.new(service_object.to_s, \"\", Array.new)\n if service_object.to_s == $evm.root.to_s\n automation_object.position = 'root'\n elsif service_object.to_s == $evm.parent.to_s\n automation_object.position = 'parent'\n elsif service_object.to_s == $evm.object.to_s\n automation_object.position = 'object'\n end\n offspring = service_object.children\n unless offspring.nil? || (offspring.kind_of?(Array) and offspring.length.zero?)\n Array.wrap(offspring).each do |child|\n automation_object.children << walk_automation_objects(child)\n end\n end\n return automation_object\nend",
"def walk_object(object_string, this_object)\n begin\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n $recursion_level += 1\n if $recursion_level > $max_recursion_level\n print_line($recursion_level, \"*** exceeded maximum recursion level ***\")\n $recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n print_line($recursion_level,\n \"Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if $debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n print_line($recursion_level, \"Debug: this_object_class = #{this_object_class}\") if $debug\n if $object_recorder.key?(this_object_class)\n if $object_recorder[this_object_class].include?(this_object_id)\n print_line($recursion_level,\n \"Object #{this_object_class} with ID #{this_object_id} has already been printed...\")\n $recursion_level -= 1\n return\n else\n $object_recorder[this_object_class] << this_object_id\n end\n else\n $object_recorder[this_object_class] = []\n $object_recorder[this_object_class] << this_object_id\n end\n #\n # Dump out the things of interest\n #\n print_attributes(object_string, this_object)\n print_virtual_columns(object_string, this_object, this_object_class)\n print_associations(object_string, this_object, this_object_class)\n print_methods(object_string, this_object) if $print_methods\n print_tags(this_object, this_object_class) if $service_model_base_supports_taggable\n print_custom_attributes(object_string, this_object)\n \n $recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{$method} (walk_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n $recursion_level -= 1\n end\nend",
"def print_recursive\n\t\tputs \"#{@name}\"\n\t\tprint_b_cpp\n\t\tprint_t_cpp\n\t\tprint_ts_cpp\n\t\tprint_cpp\n\t\tprint_hpp\n\t\tprint_ts_hpp\n\t\t@subdirs.each do |subdir|\n\t\t\tsubdir.print_recursive1(\"#{subdir.name}\")\n\t\tend\n\tend",
"def dump_object(object_string, this_object, indent_string)\n begin\n if @recursion_level == 0\n indent_string += \" \"\n else\n indent_string += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n log(:info, \"#{indent_string}#{@method}: *** exceeded maximum recursion level ***\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n log(:info, \"#{indent_string}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n log(:info, \"#{indent_string}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n\n #log(:info, \"#{indent_string}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, indent_string)\n dump_virtual_columns(object_string, this_object, this_object_class, indent_string)\n dump_associations(object_string, this_object, this_object_class, indent_string)\n dump_methods(object_string, this_object, indent_string) if @dump_methods\n\n @recursion_level -= 1\n rescue => err\n log(:error, \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end",
"def dump_object(object_string, this_object, spaces)\n begin\n if @recursion_level == 0\n spaces += \" \"\n else\n spaces += \"| \"\n end\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n @recursion_level += 1\n if @recursion_level > MAX_RECURSION_LEVEL\n $evm.log(\"info\", \"#{spaces}#{@method}: Exceeded maximum recursion level\")\n @recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}}\") if @debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object_class = #{this_object_class}\") if @debug\n if @object_recorder.key?(this_object_class)\n if @object_recorder[this_object_class].include?(this_object_id)\n $evm.log(\"info\", \"#{spaces}#{@method}: Object #{this_object_class} with ID #{this_object_id} has already been dumped...\")\n @recursion_level -= 1\n return\n else\n @object_recorder[this_object_class] << this_object_id\n end\n else\n @object_recorder[this_object_class] = []\n @object_recorder[this_object_class] << this_object_id\n end\n \n $evm.log(\"info\", \"#{spaces}#{@method}: Dumping $evm.root\") if @recursion_level == 1\n #\n # Dump out the things of interest\n #\n dump_attributes(object_string, this_object, spaces)\n dump_virtual_columns(object_string, this_object, spaces)\n dump_associations(object_string, this_object, this_object_class, spaces)\n \n @recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend",
"def print_associations(object_string, this_object, this_object_class)\n begin\n #\n # Only dump the associations of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n #\n # Print the associations of this object according to the\n # $walk_associations_whitelist & $walk_associations_blacklist hashes\n #\n associations = []\n associated_objects = []\n duplicates = []\n if this_object.respond_to?(:associations)\n associations = Array.wrap(this_object.associations)\n if associations.length.zero?\n print_line($recursion_level, \"--- no associations ---\")\n else\n print_line($recursion_level, \"--- associations follow ---\")\n duplicates = associations.select{|item| associations.count(item) > 1}\n if duplicates.length > 0\n print_line($recursion_level,\n \"*** De-duplicating the following associations: #{duplicates.inspect} ***\")\n end\n associations.uniq.sort.each do |association|\n begin\n associated_objects = Array.wrap(this_object.method_missing(:send, association))\n if associated_objects.length == 0\n print_line($recursion_level,\n \"#{object_string}.#{association} (type: Association (empty))\")\n else\n print_line($recursion_level, \"#{object_string}.#{association} (type: Association)\")\n #\n # See if we need to walk this association according to the walk_association_policy\n # variable, and the walk_association_{whitelist,blacklist} hashes\n #\n if $walk_association_policy == 'whitelist'\n if $walk_association_whitelist.has_key?(this_object_class) &&\n ($walk_association_whitelist[this_object_class].include?('ALL') ||\n $walk_association_whitelist[this_object_class].include?(association.to_s))\n walk_association(object_string, association, associated_objects)\n else\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' isn't in the walk_association_whitelist \" \\\n \"hash for #{this_object_class} ***\")\n end\n elsif $walk_association_policy == 'blacklist'\n if $walk_association_blacklist.has_key?(this_object_class) &&\n ($walk_association_blacklist[this_object_class].include?('ALL') ||\n $walk_association_blacklist[this_object_class].include?(association.to_s))\n print_line($recursion_level,\n \"*** not walking: \\'#{association}\\' is in the walk_association_blacklist \" \\\n \"hash for #{this_object_class} ***\")\n else\n walk_association(object_string, association, associated_objects)\n end\n else\n print_line($recursion_level,\n \"*** Invalid $walk_association_policy: #{$walk_association_policy} ***\")\n exit MIQ_ABORT\n end\n end\n rescue NoMethodError\n print_line($recursion_level,\n \"*** #{this_object_class} association: \\'#{association}\\', gives a \" \\\n \"NoMethodError when accessed (product bug?) ***\")\n next\n end\n end\n print_line($recursion_level, \"--- end of associations ---\")\n end\n else\n print_line($recursion_level, \"--- no associations ---\")\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_associations) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend",
"def dump_hierachy_locations msg, top, indent = ''\r\n \r\n puts \"for each component display location\" if indent.length == 0\r\n \r\n pos = top.bounds\r\n state = top.visible? ? 'visible' : 'hidden'\r\n \r\n name = top.name ? \"(#{top.name}) \" : \"\"\r\n \r\n puts \"#{indent}#{msg}: #{top.class} @ #{name}(#{pos.x}, #{pos.y}) - [#{pos.width} x #{pos.height}] (#{state})\"\r\n \r\n top.component_count.times do |i|\r\n comp = top.getComponent(i)\r\n dump_hierachy_locations \"[#{i}]\", comp, indent + ' '\r\n end\r\n \r\n end",
"def print_recursive1(parentdir)\n\t\tputs \"#{parentdir}/#{@name}\"\n\t\tprint_b_cpp\n\t\tprint_t_cpp\n\t\tprint_ts_cpp\n\t\tprint_cpp\n\t\tprint_hpp\n\t\tprint_ts_hpp\n\t\t@subdirs.each do |subdir|\n\t\t\tsubdir.print_recursive1(\"#{parentdir}/#{subdir.name}\")\n\t\tend\n\tend",
"def print_tree\n @tree.print_tree\n end",
"def print_tree(out = $stdout)\n out.puts \"## Class: #{name}\"\n out.puts \" Visible Name: #{visible_name}\"\n out.puts \" Description : #{description}\"\n tables.each do |table|\n table.print_tree(out)\n end\n end",
"def print_tree(out = $stdout)\n tree.each do |name, value|\n value.print_tree(out)\n end\n end",
"def op5PrintObjects(type,objects)\n logIt(\"* Entering: #{thisMethod()}\", DEBUG)\n# pp objects\n objects.each do |object|\n case type\n when OBJECT_TYPE_HOST\n printf \"name: %-25s alias: %-40s address: %-15s state: %i\\n\", object[\"name\"], object[\"alias\"], object[\"address\"], object[\"state\"] if (! object[\"name\"].nil?)\n when OBJECT_TYPE_HOSTGROUP, OBJECT_TYPE_CONTACTGROUP, OBJECT_TYPE_SERVICEGROUP\n\n printf \"name: %-25s alias: %-40s members: \", object[\"name\"], object[\"alias\"] if (! object[\"name\"].nil?)\n printCount=0\n object[\"members\"].each do | member |\n printf \",\" if printCount > 0\n printf \"%s\", (member.class.to_s == \"Array\") ? member[0] + \";\" + member[1] : member\n printCount += 1\n end\n printf \"\\n\"\n \n when OBJECT_TYPE_SERVICE\n printf \"host_name: %-25s description: %-40s\\n\", object[\"host\"][\"name\"], object[\"description\"] if (! object[\"description\"].nil?)\n when OBJECT_TYPE_CONTACT\n printf \"name: %-25s alias: %-30s email: %-35s contactgroups: \", object[\"name\"], object[\"alias\"], object[\"email\"] if (! object[\"name\"].nil?)\n\n printCount=0\n object[\"contactgroups\"].each do |contactgroup|\n printf \",\" if printCount > 0\n printf \"%s\", contactgroup[0][\"name\"]\n printCount += 1\n end\n printf \"\\n\"\n end\n end\nend",
"def dump_hierachy msg, top, indent = ''\r\n name = top.name ? \"(#{top.name}) \" : \"\"\r\n layout = top.get_layout ? \"<layout #{top.get_layout.class}> \" : \"\"\r\n puts \"#{indent}#{msg}: #{top.class} #{name}#{layout}contains #{top.component_count} component(s)\"\r\n top.component_count.times do |i|\r\n comp = top.getComponent(i)\r\n dump_hierachy \"[#{i}]\", comp, indent + ' '\r\n end\r\n end",
"def test_print_tree\n setup_test_tree\n #puts\n #@root.print_tree\n end",
"def print_tree(indent = 0, lines = [])\n lines << (\" \" * indent) + self.to_s\n @nodes.keys.sort.each do |reference|\n node = @nodes[reference]\n if node.is_a? APISpec::Namespace\n node.print_tree(indent + 1, lines)\n else\n lines << (\" \" * (indent + 1)) + \"#{reference} => #{node.to_s}\"\n end\n end\n lines.join(\"\\n\")\n end",
"def print_structure(structure)\n\n # Identify method entry\n debug_print \"#{ self } : #{ __method__ }\\n\"\n\n # First go through all the files in the current structure\n # The current \"structure\" should reflect a dir/subdir\n structure[:files].each do | _file |\n debug_print \"Printing info for #{ _file }\\n\"\n print_entry(_file)\n end\n\n # Next go through all the subdirs and pass them to print_structure\n structure[:subdirs].each do | _subdir |\n debug_print \"Entering #{ _subdir } to print further\\n\"\n print_structure(_subdir)\n end\n end",
"def dump indent = \"\", path = []\n if path.include? self.id\n puts \"#{indent}!!Loop back to #{self.id.to_s}: #{self.name}\"\n else\n puts \"#{indent}Referent #{self.id.to_s}: #{self.name}\"\n indent = indent + \" \"\n self.tags.each do |tag|\n puts \"#{indent}Tag #{tag.id.to_s}: #{tag.name}\"\n tag.links.each { |link| puts \"#{indent} Link #{link.id.to_s}: #{link.uri}\" }\n end\n self.children.each { |child| child.dump(indent, path+[self.id]) }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
End of walk_object_hierarchy Method: print_line Purpose: Wraps $evm.log(:info....) Arguments: indent_level: the indentation string string: the actual message to print Returns: Nothing
|
def print_line(indent_level, string)
$evm.log("info", "#{$method}:[#{indent_level.to_s}] #{string}")
end
|
[
"def print_automation_objects(indent_level, hierarchy)\n case hierarchy.position\n when 'root'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.root)\")\n when 'parent'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.parent)\")\n when 'object'\n print_line(indent_level, \"#{hierarchy.obj_name} ($evm.object)\")\n else\n print_line(indent_level, \"#{hierarchy.obj_name}\")\n end\n indent_level += 1\n hierarchy.children.each do |child|\n print_automation_objects(indent_level, child)\n end\nend",
"def log_line(data)\n @log.public_send(@level, nil) { data }\n end",
"def log\n each do |node|\n puts node.inspect\n end\n return nil\n end",
"def log_line(line)\n if config.colorize_logging\n @@row_even, message_color = if @@row_even\n [false, '4;32;1']\n else\n [true, '4;33;1']\n end\n\n config.logger.info(\" [\\e[#{message_color}m%s\\e[0m] %s\" % [@name, line])\n else\n config.logger.info(\"[%s] %s\" % [@name, line])\n end\n end",
"def print_item(level:, current_item:)\n # Print the current item\n tabs = \"\\t\" * level\n puts tabs + '+ ' + current_item[:name]\n\n # Print the current item's children\n children = $children_of[current_item[:id]]\n if children && children.length > 0\n children.each do |child|\n print_item(\n level: level + 1, \n current_item: child\n )\n end\n end\nend",
"def element_tree_line(line)\n end",
"def inspect_hierarchy(object_to_inspect, object_to_inspect_class)\n puts \"#{object_to_inspect} instance of \\\"#{object_to_inspect_class.name}\\\"\"\n\n print \"Hierarchy : \"\n object_to_inspect_class.ancestors.each do |ancestor|\n print \"#{ancestor} -> \"\n end\n puts\n puts \"#{Util::get_line_separator}\"\n end",
"def walk_object(object_string, this_object)\n begin\n #\n # Make sure that we don't exceed our maximum recursion level\n #\n $recursion_level += 1\n if $recursion_level > $max_recursion_level\n print_line($recursion_level, \"*** exceeded maximum recursion level ***\")\n $recursion_level -= 1\n return\n end\n #\n # Make sure we haven't dumped this object already (some data structure links are cyclical)\n #\n this_object_id = this_object.id.to_s rescue this_object.object_id.to_s\n print_line($recursion_level,\n \"Debug: this_object.method_missing(:class) = #{this_object.method_missing(:class)}\") if $debug\n this_object_class = \"#{this_object.method_missing(:class)}\".demodulize\n print_line($recursion_level, \"Debug: this_object_class = #{this_object_class}\") if $debug\n if $object_recorder.key?(this_object_class)\n if $object_recorder[this_object_class].include?(this_object_id)\n print_line($recursion_level,\n \"Object #{this_object_class} with ID #{this_object_id} has already been printed...\")\n $recursion_level -= 1\n return\n else\n $object_recorder[this_object_class] << this_object_id\n end\n else\n $object_recorder[this_object_class] = []\n $object_recorder[this_object_class] << this_object_id\n end\n #\n # Dump out the things of interest\n #\n print_attributes(object_string, this_object)\n print_virtual_columns(object_string, this_object, this_object_class)\n print_associations(object_string, this_object, this_object_class)\n print_methods(object_string, this_object) if $print_methods\n print_tags(this_object, this_object_class) if $service_model_base_supports_taggable\n print_custom_attributes(object_string, this_object)\n \n $recursion_level -= 1\n rescue => err\n $evm.log(\"error\", \"#{$method} (walk_object) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n $recursion_level -= 1\n end\nend",
"def add_line_info(line, node)\n return if node.is_a?(Expressions)\n return unless node.is_a?(Expression) || node.is_a?(::Enumerable)\n\n if node.is_a?(::Enumerable) then\n node.each {|el| add_line_info(line, el)}\n else\n node.line = line\n node.filename = @file\n node.instance_variables.each do |var|\n add_line_info(line, node.instance_variable_get(var))\n end\n end\n end",
"def level_order_print(tree)\n unless tree\n return\n end\n\n nodes = [tree]\n current_line_count = 1\n next_line_count = 0\n\n while nodes.length != 0\n current_node = nodes.shift\n current_line_count -= 1\n print current_node.key.to_s + ' '\n if current_node.left_child\n nodes.push(current_node.left_child)\n next_line_count += 1\n end\n if current_node.right_child\n nodes.push(current_node.right_child)\n next_line_count += 1\n end\n if current_line_count == 0\n # finished printing current level\n puts ''\n current_line_count = next_line_count\n next_line_count = current_line_count\n end\n end\nend",
"def veputs(level, t)\n t = t.dup\n nnl = nil\n if t.match(/#{NNL_MARK}$/)\n t.sub!(/#{$&}/, '')\n nnl = 1\n end\n\n if @conf[:verbose] >= level\n nnl ? print(t) : print(\"#{t}\\n\")\n $stdout.flush\n end\n end",
"def to_debug_log\n current = self\n depth = 1\n loop do\n PDK.logger.debug(\"Detected #{current.display_name} at #{current.root_path.nil? ? current.context_path : current.root_path}\")\n current = current.parent_context\n break if current.nil?\n\n depth += 1\n # Circuit breaker in case there are circular references\n break if depth > 20\n end\n nil\n end",
"def info(log)\n output.puts log if log_level <= INFO\n end",
"def print(io)\n tree.each_with_index do |(command, event_called_handlerss), index|\n io.puts '+++++++++++++++++++++++++++++++++++' if index == 0\n io.puts \"Command: #{command.class} resulted in #{event_called_handlerss.length} events\"\n event_called_handlerss.each_with_index do |event_called_handlers, i|\n io.puts '' if i > 0\n io.puts \"-- Event #{event_called_handlers.event.class} was handled by:\"\n io.puts \"-- Projectors: [#{event_called_handlers.projectors.join(', ')}]\"\n io.puts \"-- Workflows: [#{event_called_handlers.workflows.join(', ')}]\"\n end\n\n io.puts '+++++++++++++++++++++++++++++++++++'\n end\n end",
"def log_stdout\n lambda do |type, data|\n ui.info data, :new_line => false\n end\n end",
"def trail_printer(trail_instance)\n trail_instance.print_info\n 15.times {print \"*\"}\n print \"\\n\"\n end",
"def print(depth=0)\n if SYMLINK_TRACE\n if is_file?\n puts \"#{' '*(depth*2)} #{@name} => #{@target}\"\n elsif is_dir?\n puts \"#{' '*(depth*2)} [#{@name}] => #{@target}\"\n elsif @target\n puts \"#{' '*(depth*2)} [#{@name}] => #{@target} [missing?]\"\n else\n puts \"#{' '*(depth*2)} [#{@name}]\" if @target\n end\n end\n for node in children\n node.print depth+1\n end\n end",
"def print_info\n puts \"Trail Name: #{self.trail.name}\"\n puts \"Trail Length: #{self.trail.length} miles\"\n puts self.date.strftime(\"Date Hiked: %m/%d/%Y\")\n puts self.time_hiked.nil? ? \"Length of Time on Trail: Hike not completed\" : Time.at(self.time_hiked).utc.strftime(\"Length of Time on Trail: %H:%M\")\n puts \"Status: #{self.completed? ? \"completed\" : \"incomplete\"}\"\n end",
"def print_tree(indent = 0, lines = [])\n lines << (\" \" * indent) + self.to_s\n @nodes.keys.sort.each do |reference|\n node = @nodes[reference]\n if node.is_a? APISpec::Namespace\n node.print_tree(indent + 1, lines)\n else\n lines << (\" \" * (indent + 1)) + \"#{reference} => #{node.to_s}\"\n end\n end\n lines.join(\"\\n\")\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
End of ping_attr Method: str_or_sym Purpose: format a string containing the argument correctly depending on whether the value is a symbol or string Arguments: value: the thing to be stringformatted Returns: string containing either ":value" or "'value'"
|
def str_or_sym(value)
value_as_string = ""
if value.is_a?(Symbol)
value_as_string = ":#{value}"
else
value_as_string = "\'#{value}\'"
end
return value_as_string
end
|
[
"def to_str(arg)\n if arg.is_a?(Symbol)\n \":\" + arg.to_s\n elsif arg.nil?\n \"nil\"\n elsif arg.is_a?(String)\n \"'#{arg}'\"\n else\n arg.to_s\n end\n end",
"def attribute_name(sym_or_str)\n str = sym_or_str.to_s.downcase\n \n # Does str match 'something='? Still only returns :something\n return str[0...-1].to_sym if str.size>1 && str[-1] == ?=\n return str.to_sym\n end",
"def to_sym?(value)\n \"#{value}\" != ''\n end",
"def quote_if_needed(value)\n if string_value?(value)\n quote(value)\n else\n value.to_s\n end\n end",
"def quote_symbol(value)\n quote_string(value.to_s)\n end",
"def to_sym?(value); end",
"def label(argument:, explicit_label: nil)\n text = if explicit_label.nil?\n argument.is_a?(Symbol) ? \"#{argument}:\" : nil\n elsif explicit_label.respond_to?(:strip)\n s = explicit_label.strip\n s += ':' unless s[-1] == ':'\n s\n end\n\n text.nil? ? '[unknown value]:' : text.to_s\n end",
"def create_escape_value(value)\n if value.is_a?(String) || value.is_a?(Symbol)\n \"#{sanitize_escape_sequences(value.to_s)}\"\n else\n value\n end\n end",
"def format_value_for_create_or_update(value)\n # Boolean have to be casted to strings\n if !!value == value\n value.to_s\n else\n value\n end\n end",
"def attribute(value, default_value=nil)\n str = value.to_s\n not(str.empty?) ? str : default_value\n end",
"def format(value)\n if value.class.name == 'Puppet::Pops::Types::PSensitiveType::Sensitive'\n \"'#{escape_quotes(value.unwrap)}' # PuppetSensitive\"\n else\n Pwsh::Util.format_powershell_value(value)\n end\n end",
"def write_symbolized_attribute (attr_name, value)\n write_attribute(attr_name, (value.to_sym && value.to_sym.to_s rescue nil))\n end",
"def attribute_description(key, value)\n case value\n when true\n \"#{key}=anything\"\n when false\n key.to_s\n when Regexp\n \"#{key}=~#{value.inspect}\"\n else\n \"#{key}=#{value.inspect}\"\n end\n end",
"def shellify_opt(value)\n value.to_s.gsub('_', '-')\n end",
"def on_symbol_literal(value); end",
"def [](symbol_or_string)\n attributes[symbol_or_string.to_s]\n end",
"def string_PAnyType(val_type, val, format_map, _)\n f = get_format(val_type, format_map)\n Kernel.format(f.orig_fmt, val)\n end",
"def safe_str\n name_component = metric_name.to_s\n name_component << \"-#{default_attribute.gsub(%r{[^\\w]}, '')}\" if default_attribute?\n (namespace << name_component).join('.')\n end",
"def symbol(value)\n return value if value.is_a? Symbol\n value = string(value) unless value.respond_to? :to_sym\n value.to_sym\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
End of str_or_sym Method: print_attributes Purpose: Print the attributes of an object Arguments: object_string : friendly text string name for the object this_object : the Ruby object whose virtual_column_names are to be dumped Returns: None
|
def print_attributes(object_string, this_object)
begin
#
# Print the attributes of this object
#
if this_object.respond_to?(:attributes)
print_line($recursion_level, "Debug: this_object.inspected = #{this_object.inspect}") if $debug
if this_object.attributes.respond_to?(:keys)
if this_object.attributes.keys.length > 0
print_line($recursion_level, "--- attributes follow ---")
this_object.attributes.keys.sort.each do |attribute_name|
attribute_value = this_object.attributes[attribute_name]
if attribute_name != "options"
if attribute_value.is_a?(DRb::DRbObject)
if attribute_value.method_missing(:class).to_s =~ /^MiqAeMethodService.*/
print_line($recursion_level,
"#{object_string}[\'#{attribute_name}\'] => #{attribute_value} #{type(attribute_value)}")
walk_object("#{object_string}[\'#{attribute_name}\']", attribute_value)
else
print_line($recursion_level,
"Debug: not dumping, attribute_value.method_missing(:class) = " \
"#{attribute_value.method_missing(:class)}") if $debug
end
else
begin
attr_info = ping_attr(this_object, attribute_name)
if attr_info[:value].nil?
print_line($recursion_level,
"#{object_string}#{attr_info[:format_string]} = nil") if $print_nil_values
else
print_line($recursion_level,
"#{object_string}#{attr_info[:format_string]} = #{attr_info[:value]} #{type(attr_info[:value])}")
end
rescue ArgumentError
if attribute_value.nil?
print_line($recursion_level,
"#{object_string}.#{attribute_name} = nil") if $print_nil_values
else
print_line($recursion_level,
"#{object_string}.#{attribute_name} = #{attribute_value} #{type(attribute_value)}")
end
end
end
else
#
# Option key names can be mixed symbols and strings which confuses .sort
# Create an option_map hash that maps option_name.to_s => option_name
#
option_map = {}
options = attribute_value.keys
options.each do |option_name|
option_map[option_name.to_s] = option_name
end
option_map.keys.sort.each do |option|
if attribute_value[option_map[option]].nil?
print_line($recursion_level,
"#{object_string}.options[#{str_or_sym(option_map[option])}] = nil") if $print_nil_values
else
print_line($recursion_level,
"#{object_string}.options[#{str_or_sym(option_map[option])}] = " \
"#{attribute_value[option_map[option]]} #{type(attribute_value[option_map[option]])}")
end
end
end
end
print_line($recursion_level, "--- end of attributes ---")
else
print_line($recursion_level, "--- no attributes ---")
end
else
print_line($recursion_level, "*** attributes is not a hash ***")
end
else
print_line($recursion_level, "--- no attributes ---")
end
rescue => err
$evm.log("error", "#{$method} (print_attributes) - [#{err}]\n#{err.backtrace.join("\n")}")
end
end
|
[
"def dump_attributes(object_string, this_object, indent_string)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n log(:info, \"#{indent_string}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} #{type(value)}\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, indent_string)\n else\n if value.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = #{value} #{type(value)}\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = #{v} #{type(v)}\")\n end\n end\n end\n end\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no attributes\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end",
"def dump_attributes(object_string, this_object, spaces)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} (type: #{value.class})\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, spaces)\n else\n if value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = #{value} (type: #{value.class})\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = #{v} (type: #{v.class})\")\n end\n end\n end\n end\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: This object has no attributes\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend",
"def print_custom_attributes(object_string, this_object)\n begin\n if this_object.respond_to?(:custom_keys)\n custom_attribute_keys = Array.wrap(this_object.custom_keys)\n if custom_attribute_keys.length.zero?\n print_line($recursion_level, \"--- no custom attributes ---\")\n else\n print_line($recursion_level, \"--- custom attributes follow ---\")\n custom_attribute_keys.sort.each do |custom_attribute_key|\n custom_attribute_value = this_object.custom_get(custom_attribute_key)\n print_line($recursion_level, \"#{object_string}.custom_get(\\'#{custom_attribute_key}\\') = \\'#{custom_attribute_value}\\'\")\n end\n print_line($recursion_level, \"--- end of custom attributes ---\")\n end\n else\n print_line($recursion_level, \"--- object does not support custom attributes ---\")\n end \n rescue => err\n $evm.log(\"error\", \"#{$method} (print_custom_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend",
"def inspect_object_attributs(object_to_inspect)\n puts \"- Instance attributs :\"\n object_to_inspect.instance_variables.each do |attribute|\n value = object_to_inspect.instance_eval attribute.to_s\n puts \"\\t- Name : #{attribute}\"\n puts \"\\t\\t- Type : #{value.class}\"\n puts \"\\t\\t- Value : #{value.inspect}\"\n end\n puts \"#{Util::get_line_separator}\"\n end",
"def dump_attributes(my_object, my_object_name)\n if my_object.respond_to?(\"attributes\")\n self.log(@dump_log_level, \"Begin #{my_object_name}.attributes\")\n my_object.attributes.sort.each { |k, v| self.log(:info, \"#{my_object_name} Attribute - #{k}: #{v}\")}\n self.log(@dump_log_level, \"End #{my_object_name}.attributes\")\n self.log(@dump_log_level, \"\")\n else\n self.log(@dump_log_level, \"No attributes for #{my_object_name}\")\n end\n end",
"def dump_virtual_columns(object_string, this_object, spaces)\n begin\n #\n # Print the virtual columns of this object \n #\n if this_object.respond_to?(:virtual_column_names)\n $evm.log(\"info\", \"#{spaces}#{@method}: --- virtual columns follow ---\")\n this_object.virtual_column_names.sort.each do |virtual_column_name|\n virtual_column_value = this_object.send(virtual_column_name)\n if virtual_column_value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{virtual_column_name} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{virtual_column_name} = #{virtual_column_value} (type: #{virtual_column_value.class})\")\n end\n end\n $evm.log(\"info\", \"#{spaces}#{@method}: --- end of virtual columns ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_virtual_columns) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend",
"def printAttrtable(string: nil)\n raise \"printAttrtable expects a string. Missing string: 'text'\" unless string\n printGds2Record(type: 'ATTRTABLE', data: string)\n end",
"def _print_obj # print_obj object\r\n obj_id = @operands[0]\r\n\r\n text = parse_zchar_sequence peek_zchar_text (zobj obj_id).name_addr\r\n @screen.print text\r\n\r\n dbg :print { text }\r\n end",
"def dump_virtual_columns(object_string, this_object, this_object_class, indent_string)\n begin\n #\n # Print the virtual columns of this object\n #\n if this_object.respond_to?(:virtual_column_names)\n log(:info, \"#{indent_string}#{@method}: --- virtual columns follow ---\")\n this_object.virtual_column_names.sort.each do |virtual_column_name|\n begin\n virtual_column_value = this_object.send(virtual_column_name)\n if virtual_column_value.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{virtual_column_name} = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{virtual_column_name} = #{virtual_column_value} #{type(virtual_column_value)}\")\n end\n rescue NoMethodError\n log(:info, \"#{indent_string}#{@method}: *** #{this_object_class} virtual column: \\'#{virtual_column_name}\\' gives a NoMethodError when accessed (product bug?) ***\")\n end\n end\n log(:info, \"#{indent_string}#{@method}: --- end of virtual columns ---\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no virtual columns\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_virtual_columns) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end",
"def print_attribute(*) end",
"def print_attrs(obj, point=\"*\", splitter=\":\", endline=\"\\n\")\n result = \"\"\n if obj.is_a?(Hash)\n obj.each do |arg, value|\n result += \"#{point} #{arg}#{splitter} \"\n result += case value\n when Hash\n \"#{endline}#{print_attrs(value, point[0,1]+point, splitter, endline)}\"\n when Array\n \"#{value.join(\", \")}#{endline}\"\n else\n \"#{value}#{endline}\"\n end\n end\n end\n return result\n end",
"def dump_info(my_object, my_object_name)\n self.dump_attributes(my_object, my_object_name)\n self.dump_associations(my_object, my_object_name)\n self.dump_virtual_columns(my_object, my_object_name)\n end",
"def print_attributes\n @attributes.each{|attribute, value| puts \"#{attribute}: #{value}\"}\n end",
"def print_virtual_columns(object_string, this_object, this_object_class)\n begin\n #\n # Only dump the virtual columns of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n #\n # Print the virtual columns of this object \n #\n virtual_column_names = []\n if this_object.respond_to?(:virtual_column_names)\n virtual_column_names = Array.wrap(this_object.virtual_column_names)\n if virtual_column_names.length.zero?\n print_line($recursion_level, \"--- no virtual columns ---\")\n else\n print_line($recursion_level, \"--- virtual columns follow ---\")\n virtual_column_names.sort.each do |virtual_column_name|\n begin\n virtual_column_value = this_object.method_missing(:send, virtual_column_name)\n if virtual_column_value.nil?\n print_line($recursion_level,\n \"#{object_string}.#{virtual_column_name} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.#{virtual_column_name} = \" \\\n \"#{virtual_column_value} #{type(virtual_column_value)}\")\n end\n rescue NoMethodError\n print_line($recursion_level,\n \"*** #{this_object_class} virtual column: \\'#{virtual_column_name}\\' \" \\\n \"gives a NoMethodError when accessed (product bug?) ***\")\n end\n end\n print_line($recursion_level, \"--- end of virtual columns ---\")\n end\n else\n print_line($recursion_level, \"--- no virtual columns ---\")\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_virtual_columns) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend",
"def print_obj_info(obj)\n obj.instance_variables.map{|var| puts [var, obj.instance_variable_get(var)].join(\":\")}\n end",
"def parse_model_attributes(object, attributes = [])\n return \"\" unless attributes.length > 0\n\n i = 1\n data = \"<table class='attributes-table'>\"\n attributes.each do |a|\n unless object[a.to_sym].blank?\n i.modulo(2) == 0 ? style = \"even\" : style = \"odd\"\n data << \"<tr class='#{style}'>\"\n\n descriptor = a.humanize\n\n # Custom descriptor substitutions\n descriptor.gsub!(/(G|g)(C|c)/, 'GC')\n descriptor.gsub!(/accession/, 'NCBI accession')\n descriptor.gsub!(/(N|n)cbi/, 'NCBI')\n descriptor.gsub!(/(G|g)rin/, 'GRIN')\n descriptor.gsub!(/(S|s)elf incompatibility/, 'Mating system')\n\n ## Column One ##\n data << \"<td>#{descriptor}</td>\"\n\n # Custom values\n ## Column Two ##\n case a.to_sym\n when :ncbi_taxon_id\n data << \"<td>#{link_to object[a.to_sym], NCBI_URL + object[a.to_sym]}</td>\"\n when :grin_taxon_id\n data << \"<td>#{link_to object[a.to_sym], GRIN_URL + object[a.to_sym]}</td>\"\n when :gc_content_genome\n data << \"<td>#{object[a.to_sym]}%</td>\"\n when :gc_content_transcriptome\n data << \"<td>#{object[a.to_sym]}%</td>\"\n when :genome_size\n data << \"<td>#{object[a.to_sym]} (Mbp)</td>\"\n when :chloroplast_genome_size\n data << \"<td>#{object[a.to_sym]} (kbp)</td>\"\n when :mitochondria_genome_size\n data << \"<td>#{object[a.to_sym]} (kbp)</td>\"\n else\n data << \"<td>#{object[a.to_sym]}</td>\"\n end\n\n information = \"#{a}_information\".to_sym\n # If the attribute has additional information, add the dialog box.\n ## Column Three ##\n unless object[information].blank?\n data << \"<td>\"\n details = object[information]\n title = information.to_s.humanize.gsub(/(G|g)(C|c)/, 'GC')\n # Text container\n data << \"<div id='#{a}_information_dialog' title='#{title}'>#{details}</div>\"\n data << \" <a id='#{a}_information_opener' href='#'>Read More »</a>\"\n # jQuery dialog box\n data << \"<script>$j(function($){$('##{a}_information_dialog').dialog(\" +\n \"{autoOpen:false,show:'blind',hide:'blind',width:450});\" +\n \"$('##{a}_information_opener').click(function(){\" +\n \"$('##{a}_information_dialog').dialog('open');return false;});});\" +\n \"</script>\"\n data << \"</td>\"\n else\n data << \"<td></td>\"\n end\n data << \"</tr>\"\n i += 1\n end\n end\n data << \"</table>\"\n\n data.html_safe\n end",
"def display object\n # stringify symbols in YAML output for better readability\n puts object.to_yaml.gsub(/^([[:blank:]]*(- )?):(?=@?\\w+: )/, '\\1')\n rescue\n require 'pp'\n pp object\n end",
"def inspectObject (theObject)\n puts theObject.inspect\nend",
"def awesome_active_record_instance(object)\n return object.inspect if !defined?(ActiveSupport::OrderedHash)\n\n data = object.class.column_names.inject(ActiveSupport::OrderedHash.new) do |hash, name|\n hash[name.to_sym] = object.send(name) if object.has_attribute?(name) || object.new_record?\n hash\n end\n \"#{object} \" + awesome_hash(data)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
End of print_attributes Method: print_virtual_columns Purpose: Prints the virtual_columns_names of the object passed to it Arguments: object_string : friendly text string name for the object this_object : the Ruby object whose virtual_column_names are to be dumped this_object_class : the class of the object whose associations are to be dumped Returns: None
|
def print_virtual_columns(object_string, this_object, this_object_class)
begin
#
# Only dump the virtual columns of an MiqAeMethodService::* class
#
if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/
#
# Print the virtual columns of this object
#
virtual_column_names = []
if this_object.respond_to?(:virtual_column_names)
virtual_column_names = Array.wrap(this_object.virtual_column_names)
if virtual_column_names.length.zero?
print_line($recursion_level, "--- no virtual columns ---")
else
print_line($recursion_level, "--- virtual columns follow ---")
virtual_column_names.sort.each do |virtual_column_name|
begin
virtual_column_value = this_object.method_missing(:send, virtual_column_name)
if virtual_column_value.nil?
print_line($recursion_level,
"#{object_string}.#{virtual_column_name} = nil") if $print_nil_values
else
print_line($recursion_level,
"#{object_string}.#{virtual_column_name} = " \
"#{virtual_column_value} #{type(virtual_column_value)}")
end
rescue NoMethodError
print_line($recursion_level,
"*** #{this_object_class} virtual column: \'#{virtual_column_name}\' " \
"gives a NoMethodError when accessed (product bug?) ***")
end
end
print_line($recursion_level, "--- end of virtual columns ---")
end
else
print_line($recursion_level, "--- no virtual columns ---")
end
end
rescue => err
$evm.log("error", "#{$method} (print_virtual_columns) - [#{err}]\n#{err.backtrace.join("\n")}")
end
end
|
[
"def dump_virtual_columns(object_string, this_object, this_object_class, indent_string)\n begin\n #\n # Print the virtual columns of this object\n #\n if this_object.respond_to?(:virtual_column_names)\n log(:info, \"#{indent_string}#{@method}: --- virtual columns follow ---\")\n this_object.virtual_column_names.sort.each do |virtual_column_name|\n begin\n virtual_column_value = this_object.send(virtual_column_name)\n if virtual_column_value.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{virtual_column_name} = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{virtual_column_name} = #{virtual_column_value} #{type(virtual_column_value)}\")\n end\n rescue NoMethodError\n log(:info, \"#{indent_string}#{@method}: *** #{this_object_class} virtual column: \\'#{virtual_column_name}\\' gives a NoMethodError when accessed (product bug?) ***\")\n end\n end\n log(:info, \"#{indent_string}#{@method}: --- end of virtual columns ---\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no virtual columns\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_virtual_columns) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end",
"def dump_virtual_columns(object_string, this_object, spaces)\n begin\n #\n # Print the virtual columns of this object \n #\n if this_object.respond_to?(:virtual_column_names)\n $evm.log(\"info\", \"#{spaces}#{@method}: --- virtual columns follow ---\")\n this_object.virtual_column_names.sort.each do |virtual_column_name|\n virtual_column_value = this_object.send(virtual_column_name)\n if virtual_column_value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{virtual_column_name} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{virtual_column_name} = #{virtual_column_value} (type: #{virtual_column_value.class})\")\n end\n end\n $evm.log(\"info\", \"#{spaces}#{@method}: --- end of virtual columns ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_virtual_columns) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend",
"def dump_virtual_columns(my_object, my_object_name)\n if my_object.respond_to?(\"virtual_column_names\")\n self.log(@dump_log_level, \"Begin #{my_object_name}.virtual_columns\")\n my_object.virtual_column_names.sort.each { |vcn| self.log(:info, \"#{my_object_name} Virtual Column - #{vcn}\")}\n self.log(@dump_log_level, \"End #{my_object_name}.virtual_columns\")\n self.log(@dump_log_level, \"\")\n else\n log(@dump_log_level, \"No virtual_columns for #{my_object_name}\")\n end\n end",
"def print_custom_attributes(object_string, this_object)\n begin\n if this_object.respond_to?(:custom_keys)\n custom_attribute_keys = Array.wrap(this_object.custom_keys)\n if custom_attribute_keys.length.zero?\n print_line($recursion_level, \"--- no custom attributes ---\")\n else\n print_line($recursion_level, \"--- custom attributes follow ---\")\n custom_attribute_keys.sort.each do |custom_attribute_key|\n custom_attribute_value = this_object.custom_get(custom_attribute_key)\n print_line($recursion_level, \"#{object_string}.custom_get(\\'#{custom_attribute_key}\\') = \\'#{custom_attribute_value}\\'\")\n end\n print_line($recursion_level, \"--- end of custom attributes ---\")\n end\n else\n print_line($recursion_level, \"--- object does not support custom attributes ---\")\n end \n rescue => err\n $evm.log(\"error\", \"#{$method} (print_custom_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend",
"def dump_attributes(object_string, this_object, indent_string)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n log(:info, \"#{indent_string}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} #{type(value)}\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, indent_string)\n else\n if value.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{key} = #{value} #{type(value)}\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string}.options[:#{k}] = #{v} #{type(v)}\")\n end\n end\n end\n end\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no attributes\")\n end\n rescue => err\n log(:error, \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end",
"def dump_info(my_object, my_object_name)\n self.dump_attributes(my_object, my_object_name)\n self.dump_associations(my_object, my_object_name)\n self.dump_virtual_columns(my_object, my_object_name)\n end",
"def print_attributes(object_string, this_object)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n print_line($recursion_level, \"Debug: this_object.inspected = #{this_object.inspect}\") if $debug\n if this_object.attributes.respond_to?(:keys)\n if this_object.attributes.keys.length > 0\n print_line($recursion_level, \"--- attributes follow ---\")\n this_object.attributes.keys.sort.each do |attribute_name|\n attribute_value = this_object.attributes[attribute_name]\n if attribute_name != \"options\"\n if attribute_value.is_a?(DRb::DRbObject)\n if attribute_value.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n print_line($recursion_level,\n \"#{object_string}[\\'#{attribute_name}\\'] => #{attribute_value} #{type(attribute_value)}\")\n walk_object(\"#{object_string}[\\'#{attribute_name}\\']\", attribute_value)\n else\n print_line($recursion_level,\n \"Debug: not dumping, attribute_value.method_missing(:class) = \" \\\n \"#{attribute_value.method_missing(:class)}\") if $debug\n end\n else\n begin\n attr_info = ping_attr(this_object, attribute_name)\n if attr_info[:value].nil?\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}#{attr_info[:format_string]} = #{attr_info[:value]} #{type(attr_info[:value])}\")\n end\n rescue ArgumentError\n if attribute_value.nil?\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.#{attribute_name} = #{attribute_value} #{type(attribute_value)}\")\n end\n end\n end\n else\n #\n # Option key names can be mixed symbols and strings which confuses .sort\n # Create an option_map hash that maps option_name.to_s => option_name\n #\n option_map = {}\n options = attribute_value.keys\n options.each do |option_name|\n option_map[option_name.to_s] = option_name\n end\n option_map.keys.sort.each do |option|\n if attribute_value[option_map[option]].nil?\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = nil\") if $print_nil_values\n else\n print_line($recursion_level,\n \"#{object_string}.options[#{str_or_sym(option_map[option])}] = \" \\\n \"#{attribute_value[option_map[option]]} #{type(attribute_value[option_map[option]])}\")\n end\n end\n end\n end\n print_line($recursion_level, \"--- end of attributes ---\")\n else \n print_line($recursion_level, \"--- no attributes ---\")\n end\n else\n print_line($recursion_level, \"*** attributes is not a hash ***\")\n end\n else\n print_line($recursion_level, \"--- no attributes ---\")\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend",
"def dump_attributes(object_string, this_object, spaces)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n $evm.log(\"info\", \"#{spaces}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\n this_object.attributes.sort.each do |key, value|\n if key != \"options\"\n if value.is_a?(DRb::DRbObject)\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}[\\'#{key}\\'] => #{value} (type: #{value.class})\")\n dump_object(\"#{object_string}[\\'#{key}\\']\", value, spaces)\n else\n if value.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.#{key} = #{value} (type: #{value.class})\")\n end\n end\n else\n value.sort.each do |k,v|\n if v.nil?\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = nil\") if @print_nil_values\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: #{object_string}.options[:#{k}] = #{v} (type: #{v.class})\")\n end\n end\n end\n end\n else\n $evm.log(\"info\", \"#{spaces}#{@method}: This object has no attributes\")\n end\n rescue => err\n $evm.log(\"error\", \"#{@method} (dump_attributes) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n exit MIQ_ABORT\n end\nend",
"def inspect_object_attributs(object_to_inspect)\n puts \"- Instance attributs :\"\n object_to_inspect.instance_variables.each do |attribute|\n value = object_to_inspect.instance_eval attribute.to_s\n puts \"\\t- Name : #{attribute}\"\n puts \"\\t\\t- Type : #{value.class}\"\n puts \"\\t\\t- Value : #{value.inspect}\"\n end\n puts \"#{Util::get_line_separator}\"\n end",
"def print_methods(object_string, this_object)\n begin\n #\n # Only dump the methods of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n print_line($recursion_level,\n \"Class of remote DRb::DRbObject is: #{this_object.method_missing(:class)}\") if $debug\n #\n # Get the instance methods of the class and convert to string\n #\n if this_object.method_missing(:class).respond_to?(:instance_methods)\n instance_methods = this_object.method_missing(:class).instance_methods.map { |x| x.to_s }\n #\n # Now we need to remove method names that we're not interested in...\n #\n # ...attribute names...\n #\n attributes = []\n if this_object.respond_to?(:attributes)\n if this_object.attributes.respond_to? :each\n this_object.attributes.each do |key, value|\n attributes << key\n end\n end\n end\n attributes << \"attributes\"\n $evm.log(\"info\", \"Removing attributes: #{instance_methods & attributes}\") if $debug\n instance_methods -= attributes\n #\n # ...association names...\n #\n associations = []\n if this_object.respond_to?(:associations)\n associations = Array.wrap(this_object.associations)\n end\n associations << \"associations\"\n $evm.log(\"info\", \"Removing associations: #{instance_methods & associations}\") if $debug\n instance_methods -= associations\n #\n # ...virtual column names...\n #\n virtual_column_names = []\n virtual_column_names = this_object.method_missing(:virtual_column_names)\n virtual_column_names << \"virtual_column_names\"\n $evm.log(\"info\", \"Removing virtual_column_names: #{instance_methods & virtual_column_names}\") if $debug\n instance_methods -= virtual_column_names\n #\n # ... MiqAeServiceModelBase methods ...\n #\n $evm.log(\"info\", \"Removing MiqAeServiceModelBase methods: \" \\\n \"#{instance_methods & $service_mode_base_instance_methods}\") if $debug\n instance_methods -= $service_mode_base_instance_methods\n #\n # Add in the base methods as it's useful to show that they can be used with this object\n #\n instance_methods += ['inspect', 'inspect_all', 'reload', 'model_suffix']\n if this_object.respond_to?(:taggable?)\n if this_object.taggable?\n instance_methods += ['tags', 'tag_assign', 'tag_unassign', 'tagged_with?']\n end\n else\n instance_methods += ['tags', 'tag_assign', 'tag_unassign', 'tagged_with?']\n end\n #\n # and finally dump out the list\n #\n if instance_methods.length.zero?\n print_line($recursion_level, \"--- no methods ---\")\n else\n print_line($recursion_level, \"--- methods follow ---\")\n instance_methods.sort.each do |instance_method|\n print_line($recursion_level, \"#{object_string}.#{instance_method}\")\n end\n print_line($recursion_level, \"--- end of methods ---\")\n end\n else\n print_line($recursion_level, \"--- no methods ---\")\n end\n end\n rescue => err\n $evm.log(\"error\", \"#{$method} (print_methods) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\nend",
"def print_properties\n orientdb.print_class_properties self\n end",
"def print_class_properties\n orientdb.print_class_properties self\n end",
"def dump_methods(object_string, this_object, indent_string)\n begin\n unless object_string == \"$evm.root\"\n log(:info, \"#{indent_string}#{@method}: Class of remote DRb::DRbObject is: #{this_object.method_missing(:class)}\") if @debug\n #\n # Get the instance methods of the class and convert to string\n #\n if this_object.method_missing(:class).respond_to?(:instance_methods)\n instance_methods = this_object.method_missing(:class).instance_methods.map { |x| x.to_s }\n #\n # Now we need to remove method names that we're not interested in...\n #\n # ...attribute names...\n #\n attributes = []\n if this_object.respond_to?(:attributes)\n this_object.attributes.sort.each do |key, value|\n attributes << key\n end\n end\n attributes << \"attributes\"\n log(:info, \"Removing attributes: #{instance_methods & attributes}\") if @debug\n instance_methods = instance_methods - attributes\n #\n # ...association names...\n #\n associations = []\n if this_object.respond_to?(:associations)\n associations = Array(this_object.associations)\n end\n associations << \"associations\"\n log(:info, \"Removing associations: #{instance_methods & associations}\") if @debug\n instance_methods = instance_methods - associations\n #\n # ...virtual column names...\n #\n virtual_column_names = []\n virtual_column_names = this_object.method_missing(:virtual_column_names)\n virtual_column_names << \"virtual_column_names\"\n log(:info, \"Removing virtual_column_names: #{instance_methods & virtual_column_names}\") if @debug\n instance_methods = instance_methods - virtual_column_names\n #\n # ... MiqAeServiceModelBase methods ...\n #\n log(:info, \"Removing MiqAeServiceModelBase methods: #{instance_methods & @service_mode_base_instance_methods}\") if @debug\n instance_methods = instance_methods - @service_mode_base_instance_methods\n #\n # and finally dump out the remainder\n #\n log(:info, \"#{indent_string}#{@method}: --- methods follow ---\")\n instance_methods.sort.each do | instance_method |\n log(:info, \"#{indent_string}#{@method}: #{object_string}.#{instance_method}\")\n end\n log(:info, \"#{indent_string}#{@method}: --- end of methods ---\")\n else\n log(:info, \"#{indent_string}#{@method}: #{object_string} has no instance methods\")\n end\n end\n rescue => err\n log(:error, \"#{@method} (dump_methods) - [#{err}]\\n#{err.backtrace.join(\"\\n\")}\")\n end\n end",
"def show_sobjects klass, val, cols = nil\n\t\t\tif cols.nil? || cols.length.zero?\n\t\t\t\tcols = klass.attributes\n\t\t\telse\n\t\t\t\ttmp = []\n\t\t\t\tcols.each do |c|\n\t\t\t\t\tflg = klass.attributes.find_index{|a| a.downcase == c.downcase}\n\t\t\t\t\t$stderr.puts \"Unknown column: #{c}\" if flg.nil?\n\t\t\t\t\ttmp << klass.attributes[flg] unless flg.nil?\n\t\t\t\tend\n\t\t\t\tcols = tmp\n\t\t\t\tcols << 'Id' if cols.length.zero?\n\t\t\tend\n\t\t\tshow_table val, cols\n\t\tend",
"def dump_attributes(my_object, my_object_name)\n if my_object.respond_to?(\"attributes\")\n self.log(@dump_log_level, \"Begin #{my_object_name}.attributes\")\n my_object.attributes.sort.each { |k, v| self.log(:info, \"#{my_object_name} Attribute - #{k}: #{v}\")}\n self.log(@dump_log_level, \"End #{my_object_name}.attributes\")\n self.log(@dump_log_level, \"\")\n else\n self.log(@dump_log_level, \"No attributes for #{my_object_name}\")\n end\n end",
"def print_description_list(columns, obj, opts={})\n # raise \"oh no.. replace with as_description_list()\"\n print as_description_list(obj, columns, opts)\n end",
"def supports_virtual_columns?; end",
"def column_full_names\n attributes.keys.collect{ |key| \"#{@column_family_name}:#{key}\"}\n end",
"def awesome_active_record_class(object)\n if object.respond_to?(:columns)\n data = object.columns.inject(ActiveSupport::OrderedHash.new) do |hash, c|\n hash[c.name.to_sym] = c.type\n hash\n end\n \"class #{object} < #{object.superclass} \" << awesome_hash(data)\n else\n object.inspect\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
End of print_virtual_columns Method: is_plural? Purpose: Test whether a string is plural (as opposed to singular) Arguments: astring: text string to be tested Returns: Boolean
|
def is_plural?(astring)
astring.singularize != astring
end
|
[
"def is_plural?(astring)\n astring.singularize != astring\n end",
"def pluralize?(str)\n str.pluralize == str\n end",
"def is_plural?(value)\n\t(value > 1) || (value < 1)\nend",
"def plural?\n !singular?\n end",
"def plural?\n self.class.pluralized || false\n end",
"def plural?\n self.plural_head\n end",
"def plural?(word)\n word[-1] == 'S' && word[-2] != 'S'\n end",
"def plural?(word)\n word = require_string!(word)\n\n word == pluralize(word)\n end",
"def is_are_pluralize( count, singular, plural = nil )\n ( count == 1 ? \"is\" : \"are\" ) + \" \" + pluralize( count, singular, plural )\n end",
"def plural?\n !@msgid_plural.nil?\n end",
"def plural?(noun)\n @plural_to_singulars.has_key?(noun)\n end",
"def test_plural_ruby\n\t\tp = Print.new\n\t\tassert_equal('rubies',p.singular_or_plural(0,'rubies'))\n\tend",
"def test_plural_ruby\n @test_p.plural?(1, 3)\n assert_equal @test_p.ruby_string, 'ruby'\n end",
"def has_all_plural_forms?\n !self.zero.blank? && !self.one.blank? && !self.many.blank?\n end",
"def msgid_plural\n begin\n if @scanner.scan(/msgid_plural/)\n skip_whitespace\n text = message_line\n add_result(:msgid_plural, text)\n message_multiline(:msgid_plural) if @scanner.peek(1) == '\"'\n true\n else\n false\n end\n rescue PoSyntaxError => pe\n raise PoSyntaxError, \"Syntax error in msgid\\n\" + pe.message, pe.backtrace\n end\n end",
"def plural?(num)\n return 'ruby' if num == 1\n return 'rubies' if num > 1\n end",
"def plural?(method)\n str = method.to_s\n plr = str.to_sym\n sgl = str.sub(/e?s$/, '').to_sym\n\n /s$/ === str && Watirsome.watir_methods.include?(plr) && Watirsome.watir_methods.include?(sgl)\n end",
"def _pluralize(number, singular, plural: nil)\n number == 1 ? singular : (plural || \"#{singular}s\")\n end",
"def plural_noun?\n !!(content =~ /^NNP?S/)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.