anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
List zset keys between `start` and `stop`. | def zlist(start, stop, opts = {})
limit = opts[:limit] || -1
mon_synchronize do
perform ["zlist", start, stop, limit], :multi => true
end
end |
Return all of the tasks that should be run: No duplicates, no tasks that have previously been run successfully. | def all_tasks_to_run
self.all_tasks - all_tasks_previously_run - all_tasks_duplicates
end |
Prepare the Plot for the next turn of gameplay. This method is typically called by the Engine that manages game execution. | def ready
playbook.freeze
@running = true
# Call the initial state to make sure it's set
initial_state
call_ready
call_player_ready
p_subplots.each { |s| s.ready }
end |
the key attribute of a query | def initialize(lipid, mods=[])
@lipid = lipid
@modifications = mods
@mz = nil
end |
This method creates a new `Node` using `data`, and inserts it at the end of the list. | def add_to_tail(node)
if self.tail == nil
self.tail = node
self.head = node
node.next = nil
return
end
old_tail = self.tail
old_tail.next = node
node.next = nil
self.tail = node
end |
print a character at given column/row | def char(column, row, char)
command "T#{column},#{row},#{char}"
end |
PATCH/PUT /opinion_reports/1 PATCH/PUT /opinion_reports/1.json | def update
respond_to do |format|
if @opinion_report.update(opinion_report_params)
format.html { redirect_to @opinion_report, notice: 'Opinion report was successfully updated.' }
format.json { render :show, status: :ok, location: @opinion_report }
else
format.html { render :edit ... |
custom actions with paper trail events | def archive
self.paper_trail_event = "archive"
self.discard
end |
Confirms a loggedin user. | def logged_in_user
unless logged_in?
store_location
flash[:danger] = "Please log in."
redirect_to login_url
end
end |
Return a new TodoList object containing only the done items | def all_done
self.select { |todo| todo.done? }
end |
Prints out the terminal message. | def done
@out.puts "\n#{@terminal_message}"
end |
Remove the next option and return it. Return nil when there are no more options. | def next_argument
if @remaining.empty?
return nil
else
return @remaining.shift
end
end |
Search for organizations via External APIs | def search_externally(search_term:)
return [] unless search_term.present? && search_term.length > 2
orgs = externals_search(search_term: search_term)
prepare(search_term: search_term, records: orgs)
end |
Used to perform a key up on this view in the remote application You can either type a printable character or a function key. If you want to type a printable character then the 'key' parameter just has to be a string, such as 'a'. If you want to type a function key such as F1, then the 'key' parameter must be the corres... | def key_up(key)
focus
@driver.sc_key_up action_target, key, *action_locator_args
stall :key_up
end |
Given a number, find the level that includes it Ex: Number 7 returns level 1 Level 1: Min Value: 2 Max Value: 9 | def find_level
level = 0
max_value = max_number_of_a_level(level)
while max_value < input
level += 1
max_value = max_number_of_a_level(level)
end
level
end |
Read the sheet, and return each nonheader row to the passed block. This first reads the headers and cleans them up (see "read_headers"). When each row is read, the values are stored in a hash with the cleaned up column names as keys. If a method exists called "method_", this is used to convert the value. Spreadsheet se... | def read(&blk)
## Preconditions:
# NOTE: you can't grab a row or just read a line in roo, you have to ask
# about the bounds and explcitly iter over the cell contents.
row_start = @wbook.first_row
row_stop = @wbook.last_row
col_start = @wbook.first_column
col_stop = @wbook.last_column
i... |
all public methods in here will be run in order | def add_views
output "I'm copying the default views into app/views/gem_displays for you.", :magenta
template "index.html.haml", "app/views/gem_displays/index.html.haml"
template "show.html.haml", "app/views/gem_displays/show.html.haml"
template "_widget.html.haml", "app/views/gem_displays/_widge... |
=begin This method checks if a user thumbed down this comment before Inputs: user who we want to check if he upped or not. Output: boolean true or false Author: Menisy =end | def downed_by_user?(user)
down = self.comment_up_downs.find_by_user_id_and_action(user.id,2) # get the down that a user gave to this comment before "if exists"
!down.nil? # if down is nil then return false if not then return true
end |
Most of the class omitted... | def each
words.each { |word| yield( word ) }
end |
Submit a timesheet for approval. | def submitForApproval(period=nil, comment='', name=@username)
if period.nil? then
# First day of work week
cur = currentApprovalStatus(nil, name)
period = cur.access 'period.dateFrom'
end
verbose "Submitting timesheet for #{period}"
post('times... |
Returns a list of Folder and File objects. | def search(q)
results = []
url = "https://#{@subdomain}.sharefile.com/rest/search.aspx?op=search&query=#{q}&authid=#{@authid}&fmt=json"
response = JSON.parse(open(url).read)
if response["error"] == false #success
response["value"].each do |item|
if item["type"] == "folder"
... |
Aceite Nao tem no manual, foi baseado em boleto modelo enviado pela prefeitura | def aceite
'N'
end |
Methods cannot take more than one block Yield can be used multiple times | def print_twice
yield
yield
end |
Adds "(from ...)" to +out+ for +store+ | def add_from out, store
out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})")
end |
REFERENCE NUMBER Selects the next autogenerated reference number and inserts it into the test data set | def select_auto_reference_nbr(test_data)
hide_notifications_bar
ref_nbr = select_id_generator_option(reference_nbr_input, reference_nbr_options)
logger.info "Selected auto-generated reference number '#{ref_nbr}'"
test_data.merge!({CoreUseOfCollectionsData::REFERENCE_NBR.name => ref_nbr})
end |
Virtually makes this publicly global for the app. | def add_restriction(name, condition, &default_block)
@ACL ||= AccessControlList.new
@ACL.add_restriction(name, condition, default_block)
end |
Allows +tag+ to be decorated with additional information. | def annotate(tag)
tag
end |
reads sident from webservice and change it for students | def repair_sident(indices)
@@mylog.info "There are %i students" % indices.size
@client = SOAP::NetHttpClient.new
service = SERVICE_URL + SIDENT_SERVICE_PATH
f = File.new("sident_errs.txt", "wb")
indices.each do |index|
@@mylog.info "Procesing index #%i" % index.id
service_... |
One of the special globals $&, $`, $' or $+. | def back_ref(kind)
if lm = last_match()
res = case kind
when :&
lm[0]
when :"`"
lm.pre_match
when :"'"
lm.post_match
when :+
lm.captures.last
end
return res
end
return nil
end |
Creates a new Attr with body +text+, +name+, read/write status +rw+ and +comment+. +singleton+ marks this as a class attribute. | def initialize(text, name, rw, comment, singleton = false)
super text, name
@rw = rw
@singleton = singleton
self.comment = comment
end |
Allow clients to get the a specific phone number. | def get_telephone_number(account_number, telephone_number)
# the base uri for api requests
query_builder = Configuration.base_uri.dup
# prepare query string for API call
query_builder << '/accounts/{account_number}/dids/{telephone_number}'
# process optional query parameters
... |
PATCH/PUT /events/1 PATCH/PUT /events/1.json | def update
tag_array = event_params2['tags'].split(',')
tag_array.each do |x|
if Tag.find_by(desc: x)
@tag = Tag.find_by(desc: x)
else
@tag = Tag.create(desc: x)
end
@event.tags << @tag
# EventTag.create(event_id: @event.id, tag_id: @tag.id)
end
respond_to... |
GET /bid_winners/1 GET /bid_winners/1.json | def show
end |
Returns +true+ if +self+ follows +other+. TimeOfDay.new("09:00") true | def >(other)
return true if self.hour > other.hour
return false if self.hour < other.hour
self.minute > other.minute
end |
Deliver the item to the customer | def pickup_item
if status == :confirmed
transaction do
update(:status => :in_progress)
# Create newsfeed
::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking',
action: 'pickup_item',
... |
Create a monthly recurrence. | def monthly(options = {})
branch options.merge(every: :month)
end |
Never trust parameters from the scary internet, only allow the white list through. | def client_event_params
params.require(:client_event).permit(:event_id, :client_id, :payment_method_id, :ticket_id)
end |
Remember that we can access an array element at particular index with the following syntax: array[index_number] !!! | def position_taken?(board,index)
if board[index] == " "
false
elsif board[index] == ""
false
elsif board[index] == nil
false
else board[index] == "X" || "O"
true
end
end |
The current user permissions can be policy checked in views: | def can?(query, record)
query = "#{query}?"
policy = Pundit.policy!(pundit_user, record)
!! policy.public_send(query)
end |
Returns true if User has at least one related Patient | def has_related_patient?
if registrations.count > 0
return true
end
under_supervision_clinics.each do |clinic|
clinic.registrations.each do |reg|
return true
end
end
return false
end |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.