anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
in params complete donation needed (with charity, amount, etc.) | def create
@donation = Donation.new(donation_params)
before_donation_creation @donation
if @donation.save
after_donation_creation @donation
set_after_create_flash_message
redirect_to donation_path(@donation)
else
redirect_to charities_path
end
end |
If the payment was successful, Cybersource will send us back a decision of 'ACCEPT' | def payment_success?
@fields['decision'] == 'ACCEPT'
end |
For all responses in this controller, return the CORS access control headers. | def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Max-Age'] = "1728000"
end |
Only allow a list of trusted parameters through. | def post_params
params.require(:post).permit(:title, :image, :description, :category, :ingredients, :method, :prep, :cook, :difficult)
end |
returns the property definitions for the project. | def property_definitions
set_attributes_for(PropertyDefinition)
PropertyDefinition.find(:all)
end |
takes player name and url params constructs url and uses Nokogiri to open connection with required parameters returns array of form [Games, AB, Runs, Hits, 2B, 3B, HR, RBI, BB, HBP, CS, SH, SF, GDP, BA, OBA, Slug%, OPS] | def scrape
player = params[:player]
url = params[:url]
endDate = params[:EndDate]
filler = '&GameType=all&PlayedFor=0&PlayedVs=0&Park=0&PlayerID='
id = Player.find_by_name(player).number.to_s
fullUrl = url + '&EndDate=' + endDate + filler + id
page = Nokogiri::HTML(open(fullUrl))
totalsAr... |
Array of all letters of the alphablet in uppercase | def alphabet_array
('A'..'Z').to_a
end |
Public: resolves a template file by looking in the template path. template the template name. extension the extension of the desired template. Returns a string with the full path of the template file, or nil if it is not found. | def which(template, extension)
template_with_extension = with_extension(template, extension)
path = absolute_paths.find do |path|
File.exists?(File.join(path, template_with_extension))
end
if path
File.join(path, template_with_extension)
end
end |
Deletes a pipeline on AWS Elastic Transcoder given an id | def delete_pipeline id
begin
@elastictranscoder.delete_pipeline(id: id)
rescue
#Raise informative exception
end
end |
PATCH/PUT /projects/1 PATCH/PUT /projects/1.json | def update
respond_to do |format|
if @project.update(project_params)
format.html { redirect_to @project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: @project }
else
format.html { render :edit }
format.json { render json... |
GET /commodities GET /commodities.json | def index
@commodities = Commodity.all
if params[:search].present?
@commodities = @commodities.query(params[:search].to_s)
end
@commodities = @commodities.page(params[:page])
respond_to do |format|
format.html
format.js {}
format.json {
render json: {:commodities =... |
Enlace que se muestra solo si el usuario ha ingresado al sistema | def link_usuario(titulo, enlace)
link_to titulo, enlace if not session[:usuario]
end |
Logs +message+ if verbose | def log(message)
$stderr.puts message if @verbose
ActionMailer::Base.logger.info "ar_sendmail: #{message}"
end |
Challenge IV: Adding Data adding operates on the shipping_manifest hash to add a key/value pair add 2 muskets to the shipping_manifest hash below add 4 gun powder to the shipping_manifest hash below return the shipping_manifest hash below | def adding
shipping_manifest = {"whale bone corsets" => 5, "porcelain vases" => 2, "oil paintings" => 3}
shipping_manifest["muskets"] = 2
shipping_manifest["gun powder"] = 4
shipping_manifest
end |
Notice how it's currently impossible to tell if a key is simply mistyped as a public or private key, or if it's a badly formatted key. Too bad. | def test_bogus_raise
bogus_key = "Oh hey I'm a key. Ok, not really."
assert_raise OpenSSL::PKey::PKeyError do
Net::SSH::Utils::Key.fingerprint(:data => bogus_key)
end
end |
Check exploit vulnerability basically // 'Appears' more convenient | def check
res = inject(Rex::Text.rand_text_alpha(1))
if res.code = "200" && res.headers['set-cookie'] =~ /JSESSIONID/
Exploit::CheckCode::Appears
else
Exploit::CheckCode::Safe
end
end |
Whether or not to disable Solr. Defaults to false. | def disabled?
@disabled ||= (user_configuration_from_key('disabled') || false)
end |
Adds a tag into the page with the desired url or content. | def add_script_tag(url: nil, path: nil, content: nil, type: '')
# param url [String]
# param type [String]
#
# return [Promise<HTMLElement>]
#
add_script_url = <<~JAVASCRIPT
async function addScriptUrl(url, type) {
const script = document.createElement('script');
... |
function for get the targets cttctt in the exons | def obtain_target_from_seq(bioseq_seq)
#we are going to keep all the targets from each gene,
#hash of hashes :)
targets=Hash.new
len_bioseq = bioseq_seq.length + 1
nstrand_targets = []
pstrand_targets = []
for i in (0..bioseq_seq.length-5)
if bioseq_seq.complement[i..i+5] == ... |
DELETE /coupons/1 DELETE /coupons/1.json | def destroy
if session[:coupon_code].present?
session[:coupon_code] = nil
@message = "Coupon Removed"
end
@cart_items = current_user.cart_items
@sub_total, @discount, @tax, @shipping_cost, @final_total = Coupon.destroy_coupon(@cart_items, session[:coupon_code])
respond_to do |format|
... |
Sets the restartNotificationSnoozeDurationInMinutes property value. The number of minutes to snooze the restart notification dialog when the snooze button is selected. | def restart_notification_snooze_duration_in_minutes=(value)
@restart_notification_snooze_duration_in_minutes = value
end |
returns the original title of the document or missing_title | def attachment_title
orig_title = super
orig_title.blank? ? missing_title : orig_title
rescue NoMethodError
missing_title
end |
Only allow a trusted parameter "white list" through. | def user_params
params.require(:user).permit(:id)
end |
Two tiles are equal when their vertixes are geometrically equal. | def ==(tile)
self.vtx == tile.vtx
end |
PATCH/PUT /student_app_cat_regnos/1 PATCH/PUT /student_app_cat_regnos/1.json | def update
respond_to do |format|
if @student_app_cat_regno.update(student_app_cat_regno_params)
format.html { redirect_to @student_app_cat_regno, notice: 'Student app cat regno was successfully updated.' }
format.json { render :show, status: :ok, location: @student_app_cat_regno }
else
... |
Never trust parameters from the scary internet, only allow the white list through. | def admin_banner_params
params.fetch(:banner).permit!
end |
Create a yearly recurrence. | def yearly(options = {})
branch options.merge(every: :year)
end |
min=arr.first arr.each do |x| nested_min = x arr.each do |y| next if x == y nested_min = y < x ? y : x end min = nested_min < min ? nested_min : min end min end | def my_min(arr)
min = arr.first
arr.each do |el|
min = el if el < min
end
min
end |
Never trust parameters from the scary internet, only allow the white list through. | def user_feedback_params
params.require(:user_feedback).permit(:email, :feedback)
end |
== Description Returns the full path for an HTTP request, as required by Net::HTTP::Get. If the URI contains a query, the full path is URIpath + '?' + URIquery. Otherwise, the path is simply URIpath. Example: uri = URI::HTTP.build(path: '/foo/bar', query: 'test=true') uri.request_uri => "/foo/bar?test=true" | def request_uri
return unless @path
url = @query ? "#@path?#@query" : @path.dup
url.start_with?(?/.freeze) ? url : ?/ + url
end |
The names of the nested fields as symbols if the type property is set to `RECORD`. Will be empty otherwise. | def headers
fields.map(&:name).map(&:to_sym)
end |
Parse sub methods like to_string, to_integer | def parse_sub_methods(line)
new_line = []
line.each do |token|
next unless token[:type] == :IDENTIFIER
arguments_size = 0
SUBMETHODS.each do |submethod|
next unless submethod[:ikea_name] == token[:value].to_sym
arguments_size = submethod[:arguments]
end
value = ... |
def inc_vote_count increment! :vote_count planet.inc_vote_count, self end def dec_vote_count decrement! :vote_count planet.dec_vote_count, self end | def add_vote_from_user(user)
votes.create(user: user)
end |
Tells the backend to load translations now. Used in situations like the Rails production environment. Backends can implement whatever strategy is useful. source://i18n//lib/i18n.rb90 | def eager_load!; end |
returns true if pkgname is an autoproj meta package | def is_metapackage?(package_name)
raise RuntimeError, "#{self.class} needs to overwrite is_metapackage?"
end |
Unregisters the event by name, effectively deleting the associated events bound with it also. | def unevent(name)
Events.remove(name)
end |
Finds a link reference for `label` and creates a new link to it with `content` as the link text. If `label` was not encountered in the referencegathering parser pass the label and content are reconstructed with the linking `text` (usually whitespace). | def link_to content, label = content, text = nil
raise ParseError, 'enable notes extension' if
content.start_with? '^' and label.equal? content
if ref = @references[label] then
"{#{content}}[#{ref}]"
elsif label.equal? content then
"[#{content}]#{text}"
else
"[#{content}]#{text}... |
GET /sites/:id GET /projects/:project_id/sites/:id | def show
do_load_resource
get_project_if_exists
do_authorize_instance
respond_to do |format|
format.html { @site }
format.json { respond_show }
end
end |
function7 ===> test no.7 | def stock_count(petshop)
return petshop[:pets].size()
end |
Returns a Boolean indicating whether this character is a hiragana or katakana character. (This string must contain only one character.) | def kana?
codepoint.kana?
end |
Get active positions return [Array] | def active_positions
authenticated_post("auth/positions").body
end |
Never trust parameters from the scary internet, only allow the white list through. | def activity_params
params.fetch(:activity, {}).permit(
:name,
:start,
:duration,
:activity_type_id
)
end |
Indicates whether its possible to capture the payment | def can_capture?(payment)
['checkout', 'pending'].include?(payment.state)
end |
Adds a single extension module +include+ from +store+ to +out+ | def add_extension_modules_single out, store, include # :nodoc:
name = include.name
path = store.friendly_path
out << RDoc::Markup::Paragraph.new("#{name} (from #{path})")
if include.comment then
out << RDoc::Markup::BlankLine.new
out << include.comment
end
end |
Physical ID of the resource created | def physical_resource_id
"#{self.class.name.split('::').last}-#{Carnivore.uuid}"
end |
PUT /definitions/1 PUT /definitions/1.json | def update
@definition = Definition.find(params[:id])
respond_to do |format|
if @definition.update_attributes(params[:definition])
format.html { redirect_to @definition, notice: 'Definition was successfully updated.' }
format.json { head :no_content }
else
format.html { rend... |
An initializer called by the framework once per billling cycle. Override this method if you need to perform highlatency operations, like network transactions, that should not be performed perresource. | def setup(resources) ; end |
Never trust parameters from the scary internet, only allow the white list through. | def project_params
params.require(:project).permit(:title, :image, :banner, :date, :description, :summary, :link, :status)
end |
Expecting string: "A1:hit B10:miss" Processes the result, marks the field appropriately, changes the sequence of shots accordingly. | def process_shot_result(shot_result)
shot_result.split(/:|\s/).each_slice(2) do |location, result|
field[location] = result.to_sym
has_hit(location) if field[location] == :hit
end
end |
Does a sanity check on the specification. Raises InvalidSpecificationException if the spec does not pass the checks. It also performs some validations that do not raise but print warning messages instead. | def validate(strict = false)
validate_required!
validate_optional(strict) if packaging || strict
true
end |
(Experimental) Embeds a "pure" (nonNetzke) Ext component into the view, e.g.: :panel, :html => "Simple Panel" | def ext(name, config = {}) #:doc:
comp = Netzke::ExtComponent.new(name, config)
content_for :netzke_on_ready, raw("#{comp.js_component_render}")
raw(comp.js_component_html)
end |
GET /rodzaj_pracownikas/1 GET /rodzaj_pracownikas/1.json | def show
end |
Synchronously upgrade an environment | def upgrade(job, environment, plugin, options = {})
worker = Worker.new(job, environment.freeze, plugin.freeze, options.freeze)
worker.run
ensure
worker.terminate if worker && worker.alive?
job.terminate if job && job.alive?
end |
Displays a specific tape. API Key Scope: tapes / show | def show_tape_by_pool(pool_id, tape_id, opts = {})
data, _status_code, _headers = show_tape_by_pool_with_http_info(pool_id, tape_id, opts)
data
end |
if all the digits are the same we dont need to compute since the number cant get bigger with permutations | def all_digits_are_the_same?(digits)
digits.uniq.length == 1
end |
Sends a chat message to the client. | def send_message(msg, from = nil)
msg = "#{msg} (@#{from})" unless from.nil?
@auth_required ? @after_auth.push({:m => msg}) : send_data({:m => msg})
end |
POST /guest_books POST /guest_books.xml | def create
@guest_book = GuestBook.new(params[:guest_book])
respond_to do |format|
if @guest_book.save
flash[:notice] = 'Thank you for signing the guestbook'
# format.html { redirect_to(@guest_book) }
format.html { render :action => "created" }
format.xml { render :xml =>... |
GET /cake_flavors/1 GET /cake_flavors/1.json | def show
end |
lexer rule t__25! (T__25) (in Ingredients.g) | def t__25!
# -> uncomment the next line to manually enable rule tracing
# trace_in( __method__, 18 )
type = T__25
channel = ANTLR3::DEFAULT_CHANNEL
# - - - - main rule block - - - -
# at line 34:9: 's'
match( 0x73 )
@state.type = type
@state.channel... |
POST /configuration_files POST /configuration_files.json | def create
@configuration_file = ConfigurationFile.new(configuration_file_params)
respond_to do |format|
if @configuration_file.save
format.html { redirect_to @configuration_file, notice: 'Configuration file was successfully created.' }
format.json { render :show, status: :created, locati... |
Return start time for this element, relative to the beginning of the production. | def t1
_absolute(enter)
end |
sorted by how they should be displayed | def users
self.triples.map(&:first)
end |
add info in the json file | def add(class_name, object)
@data = get_all()
@data[class_name].push(object.to_hash())
save()
end |
SHOW GIFTS (ALL OF THEM) | def index
@occasion = Occasion.find params[:occasion_id]
@gifts = Gift.all
end |
Use for_model instead of instatiating a record directly. | def initialize(model_class)
@model_class = model_class
@records = []
end |
Permitted params for the model | def permitted_params
params.require(params[:asset_type].underscore.gsub('/', '_').to_sym).permit(
:name,
:filename,
:body,
:content_type,
:width,
:height,
:asset_type,
:ratio
)
end |
start by buliding array | def anna_3_5
annas_counter = 0 #variable used inside the function
a = (1..100).to_a #building array of a hundred elements
while annas_counter < 100
annas_counter += 1
if annas_counter % 3 == 0 && annas_counter % 5 == 0 #way to do both 3 and 5 together(15 a factor of both)
a[annas_counter -1] = "minedminds"
... |
two edge cases pawn can go two moves at first pawn can move diagonally to take another piece | def take(current_position)
if direction == 1
diagonals(current_position, 1)[0..1]
elsif direction == 2
diagonals(current_position, 1)[1...-1]
end
end |
global alias so we can write 'df.world.units.all[0]' | def df
DFHack
end |
Populate the response with content. Set the response's content type to the given type. Raise an error if the developer tries to double render. | def render_content(content, type)
raise "already built response" if already_built_response?
self.session.store_session(@res)
self.flash.store_flash(@res)
@res.content_type = type
@res.body = content
@already_built_response = true
end |
GET /step_commands/1 GET /step_commands/1.json | def show
end |
GET /actionables GET /actionables.json | def index
@actionables = Actionable.all
end |
Returns the framework input paths for the given framework paths | def embed_frameworks_input_paths(framework_paths, xcframeworks)
input_paths = framework_paths.map(&:source_path)
# Only include dynamic xcframeworks as the input since we will not be copying static xcframework slices
xcframeworks.select { |xcf| xcf.build_type.dynamic_framework? }.eac... |
Prints a list of links for the Main Menu | def print_link_list(items)
linkString = ""
if(!items.empty? && items[0].is_a?(Category))
linkString += "<tr><td>#{link_to "New Category", new_category_url, {:style=>'color:#FF8000'}}</td></tr>"
linkString += "<tr><td>#{main_menu_accord(all_category_hash)}</td></tr>"
elsif(!items.empty? && ite... |
PATCH/PUT /promulher_forms/1 PATCH/PUT /promulher_forms/1.json | def update
respond_to do |format|
if @promulher_form.update(promulher_form_params)
format.html { redirect_to @promulher_form, notice: 'Promulher form was successfully updated.' }
format.json { render :show, status: :ok, location: @promulher_form }
else
format.html { render :edit ... |
Use the connection from the connection class | def connection
@connection_class.connection
end |
> compress [1, 1, 2, 3, 3, 3] => [1, 2, 3] | def compress(array)
array.uniq
end |
:registerable dragonfly_accessor :last_sign_in_ip image_accessor :last_sign_in_ip | def send_survey
Message.send_survey_to(self)
end |
Example: foo(42) ^^^ foo 42 ^^^ | def spot_fcall_for_name
mid, _nd_args = @node.children
fetch_line(@node.first_lineno)
if @snippet.match(/(#{ Regexp.quote(mid) })/, @node.first_column)
@beg_column = $~.begin(1)
@end_column = $~.end(1)
end
end |
Note: These tests assume a default storage class with a dynamic provisioner and 'Immediate' bind | def test_pvc
pvname = "local0001"
storage_class_name = "k8s-deploy-test"
assert_deploy_success(deploy_global_fixtures_non_namespaced("pvc",
subset: ["wait_for_first_consumer_storage_class.yml"]))
TestProvisioner.prepare_pv(pvname, storage_class_name: storage_class_name)
assert_deploy_success... |
Get response for sending KYC deny email Author: Mayur Date: 14/12/2018 Reviewed By: | def email_kyc_deny(data_to_format)
{}
end |
Render a split table view based on the data passed when creating the CsvDiffer instance. The split view renders two tables, that individually have a horizontal scrollbar. | def split
builder = Builder::XmlMarkup.new
builder.div do
split_build_table(builder, @gen_headers, true)
split_build_table(builder, @exp_headers, false)
end.html_safe
end |
method called to check status of player | def status
"#{@name}: #{@lives}/3 "
end |
Get the top 10 popular contents over the last 14 days | def top_paths(repo, options = {})
opts = ensure_api_media_type(:traffic, options)
get "#{Repository.path repo}/traffic/popular/paths", opts
end |
GET /ches GET /ches.json | def index
@ches = Ch.all
end |
List L2 Bridge Endpoint Profiles List all L2 bridge profiles | def list_l2_bridge_profiles_with_http_info(site_id, enforcement_point_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PolicyNetworkingConnectivitySegmentsEdgeBridgeProfilesApi.list_l2_bridge_profiles ...'
end
# verify the required parameter 'site_id... |
PATCH/PUT /questions/1 PATCH/PUT /questions/1.json | def update
check_delete_flg
respond_to do |format|
if @question.update_attributes(question_params)
format.html { redirect_to @question, notice: 'Question was successfully updated.' }
format.json { render :show, status: :ok, location: @question }
else
format.html { render :edi... |
Register this field with the class, overriding a previous one if needed. | def add_field(field_defn, method_conflict_warning: field_defn.method_conflict_warning?)
# Check that `field_defn.original_name` equals `resolver_method` and `method_sym` --
# that shows that no override value was given manually.
if method_conflict_warning &&
CONFLICT_FIELD_NA... |
PATCH/PUT /solicitacao_tipos/1 PATCH/PUT /solicitacao_tipos/1.json | def update
respond_to do |format|
if @solicitacao_tipo.update(solicitacao_tipo_params)
format.html { redirect_to @solicitacao_tipo, notice: 'Solicitacao tipo was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.js... |
attr_reader :threads2frames Hash[thread_id] > top_frame | def adjust_frame(frame_num, absolute_pos)
frame, frame_num = get_frame(frame_num, absolute_pos)
if frame
@frame = frame
@frame.index = frame_num
prefix = "--> ##{frame_num} "
unless @settings[:traceprint]
msg("#{prefix}%s" %
@frame.describe(:basename => settings[:b... |
Only allow a trusted parameter "white list" through. | def bulk_action_params
params.require(:bulk_action).permit(
:action_type,
:description,
:pids,
manage_release: [:tag, :what, :who, :to],
set_governing_apo: [:new_apo_id],
manage_catkeys: [:catkeys]
)
end |
Test if crew is not missing methods | def test( crew )
[ 'board', 'step', 'event', 'identifier' ].each do | method |
if not crew.respond_to?( method )
raise "Crew should respond to #{method}"
end
end
end |
This calculates and stores the offset at which each column starts. Used when going to next column or doing a find for a string in the table. | def _calculate_column_offsets
total = 0
coffsets = []
ctr = 0
## ix will have gaps in between for hidden fields
each_column { | c, ix|
v = c.width
coffsets[ctr] = total
ctr += 1
total += v + 2 ## blank space plus separator
}
... |
PUT /contract_doc_categories/1 PUT /contract_doc_categories/1.json | def update
@contract_doc_category = ContractDocCategory.find(params[:id])
respond_to do |format|
if @contract_doc_category.update_attributes(params[:contract_doc_category])
format.html { redirect_to @contract_doc_category, notice: 'Contract doc category was successfully updated.' }
format... |
remove leading and trailing whitespace from expression | def trim_whitespace
@expression.strip!
end |
PATCH/PUT /admin_panels/1 PATCH/PUT /admin_panels/1.json | def update
respond_to do |format|
if @admin_panel.update(admin_panel_params)
format.html { redirect_to @admin_panel, notice: 'Admin panel was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @a... |
POST /citizens POST /citizens.json | def create
@citizen = Citizen.new(citizen_params)
@citizen.credits = 1000
unless current_user
@user = User.new(email: params[:email], password: params[:password], password_confirmation: params[:password_confirmation])
unless @user.save
respond_to do |format|
format.html { ren... |
Simulates the user pressing the alt key and hold it down until do_alt_up() is called or a new page is loaded. | def alt_key_down
command 'altKeyDown'
end |
Returns the delay in seconds | def delay
if @delay_den != 0
@delay_num/@delay_den
else
@delay_num/100
end
end |
end test Test that the graph class will not let you to_s on an incomplete graph | def test_graph_to_s_incomplete
sut_graph = Graph.new
sut_graph.name="test_graph"
#sut_graph.type=:digraph
sut_graph.node_style=:ellipse
sut_graph.add_edge("TEST1" , "TEST2" , "take_me_to_test_2")
assert_raises RuntimeError do
returned_obj = sut_graph.to_s
end # end asser... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.