_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 30
4.3k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q900 | ActionAccess.UserUtilities.can? | train | def can?(action, resource, options = {})
keeper = ActionAccess::Keeper.instance
clearance_levels = Array(clearance_levels())
| ruby | {
"resource": ""
} |
q901 | Telegram.TelegramBase.send_image | train | def send_image(path, refer, &callback)
if @type == 'encr_chat'
logger.warn("Currently telegram-cli has a bug with send_typing, then prevent this for safety")
return
| ruby | {
"resource": ""
} |
q902 | Telegram.TelegramBase.send_image_url | train | def send_image_url(url, opt, refer, &callback)
begin
opt = {} if opt.nil?
http = EM::HttpRequest.new(url, :connect_timeout => 2, :inactivity_timeout => 5).get opt
file = Tempfile.new(['image', 'jpg'])
http.stream { |chunk|
file.write(chunk)
}
http.callback {
file.close
type = FastImage.type(file.path)
if %i(jpeg png gif).include?(type)
send_image(file.path, refer, &callback)
| ruby | {
"resource": ""
} |
q903 | Telegram.TelegramBase.send_video | train | def send_video(path, refer, &callback)
fail_back(&callback) if not File.exist?(path)
| ruby | {
"resource": ""
} |
q904 | Telegram.TelegramMessage.reply | train | def reply(type, content, target=nil, &callback)
target = @target if target.nil?
case type
when :text
target.send_message(content, self, &callback)
when :image
option = nil
content, option = content if content.class == Array
if content.include?('http')
target.method(:send_image_url).call(content, option, self, &callback)
| ruby | {
"resource": ""
} |
q905 | Telegram.API.update! | train | def update!(&cb)
done = false
EM.synchrony do
multi = EM::Synchrony::Multi.new
multi.add :profile, update_profile!
multi.add :contacts, update_contacts!
multi.add :chats, update_chats!
multi.perform
done = true
end
check_done = Proc.new {
if done
@starts_at = Time.now
cb.call unless | ruby | {
"resource": ""
} |
q906 | Telegram.API.update_profile! | train | def update_profile!
assert!
callback = Callback.new
@profile = nil
@connection.communicate('get_self') do |success, data|
if success
callback.trigger(:success)
contact = TelegramContact.pick_or_new(self, data)
| ruby | {
"resource": ""
} |
q907 | Telegram.API.update_contacts! | train | def update_contacts!
assert!
callback = Callback.new
@contacts = []
@connection.communicate('contact_list') do |success, data|
if success and data.class == Array
callback.trigger(:success)
data.each { |contact|
contact = TelegramContact.pick_or_new(self, contact)
| ruby | {
"resource": ""
} |
q908 | Telegram.API.update_chats! | train | def update_chats!
assert!
callback = Callback.new
collected = 0
collect_done = Proc.new do |id, data, count|
collected += 1
@chats << TelegramChat.new(self, data)
callback.trigger(:success) if collected == count
end
collect = Proc.new do |id, count|
@connection.communicate(['chat_info', "chat\##{id}"]) do |success, data|
collect_done.call(id, data, count) if success
end
end
@chats = []
@connection.communicate('dialog_list') do |success, data|
if success and data.class == Array
chatsize = data.count { |chat| chat['peer_type'] == 'chat' }
| ruby | {
"resource": ""
} |
q909 | Telegram.API.send_contact | train | def send_contact(peer, phone, first_name, last_name)
assert!
| ruby | {
"resource": ""
} |
q910 | Telegram.API.download_attachment | train | def download_attachment(type, seq, &callback)
assert!
raise "Type mismatch" unless %w(photo video audio).include?(type)
| ruby | {
"resource": ""
} |
q911 | Telegram.Event.format_message | train | def format_message
message = Message.new
message.id = @id
message.text = @raw_data['text'] ||= ''
media = @raw_data['media']
message.type = media ? media['type'] : 'text'
message.raw_from = @raw_data['from']['peer_id']
message.from_type = @raw_data['from']['peer_type']
message.raw_to = @raw_data['to']['peer_id']
message.to_type = @raw_data['to']['peer_type']
from = @client.contacts.find { |c| c.id == message.raw_from }
to = @client.contacts.find { |c| c.id == message.raw_to }
to = @client.chats.find { |c| c.id == message.raw_to } if to.nil?
message.from | ruby | {
"resource": ""
} |
q912 | Telegram.Connection.communicate | train | def communicate(*messages, &callback)
@available = false
@data = ''
@callback = callback
messages = messages.first if messages.size | ruby | {
"resource": ""
} |
q913 | Telegram.Connection.receive_data | train | def receive_data(data)
@data << data
return unless data.index("\n\n")
begin
result = _receive_data(@data)
rescue
raise
result = nil
end
| ruby | {
"resource": ""
} |
q914 | Telegram.ConnectionPool.acquire | train | def acquire(&callback)
acq = Proc.new {
conn = self.find { |conn| conn.available? }
if not conn.nil? and conn.connected?
| ruby | {
"resource": ""
} |
q915 | Telegram.Client.execute | train | def execute
cli_arguments = Telegram::CLIArguments.new(@config)
command = "'#{@config.daemon}' #{cli_arguments.to_s}"
| ruby | {
"resource": ""
} |
q916 | Telegram.Client.poll | train | def poll
logger.info("Start polling for events")
while (data = @stdout.gets)
begin
brace = data.index('{')
data = data[brace..-2]
| ruby | {
"resource": ""
} |
q917 | Telegram.Client.connect | train | def connect(&block)
logger.info("Trying to start telegram-cli and then connect")
@connect_callback = block
process_data
| ruby | {
"resource": ""
} |
q918 | Poseidon.MessageSet.flatten | train | def flatten
messages = struct.messages.map do |message|
if message.compressed?
s = message.decompressed_value
| ruby | {
"resource": ""
} |
q919 | Poseidon.MessagesForBroker.add | train | def add(message, partition_id)
@messages << message
@topics[message.topic] ||= {}
@topics[message.topic][partition_id] | ruby | {
"resource": ""
} |
q920 | Poseidon.MessagesForBroker.build_protocol_objects | train | def build_protocol_objects(compression_config)
@topics.map do |topic, messages_by_partition|
codec = compression_config.compression_codec_for_topic(topic)
messages_for_partitions = messages_by_partition.map do |partition, messages|
message_set = MessageSet.new(messages)
if codec
| ruby | {
"resource": ""
} |
q921 | Poseidon.MessagesToSendBatch.messages_for_brokers | train | def messages_for_brokers
messages_for_broker_ids = {}
@messages.each do |message|
partition_id, broker_id = @message_conductor.destination(message.topic,
message.key)
# Create a | ruby | {
"resource": ""
} |
q922 | Poseidon.Connection.produce | train | def produce(required_acks, timeout, messages_for_topics)
ensure_connected
req = ProduceRequest.new( request_common(:produce),
required_acks,
timeout,
messages_for_topics) | ruby | {
"resource": ""
} |
q923 | Poseidon.Connection.fetch | train | def fetch(max_wait_time, min_bytes, topic_fetches)
ensure_connected
req = FetchRequest.new( request_common(:fetch),
REPLICA_ID,
max_wait_time,
| ruby | {
"resource": ""
} |
q924 | Poseidon.Connection.topic_metadata | train | def topic_metadata(topic_names)
ensure_connected
req = MetadataRequest.new( request_common(:metadata),
| ruby | {
"resource": ""
} |
q925 | Poseidon.ClusterMetadata.update | train | def update(topic_metadata_response)
update_brokers(topic_metadata_response.brokers)
| ruby | {
"resource": ""
} |
q926 | Poseidon.MessageConductor.destination | train | def destination(topic, key = nil)
topic_metadata = topic_metadatas[topic]
if topic_metadata && topic_metadata.leader_available?
partition_id = determine_partition(topic_metadata, key)
broker_id = topic_metadata.partition_leader(partition_id) || NO_BROKER
| ruby | {
"resource": ""
} |
q927 | Poseidon.PartitionConsumer.fetch | train | def fetch(options = {})
fetch_max_wait = options.delete(:max_wait_ms) || max_wait_ms
fetch_max_bytes = options.delete(:max_bytes) || max_bytes
fetch_min_bytes = options.delete(:min_bytes) || min_bytes
if options.keys.any?
raise ArgumentError, "Unknown options: #{options.keys.inspect}"
end
topic_fetches = build_topic_fetch_request(fetch_max_bytes)
fetch_response = @connection.fetch(fetch_max_wait, fetch_min_bytes, topic_fetches)
topic_response = fetch_response.topic_fetch_responses.first
partition_response = topic_response.partition_fetch_responses.first
unless partition_response.error == Errors::NO_ERROR_CODE
if @offset < 0 &&
Errors::ERROR_CODES[partition_response.error] == Errors::OffsetOutOfRange
@offset = :earliest_offset
return fetch(options)
| ruby | {
"resource": ""
} |
q928 | Poseidon.Producer.send_messages | train | def send_messages(messages)
raise Errors::ProducerShutdownError if @shutdown
if !messages.respond_to?(:each)
raise ArgumentError, "messages must respond to #each"
| ruby | {
"resource": ""
} |
q929 | TTY.Screen.size | train | def size
size = size_from_java
size ||= size_from_win_api
size ||= size_from_ioctl
size ||= size_from_io_console
size ||= size_from_readline
size ||= size_from_tput | ruby | {
"resource": ""
} |
q930 | TTY.Screen.size_from_win_api | train | def size_from_win_api(verbose: nil)
require 'fiddle'
kernel32 = Fiddle::Handle.new('kernel32')
get_std_handle = Fiddle::Function.new(kernel32['GetStdHandle'],
[-Fiddle::TYPE_INT], Fiddle::TYPE_INT)
get_console_buffer_info = Fiddle::Function.new(
kernel32['GetConsoleScreenBufferInfo'],
[Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT)
| ruby | {
"resource": ""
} |
q931 | TTY.Screen.size_from_java | train | def size_from_java(verbose: nil)
return unless jruby?
require 'java'
java_import 'jline.TerminalFactory'
terminal = TerminalFactory.get
size = [terminal.get_height, terminal.get_width]
| ruby | {
"resource": ""
} |
q932 | TTY.Screen.size_from_ioctl | train | def size_from_ioctl
return if jruby?
return unless @output.respond_to?(:ioctl)
format = 'SSSS'
buffer = ([0] * format.size).pack(format)
if ioctl?(TIOCGWINSZ, buffer) || ioctl?(TIOCGWINSZ_PPC, buffer)
| ruby | {
"resource": ""
} |
q933 | TTY.Screen.size_from_readline | train | def size_from_readline
if defined?(Readline) && Readline.respond_to?(:get_screen_size)
size = Readline.get_screen_size
| ruby | {
"resource": ""
} |
q934 | TTY.Screen.size_from_tput | train | def size_from_tput
return unless @output.tty?
lines = run_command('tput', 'lines').to_i
cols = run_command('tput', 'cols').to_i
[lines, | ruby | {
"resource": ""
} |
q935 | TTY.Screen.size_from_stty | train | def size_from_stty
return unless @output.tty?
out = run_command('stty', 'size')
return unless out
size = out.split.map(&:to_i)
| ruby | {
"resource": ""
} |
q936 | TTY.Screen.run_command | train | def run_command(*args)
require 'tempfile'
out = Tempfile.new('tty-screen')
result = system(*args, out: out.path, err: File::NULL)
| ruby | {
"resource": ""
} |
q937 | MultiMail.Service.validate_options | train | def validate_options(options, raise_error_if_unrecognized = true)
keys = []
for key, value in options
unless value.nil?
keys << key
end
end
missing = requirements - keys
unless missing.empty?
raise ArgumentError, "Missing | ruby | {
"resource": ""
} |
q938 | Crass.Parser.consume_at_rule | train | def consume_at_rule(input = @tokens)
rule = {}
rule[:tokens] = input.collect do
rule[:name] = input.consume[:value]
rule[:prelude] = []
while token = input.consume
node = token[:node]
if node == :comment # Non-standard.
next
elsif node == :semicolon
break
elsif node === :'{'
# Note: The spec says the block should _be_ the consumed simple
# block, but Simon Sapin's CSS parsing tests and tinycss2 expect
# only the _value_ of the consumed simple block here. I assume | ruby | {
"resource": ""
} |
q939 | Crass.Parser.consume_component_value | train | def consume_component_value(input = @tokens)
return nil unless token = input.consume
case token[:node]
when :'{', :'[', :'('
consume_simple_block(input)
when :function
if token.key?(:name)
# This is a parsed function, not a function token. This step isn't
# mentioned in | ruby | {
"resource": ""
} |
q940 | Crass.Parser.consume_declaration | train | def consume_declaration(input = @tokens)
declaration = {}
value = []
declaration[:tokens] = input.collect do
declaration[:name] = input.consume[:value]
next_token = input.peek
while next_token && next_token[:node] == :whitespace
input.consume
next_token = input.peek
end
unless next_token && next_token[:node] == :colon
# Parse error.
#
# Note: The spec explicitly says to return nothing here, but Simon
# Sapin's CSS parsing tests expect an error node.
return create_node(:error, :value => 'invalid')
end
input.consume
until input.peek.nil?
value << consume_component_value(input)
end
end
# Look for !important.
important_tokens = value.reject {|token|
node = token[:node]
node == :whitespace || node == :comment || node == :semicolon
}.last(2)
if important_tokens.size == 2 &&
important_tokens[0][:node] == :delim &&
important_tokens[0][:value] == '!' &&
important_tokens[1][:node] == :ident &&
| ruby | {
"resource": ""
} |
q941 | Crass.Parser.consume_declarations | train | def consume_declarations(input = @tokens, options = {})
declarations = []
while token = input.consume
case token[:node]
# Non-standard: Preserve comments, semicolons, and whitespace.
when :comment, :semicolon, :whitespace
declarations << token unless options[:strict]
when :at_keyword
# When parsing a style rule, this is a parse error. Otherwise it's
# not.
input.reconsume
declarations << consume_at_rule(input)
when :ident
decl_tokens = [token]
while next_token = input.peek
break if next_token[:node] == :semicolon
decl_tokens << consume_component_value(input)
end
if decl = consume_declaration(TokenScanner.new(decl_tokens))
declarations << decl
end
else
# Parse error (invalid property name, etc.).
#
| ruby | {
"resource": ""
} |
q942 | Crass.Parser.consume_function | train | def consume_function(input = @tokens)
function = {
:name => input.current[:value],
:value => [],
:tokens => [input.current] # Non-standard, used for serialization.
}
function[:tokens].concat(input.collect {
while token = input.consume
case token[:node]
when :')'
break
# Non-standard.
| ruby | {
"resource": ""
} |
q943 | Crass.Parser.consume_qualified_rule | train | def consume_qualified_rule(input = @tokens)
rule = {:prelude => []}
rule[:tokens] = input.collect do
while true
unless token = input.consume
# Parse error.
#
# Note: The spec explicitly says to return nothing here, but Simon
# Sapin's CSS parsing tests expect an error node.
return create_node(:error, :value => 'invalid')
end
if token[:node] == :'{'
# Note: The spec says the block should _be_ the consumed simple
# block, but Simon Sapin's CSS parsing tests and tinycss2 expect
# only the _value_ of the consumed simple block here. I assume I'm
# interpreting the spec too literally, so I'm going with the
# tinycss2 behavior.
rule[:block] = consume_simple_block(input)[:value]
break
elsif token[:node] == :simple_block && token[:start] == '{'
# Note: The spec says the block should _be_ the simple block, but
| ruby | {
"resource": ""
} |
q944 | Crass.Parser.consume_rules | train | def consume_rules(flags = {})
rules = []
while token = @tokens.consume
case token[:node]
# Non-standard. Spec says to discard comments and whitespace, but we
# keep them so we can serialize faithfully.
when :comment, :whitespace
rules << token
when :cdc, :cdo
unless flags[:top_level]
@tokens.reconsume
rule = consume_qualified_rule
rules << rule if rule
| ruby | {
"resource": ""
} |
q945 | Crass.Parser.consume_simple_block | train | def consume_simple_block(input = @tokens)
start_token = input.current[:node]
end_token = BLOCK_END_TOKENS[start_token]
block = {
:start => start_token.to_s,
:end => end_token.to_s,
:value => [],
:tokens => [input.current] # Non-standard. Used for serialization.
}
block[:tokens].concat(input.collect do
| ruby | {
"resource": ""
} |
q946 | Crass.Parser.parse_component_value | train | def parse_component_value(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
return create_node(:error, :value => 'empty')
end
value = consume_component_value(input)
| ruby | {
"resource": ""
} |
q947 | Crass.Parser.parse_component_values | train | def parse_component_values(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
tokens = []
while token | ruby | {
"resource": ""
} |
q948 | Crass.Parser.parse_declaration | train | def parse_declaration(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
# Syntax error.
return create_node(:error, :value => 'empty')
elsif input.peek[:node] != :ident
# | ruby | {
"resource": ""
} |
q949 | Crass.Parser.parse_declarations | train | def parse_declarations(input = @tokens, options = {})
input = TokenScanner.new(input) | ruby | {
"resource": ""
} |
q950 | Crass.Parser.parse_rule | train | def parse_rule(input = @tokens)
input = TokenScanner.new(input) unless input.is_a?(TokenScanner)
while input.peek && input.peek[:node] == :whitespace
input.consume
end
if input.peek.nil?
# Syntax error.
return create_node(:error, :value => 'empty')
elsif input.peek[:node] == :at_keyword
rule = consume_at_rule(input)
else
| ruby | {
"resource": ""
} |
q951 | Crass.Parser.parse_value | train | def parse_value(nodes)
nodes = [nodes] unless nodes.is_a?(Array)
string = String.new
nodes.each do |node|
case node[:node]
when :comment, :semicolon
next
when :at_keyword, :ident
string << node[:value]
when :function
if node[:value].is_a?(String)
string << node[:value]
string << '('
else
string << parse_value(node[:tokens])
| ruby | {
"resource": ""
} |
q952 | Crass.Tokenizer.consume_bad_url | train | def consume_bad_url
text = String.new
until @s.eos?
if valid_escape?
text << consume_escaped
elsif valid_escape?(@s.peek(2))
@s.consume
text << consume_escaped
else
| ruby | {
"resource": ""
} |
q953 | Crass.Tokenizer.consume_comments | train | def consume_comments
if @s.peek(2) == '/*'
@s.consume
@s.consume
if text = @s.scan_until(RE_COMMENT_CLOSE)
text.slice!(-2, 2)
else
# Parse error.
| ruby | {
"resource": ""
} |
q954 | Crass.Tokenizer.consume_escaped | train | def consume_escaped
return "\ufffd" if @s.eos?
if hex_str = @s.scan(RE_HEX)
@s.consume if @s.peek =~ RE_WHITESPACE
codepoint = hex_str.hex
if codepoint == 0 ||
codepoint.between?(0xD800, 0xDFFF) ||
| ruby | {
"resource": ""
} |
q955 | Crass.Tokenizer.consume_ident | train | def consume_ident
value = consume_name
if @s.peek == '('
@s.consume
if value.downcase == 'url'
@s.consume while @s.peek(2) =~ RE_WHITESPACE_ANCHORED
if @s.peek(2) =~ RE_QUOTED_URL_START
create_token(:function, :value => value)
else
| ruby | {
"resource": ""
} |
q956 | Crass.Tokenizer.consume_name | train | def consume_name
result = String.new
until @s.eos?
if match = @s.scan(RE_NAME)
result << match
next
end
char = @s.consume
if valid_escape?
result << consume_escaped
# Non-standard: IE * hack
| ruby | {
"resource": ""
} |
q957 | Crass.Tokenizer.consume_numeric | train | def consume_numeric
number = consume_number
if start_identifier?(@s.peek(3))
create_token(:dimension,
:repr => number[0],
:type => number[2],
:unit => consume_name,
:value => number[1])
| ruby | {
"resource": ""
} |
q958 | Crass.Tokenizer.consume_string | train | def consume_string(ending = nil)
ending = @s.current if ending.nil?
value = String.new
until @s.eos?
case char = @s.consume
when ending
break
when "\n"
# Parse error.
@s.reconsume
return create_token(:bad_string,
:error => true,
:value => value)
when '\\'
case @s.peek
when ''
| ruby | {
"resource": ""
} |
q959 | Crass.Tokenizer.consume_unicode_range | train | def consume_unicode_range
value = @s.scan(RE_HEX) || String.new
while value.length < 6
break unless @s.peek == '?'
value << @s.consume
end
range = {}
if value.include?('?')
range[:start] = value.gsub('?', '0').hex
range[:end] = value.gsub('?', 'F').hex
return create_token(:unicode_range, range)
end
| ruby | {
"resource": ""
} |
q960 | Crass.Tokenizer.consume_url | train | def consume_url
value = String.new
@s.scan(RE_WHITESPACE)
until @s.eos?
case char = @s.consume
when ')'
break
when RE_WHITESPACE
@s.scan(RE_WHITESPACE)
if @s.eos? || @s.peek == ')'
@s.consume
break
else
return create_token(:bad_url, :value => value + consume_bad_url)
| ruby | {
"resource": ""
} |
q961 | Crass.Tokenizer.convert_string_to_number | train | def convert_string_to_number(str)
matches = RE_NUMBER_STR.match(str)
s = matches[:sign] == '-' ? -1 : 1
i = matches[:integer].to_i
f = matches[:fractional].to_i
d = matches[:fractional] | ruby | {
"resource": ""
} |
q962 | Crass.Tokenizer.preprocess | train | def preprocess(input)
input = input.to_s.encode('UTF-8',
:invalid => :replace,
:undef => :replace)
| ruby | {
"resource": ""
} |
q963 | Crass.Tokenizer.start_identifier? | train | def start_identifier?(text = nil)
text = @s.current + @s.peek(2) if text.nil?
case text[0]
when '-'
nextChar = text[1]
!!(nextChar == '-' || nextChar =~ RE_NAME_START || valid_escape?(text[1, 2]))
| ruby | {
"resource": ""
} |
q964 | Crass.Tokenizer.start_number? | train | def start_number?(text = nil)
text = @s.current + @s.peek(2) if text.nil?
case text[0]
when '+', '-'
!!(text[1] =~ RE_DIGIT || (text[1] == '.' && text[2] =~ RE_DIGIT))
when | ruby | {
"resource": ""
} |
q965 | Mongoid.Autoinc.assign! | train | def assign!(field)
options = self.class.incrementing_fields[field]
fail AutoIncrementsError if options[:auto]
fail | ruby | {
"resource": ""
} |
q966 | Mongoid.Autoinc.update_auto_increments | train | def update_auto_increments
self.class.incrementing_fields.each do |field, options|
| ruby | {
"resource": ""
} |
q967 | Mongoid.Autoinc.increment! | train | def increment!(field, options)
options = options.dup
model_name = (options.delete(:model_name) || self.class.model_name).to_s
options[:scope] = evaluate_scope(options[:scope]) if options[:scope]
options[:step] = evaluate_step(options[:step]) if options[:step]
| ruby | {
"resource": ""
} |
q968 | Mongoid.Autoinc.evaluate_scope | train | def evaluate_scope(scope)
return send(scope) if scope.is_a? Symbol
return instance_exec(&scope) if scope.is_a? Proc
| ruby | {
"resource": ""
} |
q969 | Mongoid.Autoinc.evaluate_step | train | def evaluate_step(step)
return step if step.is_a? Integer
return evaluate_step_proc(step) if step.is_a? Proc
| ruby | {
"resource": ""
} |
q970 | Mongoid.Autoinc.evaluate_step_proc | train | def evaluate_step_proc(step_proc)
result = instance_exec(&step_proc)
| ruby | {
"resource": ""
} |
q971 | EquivalentXml.Processor.same_namespace? | train | def same_namespace?(node_1, node_2)
args = [node_1,node_2]
# CharacterData nodes shouldn't have namespaces. But in Nokogiri,
# they do. And they're invisible. And they get corrupted easily.
# So let's wilfully ignore them. And while we're at it, let's
# ignore any class that doesn't know it has a namespace.
if args.all? { |node| not node.is_namespaced? | ruby | {
"resource": ""
} |
q972 | EasyCaptcha.ControllerHelpers.generate_captcha | train | def generate_captcha
if EasyCaptcha.cache
# create cache dir
FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir)
# select all generated captchas from cache
files = Dir.glob(EasyCaptcha.cache_temp_dir + "*.png")
unless files.size < EasyCaptcha.cache_size
file = File.open(files.at(Kernel.rand(files.size)))
session[:captcha] = File.basename(file.path, '.*')
if file.mtime < EasyCaptcha.cache_expire.ago
File.unlink(file.path)
# remove speech version
File.unlink(file.path.gsub(/png\z/, "wav")) if File.exists?(file.path.gsub(/png\z/, "wav"))
else
return file.readlines.join
end
| ruby | {
"resource": ""
} |
q973 | EasyCaptcha.ControllerHelpers.generate_speech_captcha | train | def generate_speech_captcha
raise RuntimeError, "espeak disabled" unless EasyCaptcha.espeak?
if EasyCaptcha.cache
File.read(speech_captcha_cache_path(current_captcha_code))
else
wav_file = Tempfile.new("#{current_captcha_code}.wav") | ruby | {
"resource": ""
} |
q974 | EasyCaptcha.ControllerHelpers.generate_captcha_code | train | def generate_captcha_code
session[:captcha] = EasyCaptcha.length.times.collect | ruby | {
"resource": ""
} |
q975 | EasyCaptcha.ControllerHelpers.captcha_valid? | train | def captcha_valid?(code)
return false if session[:captcha].blank? | ruby | {
"resource": ""
} |
q976 | EasyCaptcha.ViewHelpers.captcha_tag | train | def captcha_tag(*args)
options = { :alt => 'captcha', :width => EasyCaptcha.image_width, :height => EasyCaptcha.image_height }
| ruby | {
"resource": ""
} |
q977 | RGallery.Photo.source_photos | train | def source_photos
return [] unless sources.kind_of? Array
@source_photos ||= sources.map do |source|
| ruby | {
"resource": ""
} |
q978 | RGallery.Photo.sources= | train | def sources= sources = []
return unless sources.kind_of? Array
@sources = | ruby | {
"resource": ""
} |
q979 | Authenticate.Configuration.modules | train | def modules
modules = @modules.dup # in case the user pushes any on
modules << @authentication_strategy
modules << :db_password
modules << :password_reset
| ruby | {
"resource": ""
} |
q980 | Authenticate.Session.login | train | def login(user)
@current_user = user
@current_user.generate_session_token if user.present?
message = catch(:failure) do
Authenticate.lifecycle.run_callbacks(:after_set_user, @current_user, self, event: :authentication)
Authenticate.lifecycle.run_callbacks(:after_authentication, @current_user, self, | ruby | {
"resource": ""
} |
q981 | Authenticate.Controller.require_login | train | def require_login
debug "!!!!!!!!!!!!!!!!!! controller#require_login " # logged_in? #{logged_in?}"
unauthorized unless logged_in?
message = catch(:failure) do
current_user = authenticate_session.current_user
| ruby | {
"resource": ""
} |
q982 | Authenticate.Controller.unauthorized | train | def unauthorized(msg = t('flashes.failure_when_not_signed_in'))
authenticate_session.logout
respond_to do |format|
format.any(:js, :json, :xml) { head | ruby | {
"resource": ""
} |
q983 | JadePug.Config.method_missing | train | def method_missing(name, *args, &block)
return super if block
case args.size
when 0
# config.client?
if name =~ /\A(\w+)\?\z/
!!(respond_to?($1) ? send($1) : instance_variable_get("@#{ $1 }"))
# config.client
elsif name =~ /\A(\w+)\z/
instance_variable_get("@#{ $1 }")
else
super
end
| ruby | {
"resource": ""
} |
q984 | JadePug.Config.to_hash | train | def to_hash
instance_variables.each_with_object({}) do |var, h|
| ruby | {
"resource": ""
} |
q985 | JadePug.Compiler.prepare_options | train | def prepare_options(options)
options = engine.config.to_hash.merge(options)
options.keys.each { |k| options[k.to_s.gsub(/_([a-z])/) { | ruby | {
"resource": ""
} |
q986 | JadePug.ShippedCompiler.read_compiler_source | train | def read_compiler_source(path)
raise engine::CompilerError, "Couldn't | ruby | {
"resource": ""
} |
q987 | JadePug.SystemCompiler.version | train | def version
stdout, exit_status = Open3.capture2 "node", "--eval", \
"console.log(require(#{ JSON.dump(File.join(npm_package_path, "package.json")) }).version)"
| ruby | {
"resource": ""
} |
q988 | JadePug.SystemCompiler.check_npm_package! | train | def check_npm_package!
exit_status = Open3.capture2("node", "--eval", npm_package_require_snippet)[1]
unless exit_status.success?
raise engine::CompilerError, \
%{No #{ | ruby | {
"resource": ""
} |
q989 | Rufus::Lua.StateMixin.loadstring_and_call | train | def loadstring_and_call(s, bndng, filename, lineno)
bottom = stack_top
chunk = filename ? "#{filename}:#{lineno}" : 'line'
err = Lib.luaL_loadbuffer(@pointer, s, s.bytesize, chunk)
fail_if_error('eval:compile', err, | ruby | {
"resource": ""
} |
q990 | Rufus::Lua.StateMixin.stack_to_s | train | def stack_to_s
# warning : don't touch at stack[0]
s = (1..stack_top).inject([]) { |a, i|
type, tname = stack_type_at(i)
val =
if type == TSTRING
"\"#{stack_fetch(i)}\""
| ruby | {
"resource": ""
} |
q991 | Rufus::Lua.StateMixin.stack_push | train | def stack_push(o)
return stack_push(o.to_lua) if o.respond_to?(:to_lua)
case o
when NilClass then Lib.lua_pushnil(@pointer)
when TrueClass then Lib.lua_pushboolean(@pointer, 1)
when FalseClass then Lib.lua_pushboolean(@pointer, 0)
when Integer then Lib.lua_pushinteger(@pointer, o)
when Float then Lib.lua_pushnumber(@pointer, o)
when String then Lib.lua_pushlstring(@pointer, o, o.bytesize)
when Symbol then Lib.lua_pushlstring(@pointer, o.to_s, | ruby | {
"resource": ""
} |
q992 | Rufus::Lua.StateMixin.stack_push_hash | train | def stack_push_hash(h)
Lib.lua_createtable(@pointer, 0, h.size)
# since we already know the size of the table...
h.each do |k, v|
| ruby | {
"resource": ""
} |
q993 | Rufus::Lua.StateMixin.stack_push_array | train | def stack_push_array(a)
Lib.lua_createtable(@pointer, a.size, 0)
# since we already know the size of the table...
a.each_with_index do |e, i|
| ruby | {
"resource": ""
} |
q994 | SeamlessDatabasePool.ControllerFilter.set_read_only_connection_for_block | train | def set_read_only_connection_for_block(action)
read_pool_method = nil
if session
read_pool_method = session[:next_request_db_connection]
session.delete(:next_request_db_connection) if session[:next_request_db_connection]
end
read_pool_method ||= seamless_database_pool_options[action.to_sym] || | ruby | {
"resource": ""
} |
q995 | Rufus::Lua.Function.call | train | def call(*args)
bottom = stack_top
load_onto_stack
# load function on stack
args.each { |arg| stack_push(arg) }
| ruby | {
"resource": ""
} |
q996 | Rufus::Lua.Coroutine.resume | train | def resume(*args)
bottom = stack_top
fetch_library_method('coroutine.resume').load_onto_stack
| ruby | {
"resource": ""
} |
q997 | Rufus::Lua.Table.[]= | train | def []=(k, v)
load_onto_stack
stack_push(k)
stack_push(v)
| ruby | {
"resource": ""
} |
q998 | Rufus::Lua.Table.to_h | train | def to_h
load_onto_stack
table_pos = stack_top
Lib.lua_pushnil(@pointer)
h = {}
while Lib.lua_next(@pointer, table_pos) != 0 do
value = stack_fetch(-1)
value.load_onto_stack if value.is_a?(Ref)
key = stack_fetch(-2)
| ruby | {
"resource": ""
} |
q999 | Rufus::Lua.Table.to_a | train | def to_a(pure=true)
h = self.to_h
pure && h.keys.find { |k| not [ Float ].include?(k.class) } &&
fail('cannot turn hash into array, some keys are not numbers')
a_keys = (1..objlen).to_a.collect { |k| k.to_f } | ruby | {
"resource": ""
} |