_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q15900
JSS.NetworkSegment.override_departments=
train
def override_departments=(newval) raise JSS::InvalidDataError, 'New value must be boolean true or false' unless JSS::TRUE_FALSE.include? newval @override_departments = newval @need_to_update = true end
ruby
{ "resource": "" }
q15901
JSS.NetworkSegment.distribution_point=
train
def distribution_point=(newval) new = JSS::DistributionPoint.all.select { |b| (b[:id] == newval) || (b[:name] == newval) }[0] raise JSS::MissingDataError, "No distribution_point matching '#{newval}' in the JSS" unless new @distribution_point = new[:name] @need_to_update = true end
ruby
{ "resource": "" }
q15902
JSS.NetworkSegment.netboot_server=
train
def netboot_server=(newval) new = JSS::NetbootServer.all.select { |b| (b[:id] == newval) || (b[:name] == newval) }[0] raise JSS::MissingDataError, "No netboot_server matching '#{newval}' in the JSS" unless new @netboot_server = new[:name] @need_to_update = true end
ruby
{ "resource": "" }
q15903
JSS.NetworkSegment.swu_server=
train
def swu_server=(newval) new = JSS::SoftwareUpdateServer.all.select { |b| (b[:id] == newval) || (b[:name] == newval) }[0] raise JSS::MissingDataError, "No swu_server matching '#{newval}' in the JSS" unless new @swu_server = new[:name] @need_to_update = true end
ruby
{ "resource": "" }
q15904
JSS.NetworkSegment.set_ip_range
train
def set_ip_range(starting_address: nil, ending_address: nil, mask: nil, cidr: nil) range = self.class.ip_range( starting_address: starting_address, ending_address: ending_address, mask: mask, cidr: cidr ) @starting_address = range.first @ending_address = range.last @need_to_update = true end
ruby
{ "resource": "" }
q15905
JSS.Script.name=
train
def name=(new_val) return nil if new_val == @name new_val = nil if new_val == '' raise JSS::MissingDataError, "Name can't be empty" unless new_val raise JSS::AlreadyExistsError, "A #{RSRC_OBJECT_KEY} already exists with the name '#{args[:name]}'" if JSS.send(LIST_METHOD).values.include? ### if the filename is the same, keep it the same @filename = new_val if @filename == @name @name = new_val ### if our REST resource is based on the name, update that too @rest_rsrc = "#{RSRC_BASE}/name/#{CGI.escape @name}" if @rest_rsrc.include? '/name/' @need_to_update = true end
ruby
{ "resource": "" }
q15906
JSS.Script.os_requirements=
train
def os_requirements=(new_val) ### nil should be an empty array new_val = [] if new_val.to_s.empty? ### if any value starts with >=, expand it case new_val when String new_val = JSS.expand_min_os(new_val) if new_val =~ /^>=/ when Array new_val.map! { |a| a =~ /^>=/ ? JSS.expand_min_os(a) : a } new_val.flatten! new_val.uniq! else raise JSS::InvalidDataError, 'os_requirements must be a String or an Array of strings' end # case ### get the array version @os_requirements = JSS.to_s_and_a(new_val)[:arrayform] @need_to_update = true end
ruby
{ "resource": "" }
q15907
JSS.Script.priority=
train
def priority=(new_val) return nil if new_val == @priority new_val = DEFAULT_PRIORITY if new_val.nil? || (new_val == '') raise JSS::InvalidDataError, ":priority must be one of: #{PRIORITIES.join ', '}" unless PRIORITIES.include? new_val @priority = new_val @need_to_update = true end
ruby
{ "resource": "" }
q15908
JSS.Script.parameters=
train
def parameters=(new_val) return nil if new_val == @parameters new_val = {} if new_val.nil? || (new_val == '') ### check the values raise JSS::InvalidDataError, ':parameters must be a Hash with keys :parameter4 thru :parameter11' unless \ new_val.is_a?(Hash) && ((new_val.keys & PARAMETER_KEYS) == new_val.keys) new_val.each do |_k, v| raise JSS::InvalidDataError, ':parameter values must be strings or nil' unless v.nil? || v.is_a?(String) end @parameters = new_val @need_to_update = true end
ruby
{ "resource": "" }
q15909
JSS.Script.set_parameter
train
def set_parameter(param_num, new_val) raise JSS::NoSuchItemError, 'Parameter numbers must be from 4-11' unless (4..11).cover? param_num pkey = "parameter#{param_num}".to_sym raise JSS::InvalidDataError, 'parameter values must be strings or nil' unless new_val.nil? || new_val.is_a?(String) return nil if new_val == @parameters[pkey] @parameters[pkey] = new_val @need_to_update = true end
ruby
{ "resource": "" }
q15910
JSS.Script.script_contents=
train
def script_contents=(new_val) new_code = case new_val when String if new_val.start_with? '/' Pathname.new(new_val).read else new_val end # if when Pathname new_val.read else raise JSS::InvalidDataError, 'New code must be a String (path or code) or Pathname instance' end # case raise JSS::InvalidDataError, "Script contents must start with '#!'" unless new_code.start_with? '#!' @script_contents = new_code @need_to_update = true end
ruby
{ "resource": "" }
q15911
JSS.Script.delete_master_file
train
def delete_master_file(rw_pw, unmount = true) file = JSS::DistributionPoint.master_distribution_point.mount(rw_pw, :rw) + "#{DIST_POINT_SCRIPTS_FOLDER}/#{@filename}" if file.exist? file.delete did_it = true else did_it = false end # if exists JSS::DistributionPoint.master_distribution_point.unmount if unmount did_it end
ruby
{ "resource": "" }
q15912
JSS.Script.run
train
def run(opts = {}) opts[:target] ||= '/' opts[:p1] ||= @parameters[:parameter4] opts[:p2] ||= @parameters[:parameter5] opts[:p3] ||= @parameters[:parameter6] opts[:p4] ||= @parameters[:parameter7] opts[:p5] ||= @parameters[:parameter8] opts[:p6] ||= @parameters[:parameter9] opts[:p7] ||= @parameters[:parameter10] opts[:p8] ||= @parameters[:parameter11] dp_mount_pt = nil delete_exec = false begin # do we have the code already? if so, save it out and make it executable if @script_contents && !@script_contents.empty? script_path = JSS::Client::DOWNLOADS_FOLDER executable = script_path + @filename executable.jss_touch executable.chmod 0o700 executable.jss_save @script_contents delete_exec = true # otherwise, get it from the dist. point else dist_point = JSS::DistributionPoint.my_distribution_point api: @api ### how do we access our dist. point? if dist_point.http_downloads_enabled script_path = dist_point.http_url + "/#{DIST_POINT_SCRIPTS_FOLDER}/" else dp_mount_pt = dist_point.mount opts[:ro_pw] script_path = (dp_mount_pt + DIST_POINT_SCRIPTS_FOLDER) end # if http enabled end # if @script_contents and (not @script_contents.empty?) # build the command as an array. command_arry = ['-script', @filename, '-path', script_path.to_s] command_arry << '-target' command_arry << opts[:target].to_s command_arry << '-computerName' if opts[:computer_name] command_arry << opts[:computer_name] if opts[:computer_name] command_arry << '-username' if opts[:username] command_arry << opts[:username] if opts[:username] command_arry << '-p1' if opts[:p1] command_arry << opts[:p1] if opts[:p1] command_arry << '-p2' if opts[:p2] command_arry << opts[:p2] if opts[:p2] command_arry << '-p3' if opts[:p3] command_arry << opts[:p3] if opts[:p3] command_arry << '-p4' if opts[:p4] command_arry << opts[:p4] if opts[:p4] command_arry << '-p5' if opts[:p5] command_arry << opts[:p5] if opts[:p5] command_arry << '-p6' if opts[:p6] command_arry << opts[:p6] if opts[:p6] command_arry << '-p7' if opts[:p7] command_arry << opts[:p7] if opts[:p7] command_arry << '-p8' if opts[:p8] command_arry << opts[:p8] if opts[:p8] command_arry << '-verbose' if opts[:verbose] command = command_arry.shelljoin jamf_output = JSS::Client.run_jamf 'runScript', command, opts[:show_output] jamf_output =~ /^.*Script exit code: (\d+)(\D|$)/ script_exitstatus = Regexp.last_match(1).to_i ensure executable.delete if delete_exec && executable.exist? dist_point.unmount if dp_mount_pt && dp_mount_pt.mountpoint? && opts[:unmount] end # begin/ensure [script_exitstatus, jamf_output] end
ruby
{ "resource": "" }
q15913
JSS.Script.rest_xml
train
def rest_xml doc = REXML::Document.new scpt = doc.add_element 'script' scpt.add_element('filename').text = @filename scpt.add_element('id').text = @id scpt.add_element('info').text = @info scpt.add_element('name').text = @name scpt.add_element('notes').text = @notes scpt.add_element('os_requirements').text = JSS.to_s_and_a(@os_requirements)[:stringform] scpt.add_element('priority').text = @priority add_category_to_xml(doc) if @parameters.empty? scpt.add_element('parameters').text = nil else pars = scpt.add_element('parameters') PARAMETER_KEYS.each { |p| pars.add_element(p.to_s).text = @parameters[p] } end scpt.add_element('script_contents_encoded').text = Base64.encode64(@script_contents) doc.to_s end
ruby
{ "resource": "" }
q15914
JSS.PeripheralType.set_field
train
def set_field(order, field = {}) raise JSS::NoSuchItemError, "No field with number '#{order}'. Use #append_field, #prepend_field, or #insert_field" unless @fields[order] field_ok? field @fields[order] = field @need_to_update = true end
ruby
{ "resource": "" }
q15915
JSS.PeripheralType.insert_field
train
def insert_field(order,field = {}) field_ok? field @fields.insert((order -1), field) order_fields @need_to_update = true end
ruby
{ "resource": "" }
q15916
JSS.PeripheralType.delete_field
train
def delete_field(order) if @fields[order] raise JSS::MissingDataError, "Fields can't be empty" if @fields.count == 1 @fields.delete_at index order_fields @need_to_update = true end end
ruby
{ "resource": "" }
q15917
JSS.PeripheralType.field_ok?
train
def field_ok?(field) raise JSS::InvalidDataError, "Field elements must be hashes with :name, :type, and possibly :choices" unless field.kind_of? Hash raise JSS::InvalidDataError, "Fields require names" if field[:name].to_s.empty? raise JSS::InvalidDataError, "Fields :type must be one of: :#{FIELD_TYPES.join(', :')}" unless FIELD_TYPES.include? field[:type].to_sym if field[:type].to_sym == :menu unless field[:choices].kind_of? Array and field[:choices].reject{|c| c.kind_of? String}.empty? raise JSS::InvalidDataError, "Choices for menu fields must be an Array of Strings" end # unless else field[:choices] = [] end # if type -- menu true end
ruby
{ "resource": "" }
q15918
JSS.Group.remove_member
train
def remove_member(mem) raise InvalidDataError, "Smart group members can't be changed." if @is_smart raise InvalidDataError, "Can't remove nil" if mem.nil? removed = @members.reject! { |mm| [mm[:id], mm[:name], mm[:username]].include? mem } @need_to_update = true if removed end
ruby
{ "resource": "" }
q15919
JSS.Group.check_member
train
def check_member(m) potential_members = self.class::MEMBER_CLASS.map_all_ids_to(:name, api: @api) if m.to_s =~ /^\d+$/ return { id: m.to_i, name: potential_members[m] } if potential_members.key?(m.to_i) else return { name: m, id: potential_members.invert[m] } if potential_members.value?(m) end raise JSS::NoSuchItemError, "No #{self.class::MEMBER_CLASS::RSRC_OBJECT_KEY} matching '#{m}' in the JSS." end
ruby
{ "resource": "" }
q15920
JSS.PatchTitle.email_notification=
train
def email_notification=(new_setting) return if email_notification == new_setting raise JSS::InvalidDataError, 'New Setting must be boolean true or false' unless JSS::TRUE_FALSE.include? @email_notification = new_setting @need_to_update = true end
ruby
{ "resource": "" }
q15921
JSS.PatchTitle.web_notification=
train
def web_notification=(new_setting) return if web_notification == new_setting raise JSS::InvalidDataError, 'New Setting must be boolean true or false' unless JSS::TRUE_FALSE.include? @web_notification = new_setting @need_to_update = true end
ruby
{ "resource": "" }
q15922
JSS.PatchTitle.rest_xml
train
def rest_xml doc = REXML::Document.new # JSS::APIConnection::XML_HEADER obj = doc.add_element RSRC_OBJECT_KEY.to_s obj.add_element('name').text = name obj.add_element('name_id').text = name_id obj.add_element('source_id').text = source_id notifs = obj.add_element 'notifications' notifs.add_element('web_notification').text = web_notification?.to_s notifs.add_element('email_notification').text = email_notification?.to_s add_changed_pkg_xml obj unless @changed_pkgs.empty? add_category_to_xml doc add_site_to_xml doc doc.to_s end
ruby
{ "resource": "" }
q15923
JSS.PatchTitle.add_changed_pkg_xml
train
def add_changed_pkg_xml(obj) versions_elem = obj.add_element 'versions' @changed_pkgs.each do |vers| velem = versions_elem.add_element 'version' velem.add_element('software_version').text = vers.to_s pkg = velem.add_element 'package' # leave am empty package element to remove the pkg assignement next if versions[vers].package_id == :none pkg.add_element('id').text = versions[vers].package_id.to_s end # do vers end
ruby
{ "resource": "" }
q15924
JSS.APIObject.validate_object_history_available
train
def validate_object_history_available raise JSS::NoSuchItemError, 'Object not yet created' unless @id && @in_jss raise JSS::InvalidConnectionError, 'Not connected to MySQL' unless JSS::DB_CNX.connected? raise JSS::UnsupportedError, "Object History access is not supported for #{self.class} objects at this time" unless defined? self.class::OBJECT_HISTORY_OBJECT_TYPE end
ruby
{ "resource": "" }
q15925
JSS.APIObject.validate_external_init_data
train
def validate_external_init_data # data must include all they keys in REQUIRED_DATA_KEYS + VALID_DATA_KEYS # in either the main hash keys or the :general sub-hash, if it exists hash_to_check = @init_data[:general] ? @init_data[:general] : @init_data combined_valid_keys = self.class::REQUIRED_DATA_KEYS + self.class::VALID_DATA_KEYS keys_ok = (hash_to_check.keys & combined_valid_keys).count == combined_valid_keys.count unless keys_ok raise( JSS::InvalidDataError, ":data is not valid JSON for a #{self.class::RSRC_OBJECT_KEY} from the API. It needs at least the keys :#{combined_valid_keys.join ', :'}" ) end # and the id must be in the jss raise NoSuchItemError, "No #{self.class::RSRC_OBJECT_KEY} with JSS id: #{@init_data[:id]}" unless \ self.class.all_ids(api: @api).include? hash_to_check[:id] end
ruby
{ "resource": "" }
q15926
JSS.APIObject.validate_init_for_creation
train
def validate_init_for_creation(args) raise JSS::UnsupportedError, "Creating #{self.class::RSRC_LIST_KEY} isn't yet supported. Please use other Casper workflows." unless creatable? raise JSS::MissingDataError, "You must provide a :name to create a #{self.class::RSRC_OBJECT_KEY}." unless args[:name] raise JSS::AlreadyExistsError, "A #{self.class::RSRC_OBJECT_KEY} already exists with the name '#{args[:name]}'" if self.class.all_names(api: @api).include? args[:name] end
ruby
{ "resource": "" }
q15927
JSS.APIObject.look_up_object_data
train
def look_up_object_data(args) rsrc = if args[:fetch_rsrc] args[:fetch_rsrc] else # what lookup key are we using? # TODO: simplify this, see the notes at #find_rsrc_keys rsrc_key, lookup_value = find_rsrc_keys(args) "#{self.class::RSRC_BASE}/#{rsrc_key}/#{lookup_value}" end # if needed, a non-standard object key can be passed by a subclass. # e.g. User when loookup is by email. args[:rsrc_object_key] ||= self.class::RSRC_OBJECT_KEY raw_json = if defined? self.class::USE_XML_WORKAROUND # if we're here, the API JSON is borked, so use the XML JSS::XMLWorkaround.data_via_xml rsrc, self.class::USE_XML_WORKAROUND, @api else # otherwise @api.get_rsrc(rsrc) end raw_json[args[:rsrc_object_key]] rescue RestClient::ResourceNotFound raise NoSuchItemError, "No #{self.class::RSRC_OBJECT_KEY} found matching resource #{rsrc}" end
ruby
{ "resource": "" }
q15928
JSS.APIObject.rest_xml
train
def rest_xml doc = REXML::Document.new JSS::APIConnection::XML_HEADER tmpl = doc.add_element self.class::RSRC_OBJECT_KEY.to_s tmpl.add_element('name').text = @name doc.to_s end
ruby
{ "resource": "" }
q15929
JSS.Configuration.reload
train
def reload(file = nil) clear_all if file read file return true end read_global read_user return true end
ruby
{ "resource": "" }
q15930
JSS.Configuration.read
train
def read(file) Pathname.new(file).read.each_line do |line| # skip blank lines and those starting with # next if line =~ /^\s*(#|$)/ line.strip =~ /^(\w+?):\s*(\S.*)$/ next unless $1 attr = $1.to_sym setter = "#{attr}=".to_sym value = $2.strip if CONF_KEYS.keys.include? attr if value # convert the value to the correct class value = value.send(CONF_KEYS[attr]) end self.send(setter, value) end # if end # do line end
ruby
{ "resource": "" }
q15931
JSS.VPPable.assign_vpp_device_based_licenses=
train
def assign_vpp_device_based_licenses=(new_val) return nil if new_val == @assign_vpp_device_based_licenses raise JSS::InvalidDataError, 'New value must be true or false' unless new_val.jss_boolean? @assign_vpp_device_based_licenses = new_val @need_to_update = true end
ruby
{ "resource": "" }
q15932
JSS.VPPable.add_vpp_xml
train
def add_vpp_xml(xdoc) doc_root = xdoc.root vpp = doc_root.add_element 'vpp' vpp.add_element('assign_vpp_device_based_licenses').text = @assign_vpp_device_based_licenses end
ruby
{ "resource": "" }
q15933
LetsEncrypt.CertificateVerifiable.verify
train
def verify create_order start_challenge wait_verify_status check_verify_status rescue Acme::Client::Error => e retry_on_verify_error(e) end
ruby
{ "resource": "" }
q15934
Whois.SafeRecord.properties
train
def properties hash = {} Parser::PROPERTIES.each do |property| hash[property] = __send__(property) end hash end
ruby
{ "resource": "" }
q15935
MethodProfiler.Report.to_a
train
def to_a if @order == :ascending @data.sort { |a, b| a[@sort_by] <=> b[@sort_by] } else @data.sort { |a, b| b[@sort_by] <=> a[@sort_by] } end end
ruby
{ "resource": "" }
q15936
MethodProfiler.Report.to_s
train
def to_s [ "MethodProfiler results for: #{@name}", Hirb::Helpers::Table.render( to_a, headers: HEADERS.dup, fields: FIELDS.dup, filters: { min: :to_milliseconds, max: :to_milliseconds, average: :to_milliseconds, total_time: :to_milliseconds, }, description: false ) ].join("\n") end
ruby
{ "resource": "" }
q15937
SeccompTools.Asm.asm
train
def asm(str, arch: nil) arch = Util.system_arch if arch.nil? # TODO: show warning compiler = Compiler.new(arch) str.lines.each { |l| compiler.process(l) } compiler.compile!.map(&:asm).join end
ruby
{ "resource": "" }
q15938
SeccompTools.CLI.work
train
def work(argv) # all -h equivalent to --help argv = argv.map { |a| a == '-h' ? '--help' : a } idx = argv.index { |c| !c.start_with?('-') } preoption = idx.nil? ? argv.shift(argv.size) : argv.shift(idx) # handle --version or --help or nothing return show("SeccompTools Version #{SeccompTools::VERSION}") if preoption.include?('--version') return show(USAGE) if idx.nil? # let's handle commands cmd = argv.shift argv = %w[--help] if preoption.include?('--help') return show(invalid(cmd)) if COMMANDS[cmd].nil? COMMANDS[cmd].new(argv).handle end
ruby
{ "resource": "" }
q15939
SeccompTools.Disasm.disasm
train
def disasm(raw, arch: nil) codes = to_bpf(raw, arch) contexts = Array.new(codes.size) { Set.new } contexts[0].add(Context.new) # all we care is if A is exactly one of data[*] dis = codes.zip(contexts).map do |code, ctxs| ctxs.each do |ctx| code.branch(ctx) do |pc, c| contexts[pc].add(c) unless pc >= contexts.size end end code.contexts = ctxs code.disasm end.join("\n") <<EOS + dis + "\n" line CODE JT JF K ================================= EOS end
ruby
{ "resource": "" }
q15940
SeccompTools.BPF.inst
train
def inst @inst ||= case command when :alu then SeccompTools::Instruction::ALU when :jmp then SeccompTools::Instruction::JMP when :ld then SeccompTools::Instruction::LD when :ldx then SeccompTools::Instruction::LDX when :misc then SeccompTools::Instruction::MISC when :ret then SeccompTools::Instruction::RET when :st then SeccompTools::Instruction::ST when :stx then SeccompTools::Instruction::STX end.new(self) end
ruby
{ "resource": "" }
q15941
SeccompTools.Util.supported_archs
train
def supported_archs @supported_archs ||= Dir.glob(File.join(__dir__, 'consts', '*.rb')) .map { |f| File.basename(f, '.rb').to_sym } .sort end
ruby
{ "resource": "" }
q15942
SeccompTools.Util.colorize
train
def colorize(s, t: nil) s = s.to_s return s unless colorize_enabled? cc = COLOR_CODE color = cc[t] "#{color}#{s.sub(cc[:esc_m], cc[:esc_m] + color)}#{cc[:esc_m]}" end
ruby
{ "resource": "" }
q15943
Script.CommandsChecker.get_mjsonwp_routes
train
def get_mjsonwp_routes(to_path = './mjsonwp_routes.js') uri = URI 'https://raw.githubusercontent.com/appium/appium-base-driver/master/lib/protocol/routes.js?raw=1' result = Net::HTTP.get uri File.delete to_path if File.exist? to_path File.write to_path, result to_path end
ruby
{ "resource": "" }
q15944
Script.CommandsChecker.diff_except_for_webdriver
train
def diff_except_for_webdriver result = compare_commands(@spec_commands, @implemented_core_commands) white_list.each { |v| result.delete v } result end
ruby
{ "resource": "" }
q15945
NameOfPerson.AssignableName.name=
train
def name=(name) full_name = NameOfPerson::PersonName.full(name) self.first_name, self.last_name = full_name&.first, full_name&.last end
ruby
{ "resource": "" }
q15946
SEPA.Message.message_identification=
train
def message_identification=(value) raise ArgumentError.new('message_identification must be a string!') unless value.is_a?(String) regex = /\A([A-Za-z0-9]|[\+|\?|\/|\-|\:|\(|\)|\.|\,|\'|\ ]){1,35}\z/ raise ArgumentError.new("message_identification does not match #{regex}!") unless value.match(regex) @message_identification = value end
ruby
{ "resource": "" }
q15947
SEPA.Message.batch_id
train
def batch_id(transaction_reference) grouped_transactions.each do |group, transactions| if transactions.select { |transaction| transaction.reference == transaction_reference }.any? return payment_information_identification(group) end end end
ruby
{ "resource": "" }
q15948
TweetStream.Client.follow
train
def follow(*user_ids, &block) query = TweetStream::Arguments.new(user_ids) filter(query.options.merge(:follow => query), &block) end
ruby
{ "resource": "" }
q15949
TweetStream.Client.userstream
train
def userstream(query_params = {}, &block) stream_params = {:host => 'userstream.twitter.com'} query_params.merge!(:extra_stream_parameters => stream_params) start('/1.1/user.json', query_params, &block) end
ruby
{ "resource": "" }
q15950
TweetStream.Client.start
train
def start(path, query_parameters = {}, &block) if EventMachine.reactor_running? connect(path, query_parameters, &block) else if EventMachine.epoll? EventMachine.epoll elsif EventMachine.kqueue? EventMachine.kqueue else Kernel.warn('Your OS does not support epoll or kqueue.') end EventMachine.run do connect(path, query_parameters, &block) end end end
ruby
{ "resource": "" }
q15951
TweetStream.Client.connect
train
def connect(path, options = {}, &block) stream_parameters, callbacks = connection_options(path, options) @stream = EM::Twitter::Client.connect(stream_parameters) @stream.each do |item| begin hash = MultiJson.decode(item, :symbolize_keys => true) rescue MultiJson::DecodeError invoke_callback(callbacks['error'], "MultiJson::DecodeError occured in stream: #{item}") next end unless hash.is_a?(::Hash) invoke_callback(callbacks['error'], "Unexpected JSON object in stream: #{item}") next end respond_to(hash, callbacks, &block) yield_message_to(callbacks['anything'], hash) end @stream.on_close { invoke_callback(callbacks['close']) } @stream.on_error do |message| invoke_callback(callbacks['error'], message) end @stream.on_unauthorized { invoke_callback(callbacks['unauthorized']) } @stream.on_enhance_your_calm { invoke_callback(callbacks['enhance_your_calm']) } @stream.on_reconnect do |timeout, retries| invoke_callback(callbacks['reconnect'], timeout, retries) end @stream.on_max_reconnects do |timeout, retries| fail TweetStream::ReconnectError.new(timeout, retries) end @stream.on_no_data_received { invoke_callback(callbacks['no_data_received']) } @stream end
ruby
{ "resource": "" }
q15952
PuppetSyntax.Hiera.check_eyaml_data
train
def check_eyaml_data(name, val) error = nil if val.is_a? String err = check_eyaml_blob(val) error = "Key #{name} #{err}" if err elsif val.is_a? Array val.each_with_index do |v, idx| error = check_eyaml_data("#{name}[#{idx}]", v) break if error end elsif val.is_a? Hash val.each do |k,v| error = check_eyaml_data("#{name}['#{k}']", v) break if error end end error end
ruby
{ "resource": "" }
q15953
Danger.DangerJunit.parse_files
train
def parse_files(*files) require 'ox' @tests = [] failed_tests = [] Array(files).flatten.each do |file| raise "No JUnit file was found at #{file}" unless File.exist? file xml_string = File.read(file) doc = Ox.parse(xml_string) suite_root = doc.nodes.first.value == 'testsuites' ? doc.nodes.first : doc @tests += suite_root.nodes.map(&:nodes).flatten.select { |node| node.kind_of?(Ox::Element) && node.value == 'testcase' } failed_suites = suite_root.nodes.select { |suite| suite[:failures].to_i > 0 || suite[:errors].to_i > 0 } failed_tests += failed_suites.map(&:nodes).flatten.select { |node| node.kind_of?(Ox::Element) && node.value == 'testcase' } end @failures = failed_tests.select do |test| test.nodes.count > 0 end.select do |test| node = test.nodes.first node.kind_of?(Ox::Element) && node.value == 'failure' end @errors = failed_tests.select do |test| test.nodes.count > 0 end.select do |test| node = test.nodes.first node.kind_of?(Ox::Element) && node.value == 'error' end @skipped = tests.select do |test| test.nodes.count > 0 end.select do |test| node = test.nodes.first node.kind_of?(Ox::Element) && node.value == 'skipped' end @passes = tests - @failures - @errors - @skipped end
ruby
{ "resource": "" }
q15954
Danger.DangerJunit.report
train
def report return if failures.nil? # because danger calls `report` before loading a file warn("Skipped #{skipped.count} tests.") if show_skipped_tests && skipped.count > 0 unless failures.empty? && errors.empty? fail('Tests have failed, see below for more information.', sticky: false) message = "### Tests: \n\n" tests = (failures + errors) common_attributes = tests.map{|test| test.attributes.keys }.inject(&:&) # check the provided headers are available unless headers.nil? not_available_headers = headers.select { |header| not common_attributes.include?(header) } raise "Some of headers provided aren't available in the JUnit report (#{not_available_headers})" unless not_available_headers.empty? end keys = headers || common_attributes attributes = keys.map(&:to_s).map(&:capitalize) # Create the headers message << attributes.join(' | ') + "|\n" message << attributes.map { |_| '---' }.join(' | ') + "|\n" # Map out the keys to the tests tests.each do |test| row_values = keys.map { |key| test.attributes[key] }.map { |v| auto_link(v) } message << row_values.join(' | ') + "|\n" end markdown message end end
ruby
{ "resource": "" }
q15955
GitFame.Base.to_csv
train
def to_csv CSV.generate do |csv| csv << fields authors.each do |author| csv << fields.map do |f| author.send(f) end end end end
ruby
{ "resource": "" }
q15956
GitFame.Base.printable_fields
train
def printable_fields raw_fields.map do |field| field.is_a?(Array) ? field.last : field end end
ruby
{ "resource": "" }
q15957
GitFame.Base.execute
train
def execute(command, silent = false, &block) result = run_with_timeout(command) if result.success? or silent warn command if @verbose return result unless block return block.call(result) end raise Error, cmd_error_message(command, result.data) rescue Errno::ENOENT raise Error, cmd_error_message(command, $!.message) end
ruby
{ "resource": "" }
q15958
GitFame.Base.current_files
train
def current_files if commit_range.is_range? execute("git #{git_directory_params} -c diff.renames=0 -c diff.renameLimit=1000 diff -M -C -c --name-only --ignore-submodules=all --diff-filter=AM #{encoding_opt} #{default_params} #{commit_range.to_s}") do |result| filter_files(result.to_s.split(/\n/)) end else submodules = current_submodules execute("git #{git_directory_params} ls-tree -r #{commit_range.to_s} --name-only") do |result| filter_files(result.to_s.split(/\n/).select { |f| !submodules.index(f) }) end end end
ruby
{ "resource": "" }
q15959
PusherFake.Configuration.to_options
train
def to_options(options = {}) options.merge( wsHost: socket_options[:host], wsPort: socket_options[:port], cluster: "us-east-1", disableStats: disable_stats ) end
ruby
{ "resource": "" }
q15960
PusherFake.Connection.emit
train
def emit(event, data = {}, channel = nil) message = { event: event, data: MultiJson.dump(data) } message[:channel] = channel if channel PusherFake.log("SEND #{id}: #{message}") socket.send(MultiJson.dump(message)) end
ruby
{ "resource": "" }
q15961
PusherFake.Connection.process
train
def process(data) message = MultiJson.load(data, symbolize_keys: true) event = message[:event] PusherFake.log("RECV #{id}: #{message}") if event.start_with?(CLIENT_EVENT_PREFIX) process_trigger(event, message) else process_event(event, message) end end
ruby
{ "resource": "" }
q15962
Ougai.Logging.trace
train
def trace(message = nil, ex = nil, data = nil, &block) log(TRACE, message, ex, data, block) end
ruby
{ "resource": "" }
q15963
Ougai.Logging.debug
train
def debug(message = nil, ex = nil, data = nil, &block) log(DEBUG, message, ex, data, block) end
ruby
{ "resource": "" }
q15964
Ougai.Logging.info
train
def info(message = nil, ex = nil, data = nil, &block) log(INFO, message, ex, data, block) end
ruby
{ "resource": "" }
q15965
Ougai.Logging.warn
train
def warn(message = nil, ex = nil, data = nil, &block) log(WARN, message, ex, data, block) end
ruby
{ "resource": "" }
q15966
Ougai.Logging.error
train
def error(message = nil, ex = nil, data = nil, &block) log(ERROR, message, ex, data, block) end
ruby
{ "resource": "" }
q15967
Ougai.Logging.fatal
train
def fatal(message = nil, ex = nil, data = nil, &block) log(FATAL, message, ex, data, block) end
ruby
{ "resource": "" }
q15968
Ougai.Logging.unknown
train
def unknown(message = nil, ex = nil, data = nil, &block) args = block ? yield : [message, ex, data] append(UNKNOWN, args) end
ruby
{ "resource": "" }
q15969
CukeSniffer.CLI.catalog_step_calls
train
def catalog_step_calls puts "\nCataloging Step Calls: " steps = CukeSniffer::CukeSnifferHelper.get_all_steps(@features, @step_definitions) steps_map = build_steps_map(steps) @step_definitions.each do |step_definition| print '.' calls = steps_map.find_all {|step, location| step =~ step_definition.regex } step_definition.calls = build_stored_calls_map(calls) end steps_with_expressions = CukeSniffer::CukeSnifferHelper.get_steps_with_expressions(steps) converted_steps = CukeSniffer::CukeSnifferHelper.convert_steps_with_expressions(steps_with_expressions) CukeSniffer::CukeSnifferHelper.catalog_possible_dead_steps(@step_definitions, converted_steps) end
ruby
{ "resource": "" }
q15970
Vandamme.Parser.parse
train
def parse @changelog.scan(@version_header_exp) do |match| version_content = $~.post_match changelog_scanner = StringScanner.new(version_content) changelog_scanner.scan_until(@version_header_exp) @changelog_hash[match[@match_group]] = (changelog_scanner.pre_match || version_content).gsub(/(\A\n+|\n+\z)/, '') end @changelog_hash end
ruby
{ "resource": "" }
q15971
TransmissionRSS.Client.add_torrent
train
def add_torrent(file, type = :url, options = {}) arguments = set_arguments_from_options(options) case type when :url file = URI.encode(file) if URI.decode(file) == file arguments.filename = file when :file arguments.metainfo = Base64.encode64(File.read(file)) else raise ArgumentError.new('type has to be :url or :file.') end response = rpc('torrent-add', arguments) id = get_id_from_response(response) log_message = 'torrent-add result: ' + response.result log_message << ' (id ' + id.to_s + ')' if id @log.debug(log_message) if id && options[:seed_ratio_limit] set_torrent(id, { 'seedRatioLimit' => options[:seed_ratio_limit].to_f, 'seedRatioMode' => 1 }) end response end
ruby
{ "resource": "" }
q15972
TransmissionRSS.Client.get_session_id
train
def get_session_id get = Net::HTTP::Get.new(@rpc_path) add_basic_auth(get) response = request(get) id = response.header['x-transmission-session-id'] if id.nil? @log.debug("could not obtain session id (#{response.code}, " + "#{response.class})") else @log.debug('got session id ' + id) end id end
ruby
{ "resource": "" }
q15973
TransmissionRSS.Config.merge_yaml!
train
def merge_yaml!(path, watch = true) self.merge!(YAML.load_file(path)) rescue TypeError # If YAML loading fails, .load_file returns `false`. else watch_file(path) if watch && linux? end
ruby
{ "resource": "" }
q15974
TransmissionRSS.Aggregator.run
train
def run(interval = 600) @log.debug('aggregator start') loop do @feeds.each do |feed| @log.debug('aggregate ' + feed.url) options = {allow_redirections: :safe} unless feed.validate_cert @log.debug('aggregate certificate validation: false') options[:ssl_verify_mode] = OpenSSL::SSL::VERIFY_NONE end begin content = open(feed.url, options).read rescue StandardError => e @log.debug("retrieval error (#{e.class}: #{e.message})") next end # gzip HTTP Content-Encoding is not automatically decompressed in # Ruby 1.9.3. content = decompress(content) if RUBY_VERSION == '1.9.3' begin items = RSS::Parser.parse(content, false).items rescue StandardError => e @log.debug("parse error (#{e.class}: #{e.message})") next end items.each do |item| result = process_link(feed, item) next if result.nil? end end if interval == -1 @log.debug('single run mode, exiting') break end sleep(interval) end end
ruby
{ "resource": "" }
q15975
TransmissionRSS.Callback.callback
train
def callback(*names) names.each do |name| self.class_eval do define_method name, ->(*args, &block) do @callbacks ||= {} if block @callbacks[name] = block elsif @callbacks[name] @callbacks[name].call(*args) end end end end end
ruby
{ "resource": "" }
q15976
AppEngine.Exec.start
train
def start resolve_parameters version_info = version_info @service, @version env_variables = version_info["envVariables"] || {} beta_settings = version_info["betaSettings"] || {} cloud_sql_instances = beta_settings["cloud_sql_instances"] || [] image = version_info["deployment"]["container"]["image"] config = build_config command, image, env_variables, cloud_sql_instances file = ::Tempfile.new ["cloudbuild_", ".json"] begin ::JSON.dump config, file file.flush Util::Gcloud.execute [ "builds", "submit", "--no-source", "--config=#{file.path}", "--timeout=#{@timeout}"] ensure file.close! end end
ruby
{ "resource": "" }
q15977
Lolcommits.CaptureWindowsAnimated.device_names
train
def device_names @device_names ||= begin names = [] cmd_output = '' count = 0 while cmd_output.empty? || !cmd_output.split('DirectShow')[2] cmd_output = system_call(ffpmeg_list_devices_cmd, true) count += 1 raise 'failed to find a video capture device with ffmpeg -list_devices' if count == 5 sleep 0.1 end cmd_output.gsub!("\r\n", "\n") video = cmd_output.split('DirectShow')[1] video.lines.map do |line| names << Regexp.last_match(1) if line =~ /"(.+)"\n/ end debug "Capturer: found #{names.length} video devices: #{names.join(', ')}" names end end
ruby
{ "resource": "" }
q15978
Lolcommits.Runner.run_capture
train
def run_capture puts '*** Preserving this moment in history.' unless capture_stealth self.snapshot_loc = config.raw_image(image_file_type) self.main_image = config.main_image(sha, image_file_type) capturer = Platform.capturer_class(capture_animated?).new( capture_device: capture_device, capture_delay: capture_delay, snapshot_location: snapshot_loc, video_location: config.video_loc, frames_location: config.frames_loc, animated_duration: capture_animate ) capturer.capture end
ruby
{ "resource": "" }
q15979
RubyXL.ColumnRanges.get_range
train
def get_range(col_index) col_num = col_index + 1 old_range = self.locate_range(col_index) if old_range.nil? then new_range = RubyXL::ColumnRange.new else if old_range.min == col_num && old_range.max == col_num then return old_range # Single column range, OK to change in place elsif old_range.min == col_num then new_range = old_range.dup old_range.min += 1 elsif old_range.max == col_num then new_range = old_range.dup old_range.max -= 1 else range_before = old_range.dup range_before.max = col_index # col_num - 1 self << range_before old_range.min = col_num + 1 new_range = RubyXL::ColumnRange.new end end new_range.min = new_range.max = col_num self << new_range return new_range end
ruby
{ "resource": "" }
q15980
RubyXL.Workbook.save
train
def save(dst_file_path = nil) dst_file_path ||= root.source_file_path extension = File.extname(dst_file_path) unless %w{.xlsx .xlsm}.include?(extension.downcase) raise "Unsupported extension: #{extension} (only .xlsx and .xlsm files are supported)." end File.open(dst_file_path, "wb") { |output_file| FileUtils.copy_stream(root.stream, output_file) } return dst_file_path end
ruby
{ "resource": "" }
q15981
RubyXL.Workbook.[]
train
def [](ind) case ind when Integer then worksheets[ind] when String then worksheets.find { |ws| ws.sheet_name == ind } end end
ruby
{ "resource": "" }
q15982
RubyXL.Workbook.add_worksheet
train
def add_worksheet(name = nil) if name.nil? then n = 0 begin name = SHEET_NAME_TEMPLATE % (n += 1) end until self[name].nil? end new_worksheet = Worksheet.new(:workbook => self, :sheet_name => name) worksheets << new_worksheet new_worksheet end
ruby
{ "resource": "" }
q15983
RubyXL.LegacyWorksheet.validate_workbook
train
def validate_workbook() unless @workbook.nil? || @workbook.worksheets.nil? return if @workbook.worksheets.any? { |sheet| sheet.equal?(self) } end raise "This worksheet #{self} is not in workbook #{@workbook}" end
ruby
{ "resource": "" }
q15984
RubyXL.LegacyWorksheet.ensure_cell_exists
train
def ensure_cell_exists(row_index, column_index = 0) validate_nonnegative(row_index) validate_nonnegative(column_index) sheet_data.rows[row_index] || add_row(row_index) end
ruby
{ "resource": "" }
q15985
RubyXL.CellConvenienceMethods.change_fill
train
def change_fill(rgb = 'ffffff') validate_worksheet Color.validate_color(rgb) self.style_index = workbook.modify_fill(self.style_index, rgb) end
ruby
{ "resource": "" }
q15986
RubyXL.CellConvenienceMethods.change_font_name
train
def change_font_name(new_font_name = 'Verdana') validate_worksheet font = get_cell_font.dup font.set_name(new_font_name) update_font_references(font) end
ruby
{ "resource": "" }
q15987
RubyXL.CellConvenienceMethods.change_font_size
train
def change_font_size(font_size = 10) validate_worksheet raise 'Argument must be a number' unless font_size.is_a?(Integer) || font_size.is_a?(Float) font = get_cell_font.dup font.set_size(font_size) update_font_references(font) end
ruby
{ "resource": "" }
q15988
RubyXL.CellConvenienceMethods.change_font_color
train
def change_font_color(font_color = '000000') validate_worksheet Color.validate_color(font_color) font = get_cell_font.dup font.set_rgb_color(font_color) update_font_references(font) end
ruby
{ "resource": "" }
q15989
RubyXL.CellConvenienceMethods.change_font_italics
train
def change_font_italics(italicized = false) validate_worksheet font = get_cell_font.dup font.set_italic(italicized) update_font_references(font) end
ruby
{ "resource": "" }
q15990
RubyXL.CellConvenienceMethods.change_font_bold
train
def change_font_bold(bolded = false) validate_worksheet font = get_cell_font.dup font.set_bold(bolded) update_font_references(font) end
ruby
{ "resource": "" }
q15991
RubyXL.CellConvenienceMethods.change_font_underline
train
def change_font_underline(underlined = false) validate_worksheet font = get_cell_font.dup font.set_underline(underlined) update_font_references(font) end
ruby
{ "resource": "" }
q15992
RubyXL.CellConvenienceMethods.update_font_references
train
def update_font_references(modified_font) xf = workbook.register_new_font(modified_font, get_cell_xf) self.style_index = workbook.register_new_xf(xf) end
ruby
{ "resource": "" }
q15993
RubyXL.CellConvenienceMethods.font_switch
train
def font_switch(change_type, arg) case change_type when Worksheet::NAME then change_font_name(arg) when Worksheet::SIZE then change_font_size(arg) when Worksheet::COLOR then change_font_color(arg) when Worksheet::ITALICS then change_font_italics(arg) when Worksheet::BOLD then change_font_bold(arg) when Worksheet::UNDERLINE then change_font_underline(arg) when Worksheet::STRIKETHROUGH then change_font_strikethrough(arg) else raise 'Invalid change_type' end end
ruby
{ "resource": "" }
q15994
RubyXL.WorksheetConvenienceMethods.get_column_width_raw
train
def get_column_width_raw(column_index = 0) validate_workbook validate_nonnegative(column_index) range = cols.locate_range(column_index) range && range.width end
ruby
{ "resource": "" }
q15995
RubyXL.WorksheetConvenienceMethods.change_column_width_raw
train
def change_column_width_raw(column_index, width) validate_workbook ensure_cell_exists(0, column_index) range = cols.get_range(column_index) range.width = width range.custom_width = true end
ruby
{ "resource": "" }
q15996
RubyXL.WorksheetConvenienceMethods.change_row_font
train
def change_row_font(row_index, change_type, arg, font) validate_workbook ensure_cell_exists(row_index) xf = workbook.register_new_font(font, get_row_xf(row_index)) row = sheet_data[row_index] row.style_index = workbook.register_new_xf(xf) row.cells.each { |c| c.font_switch(change_type, arg) unless c.nil? } end
ruby
{ "resource": "" }
q15997
RubyXL.WorksheetConvenienceMethods.change_column_font
train
def change_column_font(column_index, change_type, arg, font, xf) validate_workbook ensure_cell_exists(0, column_index) xf = workbook.register_new_font(font, xf) cols.get_range(column_index).style_index = workbook.register_new_xf(xf) sheet_data.rows.each { |row| c = row && row[column_index] c.font_switch(change_type, arg) unless c.nil? } end
ruby
{ "resource": "" }
q15998
RubyXL.WorksheetConvenienceMethods.merge_cells
train
def merge_cells(start_row, start_col, end_row, end_col) validate_workbook self.merged_cells ||= RubyXL::MergedCells.new # TODO: add validation to make sure ranges are not intersecting with existing ones merged_cells << RubyXL::MergedCell.new(:ref => RubyXL::Reference.new(start_row, end_row, start_col, end_col)) end
ruby
{ "resource": "" }
q15999
Procodile.Instance.environment_variables
train
def environment_variables vars = @process.environment_variables.merge({ 'PROC_NAME' => self.description, 'PID_FILE' => self.pid_file_path, 'APP_ROOT' => @process.config.root }) vars['PORT'] = @port.to_s if @port vars end
ruby
{ "resource": "" }