anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
Returns this organization's pricing setup that is effective on a given date.
def effective_pricing_setup_for_date(date=Date.today) if self.pricing_setups.blank? raise ArgumentError, "Organization has no pricing setups" if self.parent.nil? return self.parent.effective_pricing_setup_for_date(date) end current_setups = self.pricing_setups.select { |x| x.effective_date.to_d...
DELETE /step_types/1 DELETE /step_types/1.json
def destroy @step_type = StepType.find(params[:id]) @step_type.destroy respond_to do |format| format.html { redirect_to step_types_url } format.json { head :no_content } end end
Execute a read operation with retrying. This method performs server selection for the specified server selector and yields to the provided block, which should execute the initial query operation and return its result. The block will be passed the server selected for the operation. If the block raises an exception, and ...
def read_with_retry(session = nil, server_selector = nil, &block) if session.nil? && server_selector.nil? # Older versions of Mongoid call read_with_retry without arguments. # This is already not correct in a MongoDB 3.6+ environment with # sessions. For compatibility we emulate the legacy...
Returns either true or false depending on whether or not the user agent of the device making the request is matched to a device in our regex.
def is_mobile_device? !!mobile_device end
Given a Pivotal Tracker `state`, give back a task prioritization.
def map_state(state) @state_mapping.each do |key, value| return key if value.include? state end :today end
| F M T + F | F F F M | F M M T | F M T
def test_and assert_false F & F, 'F & F' assert_false F & M, 'F & M' assert_false F & T, 'F & T' assert_false M & F, 'M & F' assert_maybe M & M, 'M & M' assert_maybe M & T, 'M & T' assert_false T & F, 'T & F' assert_maybe T & M, 'T & M' assert_true T & T, 'T & T' end
Change the name of the room
def name=(name) connection.post("/room/#{@id}.json", :body => { :room => { :name => name } }) end
Gross amount including tax
def gross_total self.gross_amount = self.net_total + self.tax_total end
def upload redirect_to :controller=>:photos, :action=>:add end
def signout #create a signout action at admin_helper logout redirect_to :controller=>:home, :action=>:index end
index is in Bookshow
def cors_allow_all headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS' headers['Access-Control-Request-Method'] = '*' headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization' end
Yields the correct path to the file, either the local filename or the S3 URL.
def file_path public_filename =~ ScribdFu::S3 ? public_filename : "#{RAILS_ROOT}/public#{public_filename}" end
Is this group writable by the general public?
def public_write @public_write ||= public_write_was end
Get the value associated to the given key, if any
def [](key) data.fetch(key) do _values.find {|data| !data[key].nil? } end end
Prepares and returns a request suitable for dispatching with dispatch_request. If you don't need to modify the request object before dispatching (e.g. to add cookies), you probably want to use dispatch_to instead. ==== Parameters params:: An optional hash that will end up as params in the controller instance. env:: An ...
def build_request(params = {}, env = {}) params = Merb::Parse.params_to_query_string(params) query_string = env[:query_string] || env['QUERY_STRING'] env[:query_string] = query_string ? "#{query_string}&#{params}" : params post_body = env[:post_body] || env['POST_BO...
Create an integration for the specified app.
def create_integration(app_id, integration_create_body, opts = {}) data, _status_code, _headers = create_integration_with_http_info(app_id, integration_create_body, opts) return data end
Rectify the zone data. This does not take into account the APIRECTIFY metadata. Fails on slave zones and zones that do not have DNSSEC.
def rectify_zone_with_http_info(server_id, zone_id, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: ZonesApi.rectify_zone ...' end # verify the required parameter 'server_id' is set if @api_client.config.client_side_validation && server_id.nil? ...
Gets the caller property value. Endpoint that initiated this segment.
def caller return @caller end
Return false to prevent the userstamp gem from changing the updater during duplication
def record_userstamp !duplicating? end
Dump a commaseparated list of the words making up the bit set. Split each 64 bit number into two more manageable 32 bit numbers. This generates a commaseparated list of C++like unsigned long constants.
def to_string_of_half_words s = StringBuffer.new i = 0 while i < @bits.attr_length if (!(i).equal?(0)) s.append(", ") end tmp = @bits[i] tmp &= 0xffffffff s.append(tmp) s.append("UL") s.append(", ") tmp = @bits[i] >> 32 ...
inserts based of another table. useful when copying rows between tables. DO NOT USE...
def insert_select(params = {}) db_str = GenInsert.insert_select(params) #@log.debug db_str @client.run db_str return true end
The callback that gets called when the Reader is done reading. Tells all of the associated writers to finish up.
def stopper return @stopper if @stopper @stopper = EM.Callback do log "Got called back after finished reading. Starting shutdown..." # remove this next_tick? EM.next_tick do start_loop = EM.tick_loop do if @writers.empty? || @writers.none?(&:run...
Post method which accepts form parameters from postcode lookup and redirects to constituency_path.
def postcode_lookup flash[:postcode] = params[:postcode] redirect_to constituency_path(params[:constituency_id]) end
Adds a record field to the nested schema of a record field. A block must be passed describing the nested fields of the record. For more information about nested and repeated records, see [Preparing Data for BigQuery]( This can only be called on fields that are of type `RECORD`.
def record name, description: nil, mode: nil record_check! # TODO: do we need to raise if no block was given? raise ArgumentError, "a block is required" unless block_given? nested_field = add_field name, :record, description: description, mode: mode yield ne...
this method is called by dfhack every 'onstatechange'
def onstatechange(newstate) @onstatechange_list ||= [] @onstatechange_list.each { |cb| cb.call(newstate) } end
POST /restaurants//tables POST /restaurants/1/tables.json
def create @table = @restaurant.tables.build(table_params) respond_to do |format| if @table.save format.html { redirect_to restaurant_tables_path(@restaurant), notice: 'Table was successfully created.' } format.json { render :show, status: :created, location: @table } else f...
Decrease the position of this item without adjusting the rest of the list.
def decrement_position return unless in_list? update_attribute :position, self.send(:position).to_i - 1 end
Set/Get the api method
def method(method = nil) return @method if method.nil? @method = method.to_s.capitalize end
Never trust parameters from the scary internet, only allow the white list through.
def image_params params.require(:image).permit(:image_url, :galery_id) end
Internal: (Re)Create a CSS file and write code there. dir The String directory path to write CSS file to. Returns the css file just written.
def write(dir) @dir = FileUtils.mkdir_p dir @css_file = File.join(@dir, @filename + '.css') File.delete(@css_file) if File.exist?(@css_file) @output = File.open(@css_file, 'w') { |file| file.write(@result) } @css_file end
Description: this action displays the information of the vendor Params: id of the vendor Success: a page appears to the user having the samples,packages, contact info, comments and rating Failure: none
def show @vendor = Vendor.find(params[:id]) @comments = @vendor.comments.paginate(:page => params[:page], :per_page => 10) end
The name of the message
def name message_descriptor_proto.name end
Private: Saves launched_job instance and Sets the initial status. Returns the launched_job instance.
def set_initial_status if LaunchedJob.where(job_spec: self.job_spec, status: LaunchedJob::RUNNING).size > 0 self.update(status: ERROR, start_time: Time.now) raise "JobSpec already running" else self.update(status: RUNNING, start_time: Time.now) end end
Constructor Allows us to build out the class properly
def initialize current_user @vrn = current_user.vrn @access = current_user.access_token @query = { "from": "2020-01-01", "to": "2021-01-01" } @headers = { # Authenication # Required to communicate with oAuth 'Accept': 'application/vnd.hmrc.1.0+json', 'Authorization': 'Bea...
Sort the processor inputs by their class type.
def _SortInputs @inputs.each() do |input| if(input.is_a?(Rokuby::ProjectInstance)) @projectInstance = input elsif(input.is_a?(Rokuby::ProjectDescription)) @projectDescription = input elsif(input.is_a?(Rokuby::ProjectConfiguration)) @projectConfigurations.push(...
GET /communities/1 GET /communities/1.json
def show end
Never trust parameters from the scary internet, only allow the white list through.
def snif_params params.require(:snif).permit(:name, :phone_number, :address, :city, :state, :zipcode, :mcr_rating, :beds_capacity, :medicare, :medicaid, :percentage_occupied, :beds_unavailable, :in_hospital, :population, :corporation) end
Gets Users with this Role
def users res = [] url = data['links']['roleUsers'] tmp = GoodData.get url tmp['associatedUsers']['users'].each do |user_url| user = GoodData.get user_url res << GoodData::Profile.new(user) end res end
Returns the day AFTER the last assignment ends. If there is no last assignment, returns the upcoming Friday.
def next_rotation_start_date last = order(:end_date).last if last.present? last.end_date + 1.day else 1.week.since.beginning_of_week(:friday).to_date end end
Steps I need an empty variable to hold the final reversed string I need a variable to hold my iterations I need to concatinate to the front of the final string I need to check if the original string and the new string are equal My Attempt
def is_palindrome(word) reversed = "" i = 0 while i < word.length char = word[i] reversed = char + reversed i += 1 end if word == reversed return true else return false end end
Expire memoized instance variables that can incorrectly generate, replace or miss files due changes in certain attributes used to compute them.
def invalidate_memoized_attributes @full_name = nil @cache_file = nil end
renvoie un tableau de cases contenant les erreurs qu'il y a dans la grille (lorsque la case est VIDE, ce n'est pas une erreur)
def casesIncorrect newStatutVide = StatutVide.new(VIDE) newStatutArbre = StatutArbre.new(ARBRE) tabCasesErr = Array.new grille=@grille.grille for i in 0..grille.length-1 for j in 0..grille.length-1 tabCasesErr.unshift(grille[i][j]) if (grille[i][j].statutVisible != grille[i][j].statu...
game_hash[:home][:players].collect do |ke,va| if ke == player return va[:shoe] end end game_hash[:away][:players].collect do |k,v| if k == player return v[:shoe] end end end
def team_colors(team) game_hash.each do |side, value| if value[:team_name] == team return value[:colors] end end end
HtmlAttribute = (AlphanumericAscii | "")+ Spnl ("=" Spnl (Quoted | (!">" Nonspacechar)+))? Spnl
def _HtmlAttribute _save = self.pos while true # sequence _save1 = self.pos _save2 = self.pos while true # choice _tmp = apply(:_AlphanumericAscii) break if _tmp self.pos = _save2 _tmp = match_string("-") break if _tmp self.pos = _save2 ...
Returns the status or pattern of percolator for this instance.
def percolator @_percolator || instance.class.tire.percolator || nil end
lexer rule t__10! (T__10) (in Ingredients.g)
def t__10! # -> uncomment the next line to manually enable rule tracing # trace_in( __method__, 3 ) type = T__10 channel = ANTLR3::DEFAULT_CHANNEL # - - - - main rule block - - - - # at line 19:9: 'E' match( 0x45 ) @state.type = type @state.channel ...
I'm aware that a lot of these could be oneline'd. I'll probably do that once I'm done.
def button_down(id) # Exit on escape if id == Gosu::KbEscape close end # Cursor Movement # NSEW = 0123 if id == Gosu::KbUp @player.move(0) end if id == Gosu::KbDown @player.move(1) end if id == Gosu::KbRight @player.move(2) end if id == Gosu::KbLeft @player.move(3) end ...
DRIVER TESTS GO BELOW THIS LINE
def assert yield end
Convert document +item+ to a single string array
def item_to_a(item) ary = [] ary << item.name ary << item.quantity ary << item.unit ary << item.price ary << item.tax ary << item.tax2 ary << item.tax3 ary << item.amount ary.compact end
Determine the list(with properties) of the running instances in the given autoscaling group if asg_name is nil it returns nil
def running_hosts_in_asg(asg_name) return nil unless asg_name asg = @auto_scaling.groups[asg_name] return nil unless asg # return a lost of maps having the list of running instances asg.auto_scaling_instances.collect { |i| if i.health_status != 'Healthly' ec...
Update properties of this object
def update!(**args) @history_id = args[:history_id] unless args[:history_id].nil? @id = args[:id] unless args[:id].nil? @internal_date = args[:internal_date] unless args[:internal_date].nil? @label_ids = args[:label_ids] unless args[:label_ids].nil? @payload = args[:pay...
2.8 gcd of three ints, calling 2.3
def gcd3 (v,u,w) if (u==v) return gcd(v,w) elsif (u>v) u-=v gcd(gcd(v,u),w) else gcd(gcd(u,v),w) end end
Tests that course's total_fee is not nil and is greater than or equal to 0 and returns true or false.
def total_fee_is_valid? return ((self.total_fee != nil) and (self.total_fee >= 0)) end
Enqueues a notification to be sent in the background via the persistent TCP socket, assuming apn_sender is running (or will be soon)
def notify_async(token, opts = {}) token = token.to_s.gsub(/\W/, '') if defined?(Resque) Resque.enqueue(APN::NotificationJob, token, opts) else Thread.new do APN.notify_sync(token, opts) end end end
PUT /post117s/1 PUT /post117s/1.xml
def update @post117 = Post117.find(params[:id]) respond_to do |format| if @post117.update_attributes(params[:post117]) format.html { redirect_to(@post117, :notice => 'Post117 was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" }...
Normalize the folder name
def normalize_filename self.name = Pathname.normalize_filename(name) end
You can add fixtures and/or initialization code here to make experimenting with your gem easier. You can also use a different console, if you like.
def client @client ||= Gamewisp::Client.new end
returns lowest sum of the winning and losing teams' scores
def lowest_total_score total_game_scores = games.map { |game| game.home_goals + game.away_goals} total_game_scores.min end
Method signatures: nsgettext('Fruits|apple', 'apples', 2) nsgettext(['Fruits|apple', 'apples'], 2) source://i18n//lib/i18n/gettext/helpers.rb46
def nsgettext(msgid, msgid_plural, n = T.unsafe(nil), separator = T.unsafe(nil)); end
PUT /categories/1 PUT /categories/1.xml
def update @category = Category.find(params[:id]) respond_to do |format| if @category.update_attributes(params[:category]) flash[:notice] = 'Kategoria została zapisana poprawnie.' format.html { redirect_to([:admin, @category]) } format.xml { head :ok } else format.ht...
An HTTP GET request that operates through the router. ==== Parameters path:: The path that should go to the router as the request uri. params:: An optional hash that will end up as params in the controller instance. env:: An optional hash that is passed to the fake request. Any request options should go here (see +fake...
def get(path, params = {}, env = {}, &block) env[:request_method] = "GET" mock_request(path, params, env, &block) end
POST /aggregate_metadata POST /aggregate_metadata.json
def create @aggregate_metadatum = AggregateMetadatum.new(params[:aggregate_metadatum]) respond_to do |format| if @aggregate_metadatum.save format.html { redirect_to @aggregate_metadatum, notice: 'Aggregate metadatum was successfully created.' } format.json { render json: @aggregate_metada...
Returns the filename of the HES Cloud file
def filename(options = {}) if file_url = url(options) file_url.gsub(/.*\/(.*?$)/, '\1') end end
determine the investment horizon (length of time) required to create a future value given a present value and interest rate present_value the value at the start of the period future_value the value at the end of the period rate the annual rate of return
def investment_horizon(rate,present_value,future_value) pv = present_value.to_d fv = future_value.to_d periods = Math.log(fv/pv) / Math.log(1+rate) end
Fetches the next token from the scanner
def get_tk tk = nil if @tokens.empty? then if @scanner_point >= @scanner.size return nil else tk = @scanner[@scanner_point] @scanner_point += 1 @read.push tk[:text] end else @read.push @unget_read.shift tk = @tokens.shift end if tk == n...
questID should be the symbolic name of the quest, e.g. :Quest1
def activateQuest(quest,color,story) if !quest.is_a?(Symbol) raise _INTL("The 'quest' argument should be a symbol, e.g. ':Quest1'.") end for i in 0...@active_quests.length if @active_quests[i].id == quest pbMessage("You have already started this quest.") return end end ...
The controller must return true to inform about the real deletion
def delete(sObjectType) hParams = _get_object_params(sObjectType, :delete_e, :delete, true) bState = @oProvider.delete(sObjectType, hParams) @ObjectData.delete(sObjectType) if bState bState end
Write a method that takes in 2 numbers and prints their sum, then call that method.
def sum (a, b) puts a + b end
GET /party_lists GET /party_lists.json
def index @party_lists = PartyList.all.order(:id) end
Back propagate the error
def propagate(rate = 0.1, target = nil) error = 0.0 # Is neuron in output layer if !target.nil? # Eq. 10. @error.responsibility = @error.projected = target - @activation else # The rest of the neuron compute their error responsibilities by back- # propagation ...
OPTIONAL Check if this record should be included in the batch save We need to somehow still update the model even if the record should not be saved to xero. This is causing some items to not not archive or void since they the remote server is already voided
def should_save_record?(record, model) true end
Never trust parameters from the scary internet, only allow the white list through.
def friend_params params.permit(:friend_id) end
Return templates directory path.
def templates_dir return File.join(File.dirname(__FILE__), 'server/templates') end
Displays documentation for +req+ on +res+, whether that be HTML or some asset.
def show_documentation req, res store, path = documentation_source req.path if_modified_since req, res, store.cache_path generator = generator_for store case path when nil, '', 'index.html' then res.body = generator.generate_index when 'table_of_contents.html' then res.body = gene...
GET /review_images/new GET /review_images/new.json
def new @review_image = ReviewImage.new respond_to do |format| format.html # new.html.erb format.json { render json: @review_image } end end
returns an infinite byte stream to xor against arguments are arrays
def AES256_ctr key, iv cipher = OpenSSL::Cipher::AES.new(256, :ECB) cipher.encrypt cipher.padding = 0 cipher.key = key[..31].map(&:chr).join counter = iv[..15] f = Fiber.new do loop do enc = cipher.update(counter.map(&:chr).join) enc.bytes.each {|b| Fiber.yield b} ...
Serializes information the current object
def serialize(writer) raise StandardError, 'writer cannot be null' if writer.nil? writer.write_date_time_value("createdDateTime", @created_date_time) writer.write_string_value("@odata.type", @odata_type) writer.write_string_value("reactionType", @reaction_...
SHA1 hash in salted form
def sha1_hex Digest::SHA1.hexdigest(salted_name) end
GET /photos GET /photos.json
def index @photos = Photo.where(ip: request.remote_ip).all end
TODO_PROHEALTH move to an abstract level so it can be used anywhere
def file_field(form_datum, k, file_type) file = form_datum.attachments.detect{ |a| a.section_field_id.to_s == k.to_s} file_text = file_type == 'expirable_file' ? (file.try(:expiration_date) || '') : '' unless file && file.file.url.include?('placeholder.jpg') file ? (link_to file_text, file.fil...
Returns true when the SDK is configured not to initiate HTTP requests, otherwise false.
def offline? return @_config_service ? @_config_service.offline? : true end
helper method to fill the train full of passengers
def fill_train(train) 120.times { train.board(active_passenger, station) } end
This is needed for jdbc/sqlite, which returns timestamp columns as strings
def convert_timestamp(timestamp) timestamp = db.to_application_timestamp(timestamp) if timestamp.is_a?(String) timestamp end
if the request is from the root url (eg: console.megam.io) then no message is shown if the request is form a non root url like users/1/edit, then we show message.
def require_signin if signed_in? else if request.fullpath.to_s == '/' || request.original_url.to_s == '/' redirect_to signin_path else if request.fullpath.to_s.match('auth') auth = request.env['omniauth.auth']['extra']['raw_info'] session[:auth] = { email: a...
START Feed Action Tests
def test_get_feed get :feed assert_response :success end
Actually creates after form is filled out
def create @list = current_user.lists.find params[:list_id] @item = @list.items.build(item_params) respond_to do |format| if @item.save format.html { redirect_to list_items_path(@list), notice: 'Item was successfully created.' } #format.json { render :show, status: :created, location:...
A gate which can be used to limit dangerous code to only run during provisioning or upon boot
def disruptable? @disruptable ||= node.firstboot_any_phase? || ENV['CHEF_BOOT_SERVICE'] == 'true' end
3112 Administrators cannot see other users
def index @page_title = "CBCL - Liste af Brugere" @sort = params[:sort] || 'users.created_at' @order = params[:order] || "asc" @users = current_user.get_users(:page => params[:page], :per_page => Journal.per_page, :sort => params[:sort], :order => params[:order]) if !params[:partial] render ...
Create new wiki page
def new @doc_pu_wiki = DocPuWikiPage.new() @doc_pu_wiki.use_doc_flags = true if request.post? # Save object reorder_pages(@doc_pu.doc_pu_wiki_pages.all) @doc_pu_wiki = @doc_pu.doc_pu_wiki_pages.create(parse_form params[:doc_pu_wiki]) @doc_pu_wiki.w...
GET /ingest_responses/1 GET /ingest_responses/1.json
def show end
Configuration pointing to the SPEC tests and PIN tool to be used.
def load_configuration # Default configuration. config = File.open('pin_spec.yml', 'r') { |f| YAML.load f } if ARGV[0] # If the first argument is a Yaml configuration file, use that to override # the default configuration. if ARGV[0][-4, 4] == '.yml' config.merge! File.open(ARGV[0], 'r') { |f...
Call function f with a fresh variable.
def call_fresh(f) -> (s_c) { c = cdr(s_c) f.call(var(c)).call(cons(car(s_c), c + 1)) } end
Return a Gem::Specification from this gem
def to_spec raise NotImplementedError end
Eager load the inclusions for the provided documents.
def eager_load(docs) criteria.inclusions.reject! do |metadata| metadata.eager_load(eager_loaded_ids(docs, metadata)) if !docs.empty? end self.eager_loaded = true end
Expand a Relation Tuple Use this endpoint to expand a relation tuple.
def get_expand_with_http_info(namespace, object, relation, max_depth, opts = {}) if @api_client.config.debugging @api_client.config.logger.debug 'Calling API: ReadApi.get_expand ...' end # verify the required parameter 'namespace' is set if @api_client.config.client_side_validation && na...
Converts the RDoc markup tidylink into a Markdown.style link.
def handle_regexp_TIDYLINK target text = target.text return text unless text =~ /\{(.*?)\}\[(.*?)\]/ or text =~ /(\S+)\[(.*?)\]/ label = $1 url = $2 if url =~ /^rdoc-label:foot/ then handle_rdoc_link url else gen_url url, label end end
Height in pixels when in expanded state
def expanded_height source_node[:expandedHeight].to_i end
A unique id for resources for this node
def resource_id(prefix) if default_config? [prefix, project, node_type, node_name] else [prefix, project, configuration, node_type, node_name] end.compact.join("_").tr("-", '_').tr("/", "_") end
GET /keeps/1 GET /keeps/1.json
def show end
Returns an array of all the instances for this class.
def all Maglev::PERSISTENT_ROOT[self].values end
GET /tasks/1 GET /tasks/1.json
def show end