repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.get_rsrc
def get_rsrc(rsrc, format = :json) # puts object_id validate_connected raise JSS::InvalidDataError, 'format must be :json or :xml' unless %i[json xml].include? format # TODO: fix what rubocop is complaining about in the line below. # (I doubt we want to CGI.escape the whole resource) rsrc = URI.encode rsrc begin @last_http_response = @cnx[rsrc].get(accept: format) rescue RestClient::ExceptionWithResponse => e handle_http_error e end # TODO: make sure we're returning the String version of the # response (i.e. its body) here and in POST, PUT, DELETE. format == :json ? JSON.parse(@last_http_response, symbolize_names: true) : @last_http_response end
ruby
def get_rsrc(rsrc, format = :json) # puts object_id validate_connected raise JSS::InvalidDataError, 'format must be :json or :xml' unless %i[json xml].include? format # TODO: fix what rubocop is complaining about in the line below. # (I doubt we want to CGI.escape the whole resource) rsrc = URI.encode rsrc begin @last_http_response = @cnx[rsrc].get(accept: format) rescue RestClient::ExceptionWithResponse => e handle_http_error e end # TODO: make sure we're returning the String version of the # response (i.e. its body) here and in POST, PUT, DELETE. format == :json ? JSON.parse(@last_http_response, symbolize_names: true) : @last_http_response end
[ "def", "get_rsrc", "(", "rsrc", ",", "format", "=", ":json", ")", "# puts object_id", "validate_connected", "raise", "JSS", "::", "InvalidDataError", ",", "'format must be :json or :xml'", "unless", "%i[", "json", "xml", "]", ".", "include?", "format", "# TODO: fix what rubocop is complaining about in the line below.", "# (I doubt we want to CGI.escape the whole resource)", "rsrc", "=", "URI", ".", "encode", "rsrc", "begin", "@last_http_response", "=", "@cnx", "[", "rsrc", "]", ".", "get", "(", "accept", ":", "format", ")", "rescue", "RestClient", "::", "ExceptionWithResponse", "=>", "e", "handle_http_error", "e", "end", "# TODO: make sure we're returning the String version of the", "# response (i.e. its body) here and in POST, PUT, DELETE.", "format", "==", ":json", "?", "JSON", ".", "parse", "(", "@last_http_response", ",", "symbolize_names", ":", "true", ")", ":", "@last_http_response", "end" ]
disconnect Get an arbitrary JSS resource The first argument is the resource to get (the part of the API url after the 'JSSResource/' ) By default we get the data in JSON, and parse it into a ruby data structure (arrays, hashes, strings, etc) with symbolized Hash keys. @param rsrc[String] the resource to get (the part of the API url after the 'JSSResource/' ) @param format[Symbol] either ;json or :xml If the second argument is :xml, the XML data is returned as a String. @return [Hash,String] the result of the get
[ "disconnect", "Get", "an", "arbitrary", "JSS", "resource" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L525-L542
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.put_rsrc
def put_rsrc(rsrc, xml) validate_connected # convert CRs & to 
 xml.gsub!(/\r/, '
') # send the data @last_http_response = @cnx[rsrc].put(xml, content_type: 'text/xml') rescue RestClient::ExceptionWithResponse => e handle_http_error e end
ruby
def put_rsrc(rsrc, xml) validate_connected # convert CRs & to 
 xml.gsub!(/\r/, '
') # send the data @last_http_response = @cnx[rsrc].put(xml, content_type: 'text/xml') rescue RestClient::ExceptionWithResponse => e handle_http_error e end
[ "def", "put_rsrc", "(", "rsrc", ",", "xml", ")", "validate_connected", "# convert CRs & to 
", "xml", ".", "gsub!", "(", "/", "\\r", "/", ",", "'
'", ")", "# send the data", "@last_http_response", "=", "@cnx", "[", "rsrc", "]", ".", "put", "(", "xml", ",", "content_type", ":", "'text/xml'", ")", "rescue", "RestClient", "::", "ExceptionWithResponse", "=>", "e", "handle_http_error", "e", "end" ]
Change an existing JSS resource @param rsrc[String] the API resource being changed, the URL part after 'JSSResource/' @param xml[String] the xml specifying the changes. @return [String] the xml response from the server.
[ "Change", "an", "existing", "JSS", "resource" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L552-L562
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.post_rsrc
def post_rsrc(rsrc, xml = '') validate_connected # convert CRs & to 
 xml.gsub!(/\r/, '
') if xml # send the data @last_http_response = @cnx[rsrc].post xml, content_type: 'text/xml', accept: :json rescue RestClient::ExceptionWithResponse => e handle_http_error e end
ruby
def post_rsrc(rsrc, xml = '') validate_connected # convert CRs & to 
 xml.gsub!(/\r/, '
') if xml # send the data @last_http_response = @cnx[rsrc].post xml, content_type: 'text/xml', accept: :json rescue RestClient::ExceptionWithResponse => e handle_http_error e end
[ "def", "post_rsrc", "(", "rsrc", ",", "xml", "=", "''", ")", "validate_connected", "# convert CRs & to 
", "xml", ".", "gsub!", "(", "/", "\\r", "/", ",", "'
'", ")", "if", "xml", "# send the data", "@last_http_response", "=", "@cnx", "[", "rsrc", "]", ".", "post", "xml", ",", "content_type", ":", "'text/xml'", ",", "accept", ":", ":json", "rescue", "RestClient", "::", "ExceptionWithResponse", "=>", "e", "handle_http_error", "e", "end" ]
Create a new JSS resource @param rsrc[String] the API resource being created, the URL part after 'JSSResource/' @param xml[String] the xml specifying the new object. @return [String] the xml response from the server.
[ "Create", "a", "new", "JSS", "resource" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L572-L582
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.delete_rsrc
def delete_rsrc(rsrc, xml = nil) validate_connected raise MissingDataError, 'Missing :rsrc' if rsrc.nil? # payload? return delete_with_payload rsrc, xml if xml # delete the resource @last_http_response = @cnx[rsrc].delete rescue RestClient::ExceptionWithResponse => e handle_http_error e end
ruby
def delete_rsrc(rsrc, xml = nil) validate_connected raise MissingDataError, 'Missing :rsrc' if rsrc.nil? # payload? return delete_with_payload rsrc, xml if xml # delete the resource @last_http_response = @cnx[rsrc].delete rescue RestClient::ExceptionWithResponse => e handle_http_error e end
[ "def", "delete_rsrc", "(", "rsrc", ",", "xml", "=", "nil", ")", "validate_connected", "raise", "MissingDataError", ",", "'Missing :rsrc'", "if", "rsrc", ".", "nil?", "# payload?", "return", "delete_with_payload", "rsrc", ",", "xml", "if", "xml", "# delete the resource", "@last_http_response", "=", "@cnx", "[", "rsrc", "]", ".", "delete", "rescue", "RestClient", "::", "ExceptionWithResponse", "=>", "e", "handle_http_error", "e", "end" ]
post_rsrc Delete a resource from the JSS @param rsrc[String] the resource to create, the URL part after 'JSSResource/' @return [String] the xml response from the server.
[ "post_rsrc", "Delete", "a", "resource", "from", "the", "JSS" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L590-L601
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.master_distribution_point
def master_distribution_point(refresh = false) @master_distribution_point = nil if refresh return @master_distribution_point if @master_distribution_point all_dps = JSS::DistributionPoint.all refresh, api: self @master_distribution_point = case all_dps.size when 0 raise JSS::NoSuchItemError, 'No distribution points defined' when 1 JSS::DistributionPoint.fetch id: all_dps.first[:id], api: self else JSS::DistributionPoint.fetch id: :master, api: self end end
ruby
def master_distribution_point(refresh = false) @master_distribution_point = nil if refresh return @master_distribution_point if @master_distribution_point all_dps = JSS::DistributionPoint.all refresh, api: self @master_distribution_point = case all_dps.size when 0 raise JSS::NoSuchItemError, 'No distribution points defined' when 1 JSS::DistributionPoint.fetch id: all_dps.first[:id], api: self else JSS::DistributionPoint.fetch id: :master, api: self end end
[ "def", "master_distribution_point", "(", "refresh", "=", "false", ")", "@master_distribution_point", "=", "nil", "if", "refresh", "return", "@master_distribution_point", "if", "@master_distribution_point", "all_dps", "=", "JSS", "::", "DistributionPoint", ".", "all", "refresh", ",", "api", ":", "self", "@master_distribution_point", "=", "case", "all_dps", ".", "size", "when", "0", "raise", "JSS", "::", "NoSuchItemError", ",", "'No distribution points defined'", "when", "1", "JSS", "::", "DistributionPoint", ".", "fetch", "id", ":", "all_dps", ".", "first", "[", ":id", "]", ",", "api", ":", "self", "else", "JSS", "::", "DistributionPoint", ".", "fetch", "id", ":", ":master", ",", "api", ":", "self", "end", "end" ]
Get the DistributionPoint instance for the master distribution point in the JSS. If there's only one in the JSS, return it even if not marked as master. @param refresh[Boolean] re-read from the API? @return [JSS::DistributionPoint]
[ "Get", "the", "DistributionPoint", "instance", "for", "the", "master", "distribution", "point", "in", "the", "JSS", ".", "If", "there", "s", "only", "one", "in", "the", "JSS", "return", "it", "even", "if", "not", "marked", "as", "master", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L831-L846
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.my_distribution_point
def my_distribution_point(refresh = false) @my_distribution_point = nil if refresh return @my_distribution_point if @my_distribution_point my_net_seg = my_network_segments[0] @my_distribution_point = JSS::NetworkSegment.fetch(id: my_net_seg, api: self).distribution_point if my_net_seg @my_distribution_point ||= master_distribution_point refresh @my_distribution_point end
ruby
def my_distribution_point(refresh = false) @my_distribution_point = nil if refresh return @my_distribution_point if @my_distribution_point my_net_seg = my_network_segments[0] @my_distribution_point = JSS::NetworkSegment.fetch(id: my_net_seg, api: self).distribution_point if my_net_seg @my_distribution_point ||= master_distribution_point refresh @my_distribution_point end
[ "def", "my_distribution_point", "(", "refresh", "=", "false", ")", "@my_distribution_point", "=", "nil", "if", "refresh", "return", "@my_distribution_point", "if", "@my_distribution_point", "my_net_seg", "=", "my_network_segments", "[", "0", "]", "@my_distribution_point", "=", "JSS", "::", "NetworkSegment", ".", "fetch", "(", "id", ":", "my_net_seg", ",", "api", ":", "self", ")", ".", "distribution_point", "if", "my_net_seg", "@my_distribution_point", "||=", "master_distribution_point", "refresh", "@my_distribution_point", "end" ]
Get the DistributionPoint instance for the machine running this code, based on its IP address. If none is defined for this IP address, use the result of master_distribution_point @param refresh[Boolean] should the distribution point be re-queried? @return [JSS::DistributionPoint]
[ "Get", "the", "DistributionPoint", "instance", "for", "the", "machine", "running", "this", "code", "based", "on", "its", "IP", "address", ".", "If", "none", "is", "defined", "for", "this", "IP", "address", "use", "the", "result", "of", "master_distribution_point" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L856-L864
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.network_segments_for_ip
def network_segments_for_ip(ip) ok_ip = IPAddr.new(ip) matches = [] network_ranges.each { |id, subnet| matches << id if subnet.include?(ok_ip) } matches end
ruby
def network_segments_for_ip(ip) ok_ip = IPAddr.new(ip) matches = [] network_ranges.each { |id, subnet| matches << id if subnet.include?(ok_ip) } matches end
[ "def", "network_segments_for_ip", "(", "ip", ")", "ok_ip", "=", "IPAddr", ".", "new", "(", "ip", ")", "matches", "=", "[", "]", "network_ranges", ".", "each", "{", "|", "id", ",", "subnet", "|", "matches", "<<", "id", "if", "subnet", ".", "include?", "(", "ok_ip", ")", "}", "matches", "end" ]
def network_segments Find the ids of the network segments that contain a given IP address. Even tho IPAddr.include? will take a String or an IPAddr I convert the ip to an IPAddr so that an exception will be raised if the ip isn't a valid ip. @param ip[String, IPAddr] the IP address to locate @param refresh[Boolean] should the data be re-queried? @return [Array<Integer>] the ids of the NetworkSegments containing the given ip
[ "def", "network_segments", "Find", "the", "ids", "of", "the", "network", "segments", "that", "contain", "a", "given", "IP", "address", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L899-L904
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.send_mobiledevice_mdm_command
def send_mobiledevice_mdm_command(targets, command, data = {}) JSS::MobileDevice.send_mdm_command(targets, command, opts: data, api: self) end
ruby
def send_mobiledevice_mdm_command(targets, command, data = {}) JSS::MobileDevice.send_mdm_command(targets, command, opts: data, api: self) end
[ "def", "send_mobiledevice_mdm_command", "(", "targets", ",", "command", ",", "data", "=", "{", "}", ")", "JSS", "::", "MobileDevice", ".", "send_mdm_command", "(", "targets", ",", "command", ",", "opts", ":", "data", ",", "api", ":", "self", ")", "end" ]
Send an MDM command to one or more mobile devices managed by this JSS see {JSS::MobileDevice.send_mdm_command} @deprecated Please use JSS::MobileDevice.send_mdm_command or its convenience methods. @see JSS::MDM
[ "Send", "an", "MDM", "command", "to", "one", "or", "more", "mobile", "devices", "managed", "by", "this", "JSS" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L922-L924
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.verify_basic_args
def verify_basic_args(args) # must have server, user, and pw raise JSS::MissingDataError, 'No JSS :server specified, or in configuration.' unless args[:server] raise JSS::MissingDataError, 'No JSS :user specified, or in configuration.' unless args[:user] raise JSS::MissingDataError, "Missing :pw for user '#{args[:user]}'" unless args[:pw] end
ruby
def verify_basic_args(args) # must have server, user, and pw raise JSS::MissingDataError, 'No JSS :server specified, or in configuration.' unless args[:server] raise JSS::MissingDataError, 'No JSS :user specified, or in configuration.' unless args[:user] raise JSS::MissingDataError, "Missing :pw for user '#{args[:user]}'" unless args[:pw] end
[ "def", "verify_basic_args", "(", "args", ")", "# must have server, user, and pw", "raise", "JSS", "::", "MissingDataError", ",", "'No JSS :server specified, or in configuration.'", "unless", "args", "[", ":server", "]", "raise", "JSS", "::", "MissingDataError", ",", "'No JSS :user specified, or in configuration.'", "unless", "args", "[", ":user", "]", "raise", "JSS", "::", "MissingDataError", ",", "\"Missing :pw for user '#{args[:user]}'\"", "unless", "args", "[", ":pw", "]", "end" ]
Raise execeptions if we don't have essential data for the connection @param args[Hash] The args for #connect @return [void]
[ "Raise", "execeptions", "if", "we", "don", "t", "have", "essential", "data", "for", "the", "connection" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L1024-L1029
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.verify_server_version
def verify_server_version @connected = true # the jssuser resource is readable by anyone with a JSS acct # regardless of their permissions. # However, it's marked as 'deprecated'. Hopefully jamf will # keep this basic level of info available for basic authentication # and JSS version checking. begin @server = JSS::Server.new get_rsrc('jssuser')[:user], self rescue RestClient::Unauthorized raise JSS::AuthenticationError, "Incorrect JSS username or password for '#{@user}@#{@server_host}:#{@port}'." end min_vers = JSS.parse_jss_version(JSS::MINIMUM_SERVER_VERSION)[:version] return if @server.version >= min_vers # we're good... err_msg = "JSS version #{@server.raw_version} to low. Must be >= #{min_vers}" @connected = false raise JSS::UnsupportedError, err_msg end
ruby
def verify_server_version @connected = true # the jssuser resource is readable by anyone with a JSS acct # regardless of their permissions. # However, it's marked as 'deprecated'. Hopefully jamf will # keep this basic level of info available for basic authentication # and JSS version checking. begin @server = JSS::Server.new get_rsrc('jssuser')[:user], self rescue RestClient::Unauthorized raise JSS::AuthenticationError, "Incorrect JSS username or password for '#{@user}@#{@server_host}:#{@port}'." end min_vers = JSS.parse_jss_version(JSS::MINIMUM_SERVER_VERSION)[:version] return if @server.version >= min_vers # we're good... err_msg = "JSS version #{@server.raw_version} to low. Must be >= #{min_vers}" @connected = false raise JSS::UnsupportedError, err_msg end
[ "def", "verify_server_version", "@connected", "=", "true", "# the jssuser resource is readable by anyone with a JSS acct", "# regardless of their permissions.", "# However, it's marked as 'deprecated'. Hopefully jamf will", "# keep this basic level of info available for basic authentication", "# and JSS version checking.", "begin", "@server", "=", "JSS", "::", "Server", ".", "new", "get_rsrc", "(", "'jssuser'", ")", "[", ":user", "]", ",", "self", "rescue", "RestClient", "::", "Unauthorized", "raise", "JSS", "::", "AuthenticationError", ",", "\"Incorrect JSS username or password for '#{@user}@#{@server_host}:#{@port}'.\"", "end", "min_vers", "=", "JSS", ".", "parse_jss_version", "(", "JSS", "::", "MINIMUM_SERVER_VERSION", ")", "[", ":version", "]", "return", "if", "@server", ".", "version", ">=", "min_vers", "# we're good...", "err_msg", "=", "\"JSS version #{@server.raw_version} to low. Must be >= #{min_vers}\"", "@connected", "=", "false", "raise", "JSS", "::", "UnsupportedError", ",", "err_msg", "end" ]
Verify that we can connect with the args provided, and that the server version is high enough for this version of ruby-jss. This makes the first API GET call and will raise an exception if things are wrong, like failed authentication. Will also raise an exception if the JSS version is too low (see also JSS::Server) @return [void]
[ "Verify", "that", "we", "can", "connect", "with", "the", "args", "provided", "and", "that", "the", "server", "version", "is", "high", "enough", "for", "this", "version", "of", "ruby", "-", "jss", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L1041-L1061
train
PixarAnimationStudios/ruby-jss
lib/jss/api_connection.rb
JSS.APIConnection.build_rest_url
def build_rest_url(args) @server_host = args[:server] @port = args[:port].to_i if args[:server_path] # remove leading & trailing slashes in serverpath if any @server_path = args[:server_path].sub %r{^/*(.*?)/*$}, Regexp.last_match(1) # re-add single trailing slash @server_path << '/' end # we're using ssl if: # 1) args[:use_ssl] is anything but false # or # 2) the port is a known ssl port. args[:use_ssl] = args[:use_ssl] != false || SSL_PORTS.include?(@port) @protocol = 'http' @protocol << 's' if args[:use_ssl] # and here's the URL "#{@protocol}://#{@server_host}:#{@port}/#{@server_path}#{RSRC_BASE}" end
ruby
def build_rest_url(args) @server_host = args[:server] @port = args[:port].to_i if args[:server_path] # remove leading & trailing slashes in serverpath if any @server_path = args[:server_path].sub %r{^/*(.*?)/*$}, Regexp.last_match(1) # re-add single trailing slash @server_path << '/' end # we're using ssl if: # 1) args[:use_ssl] is anything but false # or # 2) the port is a known ssl port. args[:use_ssl] = args[:use_ssl] != false || SSL_PORTS.include?(@port) @protocol = 'http' @protocol << 's' if args[:use_ssl] # and here's the URL "#{@protocol}://#{@server_host}:#{@port}/#{@server_path}#{RSRC_BASE}" end
[ "def", "build_rest_url", "(", "args", ")", "@server_host", "=", "args", "[", ":server", "]", "@port", "=", "args", "[", ":port", "]", ".", "to_i", "if", "args", "[", ":server_path", "]", "# remove leading & trailing slashes in serverpath if any", "@server_path", "=", "args", "[", ":server_path", "]", ".", "sub", "%r{", "}", ",", "Regexp", ".", "last_match", "(", "1", ")", "# re-add single trailing slash", "@server_path", "<<", "'/'", "end", "# we're using ssl if:", "# 1) args[:use_ssl] is anything but false", "# or", "# 2) the port is a known ssl port.", "args", "[", ":use_ssl", "]", "=", "args", "[", ":use_ssl", "]", "!=", "false", "||", "SSL_PORTS", ".", "include?", "(", "@port", ")", "@protocol", "=", "'http'", "@protocol", "<<", "'s'", "if", "args", "[", ":use_ssl", "]", "# and here's the URL", "\"#{@protocol}://#{@server_host}:#{@port}/#{@server_path}#{RSRC_BASE}\"", "end" ]
Build the base URL for the API connection @param args[Hash] The args for #connect @return [String] The URI encoded URL
[ "Build", "the", "base", "URL", "for", "the", "API", "connection" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_connection.rb#L1069-L1090
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/sitable.rb
JSS.Sitable.site=
def site=(new_site) return nil unless updatable? || creatable? # unset the site? Use nil or an empty string if NON_SITES.include? new_site unset_site return end new_id = JSS::Site.valid_id new_site, api: @api new_name = JSS::Site.map_all_ids_to(:name, api: @api)[new_id] # no change, go home. return nil if new_name == @site_name raise JSS::NoSuchItemError, "Site '#{new_site}' is not known to the JSS" unless new_id @site_name = new_name @site_id = new_id @need_to_update = true end
ruby
def site=(new_site) return nil unless updatable? || creatable? # unset the site? Use nil or an empty string if NON_SITES.include? new_site unset_site return end new_id = JSS::Site.valid_id new_site, api: @api new_name = JSS::Site.map_all_ids_to(:name, api: @api)[new_id] # no change, go home. return nil if new_name == @site_name raise JSS::NoSuchItemError, "Site '#{new_site}' is not known to the JSS" unless new_id @site_name = new_name @site_id = new_id @need_to_update = true end
[ "def", "site", "=", "(", "new_site", ")", "return", "nil", "unless", "updatable?", "||", "creatable?", "# unset the site? Use nil or an empty string", "if", "NON_SITES", ".", "include?", "new_site", "unset_site", "return", "end", "new_id", "=", "JSS", "::", "Site", ".", "valid_id", "new_site", ",", "api", ":", "@api", "new_name", "=", "JSS", "::", "Site", ".", "map_all_ids_to", "(", ":name", ",", "api", ":", "@api", ")", "[", "new_id", "]", "# no change, go home.", "return", "nil", "if", "new_name", "==", "@site_name", "raise", "JSS", "::", "NoSuchItemError", ",", "\"Site '#{new_site}' is not known to the JSS\"", "unless", "new_id", "@site_name", "=", "new_name", "@site_id", "=", "new_id", "@need_to_update", "=", "true", "end" ]
cat assigned? Change the site of this object. Any of the NON_SITES values will unset the site @param new_site[Integer, String] The new site @return [void]
[ "cat", "assigned?", "Change", "the", "site", "of", "this", "object", ".", "Any", "of", "the", "NON_SITES", "values", "will", "unset", "the", "site" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/sitable.rb#L120-L139
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/sitable.rb
JSS.Sitable.parse_site
def parse_site site_data = if self.class::SITE_SUBSET == :top @init_data[:site] elsif @init_data[self.class::SITE_SUBSET] @init_data[self.class::SITE_SUBSET][:site] end site_data ||= { name: NO_SITE_NAME, id: NO_SITE_ID } @site_name = site_data[:name] @site_id = site_data[:id] end
ruby
def parse_site site_data = if self.class::SITE_SUBSET == :top @init_data[:site] elsif @init_data[self.class::SITE_SUBSET] @init_data[self.class::SITE_SUBSET][:site] end site_data ||= { name: NO_SITE_NAME, id: NO_SITE_ID } @site_name = site_data[:name] @site_id = site_data[:id] end
[ "def", "parse_site", "site_data", "=", "if", "self", ".", "class", "::", "SITE_SUBSET", "==", ":top", "@init_data", "[", ":site", "]", "elsif", "@init_data", "[", "self", ".", "class", "::", "SITE_SUBSET", "]", "@init_data", "[", "self", ".", "class", "::", "SITE_SUBSET", "]", "[", ":site", "]", "end", "site_data", "||=", "{", "name", ":", "NO_SITE_NAME", ",", "id", ":", "NO_SITE_ID", "}", "@site_name", "=", "site_data", "[", ":name", "]", "@site_id", "=", "site_data", "[", ":id", "]", "end" ]
Parse the site data from any incoming API data @return [void]
[ "Parse", "the", "site", "data", "from", "any", "incoming", "API", "data" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/sitable.rb#L161-L172
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/sitable.rb
JSS.Sitable.add_site_to_xml
def add_site_to_xml(xmldoc) root = xmldoc.root site_elem = if self.class::SITE_SUBSET == :top root.add_element 'site' else parent_elem = root.elements[self.class::SITE_SUBSET.to_s] parent_elem ||= root.add_element(self.class::SITE_SUBSET.to_s) parent_elem.add_element 'site' end site_elem.add_element('name').text = site_name.to_s end
ruby
def add_site_to_xml(xmldoc) root = xmldoc.root site_elem = if self.class::SITE_SUBSET == :top root.add_element 'site' else parent_elem = root.elements[self.class::SITE_SUBSET.to_s] parent_elem ||= root.add_element(self.class::SITE_SUBSET.to_s) parent_elem.add_element 'site' end site_elem.add_element('name').text = site_name.to_s end
[ "def", "add_site_to_xml", "(", "xmldoc", ")", "root", "=", "xmldoc", ".", "root", "site_elem", "=", "if", "self", ".", "class", "::", "SITE_SUBSET", "==", ":top", "root", ".", "add_element", "'site'", "else", "parent_elem", "=", "root", ".", "elements", "[", "self", ".", "class", "::", "SITE_SUBSET", ".", "to_s", "]", "parent_elem", "||=", "root", ".", "add_element", "(", "self", ".", "class", "::", "SITE_SUBSET", ".", "to_s", ")", "parent_elem", ".", "add_element", "'site'", "end", "site_elem", ".", "add_element", "(", "'name'", ")", ".", "text", "=", "site_name", ".", "to_s", "end" ]
parse site Add the site to the XML for POSTing or PUTting to the API. @param xmldoc[REXML::Document] The in-construction XML document @return [void]
[ "parse", "site", "Add", "the", "site", "to", "the", "XML", "for", "POSTing", "or", "PUTting", "to", "the", "API", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/sitable.rb#L180-L191
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/peripheral.rb
JSS.Peripheral.associate
def associate(computer) if computer =~ /^d+$/ raise JSS::NoSuchItemError, "No computer in the JSS with id #{computer}" unless JSS::Computer.all_ids(api: @api).include? computer @computer_id = computer else raise JSS::NoSuchItemError, "No computer in the JSS with name #{computer}" unless JSS::Computer.all_names(api: @api).include? computer @computer_id = JSS::Computer.map_all_ids_to(:name, api: @api).invert[computer] end @need_to_update = true end
ruby
def associate(computer) if computer =~ /^d+$/ raise JSS::NoSuchItemError, "No computer in the JSS with id #{computer}" unless JSS::Computer.all_ids(api: @api).include? computer @computer_id = computer else raise JSS::NoSuchItemError, "No computer in the JSS with name #{computer}" unless JSS::Computer.all_names(api: @api).include? computer @computer_id = JSS::Computer.map_all_ids_to(:name, api: @api).invert[computer] end @need_to_update = true end
[ "def", "associate", "(", "computer", ")", "if", "computer", "=~", "/", "/", "raise", "JSS", "::", "NoSuchItemError", ",", "\"No computer in the JSS with id #{computer}\"", "unless", "JSS", "::", "Computer", ".", "all_ids", "(", "api", ":", "@api", ")", ".", "include?", "computer", "@computer_id", "=", "computer", "else", "raise", "JSS", "::", "NoSuchItemError", ",", "\"No computer in the JSS with name #{computer}\"", "unless", "JSS", "::", "Computer", ".", "all_names", "(", "api", ":", "@api", ")", ".", "include?", "computer", "@computer_id", "=", "JSS", "::", "Computer", ".", "map_all_ids_to", "(", ":name", ",", "api", ":", "@api", ")", ".", "invert", "[", "computer", "]", "end", "@need_to_update", "=", "true", "end" ]
Associate this peripheral with a computer. @param computer[String,Integer] the name or id of a computer in the JSS @return [void]
[ "Associate", "this", "peripheral", "with", "a", "computer", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/peripheral.rb#L233-L242
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/peripheral.rb
JSS.Peripheral.check_field
def check_field(field, value) ### get the field defs for this PeriphType, omitting the leading nil @field_defs ||= JSS::PeripheralType.fetch(:name => @type, api: @api).fields.compact ### we must have the right number of fields, and they must have the same names ### as the definition required_fields = @field_defs.map{|f| f[:name]} raise JSS::InvalidDataError, "Peripherals of type '#{@type}' doesn't have a field '#{field}', they only have: #{required_fields.join(', ')}" unless required_fields.include? field ### any menu fields can only have values as defined by the type. menu_flds = @field_defs.select{|f| f[:type] == "menu" } menu_flds.each do |mf| next unless mf[:name] == field raise JSS::InvalidDataError, "The value for field '#{field}' must be one of: #{mf[:choices].join(', ')}" unless mf[:choices].include? value end #if menu_flds.include? field end
ruby
def check_field(field, value) ### get the field defs for this PeriphType, omitting the leading nil @field_defs ||= JSS::PeripheralType.fetch(:name => @type, api: @api).fields.compact ### we must have the right number of fields, and they must have the same names ### as the definition required_fields = @field_defs.map{|f| f[:name]} raise JSS::InvalidDataError, "Peripherals of type '#{@type}' doesn't have a field '#{field}', they only have: #{required_fields.join(', ')}" unless required_fields.include? field ### any menu fields can only have values as defined by the type. menu_flds = @field_defs.select{|f| f[:type] == "menu" } menu_flds.each do |mf| next unless mf[:name] == field raise JSS::InvalidDataError, "The value for field '#{field}' must be one of: #{mf[:choices].join(', ')}" unless mf[:choices].include? value end #if menu_flds.include? field end
[ "def", "check_field", "(", "field", ",", "value", ")", "### get the field defs for this PeriphType, omitting the leading nil", "@field_defs", "||=", "JSS", "::", "PeripheralType", ".", "fetch", "(", ":name", "=>", "@type", ",", "api", ":", "@api", ")", ".", "fields", ".", "compact", "### we must have the right number of fields, and they must have the same names", "### as the definition", "required_fields", "=", "@field_defs", ".", "map", "{", "|", "f", "|", "f", "[", ":name", "]", "}", "raise", "JSS", "::", "InvalidDataError", ",", "\"Peripherals of type '#{@type}' doesn't have a field '#{field}', they only have: #{required_fields.join(', ')}\"", "unless", "required_fields", ".", "include?", "field", "### any menu fields can only have values as defined by the type.", "menu_flds", "=", "@field_defs", ".", "select", "{", "|", "f", "|", "f", "[", ":type", "]", "==", "\"menu\"", "}", "menu_flds", ".", "each", "do", "|", "mf", "|", "next", "unless", "mf", "[", ":name", "]", "==", "field", "raise", "JSS", "::", "InvalidDataError", ",", "\"The value for field '#{field}' must be one of: #{mf[:choices].join(', ')}\"", "unless", "mf", "[", ":choices", "]", ".", "include?", "value", "end", "#if menu_flds.include? field", "end" ]
check a field, the field name must match those defined in the appropriate peripheral type. If a field is a menu field, the value must also be one of those defined in the periph type. Raise an exception if wrong.
[ "check", "a", "field", "the", "field", "name", "must", "match", "those", "defined", "in", "the", "appropriate", "peripheral", "type", ".", "If", "a", "field", "is", "a", "menu", "field", "the", "value", "must", "also", "be", "one", "of", "those", "defined", "in", "the", "periph", "type", ".", "Raise", "an", "exception", "if", "wrong", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/peripheral.rb#L270-L286
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/patch_policy.rb
JSS.PatchPolicy.validate_patch_title
def validate_patch_title(a_title) if a_title.is_a? JSS::PatchTitle @patch_title = a_title return a_title.id end raise JSS::MissingDataError, ':patch_title is required' unless a_title title_id = JSS::PatchTitle.valid_id a_title return title_id if title_id raise JSS::NoSuchItemError, "No Patch Title matches '#{a_title}'" end
ruby
def validate_patch_title(a_title) if a_title.is_a? JSS::PatchTitle @patch_title = a_title return a_title.id end raise JSS::MissingDataError, ':patch_title is required' unless a_title title_id = JSS::PatchTitle.valid_id a_title return title_id if title_id raise JSS::NoSuchItemError, "No Patch Title matches '#{a_title}'" end
[ "def", "validate_patch_title", "(", "a_title", ")", "if", "a_title", ".", "is_a?", "JSS", "::", "PatchTitle", "@patch_title", "=", "a_title", "return", "a_title", ".", "id", "end", "raise", "JSS", "::", "MissingDataError", ",", "':patch_title is required'", "unless", "a_title", "title_id", "=", "JSS", "::", "PatchTitle", ".", "valid_id", "a_title", "return", "title_id", "if", "title_id", "raise", "JSS", "::", "NoSuchItemError", ",", "\"No Patch Title matches '#{a_title}'\"", "end" ]
raise an error if the patch title we're trying to use isn't available in the jss. If handed a PatchTitle instance, we assume it came from the JSS @param new_title[String,Integer,JSS::PatchTitle] the title to validate @return [Integer] the id of the valid title
[ "raise", "an", "error", "if", "the", "patch", "title", "we", "re", "trying", "to", "use", "isn", "t", "available", "in", "the", "jss", ".", "If", "handed", "a", "PatchTitle", "instance", "we", "assume", "it", "came", "from", "the", "JSS" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/patch_policy.rb#L543-L552
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/patch_policy.rb
JSS.PatchPolicy.validate_target_version
def validate_target_version(tgt_vers) raise JSS::MissingDataError, "target_version can't be nil" unless tgt_vers JSS::Validate.non_empty_string tgt_vers unless patch_title(:refresh).versions.key? tgt_vers errmsg = "Version '#{tgt_vers}' does not exist for title: #{patch_title_name}." raise JSS::NoSuchItemError, errmsg end return tgt_vers if patch_title.versions_with_packages.key? tgt_vers errmsg = "Version '#{tgt_vers}' cannot be used in Patch Policies until a package is assigned to it." raise JSS::UnsupportedError, errmsg end
ruby
def validate_target_version(tgt_vers) raise JSS::MissingDataError, "target_version can't be nil" unless tgt_vers JSS::Validate.non_empty_string tgt_vers unless patch_title(:refresh).versions.key? tgt_vers errmsg = "Version '#{tgt_vers}' does not exist for title: #{patch_title_name}." raise JSS::NoSuchItemError, errmsg end return tgt_vers if patch_title.versions_with_packages.key? tgt_vers errmsg = "Version '#{tgt_vers}' cannot be used in Patch Policies until a package is assigned to it." raise JSS::UnsupportedError, errmsg end
[ "def", "validate_target_version", "(", "tgt_vers", ")", "raise", "JSS", "::", "MissingDataError", ",", "\"target_version can't be nil\"", "unless", "tgt_vers", "JSS", "::", "Validate", ".", "non_empty_string", "tgt_vers", "unless", "patch_title", "(", ":refresh", ")", ".", "versions", ".", "key?", "tgt_vers", "errmsg", "=", "\"Version '#{tgt_vers}' does not exist for title: #{patch_title_name}.\"", "raise", "JSS", "::", "NoSuchItemError", ",", "errmsg", "end", "return", "tgt_vers", "if", "patch_title", ".", "versions_with_packages", ".", "key?", "tgt_vers", "errmsg", "=", "\"Version '#{tgt_vers}' cannot be used in Patch Policies until a package is assigned to it.\"", "raise", "JSS", "::", "UnsupportedError", ",", "errmsg", "end" ]
raise an exception if a given target version is not valid for this policy Otherwise return it
[ "raise", "an", "exception", "if", "a", "given", "target", "version", "is", "not", "valid", "for", "this", "policy", "Otherwise", "return", "it" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/patch_policy.rb#L557-L571
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/patch_policy.rb
JSS.PatchPolicy.refetch_version_info
def refetch_version_info tmp = self.class.fetch id: id @release_date = tmp.release_date @incremental_update = tmp.incremental_update @reboot = tmp.reboot @minimum_os = tmp.minimum_os @kill_apps = tmp.kill_apps end
ruby
def refetch_version_info tmp = self.class.fetch id: id @release_date = tmp.release_date @incremental_update = tmp.incremental_update @reboot = tmp.reboot @minimum_os = tmp.minimum_os @kill_apps = tmp.kill_apps end
[ "def", "refetch_version_info", "tmp", "=", "self", ".", "class", ".", "fetch", "id", ":", "id", "@release_date", "=", "tmp", ".", "release_date", "@incremental_update", "=", "tmp", ".", "incremental_update", "@reboot", "=", "tmp", ".", "reboot", "@minimum_os", "=", "tmp", ".", "minimum_os", "@kill_apps", "=", "tmp", ".", "kill_apps", "end" ]
Update our local version data after the target_version is changed
[ "Update", "our", "local", "version", "data", "after", "the", "target_version", "is", "changed" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/patch_policy.rb#L579-L586
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/user.rb
JSS.User.add_site
def add_site (site) return nil if @sites.map{|s| s[:name]}.include? site raise JSS::InvalidDataError, "No site in the JSS named #{site}" unless JSS::Site.all_names(api: @api).include? site @sites << {:name => site} @need_to_update = true end
ruby
def add_site (site) return nil if @sites.map{|s| s[:name]}.include? site raise JSS::InvalidDataError, "No site in the JSS named #{site}" unless JSS::Site.all_names(api: @api).include? site @sites << {:name => site} @need_to_update = true end
[ "def", "add_site", "(", "site", ")", "return", "nil", "if", "@sites", ".", "map", "{", "|", "s", "|", "s", "[", ":name", "]", "}", ".", "include?", "site", "raise", "JSS", "::", "InvalidDataError", ",", "\"No site in the JSS named #{site}\"", "unless", "JSS", "::", "Site", ".", "all_names", "(", "api", ":", "@api", ")", ".", "include?", "site", "@sites", "<<", "{", ":name", "=>", "site", "}", "@need_to_update", "=", "true", "end" ]
Add this user to a site @param site[String] the name of the site @return [void]
[ "Add", "this", "user", "to", "a", "site" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/user.rb#L233-L238
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/user.rb
JSS.User.remove_site
def remove_site (site) return nil unless @sites.map{|s| s[:name]}.include? site @sites.reject!{|s| s[:name] == site} @need_to_update = true end
ruby
def remove_site (site) return nil unless @sites.map{|s| s[:name]}.include? site @sites.reject!{|s| s[:name] == site} @need_to_update = true end
[ "def", "remove_site", "(", "site", ")", "return", "nil", "unless", "@sites", ".", "map", "{", "|", "s", "|", "s", "[", ":name", "]", "}", ".", "include?", "site", "@sites", ".", "reject!", "{", "|", "s", "|", "s", "[", ":name", "]", "==", "site", "}", "@need_to_update", "=", "true", "end" ]
Remove this user from a site @param site[String] the name of the site @return [void]
[ "Remove", "this", "user", "from", "a", "site" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/user.rb#L247-L251
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.overlap?
def overlap?(other_segment) raise TypeError, 'Argument must be a JSS::NetworkSegment' unless \ other_segment.is_a? JSS::NetworkSegment other_range = other_segment.range range.include?(other_range.begin) || range.include?(other_range.end) end
ruby
def overlap?(other_segment) raise TypeError, 'Argument must be a JSS::NetworkSegment' unless \ other_segment.is_a? JSS::NetworkSegment other_range = other_segment.range range.include?(other_range.begin) || range.include?(other_range.end) end
[ "def", "overlap?", "(", "other_segment", ")", "raise", "TypeError", ",", "'Argument must be a JSS::NetworkSegment'", "unless", "other_segment", ".", "is_a?", "JSS", "::", "NetworkSegment", "other_range", "=", "other_segment", ".", "range", "range", ".", "include?", "(", "other_range", ".", "begin", ")", "||", "range", ".", "include?", "(", "other_range", ".", "end", ")", "end" ]
Does this network segment overlap with another? @param other_segment[JSS::NetworkSegment] the other segment to check @return [Boolean] Does the other segment overlap this one?
[ "Does", "this", "network", "segment", "overlap", "with", "another?" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L304-L309
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.include?
def include?(thing) if thing.is_a? JSS::NetworkSegment @starting_address <= thing.range.begin && @ending_address >= thing.range.end else thing = IPAddr.new thing.to_s range.include? thing end end
ruby
def include?(thing) if thing.is_a? JSS::NetworkSegment @starting_address <= thing.range.begin && @ending_address >= thing.range.end else thing = IPAddr.new thing.to_s range.include? thing end end
[ "def", "include?", "(", "thing", ")", "if", "thing", ".", "is_a?", "JSS", "::", "NetworkSegment", "@starting_address", "<=", "thing", ".", "range", ".", "begin", "&&", "@ending_address", ">=", "thing", ".", "range", ".", "end", "else", "thing", "=", "IPAddr", ".", "new", "thing", ".", "to_s", "range", ".", "include?", "thing", "end", "end" ]
Does this network segment include an address or another segment? Inclusion means the other is completely inside this one. @param thing[JSS::NetworkSegment, String, IPAddr] the other thing to check @return [Boolean] Does this segment include the other?
[ "Does", "this", "network", "segment", "include", "an", "address", "or", "another", "segment?", "Inclusion", "means", "the", "other", "is", "completely", "inside", "this", "one", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L318-L325
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.building=
def building=(newval) new = JSS::Building.all.select { |b| (b[:id] == newval) || (b[:name] == newval) }[0] raise JSS::MissingDataError, "No building matching '#{newval}'" unless new @building = new[:name] @need_to_update = true end
ruby
def building=(newval) new = JSS::Building.all.select { |b| (b[:id] == newval) || (b[:name] == newval) }[0] raise JSS::MissingDataError, "No building matching '#{newval}'" unless new @building = new[:name] @need_to_update = true end
[ "def", "building", "=", "(", "newval", ")", "new", "=", "JSS", "::", "Building", ".", "all", ".", "select", "{", "|", "b", "|", "(", "b", "[", ":id", "]", "==", "newval", ")", "||", "(", "b", "[", ":name", "]", "==", "newval", ")", "}", "[", "0", "]", "raise", "JSS", "::", "MissingDataError", ",", "\"No building matching '#{newval}'\"", "unless", "new", "@building", "=", "new", "[", ":name", "]", "@need_to_update", "=", "true", "end" ]
Does this network segment equal another? equality means the ranges are equal @param other_segment[JSS::NetworkSegment] the other segment to check @return [Boolean] Does this segment include the other? Set the building @param newval[String, Integer] the new building by name or id, must be in the JSS @return [void]
[ "Does", "this", "network", "segment", "equal", "another?", "equality", "means", "the", "ranges", "are", "equal" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L346-L351
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.override_buildings=
def override_buildings=(newval) raise JSS::InvalidDataError, 'New value must be boolean true or false' unless JSS::TRUE_FALSE.include? newval @override_buildings = newval @need_to_update = true end
ruby
def override_buildings=(newval) raise JSS::InvalidDataError, 'New value must be boolean true or false' unless JSS::TRUE_FALSE.include? newval @override_buildings = newval @need_to_update = true end
[ "def", "override_buildings", "=", "(", "newval", ")", "raise", "JSS", "::", "InvalidDataError", ",", "'New value must be boolean true or false'", "unless", "JSS", "::", "TRUE_FALSE", ".", "include?", "newval", "@override_buildings", "=", "newval", "@need_to_update", "=", "true", "end" ]
set the override buildings option @param newval[Boolean] the new override buildings option @return [void]
[ "set", "the", "override", "buildings", "option" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L359-L363
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.department=
def department=(newval) new = JSS::Department.all.select { |b| (b[:id] == newval) || (b[:name] == newval) }[0] raise JSS::MissingDataError, "No department matching '#{newval}' in the JSS" unless new @department = new[:name] @need_to_update = true end
ruby
def department=(newval) new = JSS::Department.all.select { |b| (b[:id] == newval) || (b[:name] == newval) }[0] raise JSS::MissingDataError, "No department matching '#{newval}' in the JSS" unless new @department = new[:name] @need_to_update = true end
[ "def", "department", "=", "(", "newval", ")", "new", "=", "JSS", "::", "Department", ".", "all", ".", "select", "{", "|", "b", "|", "(", "b", "[", ":id", "]", "==", "newval", ")", "||", "(", "b", "[", ":name", "]", "==", "newval", ")", "}", "[", "0", "]", "raise", "JSS", "::", "MissingDataError", ",", "\"No department matching '#{newval}' in the JSS\"", "unless", "new", "@department", "=", "new", "[", ":name", "]", "@need_to_update", "=", "true", "end" ]
set the department @param newval[String, Integer] the new dept by name or id, must be in the JSS @return [void]
[ "set", "the", "department" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L371-L376
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.override_departments=
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
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
[ "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" ]
set the override depts option @param newval[Boolean] the new setting @return [void]
[ "set", "the", "override", "depts", "option" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L385-L389
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.distribution_point=
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
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
[ "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" ]
set the distribution_point @param newval[String, Integer] the new dist. point by name or id, must be in the JSS @return [void]
[ "set", "the", "distribution_point" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L397-L402
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.netboot_server=
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
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
[ "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" ]
set the netboot_server @param newval[String, Integer] the new netboot server by name or id, must be in the JSS @return [void]
[ "set", "the", "netboot_server" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L410-L415
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.swu_server=
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
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
[ "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" ]
set the sw update server @param newval[String, Integer] the new server by name or id, must be in the JSS @return [void]
[ "set", "the", "sw", "update", "server" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L423-L428
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/network_segment.rb
JSS.NetworkSegment.set_ip_range
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
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
[ "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" ]
set a new starting and ending addr at the same time. @see_also NetworkSegment.ip_range for how to specify the starting and ending addresses. @param starting_address[String] The starting address, possibly masked @param ending_address[String] The ending address @param mask[String] The subnet mask to apply to the starting address to get the ending address @param cidr[String, Integer] he cidr value to apply to the starting address to get the ending address @return [void]
[ "set", "a", "new", "starting", "and", "ending", "addr", "at", "the", "same", "time", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/network_segment.rb#L485-L495
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/script.rb
JSS.Script.name=
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
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
[ "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" ]
filename= Change the script's display name If the filename is the same as the name, the filename will be changed also @param new_val[String] the new display name @return [void]
[ "filename", "=", "Change", "the", "script", "s", "display", "name" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/script.rb#L178-L191
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/script.rb
JSS.Script.os_requirements=
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
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
[ "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" ]
name= Change the os_requirements Minumum OS's can be specified as a string using the notation ">=10.6.7" See the {JSS.expand_min_os} method for details. @param new_val[String, Array<String>] the new os requirements as a comma-separted String or an Array of Strings @return [void] @example String value myscript.os_requirements "10.5, 10.5.3, 10.6.x" @example Array value ok_oses = ['10.5', '10.5.3', '10.6.x'] myscript.os_requirements ok_oses @example Minimum OS myscript.os_requirements ">=10.7.5"
[ "name", "=", "Change", "the", "os_requirements" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/script.rb#L212-L231
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/script.rb
JSS.Script.priority=
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
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
[ "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" ]
os_requirements= Change the priority of this script @param new_val[Integer] the new priority, which must be one of {PRIORITIES} @return [void]
[ "os_requirements", "=", "Change", "the", "priority", "of", "this", "script" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/script.rb#L239-L245
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/script.rb
JSS.Script.parameters=
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
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
[ "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" ]
notes= Replace all the script parameters at once. This will replace the entire set with the hash provided. @param new_val[Hash] the Hash keys must exist in {PARAMETER_KEYS} @return [void]
[ "notes", "=", "Replace", "all", "the", "script", "parameters", "at", "once", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/script.rb#L283-L296
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/script.rb
JSS.Script.set_parameter
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
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
[ "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" ]
parameters= Change one of the stored parameters @param param_num[Integer] which param are we setting? must be 4..11 @param new_val[String] the new value for the parameter @return [void]
[ "parameters", "=", "Change", "one", "of", "the", "stored", "parameters" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/script.rb#L306-L313
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/script.rb
JSS.Script.script_contents=
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
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
[ "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" ]
Change the executable code of this script. If the arg is a Pathname instance, or a String starting with "/" Then the arg is assumed to be a file from which to read the code. Otherwise it should be a String with the code itself, and it must start with '#!" After doing this, use {#create} or {#update} to write it to the database or use {#upload_master_file} to save it to the master dist. point. @param new_val[String,Pathname] the new script contents or a path to a file containing it. @return [void]
[ "Change", "the", "executable", "code", "of", "this", "script", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/script.rb#L329-L347
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/script.rb
JSS.Script.delete_master_file
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
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
[ "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" ]
upload Delete the filename from the master distribution point, if it exists. If you'll be uploading several files you can specify unmount as false, and do it manually when all are finished. @param rw_pw[String] the password for the read/write account on the master Distribution Point @param unmount[Boolean] whether or not ot unount the distribution point when finished. @return [Boolean] was the file deleted?
[ "upload", "Delete", "the", "filename", "from", "the", "master", "distribution", "point", "if", "it", "exists", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/script.rb#L384-L394
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/script.rb
JSS.Script.run
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
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
[ "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", "=~", "/", "\\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" ]
Run this script on the current machine using the "jamf runScript" command. If the script code is available in the {#script_contents} attribute, then that code is saved to a tmp file, and executed. Otherwise, the script is assumed to be stored on the distribution point. If the dist. point has http downloads enabled, then the URL is used as the path with the 'jamf runScript' command. If http is not an option, the dist.point is mounted, and the script copied locally before running. In this case the options must include :ro_pw => 'somepass' to provide the read-only password for mounting the distribution point. If :unmount => true is provided, the dist. point will be unmounted immediately after copying the script locally. Otherwise it will remain mounted, in case there's further need of it. Any local on-disk copies of the script are removed after running. After the script runs, this method returns a two-item Array. - the first item is an Integer, the exit status of the script itself (0 means success) - the second item is a String, the output (stdout + stderr) of the jamf binary, which will include the script output. The exit status of the jamf binary process will be available as a Process::Status object in $? immediately after running. @param opts[Hash] the options for running the script @option opts :target[String,Pathname] the 'target drive', passed to the script as the first commandline option. Defaults to '/' @option opts :computer_name[String] the name of the computer, passed to the script as the second commandline option. Defaults to the name of the current machine @option opts :username[String] the username to be passed to the script as the third commandline option. @option opts :p1..:p8[String] the values to be passed as the 4th - 11th commandline options, overriding those defined with the script in the JSS @option opts :ro_pw[String] the read-only password for mounting the distribution point, if needed @option opts :unmount[Boolean} should the dist. point be unmounted when finished, if we mounted it? @option opts :verbose[Boolean] should the 'jamf runScript' command be verbose? @option opts :show_output[Boolean] should the output (stdout + stderr) of 'jamf runScript' be copied to stdout in realtime, as well as returned? @return [Array<(Integer,String)>] the exit status of the *script* and stdout+stderr of 'jamf runScript'. The exit status of the jamf binary will be available in $? immediately after running. *NOTE* In the WEB UI and API, the definable parameters are numbered 4-11, since 1, 2, & 3 are the target drive, computer name, and user name respectively. However, the jamf binary refers to them as p1-p8, and that's how they are expected as options to #run. So if :p1=> "new param" is given as an aption to #run, it will override any value that the API provided in @parameters[:parameter4]
[ "Run", "this", "script", "on", "the", "current", "machine", "using", "the", "jamf", "runScript", "command", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/script.rb#L450-L547
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/script.rb
JSS.Script.rest_xml
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
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
[ "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" ]
Return the xml for creating or updating this script in the JSS
[ "Return", "the", "xml", "for", "creating", "or", "updating", "this", "script", "in", "the", "JSS" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/script.rb#L564-L587
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/peripheral_type.rb
JSS.PeripheralType.set_field
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
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
[ "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" ]
Replace the details of one specific field. The order must already exist. Otherwise use {#append_field}, {#prepend_field}, or {#insert_field} @param order[Integer] which field are we replacing? @param field[Hash] the new field data @return [void]
[ "Replace", "the", "details", "of", "one", "specific", "field", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/peripheral_type.rb#L172-L177
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/peripheral_type.rb
JSS.PeripheralType.insert_field
def insert_field(order,field = {}) field_ok? field @fields.insert((order -1), field) order_fields @need_to_update = true end
ruby
def insert_field(order,field = {}) field_ok? field @fields.insert((order -1), field) order_fields @need_to_update = true end
[ "def", "insert_field", "(", "order", ",", "field", "=", "{", "}", ")", "field_ok?", "field", "@fields", ".", "insert", "(", "(", "order", "-", "1", ")", ",", "field", ")", "order_fields", "@need_to_update", "=", "true", "end" ]
Add a new field to the middle of the fields Array. @param order[Integer] where does the new field go? @param field[Hash] the new field data @return [void]
[ "Add", "a", "new", "field", "to", "the", "middle", "of", "the", "fields", "Array", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/peripheral_type.rb#L216-L221
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/peripheral_type.rb
JSS.PeripheralType.delete_field
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
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
[ "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" ]
Remove a field from the array of fields. @param order[Integer] which field to remove? @return [void]
[ "Remove", "a", "field", "from", "the", "array", "of", "fields", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/peripheral_type.rb#L230-L237
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/peripheral_type.rb
JSS.PeripheralType.field_ok?
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
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
[ "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" ]
is a Hash of field data OK for use in the JSS? Return true or raise an exception
[ "is", "a", "Hash", "of", "field", "data", "OK", "for", "use", "in", "the", "JSS?", "Return", "true", "or", "raise", "an", "exception" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/peripheral_type.rb#L250-L263
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/group.rb
JSS.Group.remove_member
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
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
[ "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" ]
Remove a member by id, or name @param m[Integer,String] the id or name of the member to remove @return [void]
[ "Remove", "a", "member", "by", "id", "or", "name" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/group.rb#L339-L344
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/group.rb
JSS.Group.check_member
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
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
[ "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" ]
Check that a potential group member is valid in the JSS. Arg must be an id or name. An exception is raised if the device doesn't exist. @return [Hash{:id=>Integer,:name=>String}] the valid id and name
[ "Check", "that", "a", "potential", "group", "member", "is", "valid", "in", "the", "JSS", ".", "Arg", "must", "be", "an", "id", "or", "name", ".", "An", "exception", "is", "raised", "if", "the", "device", "doesn", "t", "exist", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/group.rb#L403-L411
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/patch_title.rb
JSS.PatchTitle.email_notification=
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
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
[ "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" ]
Set email notifications on or off @param new_setting[Boolean] Should email notifications be on or off? @return [void]
[ "Set", "email", "notifications", "on", "or", "off" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/patch_title.rb#L428-L432
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/patch_title.rb
JSS.PatchTitle.web_notification=
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
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
[ "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" ]
Set web notifications on or off @param new_setting[Boolean] Should email notifications be on or off? @return [void]
[ "Set", "web", "notifications", "on", "or", "off" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/patch_title.rb#L440-L444
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/patch_title.rb
JSS.PatchTitle.rest_xml
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
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
[ "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" ]
Return the REST XML for this title, with the current values, for saving or updating.
[ "Return", "the", "REST", "XML", "for", "this", "title", "with", "the", "current", "values", "for", "saving", "or", "updating", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/patch_title.rb#L495-L513
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/patch_title.rb
JSS.PatchTitle.add_changed_pkg_xml
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
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
[ "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" ]
rest_xml add xml for any package changes to patch versions
[ "rest_xml", "add", "xml", "for", "any", "package", "changes", "to", "patch", "versions" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/patch_title.rb#L516-L526
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object.rb
JSS.APIObject.validate_object_history_available
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
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
[ "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" ]
Raise an exception if object history is not available for this object @return [void]
[ "Raise", "an", "exception", "if", "object", "history", "is", "not", "available", "for", "this", "object" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object.rb#L887-L893
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object.rb
JSS.APIObject.validate_external_init_data
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
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
[ "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" ]
If we were passed pre-lookedup API data, validate it, raising exceptions if not valid. DEPRECATED: pre-lookedup data is never used and support for it will be going away. TODO: delete this and all defined VALID_DATA_KEYS @return [void]
[ "If", "we", "were", "passed", "pre", "-", "lookedup", "API", "data", "validate", "it", "raising", "exceptions", "if", "not", "valid", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object.rb#L905-L920
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object.rb
JSS.APIObject.validate_init_for_creation
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
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
[ "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" ]
validate_init_data If we're making a new object in the JSS, make sure we were given valid data to do so, raise exceptions otherwise. NOTE: some subclasses may do further validation. TODO: support for objects that can have duplicate names. @param args[Hash] The args passed to #initialize @return [void]
[ "validate_init_data", "If", "we", "re", "making", "a", "new", "object", "in", "the", "JSS", "make", "sure", "we", "were", "given", "valid", "data", "to", "do", "so", "raise", "exceptions", "otherwise", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object.rb#L933-L939
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object.rb
JSS.APIObject.look_up_object_data
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
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
[ "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" ]
Given initialization args, perform an API lookup for an object. @param args[Hash] The args passed to #initialize @return [Hash] The parsed JSON data for the object from the API
[ "Given", "initialization", "args", "perform", "an", "API", "lookup", "for", "an", "object", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object.rb#L947-L973
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object.rb
JSS.APIObject.rest_xml
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
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
[ "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" ]
Return a String with the XML Resource for submitting creation or changes to the JSS via the API via the Creatable or Updatable modules Most classes will redefine this method.
[ "Return", "a", "String", "with", "the", "XML", "Resource", "for", "submitting", "creation", "or", "changes", "to", "the", "JSS", "via", "the", "API", "via", "the", "Creatable", "or", "Updatable", "modules" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object.rb#L1160-L1165
train
PixarAnimationStudios/ruby-jss
lib/jss/configuration.rb
JSS.Configuration.reload
def reload(file = nil) clear_all if file read file return true end read_global read_user return true end
ruby
def reload(file = nil) clear_all if file read file return true end read_global read_user return true end
[ "def", "reload", "(", "file", "=", "nil", ")", "clear_all", "if", "file", "read", "file", "return", "true", "end", "read_global", "read_user", "return", "true", "end" ]
Clear the settings and reload the prefs files, or another file if provided @param file[String,Pathname] a non-standard prefs file to load @return [void]
[ "Clear", "the", "settings", "and", "reload", "the", "prefs", "files", "or", "another", "file", "if", "provided" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/configuration.rb#L212-L221
train
PixarAnimationStudios/ruby-jss
lib/jss/configuration.rb
JSS.Configuration.read
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
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
[ "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" ]
Read in any prefs file @param file[String,Pathname] the file to read @return [void]
[ "Read", "in", "any", "prefs", "file" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/configuration.rb#L291-L312
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/vppable.rb
JSS.VPPable.assign_vpp_device_based_licenses=
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
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
[ "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" ]
Set whether or not the VPP licenses should be assigned by device rather than by user @param new_val[Boolean] The new value @return [void]
[ "Set", "whether", "or", "not", "the", "VPP", "licenses", "should", "be", "assigned", "by", "device", "rather", "than", "by", "user" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/vppable.rb#L77-L82
train
PixarAnimationStudios/ruby-jss
lib/jss/api_object/vppable.rb
JSS.VPPable.add_vpp_xml
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
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
[ "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" ]
Insert an appropriate vpp element into the XML for sending changes to the JSS @param xdoc[REXML::Document] The XML document to work with @return [void]
[ "Insert", "an", "appropriate", "vpp", "element", "into", "the", "XML", "for", "sending", "changes", "to", "the", "JSS" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/vppable.rb#L109-L113
train
elct9620/rails-letsencrypt
app/models/concerns/lets_encrypt/certificate_verifiable.rb
LetsEncrypt.CertificateVerifiable.verify
def verify create_order start_challenge wait_verify_status check_verify_status rescue Acme::Client::Error => e retry_on_verify_error(e) end
ruby
def verify create_order start_challenge wait_verify_status check_verify_status rescue Acme::Client::Error => e retry_on_verify_error(e) end
[ "def", "verify", "create_order", "start_challenge", "wait_verify_status", "check_verify_status", "rescue", "Acme", "::", "Client", "::", "Error", "=>", "e", "retry_on_verify_error", "(", "e", ")", "end" ]
Returns true if verify domain is succeed.
[ "Returns", "true", "if", "verify", "domain", "is", "succeed", "." ]
25aa4685320bca4f871fa7e573e10693bc2a2dc3
https://github.com/elct9620/rails-letsencrypt/blob/25aa4685320bca4f871fa7e573e10693bc2a2dc3/app/models/concerns/lets_encrypt/certificate_verifiable.rb#L9-L16
train
weppos/whois-parser
lib/whois/safe_record.rb
Whois.SafeRecord.properties
def properties hash = {} Parser::PROPERTIES.each do |property| hash[property] = __send__(property) end hash end
ruby
def properties hash = {} Parser::PROPERTIES.each do |property| hash[property] = __send__(property) end hash end
[ "def", "properties", "hash", "=", "{", "}", "Parser", "::", "PROPERTIES", ".", "each", "do", "|", "property", "|", "hash", "[", "property", "]", "=", "__send__", "(", "property", ")", "end", "hash", "end" ]
Returns a Hash containing all supported properties for this record along with corresponding values. @return [{ Symbol => Object }]
[ "Returns", "a", "Hash", "containing", "all", "supported", "properties", "for", "this", "record", "along", "with", "corresponding", "values", "." ]
9db810d187a97175c3b28edd100c4edd07d683f2
https://github.com/weppos/whois-parser/blob/9db810d187a97175c3b28edd100c4edd07d683f2/lib/whois/safe_record.rb#L83-L89
train
change/method_profiler
lib/method_profiler/report.rb
MethodProfiler.Report.to_a
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
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
[ "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" ]
Sorts the data by the currently set criteria and returns an array of profiling results. @return [Array] An array of profiling results.
[ "Sorts", "the", "data", "by", "the", "currently", "set", "criteria", "and", "returns", "an", "array", "of", "profiling", "results", "." ]
f2ddb631675211b5d52136e0c3f50ca42728c713
https://github.com/change/method_profiler/blob/f2ddb631675211b5d52136e0c3f50ca42728c713/lib/method_profiler/report.rb#L66-L72
train
change/method_profiler
lib/method_profiler/report.rb
MethodProfiler.Report.to_s
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
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
[ "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" ]
Sorts the data by the currently set criteria and returns a pretty printed table as a string. @return [String] A table of profiling results.
[ "Sorts", "the", "data", "by", "the", "currently", "set", "criteria", "and", "returns", "a", "pretty", "printed", "table", "as", "a", "string", "." ]
f2ddb631675211b5d52136e0c3f50ca42728c713
https://github.com/change/method_profiler/blob/f2ddb631675211b5d52136e0c3f50ca42728c713/lib/method_profiler/report.rb#L78-L94
train
david942j/seccomp-tools
lib/seccomp-tools/asm/asm.rb
SeccompTools.Asm.asm
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
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
[ "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" ]
Assembler of seccomp bpf. @param [String] str @return [String] Raw bpf bytes. @example asm(<<EOS) # lines start with '#' are comments A = sys_number # here's a comment, too A >= 0x40000000 ? dead : next # 'next' is a keyword, denote the next instruction A == read ? ok : next # custom defined label 'dead' and 'ok' A == 1 ? ok : next # SYS_write = 1 in amd64 return ERRNO(1) dead: return KILL ok: return ALLOW EOS #=> <raw binary bytes>
[ "Assembler", "of", "seccomp", "bpf", "." ]
8dfc288a28eab2d683d1a4cc0fed405d75dc5595
https://github.com/david942j/seccomp-tools/blob/8dfc288a28eab2d683d1a4cc0fed405d75dc5595/lib/seccomp-tools/asm/asm.rb#L27-L32
train
david942j/seccomp-tools
lib/seccomp-tools/cli/cli.rb
SeccompTools.CLI.work
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
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
[ "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" ]
Main working method of CLI. @param [Array<String>] argv Command line arguments. @return [void] @example work(%w[--help]) #=> # usage message work(%w[--version]) #=> # version message
[ "Main", "working", "method", "of", "CLI", "." ]
8dfc288a28eab2d683d1a4cc0fed405d75dc5595
https://github.com/david942j/seccomp-tools/blob/8dfc288a28eab2d683d1a4cc0fed405d75dc5595/lib/seccomp-tools/cli/cli.rb#L40-L56
train
david942j/seccomp-tools
lib/seccomp-tools/disasm/disasm.rb
SeccompTools.Disasm.disasm
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
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
[ "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\"", "EOS", "end" ]
Disassemble bpf codes. @param [String] raw The raw bpf bytes. @param [Symbol] arch Architecture.
[ "Disassemble", "bpf", "codes", "." ]
8dfc288a28eab2d683d1a4cc0fed405d75dc5595
https://github.com/david942j/seccomp-tools/blob/8dfc288a28eab2d683d1a4cc0fed405d75dc5595/lib/seccomp-tools/disasm/disasm.rb#L17-L35
train
david942j/seccomp-tools
lib/seccomp-tools/bpf.rb
SeccompTools.BPF.inst
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
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
[ "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" ]
Corresponding instruction object. @return [SeccompTools::Instruction::Base]
[ "Corresponding", "instruction", "object", "." ]
8dfc288a28eab2d683d1a4cc0fed405d75dc5595
https://github.com/david942j/seccomp-tools/blob/8dfc288a28eab2d683d1a4cc0fed405d75dc5595/lib/seccomp-tools/bpf.rb#L91-L102
train
david942j/seccomp-tools
lib/seccomp-tools/util.rb
SeccompTools.Util.supported_archs
def supported_archs @supported_archs ||= Dir.glob(File.join(__dir__, 'consts', '*.rb')) .map { |f| File.basename(f, '.rb').to_sym } .sort end
ruby
def supported_archs @supported_archs ||= Dir.glob(File.join(__dir__, 'consts', '*.rb')) .map { |f| File.basename(f, '.rb').to_sym } .sort end
[ "def", "supported_archs", "@supported_archs", "||=", "Dir", ".", "glob", "(", "File", ".", "join", "(", "__dir__", ",", "'consts'", ",", "'*.rb'", ")", ")", ".", "map", "{", "|", "f", "|", "File", ".", "basename", "(", "f", ",", "'.rb'", ")", ".", "to_sym", "}", ".", "sort", "end" ]
Get currently supported architectures. @return [Array<Symbol>] Architectures.
[ "Get", "currently", "supported", "architectures", "." ]
8dfc288a28eab2d683d1a4cc0fed405d75dc5595
https://github.com/david942j/seccomp-tools/blob/8dfc288a28eab2d683d1a4cc0fed405d75dc5595/lib/seccomp-tools/util.rb#L9-L13
train
david942j/seccomp-tools
lib/seccomp-tools/util.rb
SeccompTools.Util.colorize
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
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
[ "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" ]
Wrapper color codes. @param [String] s Contents to wrapper. @param [Symbol?] t Specific which kind of color to use, valid symbols are defined in {Util.COLOR_CODE}. @return [String] Wrapper with color codes.
[ "Wrapper", "color", "codes", "." ]
8dfc288a28eab2d683d1a4cc0fed405d75dc5595
https://github.com/david942j/seccomp-tools/blob/8dfc288a28eab2d683d1a4cc0fed405d75dc5595/lib/seccomp-tools/util.rb#L57-L64
train
appium/ruby_lib_core
script/commands.rb
Script.CommandsChecker.get_mjsonwp_routes
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
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
[ "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" ]
Set commands implemented in this core library. - implemented_mjsonwp_commands: All commands include ::Selenium::WebDriver::Remote::OSS::Bridge::COMMANDS - implemented_w3c_commands: All commands include ::Selenium::WebDriver::Remote::W3C::Bridge::COMMANDS - implemented_core_commands: All commands except for selenium-webdriver's commands - webdriver_oss_commands: ::Selenium::WebDriver::Remote::OSS::Bridge::COMMANDS - webdriver_w3c_commands: ::Selenium::WebDriver::Remote::W3C::Bridge::COMMANDS Get the bellow url's file. https://raw.githubusercontent.com/appium/appium-base-driver/master/lib/mjsonwp/routes.js?raw=1 @param [String] to_path: A file path to routes.js @return [String] The file path in which has saved `routes.js`.
[ "Set", "commands", "implemented", "in", "this", "core", "library", "." ]
2d8a8f3433f6774a1cc2d76028269ca006ca5273
https://github.com/appium/ruby_lib_core/blob/2d8a8f3433f6774a1cc2d76028269ca006ca5273/script/commands.rb#L49-L56
train
appium/ruby_lib_core
script/commands.rb
Script.CommandsChecker.diff_except_for_webdriver
def diff_except_for_webdriver result = compare_commands(@spec_commands, @implemented_core_commands) white_list.each { |v| result.delete v } result end
ruby
def diff_except_for_webdriver result = compare_commands(@spec_commands, @implemented_core_commands) white_list.each { |v| result.delete v } result end
[ "def", "diff_except_for_webdriver", "result", "=", "compare_commands", "(", "@spec_commands", ",", "@implemented_core_commands", ")", "white_list", ".", "each", "{", "|", "v", "|", "result", ".", "delete", "v", "}", "result", "end" ]
Commands, only this core library, which haven't been implemented in ruby core library yet. @return [Hash]
[ "Commands", "only", "this", "core", "library", "which", "haven", "t", "been", "implemented", "in", "ruby", "core", "library", "yet", "." ]
2d8a8f3433f6774a1cc2d76028269ca006ca5273
https://github.com/appium/ruby_lib_core/blob/2d8a8f3433f6774a1cc2d76028269ca006ca5273/script/commands.rb#L108-L112
train
basecamp/name_of_person
lib/name_of_person/assignable_name.rb
NameOfPerson.AssignableName.name=
def name=(name) full_name = NameOfPerson::PersonName.full(name) self.first_name, self.last_name = full_name&.first, full_name&.last end
ruby
def name=(name) full_name = NameOfPerson::PersonName.full(name) self.first_name, self.last_name = full_name&.first, full_name&.last end
[ "def", "name", "=", "(", "name", ")", "full_name", "=", "NameOfPerson", "::", "PersonName", ".", "full", "(", "name", ")", "self", ".", "first_name", ",", "self", ".", "last_name", "=", "full_name", "&.", "first", ",", "full_name", "&.", "last", "end" ]
Assigns first_name and last_name attributes as extracted from a supplied full name.
[ "Assigns", "first_name", "and", "last_name", "attributes", "as", "extracted", "from", "a", "supplied", "full", "name", "." ]
16978debe3d6391739bfef7da5b4df487f44ccda
https://github.com/basecamp/name_of_person/blob/16978debe3d6391739bfef7da5b4df487f44ccda/lib/name_of_person/assignable_name.rb#L6-L9
train
salesking/sepa_king
lib/sepa_king/message.rb
SEPA.Message.message_identification=
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
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
[ "def", "message_identification", "=", "(", "value", ")", "raise", "ArgumentError", ".", "new", "(", "'message_identification must be a string!'", ")", "unless", "value", ".", "is_a?", "(", "String", ")", "regex", "=", "/", "\\A", "\\+", "\\?", "\\/", "\\-", "\\:", "\\(", "\\)", "\\.", "\\,", "\\'", "\\ ", "\\z", "/", "raise", "ArgumentError", ".", "new", "(", "\"message_identification does not match #{regex}!\"", ")", "unless", "value", ".", "match", "(", "regex", ")", "@message_identification", "=", "value", "end" ]
Set unique identifer for the message
[ "Set", "unique", "identifer", "for", "the", "message" ]
bfe6a633c3a4b6077ece313414d790eca5375681
https://github.com/salesking/sepa_king/blob/bfe6a633c3a4b6077ece313414d790eca5375681/lib/sepa_king/message.rb#L73-L80
train
salesking/sepa_king
lib/sepa_king/message.rb
SEPA.Message.batch_id
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
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
[ "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" ]
Returns the id of the batch to which the given transaction belongs Identified based upon the reference of the transaction
[ "Returns", "the", "id", "of", "the", "batch", "to", "which", "the", "given", "transaction", "belongs", "Identified", "based", "upon", "the", "reference", "of", "the", "transaction" ]
bfe6a633c3a4b6077ece313414d790eca5375681
https://github.com/salesking/sepa_king/blob/bfe6a633c3a4b6077ece313414d790eca5375681/lib/sepa_king/message.rb#L105-L111
train
tweetstream/tweetstream
lib/tweetstream/client.rb
TweetStream.Client.follow
def follow(*user_ids, &block) query = TweetStream::Arguments.new(user_ids) filter(query.options.merge(:follow => query), &block) end
ruby
def follow(*user_ids, &block) query = TweetStream::Arguments.new(user_ids) filter(query.options.merge(:follow => query), &block) end
[ "def", "follow", "(", "*", "user_ids", ",", "&", "block", ")", "query", "=", "TweetStream", "::", "Arguments", ".", "new", "(", "user_ids", ")", "filter", "(", "query", ".", "options", ".", "merge", "(", ":follow", "=>", "query", ")", ",", "block", ")", "end" ]
Returns public statuses from or in reply to a set of users. Mentions ("Hello @user!") and implicit replies ("@user Hello!" created without pressing the reply "swoosh") are not matched. Requires integer user IDs, not screen names. Query parameters may be passed as the last argument.
[ "Returns", "public", "statuses", "from", "or", "in", "reply", "to", "a", "set", "of", "users", ".", "Mentions", "(", "Hello" ]
27c5f411627dc30ce1268923fc9b408652f98050
https://github.com/tweetstream/tweetstream/blob/27c5f411627dc30ce1268923fc9b408652f98050/lib/tweetstream/client.rb#L113-L116
train
tweetstream/tweetstream
lib/tweetstream/client.rb
TweetStream.Client.userstream
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
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
[ "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" ]
Make a call to the userstream api for currently authenticated user
[ "Make", "a", "call", "to", "the", "userstream", "api", "for", "currently", "authenticated", "user" ]
27c5f411627dc30ce1268923fc9b408652f98050
https://github.com/tweetstream/tweetstream/blob/27c5f411627dc30ce1268923fc9b408652f98050/lib/tweetstream/client.rb#L141-L145
train
tweetstream/tweetstream
lib/tweetstream/client.rb
TweetStream.Client.start
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
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
[ "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" ]
connect to twitter while starting a new EventMachine run loop
[ "connect", "to", "twitter", "while", "starting", "a", "new", "EventMachine", "run", "loop" ]
27c5f411627dc30ce1268923fc9b408652f98050
https://github.com/tweetstream/tweetstream/blob/27c5f411627dc30ce1268923fc9b408652f98050/lib/tweetstream/client.rb#L413-L429
train
tweetstream/tweetstream
lib/tweetstream/client.rb
TweetStream.Client.connect
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
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
[ "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" ]
connect to twitter without starting a new EventMachine run loop
[ "connect", "to", "twitter", "without", "starting", "a", "new", "EventMachine", "run", "loop" ]
27c5f411627dc30ce1268923fc9b408652f98050
https://github.com/tweetstream/tweetstream/blob/27c5f411627dc30ce1268923fc9b408652f98050/lib/tweetstream/client.rb#L432-L475
train
voxpupuli/puppet-syntax
lib/puppet-syntax/hiera.rb
PuppetSyntax.Hiera.check_eyaml_data
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
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
[ "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" ]
Recurse through complex data structures. Return on first error.
[ "Recurse", "through", "complex", "data", "structures", ".", "Return", "on", "first", "error", "." ]
eb1592218739119a2f9307b3e33b7e1f1df59a7c
https://github.com/voxpupuli/puppet-syntax/blob/eb1592218739119a2f9307b3e33b7e1f1df59a7c/lib/puppet-syntax/hiera.rb#L25-L42
train
orta/danger-junit
lib/junit/plugin.rb
Danger.DangerJunit.parse_files
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
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
[ "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" ]
Parses multiple XML files, which fills all the attributes, will `raise` for errors @return [void]
[ "Parses", "multiple", "XML", "files", "which", "fills", "all", "the", "attributes", "will", "raise", "for", "errors" ]
32fc5d2c026604a0880a3901783628dab06e4877
https://github.com/orta/danger-junit/blob/32fc5d2c026604a0880a3901783628dab06e4877/lib/junit/plugin.rb#L105-L145
train
orta/danger-junit
lib/junit/plugin.rb
Danger.DangerJunit.report
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
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
[ "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" ]
Causes a build fail if there are test failures, and outputs a markdown table of the results. @return [void]
[ "Causes", "a", "build", "fail", "if", "there", "are", "test", "failures", "and", "outputs", "a", "markdown", "table", "of", "the", "results", "." ]
32fc5d2c026604a0880a3901783628dab06e4877
https://github.com/orta/danger-junit/blob/32fc5d2c026604a0880a3901783628dab06e4877/lib/junit/plugin.rb#L151-L184
train
oleander/git-fame-rb
lib/git_fame/base.rb
GitFame.Base.to_csv
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
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
[ "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" ]
Generate csv output
[ "Generate", "csv", "output" ]
d0f17660bc26d18e27fd86952a84c4a6164689ec
https://github.com/oleander/git-fame-rb/blob/d0f17660bc26d18e27fd86952a84c4a6164689ec/lib/git_fame/base.rb#L121-L130
train
oleander/git-fame-rb
lib/git_fame/base.rb
GitFame.Base.printable_fields
def printable_fields raw_fields.map do |field| field.is_a?(Array) ? field.last : field end end
ruby
def printable_fields raw_fields.map do |field| field.is_a?(Array) ? field.last : field end end
[ "def", "printable_fields", "raw_fields", ".", "map", "do", "|", "field", "|", "field", ".", "is_a?", "(", "Array", ")", "?", "field", ".", "last", ":", "field", "end", "end" ]
Uses the more printable names in @visible_fields
[ "Uses", "the", "more", "printable", "names", "in" ]
d0f17660bc26d18e27fd86952a84c4a6164689ec
https://github.com/oleander/git-fame-rb/blob/d0f17660bc26d18e27fd86952a84c4a6164689ec/lib/git_fame/base.rb#L260-L264
train
oleander/git-fame-rb
lib/git_fame/base.rb
GitFame.Base.execute
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
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
[ "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" ]
Command to be executed at @repository @silent = true wont raise an error on exit code =! 0
[ "Command", "to", "be", "executed", "at" ]
d0f17660bc26d18e27fd86952a84c4a6164689ec
https://github.com/oleander/git-fame-rb/blob/d0f17660bc26d18e27fd86952a84c4a6164689ec/lib/git_fame/base.rb#L313-L323
train
oleander/git-fame-rb
lib/git_fame/base.rb
GitFame.Base.current_files
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
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
[ "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" ]
List all files in current git directory, excluding extensions in @extensions defined by the user
[ "List", "all", "files", "in", "current", "git", "directory", "excluding", "extensions", "in" ]
d0f17660bc26d18e27fd86952a84c4a6164689ec
https://github.com/oleander/git-fame-rb/blob/d0f17660bc26d18e27fd86952a84c4a6164689ec/lib/git_fame/base.rb#L380-L391
train
tristandunn/pusher-fake
lib/pusher-fake/configuration.rb
PusherFake.Configuration.to_options
def to_options(options = {}) options.merge( wsHost: socket_options[:host], wsPort: socket_options[:port], cluster: "us-east-1", disableStats: disable_stats ) end
ruby
def to_options(options = {}) options.merge( wsHost: socket_options[:host], wsPort: socket_options[:port], cluster: "us-east-1", disableStats: disable_stats ) end
[ "def", "to_options", "(", "options", "=", "{", "}", ")", "options", ".", "merge", "(", "wsHost", ":", "socket_options", "[", ":host", "]", ",", "wsPort", ":", "socket_options", "[", ":port", "]", ",", "cluster", ":", "\"us-east-1\"", ",", "disableStats", ":", "disable_stats", ")", "end" ]
Convert the configuration to a hash sutiable for Pusher JS options. @param [Hash] options Custom options for Pusher client.
[ "Convert", "the", "configuration", "to", "a", "hash", "sutiable", "for", "Pusher", "JS", "options", "." ]
7bd5df7253c0bff4b39f0e4eac9891ba6a1735c4
https://github.com/tristandunn/pusher-fake/blob/7bd5df7253c0bff4b39f0e4eac9891ba6a1735c4/lib/pusher-fake/configuration.rb#L63-L70
train
tristandunn/pusher-fake
lib/pusher-fake/connection.rb
PusherFake.Connection.emit
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
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
[ "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" ]
Emit an event to the connection. @param [String] event The event name. @param [Hash] data The event data. @param [String] channel The channel name.
[ "Emit", "an", "event", "to", "the", "connection", "." ]
7bd5df7253c0bff4b39f0e4eac9891ba6a1735c4
https://github.com/tristandunn/pusher-fake/blob/7bd5df7253c0bff4b39f0e4eac9891ba6a1735c4/lib/pusher-fake/connection.rb#L32-L39
train
tristandunn/pusher-fake
lib/pusher-fake/connection.rb
PusherFake.Connection.process
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
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
[ "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" ]
Process an event. @param [String] data The event data as JSON.
[ "Process", "an", "event", "." ]
7bd5df7253c0bff4b39f0e4eac9891ba6a1735c4
https://github.com/tristandunn/pusher-fake/blob/7bd5df7253c0bff4b39f0e4eac9891ba6a1735c4/lib/pusher-fake/connection.rb#L50-L61
train
tilfin/ougai
lib/ougai/logging.rb
Ougai.Logging.trace
def trace(message = nil, ex = nil, data = nil, &block) log(TRACE, message, ex, data, block) end
ruby
def trace(message = nil, ex = nil, data = nil, &block) log(TRACE, message, ex, data, block) end
[ "def", "trace", "(", "message", "=", "nil", ",", "ex", "=", "nil", ",", "data", "=", "nil", ",", "&", "block", ")", "log", "(", "TRACE", ",", "message", ",", "ex", ",", "data", ",", "block", ")", "end" ]
Log any one or more of a message, an exception and structured data as TRACE. @return [Boolean] true @see Logging#debug
[ "Log", "any", "one", "or", "more", "of", "a", "message", "an", "exception", "and", "structured", "data", "as", "TRACE", "." ]
884d8cfebcb9fb4abc3e71571a7f7b132966b561
https://github.com/tilfin/ougai/blob/884d8cfebcb9fb4abc3e71571a7f7b132966b561/lib/ougai/logging.rb#L24-L26
train
tilfin/ougai
lib/ougai/logging.rb
Ougai.Logging.debug
def debug(message = nil, ex = nil, data = nil, &block) log(DEBUG, message, ex, data, block) end
ruby
def debug(message = nil, ex = nil, data = nil, &block) log(DEBUG, message, ex, data, block) end
[ "def", "debug", "(", "message", "=", "nil", ",", "ex", "=", "nil", ",", "data", "=", "nil", ",", "&", "block", ")", "log", "(", "DEBUG", ",", "message", ",", "ex", ",", "data", ",", "block", ")", "end" ]
Log any one or more of a message, an exception and structured data as DEBUG. If the block is given for delay evaluation, it returns them as an array or the one of them as a value. @param message [String] The message to log. Use default_message if not specified. @param ex [Exception] The exception or the error @param data [Object] Any structured data @yieldreturn [String|Exception|Object|Array] Any one or more of former parameters @return [Boolean] true
[ "Log", "any", "one", "or", "more", "of", "a", "message", "an", "exception", "and", "structured", "data", "as", "DEBUG", ".", "If", "the", "block", "is", "given", "for", "delay", "evaluation", "it", "returns", "them", "as", "an", "array", "or", "the", "one", "of", "them", "as", "a", "value", "." ]
884d8cfebcb9fb4abc3e71571a7f7b132966b561
https://github.com/tilfin/ougai/blob/884d8cfebcb9fb4abc3e71571a7f7b132966b561/lib/ougai/logging.rb#L35-L37
train
tilfin/ougai
lib/ougai/logging.rb
Ougai.Logging.info
def info(message = nil, ex = nil, data = nil, &block) log(INFO, message, ex, data, block) end
ruby
def info(message = nil, ex = nil, data = nil, &block) log(INFO, message, ex, data, block) end
[ "def", "info", "(", "message", "=", "nil", ",", "ex", "=", "nil", ",", "data", "=", "nil", ",", "&", "block", ")", "log", "(", "INFO", ",", "message", ",", "ex", ",", "data", ",", "block", ")", "end" ]
Log any one or more of a message, an exception and structured data as INFO. @return [Boolean] true @see Logging#debug
[ "Log", "any", "one", "or", "more", "of", "a", "message", "an", "exception", "and", "structured", "data", "as", "INFO", "." ]
884d8cfebcb9fb4abc3e71571a7f7b132966b561
https://github.com/tilfin/ougai/blob/884d8cfebcb9fb4abc3e71571a7f7b132966b561/lib/ougai/logging.rb#L42-L44
train
tilfin/ougai
lib/ougai/logging.rb
Ougai.Logging.warn
def warn(message = nil, ex = nil, data = nil, &block) log(WARN, message, ex, data, block) end
ruby
def warn(message = nil, ex = nil, data = nil, &block) log(WARN, message, ex, data, block) end
[ "def", "warn", "(", "message", "=", "nil", ",", "ex", "=", "nil", ",", "data", "=", "nil", ",", "&", "block", ")", "log", "(", "WARN", ",", "message", ",", "ex", ",", "data", ",", "block", ")", "end" ]
Log any one or more of a message, an exception and structured data as WARN. @return [Boolean] true @see Logging#debug
[ "Log", "any", "one", "or", "more", "of", "a", "message", "an", "exception", "and", "structured", "data", "as", "WARN", "." ]
884d8cfebcb9fb4abc3e71571a7f7b132966b561
https://github.com/tilfin/ougai/blob/884d8cfebcb9fb4abc3e71571a7f7b132966b561/lib/ougai/logging.rb#L49-L51
train
tilfin/ougai
lib/ougai/logging.rb
Ougai.Logging.error
def error(message = nil, ex = nil, data = nil, &block) log(ERROR, message, ex, data, block) end
ruby
def error(message = nil, ex = nil, data = nil, &block) log(ERROR, message, ex, data, block) end
[ "def", "error", "(", "message", "=", "nil", ",", "ex", "=", "nil", ",", "data", "=", "nil", ",", "&", "block", ")", "log", "(", "ERROR", ",", "message", ",", "ex", ",", "data", ",", "block", ")", "end" ]
Log any one or more of a message, an exception and structured data as ERROR. @return [Boolean] true @see Logging#debug
[ "Log", "any", "one", "or", "more", "of", "a", "message", "an", "exception", "and", "structured", "data", "as", "ERROR", "." ]
884d8cfebcb9fb4abc3e71571a7f7b132966b561
https://github.com/tilfin/ougai/blob/884d8cfebcb9fb4abc3e71571a7f7b132966b561/lib/ougai/logging.rb#L56-L58
train
tilfin/ougai
lib/ougai/logging.rb
Ougai.Logging.fatal
def fatal(message = nil, ex = nil, data = nil, &block) log(FATAL, message, ex, data, block) end
ruby
def fatal(message = nil, ex = nil, data = nil, &block) log(FATAL, message, ex, data, block) end
[ "def", "fatal", "(", "message", "=", "nil", ",", "ex", "=", "nil", ",", "data", "=", "nil", ",", "&", "block", ")", "log", "(", "FATAL", ",", "message", ",", "ex", ",", "data", ",", "block", ")", "end" ]
Log any one or more of a message, an exception and structured data as FATAL. @return [Boolean] true @see Logging#debug
[ "Log", "any", "one", "or", "more", "of", "a", "message", "an", "exception", "and", "structured", "data", "as", "FATAL", "." ]
884d8cfebcb9fb4abc3e71571a7f7b132966b561
https://github.com/tilfin/ougai/blob/884d8cfebcb9fb4abc3e71571a7f7b132966b561/lib/ougai/logging.rb#L63-L65
train
tilfin/ougai
lib/ougai/logging.rb
Ougai.Logging.unknown
def unknown(message = nil, ex = nil, data = nil, &block) args = block ? yield : [message, ex, data] append(UNKNOWN, args) end
ruby
def unknown(message = nil, ex = nil, data = nil, &block) args = block ? yield : [message, ex, data] append(UNKNOWN, args) end
[ "def", "unknown", "(", "message", "=", "nil", ",", "ex", "=", "nil", ",", "data", "=", "nil", ",", "&", "block", ")", "args", "=", "block", "?", "yield", ":", "[", "message", ",", "ex", ",", "data", "]", "append", "(", "UNKNOWN", ",", "args", ")", "end" ]
Log any one or more of a message, an exception and structured data as UNKNOWN. @return [Boolean] true @see Logging#debug
[ "Log", "any", "one", "or", "more", "of", "a", "message", "an", "exception", "and", "structured", "data", "as", "UNKNOWN", "." ]
884d8cfebcb9fb4abc3e71571a7f7b132966b561
https://github.com/tilfin/ougai/blob/884d8cfebcb9fb4abc3e71571a7f7b132966b561/lib/ougai/logging.rb#L70-L73
train
r-cochran/cuke_sniffer
lib/cuke_sniffer/cli.rb
CukeSniffer.CLI.catalog_step_calls
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
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
[ "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" ]
Determines all normal and nested step calls and assigns them to the corresponding step definition. Does direct and fuzzy matching
[ "Determines", "all", "normal", "and", "nested", "step", "calls", "and", "assigns", "them", "to", "the", "corresponding", "step", "definition", ".", "Does", "direct", "and", "fuzzy", "matching" ]
a4fa217c3074b6a172c9be4833d9d5099dc5c317
https://github.com/r-cochran/cuke_sniffer/blob/a4fa217c3074b6a172c9be4833d9d5099dc5c317/lib/cuke_sniffer/cli.rb#L171-L184
train
tech-angels/vandamme
lib/vandamme/parser.rb
Vandamme.Parser.parse
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
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
[ "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" ]
Create a new changelog parser Options: * +changelog+:: Changelog content as a +String+. * +version_header_exp+ (optional):: regexp to match the starting line of version. Defaults to /^#{0,3} ?([\w\d\.-]+\.[\w\d\.-]+[a-zA-Z0-9])(?: \/ (\w+ \d{1,2}(?:st|nd|rd|th)?,\s\d{4}|\d{4}-\d{2}-\d{2}|\w+))?\n?[=-]*/ See http://tech-angels.github.com/vandamme/#changelogs-convention * +format+ (optional):: One of "raw", "markdown", "rdoc" call-seq: parse => aHash Parse changelog file, filling +@changelog_hash+ with versions as keys, and version changelog as content.
[ "Create", "a", "new", "changelog", "parser" ]
9bc3c0651713b24530aed1eb0f4fd9be18eabcc5
https://github.com/tech-angels/vandamme/blob/9bc3c0651713b24530aed1eb0f4fd9be18eabcc5/lib/vandamme/parser.rb#L35-L43
train
nning/transmission-rss
lib/transmission-rss/client.rb
TransmissionRSS.Client.add_torrent
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
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
[ "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" ]
POST json packed torrent add command.
[ "POST", "json", "packed", "torrent", "add", "command", "." ]
07baaf149d9e129e98b4cb496d808a528a59bc5b
https://github.com/nning/transmission-rss/blob/07baaf149d9e129e98b4cb496d808a528a59bc5b/lib/transmission-rss/client.rb#L46-L74
train
nning/transmission-rss
lib/transmission-rss/client.rb
TransmissionRSS.Client.get_session_id
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
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
[ "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" ]
Get transmission session id.
[ "Get", "transmission", "session", "id", "." ]
07baaf149d9e129e98b4cb496d808a528a59bc5b
https://github.com/nning/transmission-rss/blob/07baaf149d9e129e98b4cb496d808a528a59bc5b/lib/transmission-rss/client.rb#L85-L102
train
nning/transmission-rss
lib/transmission-rss/config.rb
TransmissionRSS.Config.merge_yaml!
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
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
[ "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" ]
Merge Config Hash with Hash from YAML file.
[ "Merge", "Config", "Hash", "with", "Hash", "from", "YAML", "file", "." ]
07baaf149d9e129e98b4cb496d808a528a59bc5b
https://github.com/nning/transmission-rss/blob/07baaf149d9e129e98b4cb496d808a528a59bc5b/lib/transmission-rss/config.rb#L72-L78
train