anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
PATCH/PUT /married_statuses/1 PATCH/PUT /married_statuses/1.json | def update
respond_to do |format|
if @married_status.update(married_status_params)
format.html { redirect_to @married_status, notice: 'Married status was successfully updated.' }
format.json { render :show, status: :ok, location: @married_status }
else
format.html { render :edit ... |
Request to dump logs to file | def dump_log(request = nil, java = false)
type_params = java ? '?type=java' : ''
url = "#{DUMP_LOG_ENDPOINT}#{type_params}"
request = request ? Request.new(symbolize_keys(request)) : {}
logger.debug('Sending dump log request to mockserver')
logger.debug("URL: #{url}. Payload: ... |
GET /quandaries GET /quandaries.json | def index
@quandaries = Quandary.all
end |
This function verifying is Freelancer description displayed | def is_freelancer_description_displayed
@driver.find_element(:xpath, FREELANCER_DESCRIPTION).displayed?
end |
prime numbers only divisible by themselves and 1 modulo will be != 0 for everything but themselves and 1 | def prime?(num)
fail_count = 0
if num < 0
num = num * (-1)
end
factors = []
range = (1..num)
range.each do |range_number|
remain = num % range_number
if remain == 0
factors.push(num)
else fail_count += 1
end
end
puts fail_count
if f... |
Yields items matching +name+ including the store they were found in, the class being searched for, the class they were found in (an ancestor) the types of methods to look up (from method_type), and the method name being searched for | def find_methods name
klass, selector, method = parse_name name
types = method_type selector
klasses = nil
ambiguous = klass.empty?
if ambiguous then
klasses = classes.keys
else
klasses = ancestors_of klass
klasses.unshift klass
end
methods = []
klasses.each do... |
GET /layers GET /layers.json | def index
@layers = Layer.all
end |
Returns +true+ if +self+ subtypes +other+. A UnionType subtypes another type if all the values in the union are subtypes of +other+. This has the effect of deferring dealing with unions on the rhs of a relation into the Type class. There may be better ways of doing this. | def <=(other)
@types.all? do |t|
t <= other
end
end |
Get issues from github repo and return the issues with a specific label This is separated from the cleaned issues as it may be used to provide a useful user facing display of issues | def get_issues( url, label )
issues = @git.client.issues( url, :per_page => 100 )
cleaned_issues = parse_issue_array( issues, label )
puts cleaned_issues.inspect
return cleaned_issues
end |
Expire all the cache entries | def expire_all
@memcache.flush_all
stop_tracking_keys
Merb.logger.info("cache: expired all")
true
end |
promote an artifact to a different environment | def promote_artifact
source_key = "#{ @environment_name }/#{ @artifact }/#{ @source_version }.gpg"
target_key = "#{ @target_environment_name }/#{ @artifact }/#{ @version }.gpg"
subsection "Promote artifact from s3://#{ @bucket.name }/#{ source_key } to s3://#{ @bucket.name }/#{ target_key }", c... |
PATCH/PUT /graphium/cities/1 PATCH/PUT /graphium/cities/1.json | def update
respond_to do |format|
if @graphium_city.update(graphium_city_params)
format.html { redirect_to @graphium_city, notice: 'City was successfully updated.' }
format.json { render :show, status: :ok, location: @graphium_city }
else
format.html { render :edit }
form... |
Register plugin with name in internal array | def register(name, plugin = false)
return unless plugin && !loaded?(name)
@plugins << plugin
end |
GET /permits/1 GET /permits/1.json | def show
end |
DELETE /roles/1 DELETE /roles/1.json | def destroy
@role = Role.find(params[:id])
if @role.destroy
msg= "Role deleted successfully!"
else
msg= "Role delete failed!"
end
redirect_to roles_path, :flash => { :notice => msg }
end |
Only allow a trusted parameter "white list" through. | def subtask_params
params.require(:subtask).permit(:description, :cost_time, :task_id)
end |
Creates a new tape drive. API Key Scope: tape_drives / create | def create_tape_drive_by_tape_library(tape_library_id, tape_drive_body, opts = {})
data, _status_code, _headers = create_tape_drive_by_tape_library_with_http_info(tape_library_id, tape_drive_body, opts)
data
end |
DELETE /archivos/1 DELETE /archivos/1.json | def destroy
@archivo.destroy
respond_to do |format|
format.html { redirect_to archivos_url }
format.json { head :no_content }
end
end |
Adjust the indentation depth. Returns the indent depth BEFORE it was adjusted. | def adj_indent(adjust = 1)
old, self.indent_depth = indent_depth, (indent_depth+adjust)
self.indent_str =
(indenting == true) ? (TAB * indent_depth) : EMPTY
old
end |
Only allow a trusted parameter "white list" through. | def tag_params
params[:tag]
end |
The ASCII string value is the sum of the ASCII values of every character in the string. (You may use Stringord to determine the ASCII value of a character.) | def ascii_value(string)
sum = 0
string.each_char { |char| sum += char.ord}
sum
end |
Executes queries using the replica database. Fails over to primary if no replica is found. if you want to execute a block of code on the replica you can go: Account.on_replica do Account.first end the first account will be found on the replica DB For oneliners you can simply do Account.on_replica.first | def on_replica(&block)
on_primary_or_replica(:replica, &block)
end |
Serializes information the current object | def serialize(writer)
raise StandardError, 'writer cannot be null' if writer.nil?
super
writer.write_string_value("connectorServerName", @connector_server_name)
writer.write_string_value("exchangeAlias", @exchange_alias)
writer.write_enum_v... |
PATCH/PUT /run_types/1 PATCH/PUT /run_types/1.json | def update
respond_to do |format|
if @run_type.update(run_type_params)
format.html { redirect_to @run_type, notice: 'Run type was successfully updated.' }
format.json { render :show, status: :ok, location: @run_type }
else
format.html { render :edit }
format.json { render... |
ID of the post to moderate. | def postId(value)
merge(mppostId: value.to_s)
end |
display all current user computers | def list
user = User.find(current_user.id)
@computers = user.computer.all
end |
DELETE /testreplyposts/1 DELETE /testreplyposts/1.json | def destroy
@testreplypost.destroy
respond_to do |format|
format.html { redirect_to testreplyposts_url, notice: 'Testreplypost was successfully destroyed.' }
format.json { head :no_content }
end
end |
Asynchronously upgrade an environment | def async_upgrade(environment, plugin, options = {})
job = Job.new(:upgrade)
async(:upgrade, job, environment, plugin, options)
job.ticket
end |
For instance, the length of "it's" is 3, not 4. | def cleanup(str)
str.gsub(/[^a-z]/i, '')
end |
Update spec dependencies from new source | def update_deps_from(new_source)
@metadata[:requires] =
non_gem_requirements +
extra_gem_requirements(new_source) +
new_source.deps.select { |r| !excludes_dep?(r.name) }
.collect { |r| RPM::Requirement.from_gem_dep(r) }.flatten
@metadata[:bu... |
Called to remove the +fd+ from the poller and delete any callbacks | def deregister(fd:)
delete_from_selector(fd: fd)
delete_callbacks(fd: fd)
end |
GET /presses/new GET /presses/new.json | def new
@press = Press.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @press }
end
end |
Define if there is a win on the board | def won?(board)
WIN_COMBINATIONS.detect do |win|
if (board[win[0]]) == "X" && (board[win[1]]) == "X" && (board[win[2]]) == "X"
return win
elsif (board[win[0]]) == "O" && (board[win[1]]) == "O" && (board[win[2]]) == "O"
return win
end
end
end |
GET /consultants GET /consultants.json | def index
@query_params = {}
build_query_params(params)
build_query_consultant_params
@conditions = []
@conditions << Consultant.arel_table[:name].matches("%#{@query_params[:name]}%") if @query_params[:name]
if @conditions.length > 0
conditions = @conditions[0]
@conditi... |
DELETE /employeer_photos/1 DELETE /employeer_photos/1.xml | def destroy
@employeer_photo = EmployeerPhoto.find(params[:id])
@employeer_photo.destroy
respond_to do |format|
format.html { redirect_to(employeer_photos_url) }
format.xml { head :ok }
end
end |
When a user signs out of Windows Live or a Windows Live application, a besteffort attempt is made at signing out the user from all other Windows Live applications the user might be logged in to. This is done by calling the handler page for each application with 'action' set to 'clearcookie' in the query string. The app... | def getClearCookieResponse()
type = "image/gif"
content = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAEALAAAAAABAAEAAAIBTAA7"
content = Base64.decode64(content)
return type, content
end |
Make department requirement junction when new requirement is made. Also serves as a Model.within(dept), minus foreign key injection | def core(d)
dept = Department.search!(d)
raise "[Requirement.core] Error: core already declared for department #{dept.name}" unless dept.core_requirements.empty?
requirement = make "#{dept.abbreviation}"
# make junctions
mk = self.method(:make)
se... |
Get an array of all fields thate have the given label | def all_fields_labeled(label_name)
@fields.values.reject do |field|
!field.has_label?(label_name.to_sym)
end
end |
Based on the density and population for a state, we're determining the number of deaths then printing out the prediction | def predicted_deaths
# predicted deaths is solely based on population density
# Use case/when for determining number of deaths
case @population_density
when @population_density >= 200; number_of_deaths = (@population * 0.4).floor
when @population_density >= 150; number_of_deaths = (@population * 0.3... |
Never trust parameters from the scary internet, only allow the white list through. | def reservation_params
params.require(:reservation).permit(:user_id, :job_id, :status,:review,:rating,:amount,:ending_time,:slug,:revision_description,:rejection_description,:pause_reason,:paused_at,:reviewed_at)
end |
ITEM GETTER & SETTER | def get_item_value(key)
@attributes[key] = get_item_record(key) unless @attributes.has_key?(key)
@attributes[key]
end |
Never trust parameters from the scary internet, only allow the white list through. | def defense_params
params.require(:defense).permit(:description)
end |
GET /posts/1 GET /posts/1.json | def show
@calendar = Calendar.find(params[:calendar_id])
@event = @calendar.events.find(params[:event_id])
#@post = Post.find[params[:id]]
end |
Never trust parameters from the scary internet, only allow the white list through. | def badge_params
params[:user].permit(:name, :badge, :admin_id)
end |
POST /organizations/1/sites POST /organizations/1/sites.json | def create
@site = @organization.sites.new(site_params)
respond_to do |format|
if @site.save
format.html { redirect_to after_create_path, notice: 'Site was successfully created.' }
format.json { render :show, status: :created, location: @site }
else
format.html... |
returns an array of possible moves from position parameter (an array with 2 elements) (e.g. [0,0] means piece is at position 0,0) | def possible_moves(position, board, color)
out_array = []
x = position[0]-1
y = position[1]-1
(x..x+2).each do |row|
break if row > 7
(y..y+2).each do |column|
break if column > 7
if !board[row][column] || board[row][column].color != color
out_array.push([row, col... |
after_save :increase_product_quantity after_destroy :decrease_product_quantity | def total
quantity * unit_price
end |
Gets the value of the packet's result TLV. | def result
return get_tlv_value(TLV_TYPE_RESULT)
end |
Computes the path for the API request | def compute_query_api_pattern_path(query_api_method_name, container, used_query_params)
container[:path] = compute_query_api_pattern_param(query_api_method_name, container[:path], container[:params_with_defaults], used_query_params)
end |
def user_project_participation(project_id) self.participants.where(project_id: project_id).first end | def current_project_participant(project_id)
# if self.has_accepted?(project_id)
Participant.where(project_id: project_id, user_id: self.id).first
# end
end |
Accessor for the store instance | def store
connection.store
end |
GET /genotypes/1 GET /genotypes/1.json | def show
@genotype = Genotype.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @genotype }
end
end |
creates a new Template object from liquid source code To enable profiling, pass in profile: true as an option. See Liquid::Profiler for more information | def parse(source, options = {})
new.parse(source, options)
end |
Example: x.foo += 42 ^^^ (for foo) x.foo += 42 ^ (for +) x.foo += 42 ^^^^^^^ (for foo=) | def spot_op_asgn2_for_name
nd_recv, _qcall, attr, op, _nd_rhs = @node.children
fetch_line(nd_recv.last_lineno)
if @snippet.match(/\G[\s)]*(\.)\s*#{ Regexp.quote(attr) }()\s*(#{ Regexp.quote(op) })(=)/, nd_recv.last_column)
case @name
when attr
@beg_column = $~.begin(1)
... |
Compiles a TypeScript file to JavaScript. | def compile_file(filepath, options={})
options = options.clone
if options[:output]
output_filename = options[:output]
elsif options[:output_dir]
filename = File.basename(filepath).gsub(/[.]ts$/, '.js')
output_filename = File.join(options[:output_dir], filename)
else
... |
Filter method to enforce a login requirement. To require logins for all actions, use this in your controllers: before_filter :login_required To require logins for specific actions, use this in your controllers: before_filter :login_required, :only => [ :edit, :update ] To skip this in a subclassed controller: skip_befo... | def login_required
# Skip this filter if the requested action is not protected
return true unless protect?(action_name)
# Check if user is logged in and authorized
return true if logged_in? and authorized?(current_user)
# Store current location so that we can redirect back after login
store_lo... |
Update a phone number provisioned for SMS. | def put_routing_sms_phonenumber_with_http_info(address_id, body, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: RoutingApi.put_routing_sms_phonenumber ..."
end
# verify the required parameter 'address_id' is set
fail ArgumentError, ... |
Hash of all files known to RDoc | def files_hash
@files_hash
end |
Wrapper around class method of same name | def admins_join_table
self.class.admins_join_table
end |
number as an arg 1 2 4 8 16 32 64 ... 2n | def power_of_two?(number)
(0..number).each do|num|
# 2**num == 16
if 2**num == number
return true
end
if 2**num > number
return false
end
end
return "problem"
end |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.