anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
renvoie un tableau de cases contenant les erreurs qu'il y a dans la grille (lorsque la case est VIDE, ce n'est pas une erreur) | def casesIncorrect
newStatutVide = StatutVide.new(VIDE)
newStatutArbre = StatutArbre.new(ARBRE)
tabCasesErr = Array.new
grille=@grille.grille
for i in 0..grille.length-1
for j in 0..grille.length-1
tabCasesErr.unshift(grille[i][j]) if (grille[i][j].statutVisible != grille[i][j].statu... |
game_hash[:home][:players].collect do |ke,va| if ke == player return va[:shoe] end end game_hash[:away][:players].collect do |k,v| if k == player return v[:shoe] end end end | def team_colors(team)
game_hash.each do |side, value|
if value[:team_name] == team
return value[:colors]
end
end
end |
HtmlAttribute = (AlphanumericAscii | "")+ Spnl ("=" Spnl (Quoted | (!">" Nonspacechar)+))? Spnl | def _HtmlAttribute
_save = self.pos
while true # sequence
_save1 = self.pos
_save2 = self.pos
while true # choice
_tmp = apply(:_AlphanumericAscii)
break if _tmp
self.pos = _save2
_tmp = match_string("-")
break if _tmp
self.pos = _save2
... |
Returns the status or pattern of percolator for this instance. | def percolator
@_percolator || instance.class.tire.percolator || nil
end |
lexer rule t__10! (T__10) (in Ingredients.g) | def t__10!
# -> uncomment the next line to manually enable rule tracing
# trace_in( __method__, 3 )
type = T__10
channel = ANTLR3::DEFAULT_CHANNEL
# - - - - main rule block - - - -
# at line 19:9: 'E'
match( 0x45 )
@state.type = type
@state.channel ... |
I'm aware that a lot of these could be oneline'd. I'll probably do that once I'm done. | def button_down(id)
# Exit on escape
if id == Gosu::KbEscape
close
end
# Cursor Movement
# NSEW = 0123
if id == Gosu::KbUp
@player.move(0)
end
if id == Gosu::KbDown
@player.move(1)
end
if id == Gosu::KbRight
@player.move(2)
end
if id == Gosu::KbLeft
@player.move(3)
end
... |
DRIVER TESTS GO BELOW THIS LINE | def assert
yield
end |
Convert document +item+ to a single string array | def item_to_a(item)
ary = []
ary << item.name
ary << item.quantity
ary << item.unit
ary << item.price
ary << item.tax
ary << item.tax2
ary << item.tax3
ary << item.amount
ary.compact
end |
Determine the list(with properties) of the running instances in the given autoscaling group if asg_name is nil it returns nil | def running_hosts_in_asg(asg_name)
return nil unless asg_name
asg = @auto_scaling.groups[asg_name]
return nil unless asg
# return a lost of maps having the list of running instances
asg.auto_scaling_instances.collect { |i|
if i.health_status != 'Healthly'
ec... |
Update properties of this object | def update!(**args)
@history_id = args[:history_id] unless args[:history_id].nil?
@id = args[:id] unless args[:id].nil?
@internal_date = args[:internal_date] unless args[:internal_date].nil?
@label_ids = args[:label_ids] unless args[:label_ids].nil?
@payload = args[:pay... |
2.8 gcd of three ints, calling 2.3 | def gcd3 (v,u,w)
if (u==v)
return gcd(v,w)
elsif (u>v)
u-=v
gcd(gcd(v,u),w)
else
gcd(gcd(u,v),w)
end
end |
Tests that course's total_fee is not nil and is greater than or equal to 0 and returns true or false. | def total_fee_is_valid?
return ((self.total_fee != nil) and (self.total_fee >= 0))
end |
Enqueues a notification to be sent in the background via the persistent TCP socket, assuming apn_sender is running (or will be soon) | def notify_async(token, opts = {})
token = token.to_s.gsub(/\W/, '')
if defined?(Resque)
Resque.enqueue(APN::NotificationJob, token, opts)
else
Thread.new do
APN.notify_sync(token, opts)
end
end
end |
PUT /post117s/1 PUT /post117s/1.xml | def update
@post117 = Post117.find(params[:id])
respond_to do |format|
if @post117.update_attributes(params[:post117])
format.html { redirect_to(@post117, :notice => 'Post117 was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }... |
Normalize the folder name | def normalize_filename
self.name = Pathname.normalize_filename(name)
end |
You can add fixtures and/or initialization code here to make experimenting with your gem easier. You can also use a different console, if you like. | def client
@client ||= Gamewisp::Client.new
end |
returns lowest sum of the winning and losing teams' scores | def lowest_total_score
total_game_scores = games.map { |game| game.home_goals + game.away_goals}
total_game_scores.min
end |
Method signatures: nsgettext('Fruits|apple', 'apples', 2) nsgettext(['Fruits|apple', 'apples'], 2) source://i18n//lib/i18n/gettext/helpers.rb46 | def nsgettext(msgid, msgid_plural, n = T.unsafe(nil), separator = T.unsafe(nil)); end |
PUT /categories/1 PUT /categories/1.xml | def update
@category = Category.find(params[:id])
respond_to do |format|
if @category.update_attributes(params[:category])
flash[:notice] = 'Kategoria została zapisana poprawnie.'
format.html { redirect_to([:admin, @category]) }
format.xml { head :ok }
else
format.ht... |
An HTTP GET request that operates through the router. ==== Parameters path:: The path that should go to the router as the request uri. params:: An optional hash that will end up as params in the controller instance. env:: An optional hash that is passed to the fake request. Any request options should go here (see +fake... | def get(path, params = {}, env = {}, &block)
env[:request_method] = "GET"
mock_request(path, params, env, &block)
end |
POST /aggregate_metadata POST /aggregate_metadata.json | def create
@aggregate_metadatum = AggregateMetadatum.new(params[:aggregate_metadatum])
respond_to do |format|
if @aggregate_metadatum.save
format.html { redirect_to @aggregate_metadatum, notice: 'Aggregate metadatum was successfully created.' }
format.json { render json: @aggregate_metada... |
Returns the filename of the HES Cloud file | def filename(options = {})
if file_url = url(options)
file_url.gsub(/.*\/(.*?$)/, '\1')
end
end |
determine the investment horizon (length of time) required to create a future value given a present value and interest rate present_value the value at the start of the period future_value the value at the end of the period rate the annual rate of return | def investment_horizon(rate,present_value,future_value)
pv = present_value.to_d
fv = future_value.to_d
periods = Math.log(fv/pv) / Math.log(1+rate)
end |
Fetches the next token from the scanner | def get_tk
tk = nil
if @tokens.empty? then
if @scanner_point >= @scanner.size
return nil
else
tk = @scanner[@scanner_point]
@scanner_point += 1
@read.push tk[:text]
end
else
@read.push @unget_read.shift
tk = @tokens.shift
end
if tk == n... |
questID should be the symbolic name of the quest, e.g. :Quest1 | def activateQuest(quest,color,story)
if !quest.is_a?(Symbol)
raise _INTL("The 'quest' argument should be a symbol, e.g. ':Quest1'.")
end
for i in 0...@active_quests.length
if @active_quests[i].id == quest
pbMessage("You have already started this quest.")
return
end
end
... |
The controller must return true to inform about the real deletion | def delete(sObjectType)
hParams = _get_object_params(sObjectType, :delete_e, :delete, true)
bState = @oProvider.delete(sObjectType, hParams)
@ObjectData.delete(sObjectType) if bState
bState
end |
Write a method that takes in 2 numbers and prints their sum, then call that method. | def sum (a, b)
puts a + b
end |
GET /party_lists GET /party_lists.json | def index
@party_lists = PartyList.all.order(:id)
end |
Back propagate the error | def propagate(rate = 0.1, target = nil)
error = 0.0
# Is neuron in output layer
if !target.nil?
# Eq. 10.
@error.responsibility = @error.projected = target - @activation
else
# The rest of the neuron compute their error responsibilities by back-
# propagation
... |
OPTIONAL Check if this record should be included in the batch save We need to somehow still update the model even if the record should not be saved to xero. This is causing some items to not not archive or void since they the remote server is already voided | def should_save_record?(record, model)
true
end |
Never trust parameters from the scary internet, only allow the white list through. | def friend_params
params.permit(:friend_id)
end |
Return templates directory path. | def templates_dir
return File.join(File.dirname(__FILE__), 'server/templates')
end |
Displays documentation for +req+ on +res+, whether that be HTML or some asset. | def show_documentation req, res
store, path = documentation_source req.path
if_modified_since req, res, store.cache_path
generator = generator_for store
case path
when nil, '', 'index.html' then
res.body = generator.generate_index
when 'table_of_contents.html' then
res.body = gene... |
GET /review_images/new GET /review_images/new.json | def new
@review_image = ReviewImage.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @review_image }
end
end |
returns an infinite byte stream to xor against arguments are arrays | def AES256_ctr key, iv
cipher = OpenSSL::Cipher::AES.new(256, :ECB)
cipher.encrypt
cipher.padding = 0
cipher.key = key[..31].map(&:chr).join
counter = iv[..15]
f = Fiber.new do
loop do
enc = cipher.update(counter.map(&:chr).join)
enc.bytes.each {|b| Fiber.yield b}
... |
Serializes information the current object | def serialize(writer)
raise StandardError, 'writer cannot be null' if writer.nil?
writer.write_date_time_value("createdDateTime", @created_date_time)
writer.write_string_value("@odata.type", @odata_type)
writer.write_string_value("reactionType", @reaction_... |
SHA1 hash in salted form | def sha1_hex
Digest::SHA1.hexdigest(salted_name)
end |
GET /photos GET /photos.json | def index
@photos = Photo.where(ip: request.remote_ip).all
end |
TODO_PROHEALTH move to an abstract level so it can be used anywhere | def file_field(form_datum, k, file_type)
file = form_datum.attachments.detect{ |a| a.section_field_id.to_s == k.to_s}
file_text = file_type == 'expirable_file' ? (file.try(:expiration_date) || '') : ''
unless file && file.file.url.include?('placeholder.jpg')
file ? (link_to file_text, file.fil... |
Returns true when the SDK is configured not to initiate HTTP requests, otherwise false. | def offline?
return @_config_service ? @_config_service.offline? : true
end |
helper method to fill the train full of passengers | def fill_train(train)
120.times { train.board(active_passenger, station) }
end |
This is needed for jdbc/sqlite, which returns timestamp columns as strings | def convert_timestamp(timestamp)
timestamp = db.to_application_timestamp(timestamp) if timestamp.is_a?(String)
timestamp
end |
if the request is from the root url (eg: console.megam.io) then no message is shown if the request is form a non root url like users/1/edit, then we show message. | def require_signin
if signed_in?
else
if request.fullpath.to_s == '/' || request.original_url.to_s == '/'
redirect_to signin_path
else
if request.fullpath.to_s.match('auth')
auth = request.env['omniauth.auth']['extra']['raw_info']
session[:auth] = { email: a... |
START Feed Action Tests | def test_get_feed
get :feed
assert_response :success
end |
Actually creates after form is filled out | def create
@list = current_user.lists.find params[:list_id]
@item = @list.items.build(item_params)
respond_to do |format|
if @item.save
format.html { redirect_to list_items_path(@list), notice: 'Item was successfully created.' }
#format.json { render :show, status: :created, location:... |
A gate which can be used to limit dangerous code to only run during provisioning or upon boot | def disruptable?
@disruptable ||=
node.firstboot_any_phase? || ENV['CHEF_BOOT_SERVICE'] == 'true'
end |
3112 Administrators cannot see other users | def index
@page_title = "CBCL - Liste af Brugere"
@sort = params[:sort] || 'users.created_at'
@order = params[:order] || "asc"
@users = current_user.get_users(:page => params[:page], :per_page => Journal.per_page, :sort => params[:sort], :order => params[:order])
if !params[:partial]
render
... |
Create new wiki page | def new
@doc_pu_wiki = DocPuWikiPage.new()
@doc_pu_wiki.use_doc_flags = true
if request.post?
# Save object
reorder_pages(@doc_pu.doc_pu_wiki_pages.all)
@doc_pu_wiki = @doc_pu.doc_pu_wiki_pages.create(parse_form params[:doc_pu_wiki])
@doc_pu_wiki.w... |
GET /ingest_responses/1 GET /ingest_responses/1.json | def show
end |
Configuration pointing to the SPEC tests and PIN tool to be used. | def load_configuration
# Default configuration.
config = File.open('pin_spec.yml', 'r') { |f| YAML.load f }
if ARGV[0]
# If the first argument is a Yaml configuration file, use that to override
# the default configuration.
if ARGV[0][-4, 4] == '.yml'
config.merge! File.open(ARGV[0], 'r') { |f... |
Call function f with a fresh variable. | def call_fresh(f)
-> (s_c) {
c = cdr(s_c)
f.call(var(c)).call(cons(car(s_c), c + 1))
}
end |
Return a Gem::Specification from this gem | def to_spec
raise NotImplementedError
end |
Eager load the inclusions for the provided documents. | def eager_load(docs)
criteria.inclusions.reject! do |metadata|
metadata.eager_load(eager_loaded_ids(docs, metadata)) if !docs.empty?
end
self.eager_loaded = true
end |
Expand a Relation Tuple Use this endpoint to expand a relation tuple. | def get_expand_with_http_info(namespace, object, relation, max_depth, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: ReadApi.get_expand ...'
end
# verify the required parameter 'namespace' is set
if @api_client.config.client_side_validation && na... |
Converts the RDoc markup tidylink into a Markdown.style link. | def handle_regexp_TIDYLINK target
text = target.text
return text unless text =~ /\{(.*?)\}\[(.*?)\]/ or text =~ /(\S+)\[(.*?)\]/
label = $1
url = $2
if url =~ /^rdoc-label:foot/ then
handle_rdoc_link url
else
gen_url url, label
end
end |
Height in pixels when in expanded state | def expanded_height
source_node[:expandedHeight].to_i
end |
A unique id for resources for this node | def resource_id(prefix)
if default_config?
[prefix, project, node_type, node_name]
else
[prefix, project, configuration, node_type, node_name]
end.compact.join("_").tr("-", '_').tr("/", "_")
end |
GET /keeps/1 GET /keeps/1.json | def show
end |
Returns an array of all the instances for this class. | def all
Maglev::PERSISTENT_ROOT[self].values
end |
GET /tasks/1 GET /tasks/1.json | def show
end |
The identifier of the CA certificate for this DB instance | def ca_certificate_identifier
@dbi.ca_certificate_identifier
end |
List of tests 1. Empty Eobqa create 2. Create with invalid data Check with nil total_fields Check with nil total_incorrect_fields Check with nil account_number Check Uniqueness of name 3. Check Eobqa count when we created and distroy Blank EOBQA | def test_blank_eobqa
eobqa = EobQa.new(:total_fields => 10, :total_incorrect_fields => 2)
assert_equal(false, eobqa.save)
end |
Lists all tapes. API Key Scope: tapes / index | def index_tapes_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: TapesApi.index_tapes ...'
end
# resource path
local_var_path = '/tapes'
# query parameters
query_params = opts[:query_params] || {}
query_params[:'li... |
remove a stock from database | def remove_stock(db,stock_ticker)
db.execute(<<-SQL
DELETE FROM stocks2
Where stock_ticker="#{stock_ticker}";
SQL
)
puts "==================================================="
puts "#{stock_ticker} has been removed from the database."
puts "=================================================... |
Sum of two points | def bbpAdd(first_point, second_point)
cxp(first_point.x + second_point.x, first_point.y + second_point.y)
end |
Change the useragent sent to the Prowl server. | def user_agent(user_agent)
@user_agent = user_agent
end |
Return a hash suitable for passing to Whitestone.run | def _whitestone_options()
{ :filter => @options.filter, :full_backtrace => @options.full_backtrace }
end |
Never trust parameters from the scary internet, only allow the white list through. | def background_params
params.require(:background).permit(:name)
end |
POST /tipocuenta POST /tipocuenta.json | def create
@tipocuentum = Tipocuentum.new(tipocuentum_params)
respond_to do |format|
if @tipocuentum.save
format.html { redirect_to @tipocuentum, notice: 'Tipocuentum was successfully created.' }
format.json { render :show, status: :created, location: @tipocuentum }
else
for... |
reduce 553 omitted reduce 554 omitted reduce 555 omitted reduce 556 omitted reduce 557 omitted reduce 558 omitted reduce 559 omitted reduce 560 omitted reduce 561 omitted reduce 562 omitted reduce 563 omitted reduce 564 omitted reduce 565 omitted reduce 566 omitted reduce 567 omitted reduce 568 omitted reduce 569 omitt... | def _reduce_574(val, _values, result)
yyerrok
result
end |
testing protected methods and everything in this module is protected | def authenticated?; super; end |
List institution by id | def show
institution = Institution.find(params[:id])
render json: { status: '200', message: "Loaded Institution with id #{params[:id]}", data: institution }, status: :ok
rescue ActiveRecord::RecordNotFound
render json: { status: '404', error: "No Institution with id #{params[:id]}", data: ... |
Update properties of this object | def update!(**args)
@next_page_token = args[:next_page_token] unless args[:next_page_token].nil?
@result_size_estimate = args[:result_size_estimate] unless args[:result_size_estimate].nil?
@threads = args[:threads] unless args[:threads].nil?
end |
Return the width and height of the named style, as a 2element array. | def dimensions(style_name=nil)
style_name ||= reflection.default_style
if style_name.equal?(:original)
original_width = from_examination(:@original_width)
original_height = from_examination(:@original_height)
[original_width, original_height]
else
resize_d... |
Method to print a list and make it look pretty input: list of hash we want to print steps: print keys as strings with corresponding value output: keys as strings and their quantity | def print_list(list)
list.each do |item, quantity| puts "#{item}: #{quantity}"
end
end |
If authorized, return the loggedin user information based on different conditionals: user has profile image and previous geolocation coordinates. | def auth
@user = current_user
render json: @user
end |
=begin To get hash value of job | def get_hash()
return @@hash;
end |
DELETE /parking_spots/1 DELETE /parking_spots/1.json | def destroy
@parking_spot = ParkingSpot.find(params[:id])
@parking_spot.destroy
respond_to do |format|
format.html { redirect_to parking_spots_url }
format.json { head :no_content }
end
end |
traverse the BBT in depth and returns the data in post order in an array | def post_order_traversal(current_node = @root)
@accumulator = []
post_order_traversal_aux(current_node)
@accumulator
end |
in a nonbooting version this should map to _add_singleton_method | def add_function function
raise "not a function #{function}" unless function.is_a? Function
raise "syserr " unless function.name.is_a? Symbol
@functions << function
end |
Append a node to the end of the list. | def append(node)
if node.head
raise ArgumentError, "Node is already in a list!"
end
node.tail = self
@head.tail = node
node.head = @head
@head = node
return added(node)
end |
Locally schedule within each basic block. | def locally_schedule_block(first_node)
# Find all the nodes in this basic block.
in_block = Set.new(nodes_in_block(first_node))
# Back up a second... our first node could be a fixed node, which
# actually has input values. Such as a branch with a condition.
# The nodes involved in that c... |
GET /customers/1 GET /customers/1.json | def show
end |
PATCH/PUT /friends/1 or /friends/1.json | def update
respond_to do |format|
if @friend.update(friend_params)
format.html { redirect_to @friend, notice: "Friend was successfully updated." }
format.json { render :show, status: :ok, location: @friend }
else
format.html { render :edit, status: :unprocessable_entity }
... |
Asserts that I see a particular tag (see HTMLAnalysis.tag) | def i_see_tag(name, opts = nil)
assert has_tag?(name, opts), __last_because + " (don't see tag <#{name} #{opts.inspect})"
end |
returns value and addr | def value_with_addr(block_num = nil)
block_num ||= @auth_block
raise Mifare::Error, "Not authenticated" unless block_num
value_ptr = FFI::MemoryPointer.new(:int32, 1)
addr_ptr = FFI::MemoryPointer.new(:uchar, 1)
res = Mifare.mifare_classic_read_value(@pointer, block_num, value_ptr, addr_ptr)
... |
End of DTM_233 Segment Details Client Specific Helper Methods End of Client Specific Helper Methods Conditions to print a Segment : Overwritten Methods | def verify_ts3_condition
Unified835Output::BenignNull.new
end |
Extract omniauth credentials from the request environment | def omniauth_credentials
if omniauth_hash = request.env['omniauth.auth']
{
provider: omniauth_hash['provider'],
uid: omniauth_hash['uid'],
email: omniauth_hash['info']['email'],
name: omniauth_hash['info']['name'],
}
else
nil
end
end |
Generated method to gather all the accepted keypresses. | def accepts
self.current_state.pressings || {}
end |
// For example, S = "abba", T = "^abba$". // ^ and $ signs are sentinels appended to each end to avoid bounds checking | def preProcess(s)
n = s.length().to_i
if n==0
return "^$"
end
ret = "^"
(0..n-1).each do |re|
ret += ('#' + s[re].to_s)
end
ret += '#$'
return ret
end |
Runs a string given in input as Ruby code or buffers it if the command is incomplete Test against level or input to check if the command has been executed | def run str
@input ||= ''
@level += str.scan(LEVEL_UP).length
@level -= str.scan(/(^|\s)end($|\s)/).length # Will probably fail with a character chain
@input += str + "\n"
if @level <= 0
tmp = input
reset
eval tmp, context
end
end |
wraper for the brand method ActiveMerchant returns master or american_express Banwire requires mastercard and amex | def get_brand(brand)
case brand
when "master"
return "mastercard"
when "american_express"
return "amex"
else
return brand
end
end |
DELETE /recipies/1 DELETE /recipies/1.json | def destroy
@recipy = Recipy.find(params[:id])
@recipy.destroy
respond_to do |format|
format.html { redirect_to recipies_url }
format.json { head :no_content }
end
end |
List Tier 1 Service Interfaces Paginated list of all Tier 1 Service Interfaces | def list_tier1_service_interfaces_0(tier_1_id, locale_service_id, opts = {})
data, _status_code, _headers = list_tier1_service_interfaces_0_with_http_info(tier_1_id, locale_service_id, opts)
data
end |
GET /passwordrecovery/remindersent The success page after the user enters email for password recovery | def reminder_sent
end |
DELETE /solos/1 DELETE /solos/1.json | def destroy
@solo.destroy
respond_to do |format|
format.html { redirect_to solos_url, notice: 'Solo was successfully destroyed.' }
format.json { head :no_content }
end
authorize @solo
end |
Constructs a dependency with +name+ and +requirements+. The last argument can optionally be the dependency type, which defaults to :runtime. | def initialize(name, *requirements)
case name
when String then # ok
when Regexp then
msg = ["NOTE: Dependency.new w/ a regexp is deprecated.",
"Dependency.new called from #{Gem.location_of_caller.join(":")}"]
warn msg.join("\n") unless Gem::Deprecate.skip
else
raise Argume... |
Initializes a LoginRadius Account object with an apikey and secret Takes in a hash containing site_name(required), api_key(required), api_secret(required) | def initialize
@site_name = ENV['SITE_NAME']
@api_key = ENV['API_KEY']
@api_secret = ENV['API_SECRET']
raise LoginRadius::Error.new, "'site_name' is a required option for Account class initialization." \
unless @site_name != '' && @site_name != nil
raise LoginRadius::Error.new, "'a... |
Create a way for the username to become encrypted | def encrypt(val)
#Usage self.encrypt(val)
return Digest::SHA1.hexdigest(val.to_s)
end |
GET /prod_cotis GET /prod_cotis.json | def index
@prod_cotis = ProdCoti.all
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.