_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q21700 | Phidgets.MotorControl.on_back_emf_update | train | def on_back_emf_update(obj=nil, &block)
@on_back_emf_update_obj = obj
@on_back_emf_update = Proc.new { |device, obj_ptr, motor, voltage|
yield self, @motors[motor], voltage, object_for(obj_ptr)
}
Klass.set_OnBackEMFUpdate_Handler(@handle, @on_back_emf_update, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21701 | Phidgets.MotorControl.on_position_update | train | def on_position_update(obj=nil, &block)
@on_position_update_obj = obj
@on_position_update = Proc.new { |device, obj_ptr, encoder, position|
yield self, @encoders[encoder], position, object_for(obj_ptr)
}
Klass.set_OnEncoderPositionUpdate_Handler(@handle, @on_position_update, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21702 | Phidgets.MotorControl.on_sensor_update | train | def on_sensor_update(obj=nil, &block)
@on_sensor_update_obj = obj
@on_sensor_update = Proc.new { |device, obj_ptr, index, value|
yield self, @sensors[index], value, object_for(obj_ptr)
}
Klass.set_OnSensorUpdate_Handler(@handle, @on_sensor_update, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21703 | Phidgets.MotorControl.ratiometric | train | def ratiometric
ptr = ::FFI::MemoryPointer.new(:int)
Klass.getRatiometric(@handle, ptr)
(ptr.get_int(0) == 0) ? false : true
end | ruby | {
"resource": ""
} |
q21704 | JSI.Base.pretty_print | train | def pretty_print(q)
q.instance_exec(self) do |obj|
text "\#<#{obj.class.to_s}"
group_sub {
nest(2) {
breakable ' '
pp obj.instance
}
}
breakable ''
text '>'
end
end | ruby | {
"resource": ""
} |
q21705 | JSI.Base.subscript_assign | train | def subscript_assign(subscript, value)
clear_memo(:[], subscript)
if value.is_a?(Base)
instance[subscript] = value.instance
else
instance[subscript] = value
end
end | ruby | {
"resource": ""
} |
q21706 | Phidgets.RFID.on_output_change | train | def on_output_change(obj=nil, &block)
@on_output_change_obj = obj
@on_output_change = Proc.new { |device, obj_ptr, index, state|
yield self, @outputs[index], (state == 0 ? false : true), object_for(obj_ptr)
}
Klass.set_OnOutputChange_Handler(@handle, @on_output_change, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21707 | Phidgets.RFID.on_tag | train | def on_tag(obj=nil, &block)
@on_tag_obj = obj
@on_tag = Proc.new { |device, obj_ptr, tag, proto|
yield self, tag.read_string, object_for(obj_ptr)
}
Klass.set_OnTag2_Handler(@handle, @on_tag, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21708 | Phidgets.RFID.on_tag_lost | train | def on_tag_lost(obj=nil, &block)
@on_tag_lost_obj = obj
@on_tag_lost = Proc.new { |device, obj_ptr, tag, proto|
yield self, tag.read_string, object_for(obj_ptr)
}
Klass.set_OnTagLost2_Handler(@handle, @on_tag_lost, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21709 | Phidgets.RFID.antenna | train | def antenna
ptr = ::FFI::MemoryPointer.new(:int)
Klass.getAntennaOn(@handle, ptr)
(ptr.get_int(0) == 0) ? false : true
end | ruby | {
"resource": ""
} |
q21710 | Phidgets.RFID.led | train | def led
ptr = ::FFI::MemoryPointer.new(:int)
Klass.getLEDOn(@handle, ptr)
(ptr.get_int(0) == 0) ? false : true
end | ruby | {
"resource": ""
} |
q21711 | Phidgets.RFID.tag_present | train | def tag_present
ptr = ::FFI::MemoryPointer.new(:int)
Klass.getTagStatus(@handle, ptr)
(ptr.get_int(0) == 0) ? false : true
end | ruby | {
"resource": ""
} |
q21712 | Phidgets.RFID.write | train | def write(tag, protocol, lock=false)
tmp = lock ? 1 : 0
Klass.write(@handle, tag, Phidgets::FFI::RFIDTagProtocol[protocol], tmp)
true
end | ruby | {
"resource": ""
} |
q21713 | Phidgets.Spatial.set_compass_correction_parameters | train | def set_compass_correction_parameters(new_mag_field, new_offset0, new_offset1, new_offset2, new_gain0, new_gain1, new_gain2, new_t0, new_t1, new_t2, new_t3, new_t4, new_t5)
Klass.setCompassCorrectionParameters(@handle, new_mag_field, new_offset0, new_offset1, new_offset2, new_gain0, new_gain1, new_gain2, new_t0, new_t1, new_t2, new_t3, new_t4, new_t5)
true
end | ruby | {
"resource": ""
} |
q21714 | Phidgets.Dictionary.open | train | def open(options)
password = (options[:password].nil? ? nil : options[:password].to_s)
if !options[:server_id].nil?
Klass.openRemote(@handle, options[:server_id].to_s, password)
else
Klass.openRemoteIP(@handle, options[:address].to_s, options[:port].to_i, password)
end
sleep 1
true
end | ruby | {
"resource": ""
} |
q21715 | Phidgets.Dictionary.delete | train | def delete(pattern)
Klass.removeKey(@handle, (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s))
true
end | ruby | {
"resource": ""
} |
q21716 | Phidgets.Dictionary.on_connect | train | def on_connect(obj=nil, &block)
@on_connect_obj = obj
@on_connect = Proc.new { |handle, obj_ptr|
# On connect, we'll need to re-add all of our change handlers
@listeners.each_pair do |pattern, (listener, proc)|
begin
next if status != :connected
Klass.set_OnKeyChange_Handler(@handle, listener, pattern, proc, pointer_for(obj))
sleep @handler_sleep
rescue
Phidgets::Log.error("#{self.class}::on_connect", $!.to_s)
end
end
yield self, object_for(obj_ptr)
}
Klass.set_OnServerConnect_Handler(@handle, @on_connect, pointer_for(obj))
sleep @handler_sleep
end | ruby | {
"resource": ""
} |
q21717 | Phidgets.Dictionary.on_disconnect | train | def on_disconnect(obj=nil, &block)
@on_disconnect_obj = obj
@on_disconnect = Proc.new { |handle, obj_ptr|
# On disconnect, we'll need to remove all of our change handlers
@listeners.each_pair do |pattern, (listener, proc)|
Klass.remove_OnKeyChange_Handler(listener.get_pointer(0))
sleep @handler_sleep
end
yield self, object_for(obj_ptr)
}
Klass.set_OnServerDisconnect_Handler(@handle, @on_disconnect, pointer_for(obj))
sleep @handler_sleep
end | ruby | {
"resource": ""
} |
q21718 | Phidgets.Dictionary.on_change | train | def on_change(pattern=".*", obj=nil, &block)
pattern = (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s)
@listeners[pattern] = [
::FFI::MemoryPointer.new(:pointer),
Proc.new { |handle, obj_ptr, key, value, reason|
yield object_for(obj_ptr), key, value, reason
}
]
Klass.set_OnKeyChange_Handler(@handle, @listeners[pattern][0], pattern, @listeners[pattern][1], pointer_for(obj))
sleep @handler_sleep
end | ruby | {
"resource": ""
} |
q21719 | Phidgets.Dictionary.remove_on_change | train | def remove_on_change(pattern=".*")
pattern = (pattern.kind_of?(Regexp) ? pattern.source : pattern.to_s)
if @listeners.has_key?(pattern)
listener, proc = @listeners.delete(pattern)
Klass.remove_OnKeyChange_Handler(listener.get_pointer(0))
sleep @handler_sleep
true
else
nil
end
end | ruby | {
"resource": ""
} |
q21720 | Iev.DbCache.fetched | train | def fetched(key)
value = self[key]
return unless value
# if value =~ /^not_found/
# value.match(/\d{4}-\d{2}-\d{2}/).to_s
# else
doc = Nokogiri::XML value
doc.at("/bibitem/fetched")&.text
# end
end | ruby | {
"resource": ""
} |
q21721 | Thumbtack.Client.action | train | def action(path, params)
response = @adapter.get(path, params)
unless response['result_code'] == 'done'
raise ResultError, response['result_code']
end
self
end | ruby | {
"resource": ""
} |
q21722 | VcoWorkflows.VcoSession.post | train | def post(endpoint, body, headers = {})
headers = { accept: :json, content_type: :json }.merge(headers)
@rest_resource[endpoint].post body, headers
end | ruby | {
"resource": ""
} |
q21723 | Phidgets.IR.on_raw_data | train | def on_raw_data(obj=nil, &block)
@on_raw_data_obj = obj
@on_raw_data = Proc.new { |device, obj_ptr, raw_data, data_length|
data = []
data_length.times { |i|
data << raw_data[i].get_int(0)
}
yield self, data, data_length, object_for(obj_ptr)
}
Klass.set_OnRawData_Handler(@handle, @on_raw_data, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21724 | Phidgets.IR.on_code | train | def on_code(obj=nil, &block)
@on_code_obj = obj
@on_code = Proc.new { |device, obj_ptr, data, data_length, bit_count, repeat|
data_string = []
data_length.times { |i|
data_string[i] = data[i].get_uchar(0).to_s(16)
}
yield self, data_string, data_length, bit_count, repeat, object_for(obj_ptr)
}
Klass.set_OnCode_Handler(@handle, @on_code, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21725 | Phidgets.IR.on_learn | train | def on_learn(obj=nil, &block)
@on_learn_obj = obj
@on_learn = Proc.new { |device, obj_ptr, int_data, data_length, code_info|
data = []
data_length.times { |i|
data[i] = int_data[i].get_uchar(0).to_s(16)
}
code_info_struct = IR_code_info.new(code_info)
yield self, data, data_length, code_info_struct, object_for(obj_ptr)
}
Klass.set_OnLearn_Handler(@handle, @on_learn, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21726 | Phidgets.IR.transmit | train | def transmit(data, code_info)
pdata = ::FFI::MemoryPointer.new(:uchar, 16)
data_ffi = []
data.size.times { |i|
data_ffi[i] = data[i].to_i(16)
}
data_ffi = ::FFI::MemoryPointer.new(:uchar, 16).write_array_of_uchar(data_ffi)
Klass.Transmit(@handle, data_ffi, code_info)
true
end | ruby | {
"resource": ""
} |
q21727 | Phidgets.IR.transmit_raw | train | def transmit_raw(data, length, carrier_frequency, duty_cycle, gap)
c_data = ::FFI::MemoryPointer.new(:int, data.size).write_array_of_int(data)
Klass.TransmitRaw(@handle, c_data, length.to_i, carrier_frequency.to_i, duty_cycle.to_i, gap.to_i)
true
end | ruby | {
"resource": ""
} |
q21728 | Phidgets.IR.last_code | train | def last_code
data_ffi = ::FFI::MemoryPointer.new(:uchar, 16)
data_length = ::FFI::MemoryPointer.new(:int)
data_length.write_int(16)
bit_count = ::FFI::MemoryPointer.new(:int)
Klass.getLastCode(@handle, data_ffi, data_length, bit_count)
data = []
data_length.get_int(0).times { |i|
data << data_ffi[i].get_uchar(0).to_s(16)
}
[data, data_length.get_int(0), bit_count.get_int(0)]
end | ruby | {
"resource": ""
} |
q21729 | Phidgets.IR.last_learned_code | train | def last_learned_code
data_ffi = ::FFI::MemoryPointer.new(:uchar, 16)
data_length = ::FFI::MemoryPointer.new(:int)
data_length.write_int(16)
code_info = ::FFI::MemoryPointer.new(IR_code_info)
Klass.getLastLearnedCode(@handle, data_ffi, data_length, code_info)
data = []
data_length.get_int(0).times { |i|
data << data_ffi[i].get_uchar(0).to_s(16)
}
code_info_struct = IR_code_info.new(code_info)
[data, data_length.get_int(0), code_info_struct]
end | ruby | {
"resource": ""
} |
q21730 | Isono.AmqpClient.publish_to | train | def publish_to(exname, message, opts={})
EventMachine.schedule {
ex = amq.exchanges[exname] || raise("Undefined exchange name : #{exname}")
case ex.type
when :topic
unless opts.has_key? :key
opts[:key] = '*'
end
end
ex.publish(Serializer.instance.marshal(message), opts)
}
end | ruby | {
"resource": ""
} |
q21731 | VcoWorkflows.Workflow.required_parameters | train | def required_parameters
required = {}
@input_parameters.each_value { |v| required[v.name] = v if v.required? }
required
end | ruby | {
"resource": ""
} |
q21732 | VcoWorkflows.Workflow.parameter | train | def parameter(parameter_name, parameter_value = nil)
if @input_parameters.key?(parameter_name)
@input_parameters[parameter_name].set parameter_value
else
$stderr.puts "\nAttempted to set a value for a non-existent WorkflowParameter!"
$stderr.puts "It appears that there is no parameter \"#{parameter}\"."
$stderr.puts "Valid parameter names are: #{@input_parameters.keys.join(', ')}"
$stderr.puts ''
fail(IOError, ERR[:no_such_parameter])
end unless parameter_value.nil?
@input_parameters[parameter_name]
end | ruby | {
"resource": ""
} |
q21733 | VcoWorkflows.Workflow.execute | train | def execute(workflow_service = nil)
# If we're not given an explicit workflow service for this execution
# request, use the one defined when we were created.
workflow_service = @service if workflow_service.nil?
# If we still have a nil workflow_service, go home.
fail(IOError, ERR[:no_workflow_service_defined]) if workflow_service.nil?
# Make sure we didn't forget any required parameters
verify_parameters
# Let's get this thing running!
@execution_id = workflow_service.execute_workflow(@id, input_parameter_json)
end | ruby | {
"resource": ""
} |
q21734 | VcoWorkflows.Workflow.log | train | def log(execution_id = nil)
execution_id = @execution_id if execution_id.nil?
log_json = @service.get_log(@id, execution_id)
VcoWorkflows::WorkflowExecutionLog.new(log_json)
end | ruby | {
"resource": ""
} |
q21735 | VcoWorkflows.Workflow.input_parameter_json | train | def input_parameter_json
tmp_params = []
@input_parameters.each_value { |v| tmp_params << v.as_struct if v.set? }
param_struct = { parameters: tmp_params }
param_struct.to_json
end | ruby | {
"resource": ""
} |
q21736 | VcoWorkflows.Workflow.verify_parameters | train | def verify_parameters
required_parameters.each do |name, wfparam|
if wfparam.required? && (wfparam.value.nil? || wfparam.value.size == 0)
fail(IOError, ERR[:param_verify_failed] << "#{name} required but not present.") # rubocop:disable Metrics/LineLength
end
end
end | ruby | {
"resource": ""
} |
q21737 | Isono.Util.default_gw_ipaddr | train | def default_gw_ipaddr
ip = case `/bin/uname -s`.rstrip
when 'Linux'
`/sbin/ip route get 8.8.8.8`.split("\n")[0].split.last
when 'SunOS'
`/sbin/ifconfig $(/usr/sbin/route -n get 1.1.1.1 | awk '$1 == "interface:" {print $2}') | awk '$1 == "inet" { print $2 }'`
else
raise "Unsupported platform to detect gateway IP address: #{`/bin/uname`}"
end
ip = ip.rstrip
raise "Failed to run command lines or empty result" if ip == '' || $?.exitstatus != 0
ip
end | ruby | {
"resource": ""
} |
q21738 | Thumbtack.Notes.list | train | def list
response = @client.get('/notes/list')
response.fetch('notes', EMPTY_ARRAY).map do |note_hash|
NoteSummary.from_hash(note_hash)
end
end | ruby | {
"resource": ""
} |
q21739 | Thumbtack.Posts.get | train | def get(options = EMPTY_HASH)
parameters = Specification.new(
tag: Types::Tags,
dt: Types::Time,
url: Types::URL,
meta: Types::Boolean
).parameters(options)
posts_from @client.get('/posts/get', parameters)
end | ruby | {
"resource": ""
} |
q21740 | Thumbtack.Posts.recent | train | def recent(options = EMPTY_HASH)
parameters = Specification.new(
tag: Types::Tags,
count: Types::Integer
).parameters(options)
posts_from @client.get('/posts/recent', parameters)
end | ruby | {
"resource": ""
} |
q21741 | Thumbtack.Posts.all | train | def all(options = EMPTY_HASH)
parameters = Specification.new(
tag: Types::Tags,
start: Types::Integer,
results: Types::Integer,
fromdt: Types::Time,
todt: Types::Time,
meta: Types::Boolean
).parameters(options)
results = @client.get('/posts/all', parameters)
results.map { |post_hash| Post.from_hash(post_hash) }
end | ruby | {
"resource": ""
} |
q21742 | Thumbtack.Posts.suggest | train | def suggest(url)
parameters = Specification.new(url: Types::URL).parameters(url: url)
Suggestion.from_array(@client.get('/posts/suggest', parameters))
end | ruby | {
"resource": ""
} |
q21743 | Thumbtack.Posts.dates | train | def dates(options = EMPTY_HASH)
parameters = Specification.new(tag: Types::Tags).parameters(options)
response = @client.get('/posts/dates', parameters)
dates_with_counts_from(response)
end | ruby | {
"resource": ""
} |
q21744 | Thumbtack.Posts.posts_from | train | def posts_from(response)
response.fetch('posts', EMPTY_ARRAY).map do |post_hash|
Post.from_hash(post_hash)
end
end | ruby | {
"resource": ""
} |
q21745 | Thumbtack.Posts.dates_with_counts_from | train | def dates_with_counts_from(response)
entries = response.fetch('dates', EMPTY_HASH).map do |date, count|
[Types::Date.deserialize(date), count.to_i]
end
Hash[entries]
end | ruby | {
"resource": ""
} |
q21746 | Phidgets.Servo.on_position_change | train | def on_position_change(obj=nil, &block)
@on_position_change_obj = obj
@on_position_change = Proc.new { |device, obj_ptr, index, position|
yield self, @servos[index], position, object_for(obj_ptr)
}
Klass.set_OnPositionChange_Handler(@handle, @on_position_change, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21747 | Phidgets.GPS.on_position_fix_status_change | train | def on_position_fix_status_change(obj=nil, &block)
@on_position_fix_status_change_obj = obj
@on_position_fix_status_change = Proc.new { |device, obj_ptr, fix_status|
yield self, (fix_status == 0 ? false : true), object_for(obj_ptr)
}
Klass.set_OnPositionFixStatusChange_Handler(@handle, @on_position_fix_status_change, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21748 | Phidgets.GPS.on_position_change | train | def on_position_change(obj=nil, &block)
@on_position_change_obj = obj
@on_position_change = Proc.new { |device, obj_ptr, lat, long, alt|
yield self, lat, long, alt, object_for(obj_ptr)
}
Klass.set_OnPositionChange_Handler(@handle, @on_position_change, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21749 | Phidgets.TemperatureSensor.on_temperature_change | train | def on_temperature_change(obj=nil, &block)
@on_temperature_change_obj = obj
@on_temperature_change = Proc.new { |device, obj_ptr, index, temperature|
yield self, @thermocouples[index], temperature, object_for(obj_ptr)
}
Klass.set_OnTemperatureChange_Handler(@handle, @on_temperature_change, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21750 | Fulfil.Request.check_auth_params | train | def check_auth_params
if (Fulfil.authentication.nil? || Fulfil.authentication[:subdomain].empty? || Fulfil.authentication[:api_key].empty?)
raise Fulfil::AuthenticationError, "Please set your subdomain and api key"
end
end | ruby | {
"resource": ""
} |
q21751 | Fulfil.Request.request | train | def request(http_method, data={}, url="")
final_url = @options[:base_url] << url
begin
case http_method
when :get
response = Curl.get(final_url, data) do |http|
http.headers['x-api-key'] = @options[:api_key]
http.headers['Accept'] = 'application/json'
end
end
rescue Curl::Err::HostResolutionError
raise Fulfil::HostResolutionError, "Invalid Subdomain"
end
parse_response response
end | ruby | {
"resource": ""
} |
q21752 | Thumbtack.Tags.get | train | def get
response = @client.get('/tags/get')
Hash[response.map { |tag, count| [tag, count.to_i] }]
end | ruby | {
"resource": ""
} |
q21753 | Thumbtack.Tags.delete | train | def delete(tag)
parameters = Specification.new(tag: Types::Tags).parameters(tag: tag)
@client.action('/tags/delete', parameters)
self
end | ruby | {
"resource": ""
} |
q21754 | Thumbtack.Tags.rename | train | def rename(old, new)
parameters = Specification.new(
old: Types::Tags,
new: Types::Tags
).parameters(old: old, new: new)
@client.action('/tags/rename', parameters)
self
end | ruby | {
"resource": ""
} |
q21755 | Wakame.Daemonize.change_privilege | train | def change_privilege(user, group=user)
Wakame.log.info("Changing process privilege to #{user}:#{group}")
uid, gid = Process.euid, Process.egid
target_uid = Etc.getpwnam(user).uid
target_gid = Etc.getgrnam(group).gid
if uid != target_uid || gid != target_gid
if pid_file && File.exist?(pid_file) && uid == 0
File.chown(target_uid, target_gid, pid_file)
end
# Change process ownership
Process.initgroups(user, target_gid)
Process::GID.change_privilege(target_gid)
Process::UID.change_privilege(target_uid)
end
rescue Errno::EPERM => e
Wakame.log.error("Couldn't change user and group to #{user}:#{group}: #{e}")
end | ruby | {
"resource": ""
} |
q21756 | VcoWorkflows.Config.to_json | train | def to_json
config = {}
config['url'] = @url
config['username'] = @username
config['password'] = @password
config['verify_ssl'] = @verify_ssl
puts JSON.pretty_generate(config)
end | ruby | {
"resource": ""
} |
q21757 | Phidgets.InterfaceKit.on_sensor_change | train | def on_sensor_change(obj=nil, &block)
@on_sensor_change_obj = obj
@on_sensor_change = Proc.new { |device, obj_ptr, index, value|
yield self, @sensors[index], value, object_for(obj_ptr)
}
Klass.set_OnSensorChange_Handler(@handle, @on_sensor_change, pointer_for(obj))
end | ruby | {
"resource": ""
} |
q21758 | DwcaHunter.Downloader.download | train | def download
raise "#{@source_url} is not accessible" unless @url.valid?
f = open(@file_path,'wb')
count = 0
@url.net_http.request_get(@url.path) do |r|
r.read_body do |s|
@download_length += s.length
f.write s
if block_given?
count += 1
if count % 100 == 0
yield @download_length
end
end
end
end
f.close
downloaded = @download_length
@download_length = 0
downloaded
end | ruby | {
"resource": ""
} |
q21759 | DynamicImage.Helper.dynamic_image_tag | train | def dynamic_image_tag(record_or_array, options = {})
record = extract_dynamic_image_record(record_or_array)
options = { alt: filename_to_alt(record.filename) }.merge(options)
size = fit_size!(record_or_array, options)
url_options = options.extract!(*allowed_dynamic_image_url_options)
html_options = { size: size }.merge(options)
image_tag(dynamic_image_path_with_size(record_or_array,
size,
url_options),
html_options)
end | ruby | {
"resource": ""
} |
q21760 | Authie.Session.touch! | train | def touch!
self.check_security!
self.last_activity_at = Time.now
self.last_activity_ip = controller.request.ip
self.last_activity_path = controller.request.path
self.requests += 1
self.save!
Authie.config.events.dispatch(:session_touched, self)
true
end | ruby | {
"resource": ""
} |
q21761 | Authie.Session.set_cookie! | train | def set_cookie!
cookies[:user_session] = {
:value => self.temporary_token,
:secure => controller.request.ssl?,
:httponly => true,
:expires => self.expires_at
}
Authie.config.events.dispatch(:session_cookie_updated, self)
true
end | ruby | {
"resource": ""
} |
q21762 | Authie.Session.check_security! | train | def check_security!
if controller
if cookies[:browser_id] != self.browser_id
invalidate!
Authie.config.events.dispatch(:browser_id_mismatch_error, self)
raise BrowserMismatch, "Browser ID mismatch"
end
unless self.active?
invalidate!
Authie.config.events.dispatch(:invalid_session_error, self)
raise InactiveSession, "Session is no longer active"
end
if self.expired?
invalidate!
Authie.config.events.dispatch(:expired_session_error, self)
raise ExpiredSession, "Persistent session has expired"
end
if self.inactive?
invalidate!
Authie.config.events.dispatch(:inactive_session_error, self)
raise InactiveSession, "Non-persistent session has expired"
end
if self.host && self.host != controller.request.host
invalidate!
Authie.config.events.dispatch(:host_mismatch_error, self)
raise HostMismatch, "Session was created on #{self.host} but accessed using #{controller.request.host}"
end
end
end | ruby | {
"resource": ""
} |
q21763 | Authie.Session.invalidate! | train | def invalidate!
self.active = false
self.save!
if controller
cookies.delete(:user_session)
end
Authie.config.events.dispatch(:session_invalidated, self)
true
end | ruby | {
"resource": ""
} |
q21764 | Authie.Session.see_password! | train | def see_password!
self.password_seen_at = Time.now
self.save!
Authie.config.events.dispatch(:seen_password, self)
true
end | ruby | {
"resource": ""
} |
q21765 | Authie.Session.mark_as_two_factored! | train | def mark_as_two_factored!
self.two_factored_at = Time.now
self.two_factored_ip = controller.request.ip
self.save!
Authie.config.events.dispatch(:marked_as_two_factored, self)
true
end | ruby | {
"resource": ""
} |
q21766 | Authie.Session.revert_to_parent! | train | def revert_to_parent!
if self.parent
self.invalidate!
self.parent.activate!
self.parent.controller = self.controller
self.parent.set_cookie!
self.parent
else
raise NoParentSessionForRevert, "Session does not have a parent therefore cannot be reverted."
end
end | ruby | {
"resource": ""
} |
q21767 | Danger.DangerProse.lint_files | train | def lint_files(files = nil)
# Installs a prose checker if needed
system 'pip install --user proselint' unless proselint_installed?
# Check that this is in the user's PATH after installing
raise "proselint is not in the user's PATH, or it failed to install" unless proselint_installed?
# Either use files provided, or use the modified + added
markdown_files = get_files files
proses = {}
to_disable = disable_linters || ["misc.scare_quotes", "typography.symbols"]
with_proselint_disabled(to_disable) do
# Convert paths to proselint results
result_jsons = Hash[markdown_files.to_a.uniq.collect { |v| [v, get_proselint_json(v)] }]
proses = result_jsons.select { |_, prose| prose['data']['errors'].count > 0 }
end
# Get some metadata about the local setup
current_slug = env.ci_source.repo_slug
# We got some error reports back from proselint
if proses.count > 0
message = "### Proselint found issues\n\n"
proses.each do |path, prose|
github_loc = "/#{current_slug}/tree/#{github.branch_for_head}/#{path}"
message << "#### [#{path}](#{github_loc})\n\n"
message << "Line | Message | Severity |\n"
message << "| --- | ----- | ----- |\n"
prose['data']['errors'].each do |error|
message << "#{error['line']} | #{error['message']} | #{error['severity']}\n"
end
end
markdown message
end
end | ruby | {
"resource": ""
} |
q21768 | Danger.DangerProse.with_proselint_disabled | train | def with_proselint_disabled(disable_linters)
# Create the disabled linters JSON in ~/.proselintrc
proselint_template = File.join(File.dirname(__FILE__), 'proselintrc')
proselintJSON = JSON.parse(File.read(proselint_template))
# Disable individual linters
disable_linters.each do |linter|
proselintJSON['checks'][linter] = false
end
# Re-save the new JSON into the home dir
temp_proselint_rc_path = File.join(Dir.home, '.proselintrc')
File.write(temp_proselint_rc_path, JSON.pretty_generate(proselintJSON))
# Run the closure
yield
# Delete .proselintrc
File.unlink temp_proselint_rc_path
end | ruby | {
"resource": ""
} |
q21769 | Grim.Page.save | train | def save(path, options={})
raise PathMissing if path.nil? || path !~ /\S/
Grim.processor.save(@pdf, @index, path, options)
end | ruby | {
"resource": ""
} |
q21770 | IpaAnalyzer.Analyzer.find_app_folder_in_ipa | train | def find_app_folder_in_ipa
raise 'IPA is not open' unless self.open?
# Check the most common location
app_folder_in_ipa = "Payload/#{File.basename(@ipa_path, File.extname(@ipa_path))}.app"
#
mobileprovision_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/embedded.mobileprovision")
info_plist_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/Info.plist")
#
if !mobileprovision_entry.nil? && !info_plist_entry.nil?
return app_folder_in_ipa
end
# It's somewhere else - let's find it!
@ipa_zipfile.dir.entries('Payload').each do |dir_entry|
next unless dir_entry =~ /.app$/
app_folder_in_ipa = "Payload/#{dir_entry}"
mobileprovision_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/embedded.mobileprovision")
info_plist_entry = @ipa_zipfile.find_entry("#{app_folder_in_ipa}/Info.plist")
break if !mobileprovision_entry.nil? && !info_plist_entry.nil?
end
if !mobileprovision_entry.nil? && !info_plist_entry.nil?
return app_folder_in_ipa
end
return nil
end | ruby | {
"resource": ""
} |
q21771 | DeathByCaptcha.Client.load_captcha | train | def load_captcha(options)
if options[:raw64]
options[:raw64]
elsif options[:raw]
Base64.encode64(options[:raw])
elsif options[:file]
Base64.encode64(options[:file].read())
elsif options[:path]
Base64.encode64(File.open(options[:path], 'rb').read)
elsif options[:url]
Base64.encode64(open_url(options[:url]))
else
''
end
rescue
''
end | ruby | {
"resource": ""
} |
q21772 | DeathByCaptcha.Client::Socket.captcha | train | def captcha(captcha_id)
response = perform('captcha', captcha: captcha_id)
DeathByCaptcha::Captcha.new(response)
end | ruby | {
"resource": ""
} |
q21773 | DeathByCaptcha.Client::Socket.perform | train | def perform(action, payload = {})
payload.merge!(
cmd: action,
version: DeathByCaptcha::API_VERSION,
username: self.username,
password: self.password
)
socket = create_socket()
socket.puts(payload.to_json)
response = socket.read()
socket.close()
begin
response = JSON.parse(response)
rescue
raise DeathByCaptcha::APIResponseError.new("invalid JSON: #{response}")
end
if !(error = response['error'].to_s).empty?
case error
when 'not-logged-in', 'invalid-credentials', 'banned', 'insufficient-funds'
raise DeathByCaptcha::APIForbidden
when 'invalid-captcha'
raise DeathByCaptcha::APIBadRequest
when 'service-overload'
raise DeathByCaptcha::APIServiceUnavailable
else
raise DeathByCaptcha::APIResponseError.new(error)
end
end
response
end | ruby | {
"resource": ""
} |
q21774 | DeathByCaptcha.Client::Socket.create_socket | train | def create_socket
socket = ::Socket.new(::Socket::AF_INET, ::Socket::SOCK_STREAM, 0)
sockaddr = ::Socket.sockaddr_in(PORTS.sample, self.hostname)
begin # emulate blocking connect
socket.connect_nonblock(sockaddr)
rescue IO::WaitWritable
IO.select(nil, [socket]) # wait 3-way handshake completion
begin
socket.connect_nonblock(sockaddr) # check connection failure
rescue Errno::EISCONN
end
end
socket
end | ruby | {
"resource": ""
} |
q21775 | DeathByCaptcha.Client::HTTP.perform | train | def perform(action, method = :get, payload = {})
payload.merge!(username: self.username, password: self.password)
headers = { 'User-Agent' => DeathByCaptcha::API_VERSION }
if method == :post
uri = URI("http://#{self.hostname}/api/#{action}")
req = Net::HTTP::Post.new(uri.request_uri, headers)
req.set_form_data(payload)
elsif method == :post_multipart
uri = URI("http://#{self.hostname}/api/#{action}")
req = Net::HTTP::Post.new(uri.request_uri, headers)
boundary, body = prepare_multipart_data(payload)
req.content_type = "multipart/form-data; boundary=#{boundary}"
req.body = body
else
uri = URI("http://#{self.hostname}/api/#{action}?#{URI.encode_www_form(payload)}")
req = Net::HTTP::Get.new(uri.request_uri, headers)
end
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
case res
when Net::HTTPSuccess, Net::HTTPSeeOther
Hash[URI.decode_www_form(res.body)]
when Net::HTTPForbidden
raise DeathByCaptcha::APIForbidden
when Net::HTTPBadRequest
raise DeathByCaptcha::APIBadRequest
when Net::HTTPRequestEntityTooLarge
raise DeathByCaptcha::APICaptchaTooLarge
when Net::HTTPServiceUnavailable
raise DeathByCaptcha::APIServiceUnavailable
else
raise DeathByCaptcha::APIResponseError.new(res.body)
end
end | ruby | {
"resource": ""
} |
q21776 | Phccontactor.MessagesController.create | train | def create
@message = Message.new(message_params)
if @message.valid?
MessageMailer.message_me(@message).deliver_now
redirect_to new_message_path, notice: "Thank you for your message."
else
render :new
end
end | ruby | {
"resource": ""
} |
q21777 | Phccontactor.MessageMailer.message_me | train | def message_me(msg)
@msg = msg
mail from: @msg.email, subject: @msg.subject, body: @msg.content
end | ruby | {
"resource": ""
} |
q21778 | RVT.Slave.send_input | train | def send_input(input)
raise ArgumentError if input.nil? or input.try(:empty?)
input.each_char { |char| @input.putc(char) }
end | ruby | {
"resource": ""
} |
q21779 | RVT.Slave.pending_output | train | def pending_output(chunk_len = 49152)
# Returns nil if there is no pending output.
return unless pending_output?
pending = String.new
while chunk = @output.read_nonblock(chunk_len)
pending << chunk
end
pending.force_encoding('UTF-8')
rescue IO::WaitReadable
pending.force_encoding('UTF-8')
rescue
raise Closed if READING_ON_CLOSED_END_ERRORS.any? { |exc| $!.is_a?(exc) }
end | ruby | {
"resource": ""
} |
q21780 | GoCardless.Utils.flatten_params | train | def flatten_params(obj, ns=nil)
case obj
when Hash
pairs = obj.map { |k,v| flatten_params(v, ns ? "#{ns}[#{k}]" : k) }
pairs.empty? ? [] : pairs.inject(&:+)
when Array
obj.map { |v| flatten_params(v, "#{ns}[]") }.inject(&:+) || []
when Time
[[ns.to_s, iso_format_time(obj)]]
else
[[ns.to_s, obj.to_s]]
end
end | ruby | {
"resource": ""
} |
q21781 | GoCardless.Utils.iso_format_time | train | def iso_format_time(time)
return time unless time.is_a? Time or time.is_a? Date
time = time.getutc if time.is_a? Time
time = time.new_offset(0) if time.is_a? DateTime
time.strftime('%Y-%m-%dT%H:%M:%SZ')
end | ruby | {
"resource": ""
} |
q21782 | GoCardless.Utils.stringify_times | train | def stringify_times(obj)
case obj
when Hash
Hash[obj.map { |k,v| [k, stringify_times(v)] }]
when Array
obj.map { |v| stringify_times(v) }
else
iso_format_time(obj)
end
end | ruby | {
"resource": ""
} |
q21783 | GoCardless.Paginator.load_page | train | def load_page(page_num)
params = @query.merge(pagination_params(page_num))
response = @client.api_request(:get, @path, :params => params)
metadata = parse_metadata(response)
@num_records, @num_pages = metadata['records'], metadata['pages']
Page.new(@resource_class, response.parsed, metadata['links'])
end | ruby | {
"resource": ""
} |
q21784 | GoCardless.Paginator.each_page | train | def each_page
page_obj = load_page(1)
loop do
yield page_obj
break unless page_obj.has_next?
page_obj = load_page(page_obj.next_page)
end
end | ruby | {
"resource": ""
} |
q21785 | GoCardless.Client.authorize_url | train | def authorize_url(options)
raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri]
params = {
:client_id => @app_id,
:response_type => 'code',
:scope => 'manage_merchant'
}
# Faraday doesn't flatten params in this case (Faraday issue #115)
options = Hash[Utils.flatten_params(options)]
@oauth_client.authorize_url(params.merge(options))
end | ruby | {
"resource": ""
} |
q21786 | GoCardless.Client.fetch_access_token | train | def fetch_access_token(auth_code, options)
raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri]
# Exchange the auth code for an access token
@access_token = @oauth_client.auth_code.get_token(auth_code, options)
# Use the scope to figure out which merchant we're managing
scope = @access_token.params[:scope] || @access_token.params['scope']
set_merchant_id_from_scope(scope)
self.scoped_access_token
end | ruby | {
"resource": ""
} |
q21787 | GoCardless.Client.access_token= | train | def access_token=(token)
token, scope = token.sub(/^bearer\s+/i, '').split(' ', 2)
if scope
warn "[DEPRECATION] (gocardless-ruby) merchant_id is now a separate " +
"attribute, the manage_merchant scope should no longer be " +
"included in the 'token' attribute. See http://git.io/G9y37Q " +
"for more info."
else
scope = ''
end
@access_token = OAuth2::AccessToken.new(@oauth_client, token)
@access_token.params['scope'] = scope
set_merchant_id_from_scope(scope) unless @merchant_id
end | ruby | {
"resource": ""
} |
q21788 | GoCardless.Client.set_merchant_id_from_scope | train | def set_merchant_id_from_scope(scope)
perm = scope.split.select {|p| p.start_with?('manage_merchant:') }.first
@merchant_id = perm.split(':')[1] if perm
end | ruby | {
"resource": ""
} |
q21789 | GoCardless.Client.request | train | def request(method, path, opts = {})
raise ClientError, 'Access token missing' unless @access_token
opts[:headers] = {} if opts[:headers].nil?
opts[:headers]['Accept'] = 'application/json'
opts[:headers]['Content-Type'] = 'application/json' unless method == :get
opts[:headers]['User-Agent'] = user_agent
opts[:body] = MultiJson.encode(opts[:data]) if !opts[:data].nil?
path = URI.encode(path)
# Reset the URL in case the environment / base URL has been changed.
@oauth_client.site = base_url
header_keys = opts[:headers].keys.map(&:to_s)
if header_keys.map(&:downcase).include?('authorization')
@oauth_client.request(method, path, opts)
else
@access_token.send(method, path, opts)
end
rescue OAuth2::Error => err
raise GoCardless::ApiError.new(err.response)
end | ruby | {
"resource": ""
} |
q21790 | GoCardless.Client.prepare_params | train | def prepare_params(params)
# Create a new hash in case is a HashWithIndifferentAccess (keys are
# always a String)
params = Utils.symbolize_keys(Hash[params])
# Only pull out the relevant parameters, other won't be included in the
# signature so will cause false negatives
keys = [:resource_id, :resource_type, :resource_uri, :state, :signature]
params = Hash[params.select { |k,v| keys.include? k }]
(keys - [:state]).each do |key|
raise ArgumentError, "Parameters missing #{key}" if !params.key?(key)
end
params
end | ruby | {
"resource": ""
} |
q21791 | GoCardless.Client.new_limit_url | train | def new_limit_url(type, limit_params)
url = URI.parse("#{base_url}/connect/#{type}s/new")
limit_params[:merchant_id] = merchant_id
redirect_uri = limit_params.delete(:redirect_uri)
cancel_uri = limit_params.delete(:cancel_uri)
state = limit_params.delete(:state)
params = {
:nonce => generate_nonce,
:timestamp => Time.now.getutc.strftime('%Y-%m-%dT%H:%M:%SZ'),
:client_id => @app_id,
type => limit_params,
}
params[:redirect_uri] = redirect_uri unless redirect_uri.nil?
params[:cancel_uri] = cancel_uri unless cancel_uri.nil?
params[:state] = state unless state.nil?
sign_params(params)
url.query = Utils.normalize_params(params)
url.to_s
end | ruby | {
"resource": ""
} |
q21792 | Hooks.Hook.run | train | def run(scope, *args)
inject(Results.new) do |results, callback|
executed = execute_callback(scope, callback, *args)
return results.halted! unless continue_execution?(executed)
results << executed
end
end | ruby | {
"resource": ""
} |
q21793 | TTY.Color.command? | train | def command?(cmd)
!!system(cmd, out: ::File::NULL, err: ::File::NULL)
end | ruby | {
"resource": ""
} |
q21794 | Spy.Nest.remove | train | def remove(spy)
if @constant_spies[spy.constant_name] == spy
@constant_spies.delete(spy.constant_name)
else
raise NoSpyError, "#{spy.constant_name} was not stubbed on #{base_module.name}"
end
self
end | ruby | {
"resource": ""
} |
q21795 | Spy.Subroutine.hook | train | def hook(opts = {})
raise AlreadyHookedError, "#{base_object} method '#{method_name}' has already been hooked" if self.class.get(base_object, method_name, singleton_method)
@hook_opts = opts
@original_method_visibility = method_visibility_of(method_name)
hook_opts[:visibility] ||= original_method_visibility
if original_method_visibility || !hook_opts[:force]
@original_method = current_method
end
if original_method && original_method.owner == base_object
original_method.owner.send(:remove_method, method_name)
end
if singleton_method
base_object.define_singleton_method(method_name, override_method)
else
base_object.define_method(method_name, override_method)
end
if [:public, :protected, :private].include? hook_opts[:visibility]
method_owner.send(hook_opts[:visibility], method_name)
end
Agency.instance.recruit(self)
@was_hooked = true
self
end | ruby | {
"resource": ""
} |
q21796 | Spy.Subroutine.unhook | train | def unhook
raise NeverHookedError, "'#{method_name}' method has not been hooked" unless hooked?
method_owner.send(:remove_method, method_name)
if original_method && method_owner == original_method.owner
original_method.owner.send(:define_method, method_name, original_method)
original_method.owner.send(original_method_visibility, method_name) if original_method_visibility
end
clear_method!
Agency.instance.retire(self)
self
end | ruby | {
"resource": ""
} |
q21797 | Spy.Subroutine.and_yield | train | def and_yield(*args)
yield eval_context = Object.new if block_given?
@plan = Proc.new do |&block|
eval_context.instance_exec(*args, &block)
end
self
end | ruby | {
"resource": ""
} |
q21798 | Spy.Subroutine.and_call_through | train | def and_call_through
if @base_object.is_a? Class
@plan = Proc.new do |object, *args, &block|
if original_method
if original_method.is_a? UnboundMethod
bound_method = original_method.bind(object)
bound_method.call(*args, &block)
else
original_method.call(*args, &block)
end
else
base_object.send(:method_missing, method_name, *args, &block)
end
end
else
@plan = Proc.new do |*args, &block|
if original_method
original_method.call(*args, &block)
else
base_object.send(:method_missing, method_name, *args, &block)
end
end
end
self
end | ruby | {
"resource": ""
} |
q21799 | Spy.Subroutine.has_been_called_with? | train | def has_been_called_with?(*args)
raise NeverHookedError unless @was_hooked
match = block_given? ? Proc.new : proc { |call| call.args == args }
calls.any?(&match)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.