anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
Checks the to +v+ component. | def check_to(v)
return true unless v
return true if v.size == 0
v.split(/[,;]/).each do |addr|
# check url safety as path-rootless
if /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*\z/ !~ addr
raise InvalidComponentError,
"an address in 'to' is invalid as URI #{addr.dump}"
... |
Contstructor method Parameters String name_player1 Name for player 1 String name_player2 Name for player 2 | def initialize(name_player1, name_player2)
@current_player = :player1
@player1 = Player.new(name_player1, PLAYER_MARKS[:player1], 1)
@player2 = Player.new(name_player2, PLAYER_MARKS[:player2], 2)
@game_array = [[nil, nil, nil],
[nil, nil, nil],
[nil, nil, nil]]
e... |
rubocop: enable MethodLength rubocop: enable AbcSize | def tpl_name
"monit_check_#{new_resource.name}"
end |
trying to set CORS response headers in controller actions | def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Content-Type'
headers['Access-Control-Max-Age'] = "1728000"
end |
Never trust parameters from the scary internet, only allow the white list through. | def work_article_params
params.require(:work_article).permit(:name)
end |
======================================================================== followers attacks engine | def fo_tool
return actor.equips[0] if actor.primary_use == 1
return actor.equips[1] if actor.primary_use == 2
return actor.assigned_item if actor.primary_use == 3
return actor.assigned_item2 if actor.primary_use == 4
return actor.assigned_item3 if actor.primary_use == 5
return ac... |
Construct a SQL literal. This is useful for sql that is too complex for Arel. | def sql_literal(value)
Arel::Nodes::SqlLiteral.new(value)
end |
create a paid up member with a given company number, make a payment with the expire date. | def create_co_and_payment(company_number, payment_exp_date, member_pay_expires: Time.zone.today + 1.year, payment_create_date: Time.zone.now)
u = create(:member_with_membership_app, company_number: company_number)
u.shf_application.update(created_at: payment_create_date, updated_at: payment_create_date)
c... |
GET /admin/interviews/new GET /admin/interviews/new.json | def new
@admin_interview = Interview.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @admin_interview }
end
end |
GET /schmos GET /schmos.json | def index
@schmos = Schmo.all
@notes = Note.all
end |
primary access control point: returns all tenant permissions for user currently not used as user will only have one tenant with current implementation | def current_tenant_permissions
if current_or_guest_user
current_or_guest_user.tenant_ids
else
nil
end
end |
recursive fun for the same | def fiboRec(no)
if no == 0
return [0]
elsif no == 1
return fiboRec(0).push(1)
else
arr = fiboRec(no-1)
return arr.push(arr[no-1] + arr[no-2])
end
end |
=begin This function opens the file, converts it into nokogiri. Then uses xpath to sort the xml into an array. That array becomes the instance variables for an email data type above. Then the email data type gets pushed into an array. It also has a error check, to make sure there is actually a file in the location sent... | def openFile(emaillist,emailXML)
begin
emails = Nokogiri::XML(File.open(emailXML))
emails.xpath("//record").each { |f| emaillist.push(Email.new(f.css(
'id//text()','first_name//text()','last_name//text()',
'email//text()','gender//text()','ip_address//text()',
'send_date//text()','email_body//text()','ema... |
This gets a game cliche from a list of cliches in a text file | def get_game_cliche
#initialize variable
chosen_line = nil
#Get the cliche
File.foreach("game_cliches.txt").each_with_index do |line, number|
chosen_line = line if rand < 1.0/(number+1)
end
return chosen_line.chomp
end |
Wait for the UI to finish processing an action | def wait_for_ui_to_update
sleep(UI_UPDATE_DELAY)
end |
PATCH/PUT /expenses/1 PATCH/PUT /expenses/1.json | def update
respond_with Expense.update(params[:id], expense_params), status: 204
end |
(This method is generated in Translator_defaultbuildImpl) | def api_deserialize_impl(r)
@is_new = (r).nil?
r = {} if @is_new
@is_incomplete = false
if Saklient::Util::exists_path(r, 'ID')
@m_id = (Saklient::Util::get_by_path(r, 'ID')).nil? ? nil : Saklient::Util::get_by_path(r, 'ID').to_s
else
@m_id = nil... |
Execute the Choreo using the specified InputSet as parameters, wait for the Choreo to complete and return a ResultSet containing the execution results. | def execute(input_set = nil)
resp = super(input_set)
results = AddURLResultSet.new(resp)
return results
end |
Estimate the cardinality of the union of several sets | def union(counter_names, time=0)
union_helper(counter_names, time)
end |
Authorization number (only if completed?). | def auth_id
params['TxAuthNo']
end |
end initialize randomly determine if this room will have an enemy | def assign_enemy
@has_enemy = rand(1..2)==1 ? true : false
#need an enemy value for the room.
end |
custom validation for custom message without standard attribute prefix | def presence_of_subject_relationship_other
if subject_relationship_other.blank?
errors.add(:subject_relationship_other, ActiveRecord::Error.new(
self, :base, :blank, {
:message => "You must specify a relationship with 'other relationship' is selected." } ) )
end
end |
Is this dependency simply asking for the latest version of a gem? | def latest_version?
@requirement.none?
end |
Returns array of: Pixel xdimension Pixel ydimension unit (see png spec) | def get_data
xd = @data[0..3].unpack("C*")
xd = Shared::interpret_bytes_4(xd)
yd = @data[4..7].unpack("C*")
yd = Shared::interpret_bytes_4(yd)
unit = @data[8].unpack("C*")[0]
if !(unit == 0 || unit == 1)
warn "Unrecognised unit value for pHYs chunk: #{unit}."
... |
Trigger auto approve update rescue task Author: Aniket Date: 06/07/2018 Reviewed By: | def trigger_auto_approve_update_rescue_task(user_extended_details_id)
BgJob.enqueue(
AutoApproveUpdateJob,
{
client_id: @client_id,
reprocess: 1,
user_extended_details_id: user_extended_details_id
}
)
Rails.logger.info("---- enqueue_job AutoApprove... |
Never trust parameters from the scary internet, only allow the white list through. | def profile_params
params.require(:profile).permit(:id, :name, :description, :cpf, :services, :mobile, :zipcode, :address, :number, :complement, :neighborhood, :city, :state, :profile)
end |
PUT /chores/1 PUT /chores/1.json | def update
# TODO: Add cron_str updating
respond_to do |format|
if @chore.update_attributes(params[:chore])
format.html { redirect_to @chore, notice: 'Chore was successfully updated.' }
format.json { head :no_content }
else
format.html { render :edit }
format.json { r... |
GET /nursing_times/1 GET /nursing_times/1.json | def show
@nursing_time = NursingTime.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @nursing_time }
end
end |
Update organization units cache table if records are more than one day old | def update_organization_units
oldest_update = AdOrganizationUnit.order('created_at').last
if bind && (oldest_update.nil? || oldest_update.created_at<1.day.ago)
filter = Net::LDAP::Filter.eq("objectClass", "organizationalunit")
results = @connection.search(:base =>"ou=Sync,"+base_distinguished_name... |
Compares the value of +self+ with the value of +other+. | def <=>(other)
other = other.value if other.is_a? self.class
return value <=> other
end |
The class of the resource that the controller handles | def controller_resource
ProjectEvaluation
end |
A method for building pair role | def mk_pair_role rpair, plural=false
suffix = plural ? 's' : ''
"#{rpair.join(UBAR)}_pair#{suffix}"
end |
Triggers an event, moving record to associated state, if permitted Returns false if event not permitted | def trigger(event, metadata={})
if (event_permitted(event) || User.is_admin?(metadata[:user_id])) &&
required_metadata_present?(event, metadata)
to_state = self.event_to_state(event)
callback_metadata = metadata.clone
transition_to(to_state, metadata)
if respond_to?(:even... |
=> Produit le pdf et l'ouvre | def generate_pdf
begin
raise( :lilyfile_does_not_exists ) unless File.exists?( path_lily_file )
`lilypond --output='#{path_affixe_file}' '#{path_lily_file}'`
`open '#{path_pdf_file}'`
rescue Exception => e
fatal_error e.message
end
end |
POST /faqs POST /faqs.json | def create
@faq = Helpdesk::Faq.new(faq_params)
respond_to do |format|
if @faq.save
format.html { redirect_to admin_faqs_url, notice: 'Faq was successfully created.' }
format.json { render json: @faq, status: :created, location: @faq }
else
format.html { render action: "new"... |
actions to register a account | def new
@user = User.new
end |
Update an account by a given account_number | def update_account(account_number, account_form)
# the base uri for api requests
query_builder = Configuration.base_uri.dup
# prepare query string for API call
query_builder << '/accounts/{account_number}'
# process optional query parameters
query_builder = APIHelper.append... |
End of N3_PR Segment Details Start of TRN Segment Details | def originating_company_id_trace(*options)
'1000000009'
end |
must follow any before filters | def parse_values_from_ui
unless self.period_value.blank? and self.period_units.blank?
p = self.period_value.to_i
self.period = p.send(self.period_units).to_i
end
unless self.breach_duration_value.blank? and self.breach_duration_units.blank?
p = self.breach_duration_value.to_i
self.breach_duration = p.... |
Procedure to place button on the screen | def place_button(x, y, message)
Gosu.draw_rect(x, y, 70, 45, Gosu::Color::GREEN, ZOrder::MIDDLE, mode=:default)
@button_font.draw_text(message, x+5, y+10, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
end |
Cleans up nokogiri search results | def cleanup(results)
results.map { |r| r.value.strip }.reject(&:empty?).uniq
end |
Serves the asset at the path in +req+ for +generator_name+ via +res+. | def asset generator_name, req, res
asset_dir = @asset_dirs[generator_name]
asset_path = File.join asset_dir, req.path
if_modified_since req, res, asset_path
res.body = File.read asset_path
res.content_type = case req.path
when /\.css\z/ then 'text/css'
... |
do eth protocol handshake and return status | def send_handshake(network_id, total_difficulty, head_hash, genesis_hash)
status = Status.new(protocol_version: 63, network_id: network_id,
total_difficulty: total_difficulty, current_block: head_hash, genesis_block: genesis_hash)
@context.send_data(Status::CODE, status.rlp_e... |
:nodoc: Return a expanded path to repository mirror build with information from configuration for repository. Replace keywords (:keyword) with value matched by it pattern. | def mirror_path(repository_owner, repository_name)
mirror_path = repository_info(repository_owner, repository_name).path || raise(GithubMirrorError, "Path for repository '#{repository_owner}/#{repository_name}' doesn\'t exist in config")
mirror_patterns = repository_info(repository_owner, repository_name).patte... |
runs an external executable, returns true on success | def run_executable(full_commandline)
log.debug "running #{full_commandline}"
Process.wait(Process.spawn(full_commandline))
$CHILD_STATUS.exitstatus == 0
end |
Initialize reservations object Holds growing and shrinking list of ticket reservations | def initialize
@reservations = {}
@lockers = Lockerz::Lockers.new
end |
GET /fotos_empresas GET /fotos_empresas.json | def index
@fotos_empresas = FotosEmpresa.all
end |
GET /frbr_manifestations/new GET /frbr_manifestations/new.json | def new
screen_name("Admin-Nuevo-Manifestacion-FRBR")
@frbr_manifestation = FrbrManifestation.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @frbr_manifestation }
end
end |
DELETE /sofas/1 DELETE /sofas/1.xml | def destroy
@sofa = Sofa.find(params[:id])
@sofa.destroy
respond_to do |format|
format.html { redirect_to(sofas_url) }
format.xml { head :ok }
end
end |
Test if we can add a comment to a post | def test_add_comment_to_post
nc = @normal_post.number_of_comments
@normal_post.comments << @comment
assert_equal(nc + 1, @normal_post.number_of_comments)
end |
Given a project's id (`pid`), get the project's name. | def project_name(pid)
Nokogiri::HTML(pivotal_tracker(project_url(pid)).content).css('project > name').text.split(' ').join
end |
DELETE /guacs/1 DELETE /guacs/1.json | def destroy
@guac.destroy
respond_to do |format|
format.html { redirect_to guacs_url, notice: 'Guac was successfully destroyed.' }
format.json { head :no_content }
end
end |
Converts +document+ to text and writes it to the pager | def display document
page do |io|
f = formatter(io)
f.width = @width if @width and f.respond_to?(:width)
text = document.accept f
io.write text
end
end |
Diagonal Top right to bottom left approach | def right_to_diagonal_left_approach
largest_prod = 0
for each_row in (0..15)
for col in (0..19)
each_col = 19 - col
a = $grid_of_numbers[each_row][each_col]
b = $grid_of_numbers[each_row+1][each_col-1]
c = $grid_of_numbers[each_row+2][each_col-2]
d = $grid_of_numbers[each_row+3][e... |
GET /entity GET /entity.json | def index
@search = @klass.search(params[:q])
@entities = @search.result.includes(@klass::ADMIN_INCLUDES).page(params[:page])
@count = @search.result.count
@search.build_condition
respond_to do |format|
format.html # index.html.erb
format.json { render json: @entities }
end
end |
takes a hash of question IDs (keys) and answers (values) | def set_answers!(params)
SurveyQuestion.with_question.find_all_by_survey_id(survey_id).each do |question| # iterate through all survey questions
if params[question.id.to_s].blank? # if the question hasn't been answered
remove_answer(question.id)
else
set_answer(question, params[question.... |
Returns the endpoint of this URL e.g. the bit after the host with any slashes included. For example: Wgit::Url.new(" returns "/about.html/". See Wgit::Urlto_path if you don't want the slashes. | def to_endpoint
endpoint = @uri.path
endpoint = '/' + endpoint unless endpoint.start_with?('/')
Wgit::Url.new(endpoint)
end |
The "type" of dependencies this manager manages. This can be the language, tool, etc. | def type
raise LicenseScout::Exceptions::Error.new("All DependencyManagers must have a `#type` method")
end |
Check if params DEVICE_CODE, DATA is present in JSON send | def has_not_mandatory_params?
!params[:email].present? || !params[:password].present?
end |
is Encoding callseq: Stringiseuc > obj or nil Returns whether self's encoding is EUCJP or not. Note don't expect this return value is MatchData. | def iseuc; Kconv.iseuc(self) end |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.