repo_name
stringlengths
2
55
dataset
stringclasses
1 value
owner
stringlengths
3
31
lang
stringclasses
10 values
func_name
stringlengths
1
104
code
stringlengths
20
96.7k
docstring
stringlengths
1
4.92k
url
stringlengths
94
241
sha
stringlengths
40
40
kamal
github_2023
basecamp
ruby
Kamal::Git.untracked_files
def untracked_files `git ls-files --others`.lines.map(&:strip) end
# returns an array of relative path names of untracked files, including gitignored files
https://github.com/basecamp/kamal/blob/6f29d4e78bc29c3392f54f93ea0451ad1ff68b13/lib/kamal/git.rb#L34-L36
6f29d4e78bc29c3392f54f93ea0451ad1ff68b13
kamal
github_2023
basecamp
ruby
Kamal::Utils.escape_shell_value
def escape_shell_value(value) value.to_s.scan(/[\x00-\x7F]+|[^\x00-\x7F]+/) \ .map { |part| part.ascii_only? ? escape_ascii_shell_value(part) : part } .join end
# Escape a value to make it safe for shell use.
https://github.com/basecamp/kamal/blob/6f29d4e78bc29c3392f54f93ea0451ad1ff68b13/lib/kamal/utils.rb#L60-L64
6f29d4e78bc29c3392f54f93ea0451ad1ff68b13
kamal
github_2023
basecamp
ruby
Kamal::Commands::Docker.installed?
def installed? docker "-v" end
# Checks the Docker client version. Fails if Docker is not installed.
https://github.com/basecamp/kamal/blob/6f29d4e78bc29c3392f54f93ea0451ad1ff68b13/lib/kamal/commands/docker.rb#L8-L10
6f29d4e78bc29c3392f54f93ea0451ad1ff68b13
rails7-startkit
github_2023
the-teacher
ruby
puma_stop
def puma_stop if inside_rails_conainer? puts 'Stopping PUMA' pids = `pgrep -f puma`.split("\n") pids.delete(Process.pid.to_s) pids.each { |pid| system "kill -9 #{pid}" } else run_rails_command('pkill -f puma') end end
# Do not use: `pkill -f puma` # It matches the running script name and kills it also :)
https://github.com/the-teacher/rails7-startkit/blob/51bb127e2114910bdc759f6974740a5c4703a53d/Rails7StartKit/bin/puma.rb#L20-L29
51bb127e2114910bdc759f6974740a5c4703a53d
rails7-startkit
github_2023
the-teacher
ruby
cache
def cache puts 'Toggle App Cache in development mode' cache_toggle_file = 'tmp/caching-dev.txt' FileUtils.chdir APP_ROOT do if File.exist?(cache_toggle_file) puts "File '#{cache_toggle_file}' exists" remove_file(cache_toggle_file) puts "File '#{cache_toggle_file}...
# def get_secret_key # container_bash_exec('rails', 'rake secret > tail') # container_bash_exec('rails', 'printenv SECRET_KEY_BASE') # end
https://github.com/the-teacher/rails7-startkit/blob/51bb127e2114910bdc759f6974740a5c4703a53d/Rails7StartKit/bin/rails7startkit.rb#L57-L80
51bb127e2114910bdc759f6974740a5c4703a53d
devise-api
github_2023
nejdetkadir
ruby
Devise.Api.Responses.ErrorResponse.error_description
def error_description return [I18n.t("devise.api.error_response.#{error}")] if record.blank? if invalid_authentication_error? && devise_lockable_info.present? && record.access_locked? return [I18n.t('devise.api.error_response.lockable.locked')] end if invalid_authenti...
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
https://github.com/nejdetkadir/devise-api/blob/bd49310c4e96ec6e56ec38c2542754718b2f1c57/lib/devise/api/responses/error_response.rb#L59-L70
bd49310c4e96ec6e56ec38c2542754718b2f1c57
revise_auth
github_2023
excid3
ruby
ReviseAuth.Authentication.login
def login(user) user_return_to = session[:user_return_to] reset_session Current.user = user session[:user_id] = user.id session[:user_return_to] = user_return_to end
# Logs in the user # - Reset the session to prevent session fixation # See: https://guides.rubyonrails.org/security.html#session-fixation-countermeasures # - Set Current.user for the current request # - Save a session cookie so the next request is authenticated
https://github.com/excid3/revise_auth/blob/6af392c5138f18c18205acfc404d355bda17d80c/lib/revise_auth/authentication.rb#L60-L66
6af392c5138f18c18205acfc404d355bda17d80c
revise_auth
github_2023
excid3
ruby
ReviseAuth.Authentication.revise_auth_controller?
def revise_auth_controller? is_a?(::ReviseAuthController) end
# Return true if it's a revise_auth_controller. false to all controllers unless # the controllers defined inside revise_auth. Useful if you want to apply a before # filter to all controllers, except the ones in revise_auth: # # before_action :authenticate_user!, unless: :revise_auth_controller?
https://github.com/excid3/revise_auth/blob/6af392c5138f18c18205acfc404d355bda17d80c/lib/revise_auth/authentication.rb#L94-L96
6af392c5138f18c18205acfc404d355bda17d80c
solid_queue
github_2023
rails
ruby
SolidQueue::Processes.Interruptible.interruptible_sleep
def interruptible_sleep(time) # Invoking this from the main thread may result in significant slowdown. # Utilizing asynchronous execution (Futures) addresses this performance issue. Concurrent::Promises.future(time) do |timeout| queue.clear unless queue.pop(timeout:).nil? end.o...
# Sleeps for 'time'. Can be interrupted asynchronously and return early via wake_up. # @param time [Numeric, Duration] the time to sleep. 0 returns immediately.
https://github.com/rails/solid_queue/blob/9cd6bc3a16826d04c63ba667c93bd8cbb094db81/lib/solid_queue/processes/interruptible.rb#L19-L31
9cd6bc3a16826d04c63ba667c93bd8cbb094db81
solid_queue
github_2023
rails
ruby
ActiveSupport::TestCase.silence_on_thread_error_for
def silence_on_thread_error_for(expected, &block) current_proc = SolidQueue.on_thread_error SolidQueue.with(on_thread_error: silent_on_thread_error_for(expected, current_proc)) do block.call end end
# Silences specified exceptions during the execution of a block # # @param [Exception, Array<Exception>] expected an Exception or an array of Exceptions to ignore # @yield Executes the provided block with specified exception(s) silenced
https://github.com/rails/solid_queue/blob/9cd6bc3a16826d04c63ba667c93bd8cbb094db81/test/test_helper.rb#L85-L91
9cd6bc3a16826d04c63ba667c93bd8cbb094db81
dockerfile-rails
github_2023
fly-apps
ruby
DockerfileGenerator.api_client_dir
def api_client_dir if api_only? scan = "*/package.json" else scan = "{client,frontend}/package.json" end file = Dir[scan].find do |file| JSON.load_file(file).dig("scripts", "build") end file && File.dirname(file) end
# scan for node clients. Do a wide scan if api_only?, otherwise look # for specific directories.
https://github.com/fly-apps/dockerfile-rails/blob/f48c9f23fc888061dd94f170d37bb6260032dde8/lib/generators/dockerfile_generator.rb#L1250-L1262
f48c9f23fc888061dd94f170d37bb6260032dde8
128iid
github_2023
aleshevdenis
ruby
CheckmarxScaHelper.fetch_all_vulns_of_project
def fetch_all_vulns_of_project(token, scan_id) print_good "\n" print_good "Getting All vulnerabilities of ScanId: #{scan_id} \n" checkmarx_sca_vulnerabilites_api_url = "https://api-sca.checkmarx.net/risk-management/risk-reports/#{scan_id}/vulnerabilities" headers = { "Content-T...
# method to fetch all vuln of foreach project
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/checkmarx_sca/lib/checkmarx_sca_helper.rb#L83-L103
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
ExpanseIssues.ExpanseIssuesMapper.default_issue_field_mapping
def default_issue_field_mapping(issue_type) { "asset" => [ { action: "copy", source: "ip", target: "ip_address" }, { action: "proc", target: "hostname", proc: lambda { |x| temp = x["domain"] ...
### ### This method provides a field mapping for an exposure, giving the caller ### the ability to process foreach field later with the data it has. ###
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/digital_footprint/expanse_issues/lib/expanse_issues_mapper.rb#L120-L174
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
Edgescan.KennaApi.upload
def upload kdi_upload(@output_dir, "batch-#{millis}.json", @kenna_connector_id, @kenna_api_host, @kenna_api_key, @skip_autoclose, @max_retries, @kdi_version) end
# Uploads whatever's in memory into Kenna and then clears memory # # Note: Uploaded data does not get imported into Kenna automatically. It just sits there # until `kickoff` is called. # This allows for uploading in batches. Once a few batches have been uploaded and # you're happy for whatever is ther...
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/edgescan/lib/kenna_api.rb#L56-L58
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
Edgescan.KennaApi.add_assets_from_specifiers
def add_assets_from_specifiers(edgescan_location_specifiers, edgescan_vulnerabilities) # Convert location specifiers into kenna assets, remove any lists within lists, or duplicate assets kenna_assets = edgescan_location_specifiers.map(&:to_kenna_asset).flatten.uniq # Add any kenna assets, ...
# Converts Edgescan location specifiers and vulnerabilities into Kenna assets and adds them to memory
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/edgescan/lib/kenna_api.rb#L68-L77
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
Edgescan.KennaApi.add_asset
def add_asset(kenna_asset) return if (@assets || []).map { |asset| asset["external_id"] }.include?(kenna_asset["external_id"]) create_kdi_asset(kenna_asset, false) end
# Adds Kenna asset into memory (if one with the same `external_id` doesn't exist already)
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/edgescan/lib/kenna_api.rb#L88-L92
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
Edgescan.KennaApi.add_finding
def add_finding(external_id, kenna_finding) create_kdi_asset_finding({ "external_id" => external_id }, kenna_finding, "external_id") end
# Adds Kenna finding into memory
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/edgescan/lib/kenna_api.rb#L100-L102
1709c456363b4f9aca306328bbad14555735d88b
128iid
github_2023
aleshevdenis
ruby
NetsparkerTask.map_state_to_triage_state
def map_state_to_triage_state(state_string) case state_string when "Present", /Revived|Scanning/ "new" when /False Positive/ "false_positive" when /Accepted Risk/ "risk_accepted" when /Fixed/ "resolved" when /Ignored/ "not...
# Possible KDI values are: "new", "in_progress", "triaged", "resolved", "false_positive", "risk_accepted", "duplicate", "not_a_security_issue". # Possible Netsparker values are: Present, Accepted Risk, False Positive, Fixed (Unconfirmed), Fixed (Confirmed), Fixed (Can't Retest), Ignored, Revived, Scanning
https://github.com/aleshevdenis/128iid/blob/1709c456363b4f9aca306328bbad14555735d88b/tasks/connectors/netsparker/netsparker_task.rb#L202-L215
1709c456363b4f9aca306328bbad14555735d88b
searchlink
github_2023
ttscoff
ruby
SL.SearchLink.get_plugin_configs
def get_plugin_configs(default_config) SL::Searches.plugins[:search].each_value do |plugin| next unless plugin.key?(:config) && !plugin[:config].nil? && !plugin[:config].empty? plugin[:config].each do |cfg| new_config = get_plugin_config(cfg) default_config += new_config ...
# # Get plugin configs # # @param default_config [String] Existing configuration # # @return [String] default_config with plugin configurations added #
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/config.rb#L241-L252
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.SearchLink.restore_prev_config
def restore_prev_config @prev_config&.each do |k, v| SL.config[k] = v $stderr.print "\r\033[0KReset config: #{k} = #{SL.config[k]}\n" unless SILENT end @prev_config = {} end
# Reset configuration
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/config.rb#L291-L297
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
footer
def footer @footer ||= [] end
# Stores the footer with reference links and footnotes
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L34-L36
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
originput
def originput @originput ||= "" end
# Stores the original input
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L54-L56
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
add_output
def add_output(str) print str if SL.printout && !SL.clipboard SL.output << str end
# Adds the given string to the output. # # @param str [String] The string to add. # # @return [nil] #
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L122-L125
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
add_report
def add_report(str) return unless SL.config["report"] unless SL.line_num.nil? position = "#{SL.line_num}:" position += SL.match_column.nil? ? "0:" : "#{SL.match_column}:" position += SL.match_length.nil? ? "0" : SL.match_length.to_s end SL.report.push("(#{position}): #{s...
# Adds the given string to the report. # # @param str [String] The string to add. # # @return [nil] #
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L174-L184
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
print_report
def print_report return if (SL.config["inline"] && SL.originput.split(/\n/).length == 1) || SL.clipboard return if SL.report.empty? out = "\n<!-- Report:\n#{SL.report.join("\n")}\n-->\n" add_output out end
# Prints the report. # # @return [String] The report. #
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/output.rb#L209-L216
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.SemVer.initialize
def initialize(version_string) raise VersionError, "Invalid semantic version number: #{version_string}" unless version_string.valid_version? @maj, @min, @patch = version_string.split(/\./) @pre = nil if @patch =~ /(-?[^0-9]+\d*)$/ @pre = Regexp.last_match(1).sub(/^-/, "") @patch...
## Initialize a Semantic Version object ## ## @param version_string [String] a semantic version number ## ## @return [SemVer] SemVer object ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/semver.rb#L14-L27
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.::String.clean
def clean gsub(/\n+/, " ") .gsub(/"/, "&quot") .gsub(/\|/, "-") .gsub(/([&?]utm_[scm].+=[^&\s!,.)\]]++?)+(&.*)/, '\2') .sub(/\?&/, "").strip end
## ## Remove newlines, escape quotes, and remove Google ## Analytics strings ## ## @return [String] cleaned URL/String ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/string.rb#L142-L148
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.::String.remove_protocol
def remove_protocol sub(%r{^(https?|s?ftp|file)://}, "") end
## ## Remove the protocol from a URL ## ## @return [String] just hostname and path of URL ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/string.rb#L165-L167
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.::String.remove_seo
def remove_seo(url) title = dup url = URI.parse(url) host = url.hostname unless host return self unless SL.config["debug"] SL.add_error("Invalid URL", "Could not remove SEO for #{url}") return self end path = url.path root_page = path =~ %r{^/?$} ? tru...
## ## Remove SEO elements from a title ## ## @param url The url of the page from which the title came ## ## @return [String] cleaned title ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/string.rb#L257-L340
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
SL.::String.truncate!
def truncate!(max) replace truncate(max) end
## ## Truncate in place ## ## @see #truncate ## ## @param max [Number] The maximum length ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/string.rb#L349-L351
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_with_timeout
def search_with_timeout(search, timeout) url = nil title = nil link_text = nil begin Timeout.timeout(timeout) do url, title, link_text = search.call end rescue Timeout::Error SL.add_error("Timeout", "Search timed out") url, tit...
## ## Execute a search with deadman's switch ## ## @param search [Proc] The search command ## @param timeout [Number] The timeout ## ## @return [Array] url, title, link_text ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/util.rb#L58-L73
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
cache_file_for
def cache_file_for(filename) cache_folder = File.expand_path("~/.config/searchlink/cache") FileUtils.mkdir_p(cache_folder) unless File.directory?(cache_folder) File.join(cache_folder, filename.sub(/(\.cache)?$/, ".cache")) end
## ## Get the path for a cache file ## ## @param filename [String] The filename to ## generate the cache for ## ## @return [String] path to new cache file ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/util.rb#L83-L87
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_paths
def search_paths(path = ENV["PATH"]) paths = if path && !path.empty? path.split(::File::PATH_SEPARATOR) else %w[/usr/local/bin /usr/ucb /usr/bin /bin /opt/homebrew/bin] end paths.select(&Dir.method(:exist?)) end
# Find default system paths # # @param [String] path # the path to search through # # @example # search_paths("/usr/local/bin:/bin") # # => ["/bin"] # # @return [Array<String>] # the array of paths to search # # @api private
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/which.rb#L87-L94
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
file_with_path?
def file_with_path?(cmd) ::File.expand_path(cmd) == cmd end
# Check if executable file is part of absolute/relative path # # @param [String] cmd # the executable to check # # @return [Boolean] # # @api private
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/which.rb#L165-L167
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
Curl.Html.extract_tag
def extract_tag(tag, attribute = nil, source: false, content: false) res = extract_tag_contents(tag, source: true) return res if source res.map! do |tag_source| m = tag_source.to_enum(:scan, /(\S+)=(['"])(.*?)\2/).map { Regexp.last_match } attrs = m.each_with_object({}) { |at, a| a[a...
## ## Extract an array of tags or tag attributes ## ## @param tag [String] The tag ## @param attribute [String] The attribute ## @param source [Boolean] Return full tag source ## (negates attribute if true) ## @param content [Boolean] Return only tag ## ...
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/curl/html.rb#L79-L102
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
Curl.Html.content_tags
def content_tags(content) return nil if content.nil? res = content.to_enum(:scan, %r{(?mix) <(?<tag>(?!</)[a-z0-9]+)(?<attrs>\s[^>]+)? (?:\s*/>|>(?<content>.*?)</\k<tag>>)}).map { Regexp.last_match } res.map do |tag| if tag["attrs"].nil? attrs = nil else ...
## ## Return an array of all tags in the content ## ## @param content [String] The content to parse ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/curl/html.rb#L243-L266
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
applemusic
def applemusic(terms, media = "music", entity = "") url = "https://itunes.apple.com/search?term=#{terms.url_encode}&country=#{SL.config['country_code']}&media=#{media}&entity=#{entity}" page = Curl::Json.new(url, compressed: true, symbolize_names: true) json = page.json return false unle...
# Search apple music # terms => search terms (unescaped) # media => music, podcast # entity => optional: artist, song, album, podcast # returns {:type=>,:id=>,:url=>,:title}
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/applemusic.rb#L76-L87
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_hook
def search_hook(search) types = %w[name path address] query = search.strip.split(" ").map { |s| types.map { |t| %(#{t} contains "#{s}") }.join(" or ") } query = query.map { |q| "(#{q})" }.join(" and ") path_matches = run_query(query) top_match = path_matches.uniq.first r...
# Search bookmark paths and addresses. Return array of bookmark hashes.
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/hook.rb#L64-L74
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search
def search(search_type, search_terms, link_text) # You can branch to multiple searches by testing the search_type case search_type when /e$/ url, title = SL.ddg("site:genius.com #{search_terms}", link_text) if url title = get_lyrics(url) # To return an...
# Every plugin must contain a #search method that takes 3 arguments: # # - `search_type` will contain the !search trigger that was used (minus the !) # - `search_terms` will include everything that came after the !search # - `link_text` will contain the text that will be used for the linked # text portion of the link. ...
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/lyrics.rb#L53-L91
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search
def search(_, search_terms, link_text) unless SL.config["pinboard_api_key"] SL.add_error("Missing Pinboard API token", "Find your api key at https://pinboard.in/settings/password and add it to your configuration (pinboard_api_key: YOURKEY)") ret...
# Search pinboard bookmarks # Begin query with '' to force exact matching (including description text) # Regular matching searches for each word of query and scores the bookmarks # exact matches in title get highest score # exact matches in description get second highest score # other bookmarks are scored based on the ...
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/pinboard.rb#L107-L187
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_edge_history
def search_edge_history(term) base = File.expand_path("~/Library/Application Support/Microsoft Edge/") profiles = Dir.glob("**/History", base: base) profiles.delete_if { |p| p =~ /^Snapshots/ } profiles.map! { |f| File.join(base, f) } res = false profiles.each do |bookm...
## Search Edge history ## ## @param term The search term ## ## @return [Array] Single bookmark, [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L61-L81
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_edge_bookmarks
def search_edge_bookmarks(term) base = File.expand_path("~/Library/Application Support/Microsoft Edge") profiles = Dir.glob("**/Bookmarks", base: base) profiles.delete_if { |p| p =~ /^Snapshots/ } profiles.map! { |f| File.join(base, f) } res = false profiles.each do |bo...
## ## Search Ege bookmarks ## ## @param term [String] The search term ## ## @return [Array] single bookmark [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L224-L243
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_chrome_bookmarks
def search_chrome_bookmarks(term) base = File.expand_path("~/Library/Application Support/Google/Chrome/") profiles = Dir.glob("**/Bookmarks", base: base) profiles.delete_if { |p| p =~ /^Snapshots/ } profiles.map! { |f| File.join(base, f) } res = false profiles.each do |...
## ## Search Chrome bookmarks ## ## @param term [String] The search term ## ## @return [Array] single bookmark [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L252-L271
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_arc_json
def search_arc_json(bookmarks_file, term) arc_bookmarks = JSON.parse(IO.read(bookmarks_file)) exact_match = false match_phrases = [] # If search terms start with ''term, only search for exact string matches if term =~ /^ *'/ exact_match = true term.gsub!(/(^...
## ## Search Arc/JSON bookmarks ## ## @param bookmarks_file [String] path to bookmarks file ## @param term [String] the string to search for ## ## @return [Array] single bookmark [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L281-L352
70a0d794424e2312833310fdf8aeb78d18d13183
searchlink
github_2023
ttscoff
ruby
search_chromium_bookmarks
def search_chromium_bookmarks(bookmarks_file, term) chrome_bookmarks = JSON.parse(IO.read(bookmarks_file)) exact_match = false match_phrases = [] # If search terms start with ''term, only search for exact string matches if term =~ /^ *'/ exact_match = true t...
## ## Generic chromium bookmark search ## ## @param bookmarks_file [String] The path to ## bookmarks file for ## selected browser ## @param term [String] The term ## ## @return [Array] single bookmark [url, title, date] ##
https://github.com/ttscoff/searchlink/blob/70a0d794424e2312833310fdf8aeb78d18d13183/lib/searchlink/searches/helpers/chromium.rb#L364-L407
70a0d794424e2312833310fdf8aeb78d18d13183
ubicloud
github_2023
ubicloud
ruby
Hosting::HetznerApis.reset
def reset(server_id, dist: "Ubuntu 22.04.2 LTS base") create_connection.post(path: "/reset/#{server_id}", body: "type=hw", expects: 200) nil end
# Cuts power to a Server and starts it again. This forcefully stops it # without giving the Server operating system time to gracefully stop. This # may lead to data loss, it’s equivalent to pulling the power cord and # plugging it in again. Reset should only be used when reboot does not work.
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/lib/hosting/hetzner_apis.rb#L31-L34
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
Strand.load
def load(snap = nil) Object.const_get("::Prog::" + prog).new(self, snap) end
# :nocov:
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/model/strand.rb#L76-L78
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
VmHost.download_cloud_hypervisor
def download_cloud_hypervisor(version_x64: nil, version_arm64: nil, sha256_ch_bin_x64: nil, sha256_ch_bin_arm64: nil, sha256_ch_remote_x64: nil, sha256_ch_remote_arm64: nil) version, sha256_ch_bin, sha256_ch_remote = if arch == "x64" [version_x64, sha256_ch_bin_x64, sha256_ch_remote_x64] elsif arch == "ar...
# Introduced for downloading cloud hypervisor via REPL.
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/model/vm_host.rb#L235-L245
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
VmHost.hardware_reset
def hardware_reset Hosting::Apis.hardware_reset_server(self) end
# Cuts power to a Server and starts it again. This forcefully stops it # without giving the Server operating system time to gracefully stop. This # may lead to data loss, it’s equivalent to pulling the power cord and # plugging it in again. Reset should only be used when reboot does not work.
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/model/vm_host.rb#L282-L284
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
VmHostSlice.allowed_cpus_cgroup
def allowed_cpus_cgroup @allowed_cpus_cgroup ||= cpus.map(&:cpu_number).sort.slice_when { |a, b| b != a + 1 }.map do |group| (group.size > 1) ? "#{group.first}-#{group.last}" : group.first.to_s end.join(",") end
# We use cgroup format here, which looks like: # 2-3,6-10 # (comma-separated ranges of cpus)
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/model/vm_host_slice.rb#L21-L25
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
Prog::Ai::InferenceEndpointReplicaNexus.ping_gateway
def ping_gateway api_key_ds = DB[:api_key] .where(owner_table: "project") .where(used_for: "inference_endpoint") .where(is_valid: true) .where(owner_id: Sequel[:project][:id]) .exists eligible_projects_ds = Project.where(api_key_ds) eligible_projects_ds = eligible_projects_ds....
# pushes latest config to inference gateway and collects billing information
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/prog/ai/inference_endpoint_replica_nexus.rb#L164-L196
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
Prog::Vnet::UpdateFirewallRules.consolidate_rules
def consolidate_rules(rules) port_segments = create_port_segments(rules) consolidated_rules = [] port_segments.each do |segment| # Find rules that overlap with the current segment overlapping_rules = rules.select do |r| r.port_range.begin <= segment[:end] && r.port_range.end - 1 >= segm...
# This method is needed to properly consolidate port_ranges + cidrs. # For example, if we have the following rules: # 1. 10.10.10.8/29 . 80-8080 # 2. 10.10.10.0/27 . 5432-10000 # # We can't just merge the cidrs because the port ranges overlap. We need to # first identify where the overlap is in the port ranges and then...
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/prog/vnet/update_firewall_rules.rb#L220-L256
05593ec0c7f3cbae7ef9214933d69a50bd29e947
ubicloud
github_2023
ubicloud
ruby
r
def r(commandline, stdin: "", expect: [0]) stdout, stderr, status = Open3.capture3(commandline, stdin_data: stdin) fail CommandFail.new("command failed: " + commandline, stdout, stderr) unless expect.include?(status.exitstatus) stdout end
# rubocop:enable Lint/InheritException
https://github.com/ubicloud/ubicloud/blob/05593ec0c7f3cbae7ef9214933d69a50bd29e947/rhizome/common/lib/util.rb#L27-L31
05593ec0c7f3cbae7ef9214933d69a50bd29e947
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Configuration.serpapi_api_key
def serpapi_api_key(**kwargs) key_lookup(:serpapi_api_key, kwargs) end
# @return [String] The SerpAPI API key either from arg or env.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars.rb#L46-L48
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Boxcar.validate_inputs
def validate_inputs(inputs:) missing_keys = input_keys - inputs.keys raise "Missing some input keys: #{missing_keys}" if missing_keys.any? inputs end
# Check that all inputs are present. # @param inputs [Hash] The inputs. # @raise [RuntimeError] If the inputs are not the same.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar.rb#L33-L38
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Boxcar.apply
def apply(input_list:) raise NotImplementedError end
# Apply the boxcar to a list of inputs. # @param input_list [Array<Hash>] The list of inputs. # @return [Array<Boxcars::Boxcar>] The list of outputs.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar.rb#L57-L59
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Boxcar.save
def save(path:) File.write(path, YAML.dump(self)) end
# save this boxcar to a file
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar.rb#L110-L112
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Conversation.check_lines
def check_lines(lines) raise ArgumentError, "Lines must be an array" unless lines.is_a?(Array) lines.each do |ln| raise ArgumentError, "Conversation item must be a array" unless ln.is_a?(Array) raise ArgumentError, "Conversation item must have 2 items, role and text" unless ln.size == 2 ...
# check the lines
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation.rb#L16-L24
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Conversation.to_a
def to_a lines end
# @return [Array] The result as a convesation array
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation.rb#L27-L29
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Conversation.as_messages
def as_messages(inputs = nil) { messages: no_history.map { |ln| { role: ln.first, content: cformat(ln.last, inputs) } } } rescue ::KeyError => e first_line = e.message.to_s.split("\n").first Boxcars.error "Missing prompt input key: #{first_line}" raise KeyError, "Prompt format error: #{first...
# compute the prompt parameters with input substitutions (used for chatGPT) # @param inputs [Hash] The inputs to use for the prompt. # @return [Hash] The formatted prompt { messages: ...}
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation.rb#L90-L96
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.ConversationPrompt.as_messages
def as_messages(inputs) conversation.as_messages(inputs) end
# prompt for chatGPT params # @param inputs [Hash] The inputs to use for the prompt. # @return [Hash] The formatted prompt.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation_prompt.rb#L20-L22
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.ConversationPrompt.with_conversation
def with_conversation(conversation) return self unless conversation new_prompt = dup new_prompt.conversation.add_conversation(conversation) new_prompt end
# tack on the ongoing conversation if present to the prompt
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/conversation_prompt.rb#L32-L38
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Engine.initialize
def initialize(description: 'Engine', name: nil, prompts: [], batch_size: 20) @name = name || self.class.name @description = description @prompts = prompts @batch_size = batch_size end
# An Engine is used by Boxcars to generate output from prompts # @param name [String] The name of the Engine. Defaults to classname. # @param description [String] A description of the Engine. # @param prompts [Array<Prompt>] The prompts to use for the Engine. # @param batch_size [Integer] The number of prompts to send ...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine.rb#L13-L18
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Train.return_stopped_response
def return_stopped_response(early_stopping_method, intermediate_steps, **kwargs) case early_stopping_method when "force" TrainFinish.new({ output: "Agent stopped due to max iterations." }, "") when "generate" thoughts = "" intermediate_steps.each do |action, observation| ...
# get the stopped response # @param early_stopping_method [String] The early stopping method. # @param intermediate_steps [Array] The intermediate steps. # @param kwargs [Hash] extra keword arguments. # @return [Boxcars::Action] The action to take.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/train.rb#L156-L185
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Train.call
def call(inputs:) prepare_for_new_call intermediate_steps = [] iterations = 0 while should_continue?(iterations) output = plan(intermediate_steps, **inputs) return pre_return(output, intermediate_steps) if output.is_a?(TrainFinish) if (boxcar = name_to_boxcar_map[output....
# execute the train train # @param inputs [Hash] The inputs. # @return [Hash] The output.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/train.rb#L202-L237
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.VectorSearch.call
def call(query:, count: 1) validate_query(query) query_vector = convert_query_to_vector(query) @vector_search_instance.call(query_vector: query_vector, count: count) end
# @param query [String] The query to search for. # @param count [Integer] The number of results to return. # @return [Array] array of hashes with :document and :distance keys # @example # [ # { # document: Boxcars::VectorStore::Document.new( # content: "hello", # embedding: [0.1, 0.2, 0.3], ...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/vector_search.rb#L42-L46
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.EngineBoxcar.initialize
def initialize(prompt:, engine: nil, **kwargs) @prompt = prompt @engine = engine || Boxcars.engine.new @top_k = kwargs.delete(:top_k) || 5 @stop = kwargs.delete(:stop) || ["Answer:"] super(**kwargs) end
# A Boxcar is a container for a single tool to run. # @param prompt [Boxcars::Prompt] The prompt to use for this boxcar with sane defaults. # @param engine [Boxcars::Engine] The engine to user for this boxcar. Can be inherited from a train if nil. # @param kwargs [Hash] Additional arguments including: name, description...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar/engine_boxcar.rb#L13-L19
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.EngineBoxcar.input_key
def input_key input_keys.first end
# the first input key for the prompt
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar/engine_boxcar.rb#L27-L29
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.JSONEngineBoxcar.extract_answer
def extract_answer(data) reply = data Result.new(status: :ok, answer: reply, explanation: reply) end
# get answer from parsed JSON # @param data [Hash] The data to extract from. # @return [Result] The result.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/boxcar/json_engine_boxcar.rb#L66-L69
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Anthropic.get_num_tokens
def get_num_tokens(text:) text.split.length # TODO: hook up to token counting gem end
# calculate the number of tokens used
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/anthropic.rb#L159-L161
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Anthropic.max_tokens_for_prompt
def max_tokens_for_prompt(prompt_text) num_tokens = get_num_tokens(prompt_text) # get max context size for model by name max_size = modelname_to_contextsize(model_name) max_size - num_tokens end
# Calculate the maximum number of tokens possible to generate for a prompt. # @param prompt_text [String] The prompt text to use. # @return [Integer] the number of tokens possible to generate.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/anthropic.rb#L172-L178
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Cohere.initialize
def initialize(name: DEFAULT_NAME, description: DEFAULT_DESCRIPTION, prompts: [], **kwargs) @llm_params = DEFAULT_PARAMS.merge(kwargs) @prompts = prompts @batch_size = 20 super(description: description, name: name) end
# A engine is the driver for a single tool to run. # @param name [String] The name of the engine. Defaults to "OpenAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prompts [Ar...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/cohere.rb#L28-L33
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.GeminiAi.initialize
def initialize(name: DEFAULT_NAME, description: DEFAULT_DESCRIPTION, prompts: [], batch_size: 20, **kwargs) @llm_parmas = DEFAULT_PARAMS.merge(kwargs) @prompts = prompts @batch_size = batch_size super(description: description, name: name) end
# A engine is a container for a single tool to run. # @param name [String] The name of the engine. Defaults to "GeminiAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prompts ...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gemini_ai.rb#L27-L32
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.GeminiAi.run
def run(question, **kwargs) prompt = Prompt.new(template: question) response = client(prompt: prompt, **kwargs) raise Error, "GeminiAI: No response from API" unless response check_response(response) response["choices"].map { |c| c.dig("message", "content") || c["text"] }.join("\n").strip ...
# get an answer from the engine for a question. # @param question [String] The question to ask the engine. # @param kwargs [Hash] Additional parameters to pass to the engine if wanted.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gemini_ai.rb#L69-L76
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.GeminiAi.default_params
def default_params llm_params end
# Get the default parameters for the engine.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gemini_ai.rb#L79-L81
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Gpt4allEng.initialize
def initialize(name: DEFAULT_NAME, description: DEFAULT_DESCRIPTION, prompts: [], batch_size: 2, **_kwargs) @prompts = prompts @batch_size = batch_size super(description: description, name: name) end
# A engine is a container for a single tool to run. # @param name [String] The name of the engine. Defaults to "OpenAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prompts [A...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gpt4all_eng.rb#L22-L26
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Gpt4allEng.client
def client(prompt:, inputs: {}, **_kwargs) gpt4all = Gpt4all::ConversationalAI.new gpt4all.prepare_resources(force_download: false) gpt4all.start_bot input_text = prompt.as_prompt(inputs: inputs)[:prompt] Boxcars.debug("Prompt after formatting:\n#{input_text}", :cyan) if Boxcars.configurat...
# Get an answer from the engine. # @param prompt [String] The prompt to use when asking the engine. # @param openai_access_token [String] The access token to use when asking the engine. # Defaults to Boxcars.configuration.openai_access_token. # @param kwargs [Hash] Additional parameters to pass to the engine if wante...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gpt4all_eng.rb#L33-L44
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Gpt4allEng.run
def run(question, **kwargs) prompt = Prompt.new(template: question) answer = client(prompt: prompt, **kwargs) Boxcars.debug("Answer: #{answer}", :cyan) answer end
# get an answer from the engine for a question. # @param question [String] The question to ask the engine. # @param kwargs [Hash] Additional parameters to pass to the engine if wanted.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/gpt4all_eng.rb#L49-L54
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.IntelligenceBase.default_model_params
def default_model_params {} end
# can be overridden by provider subclass
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/intelligence_base.rb#L24-L26
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.IntelligenceBase.validate_content
def validate_content(content) raise ArgumentError, "Content must have type and text fields" unless content[:type] && content[:text] content end
# Validate content structure
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/intelligence_base.rb#L53-L57
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Openai.initialize
def initialize(name: DEFAULT_NAME, description: DEFAULT_DESCRIPTION, prompts: [], batch_size: 20, **kwargs) @open_ai_params = DEFAULT_PARAMS.merge(kwargs) if @open_ai_params[:model] =~ /^o/ && @open_ai_params[:max_tokens].present? @open_ai_params[:max_completion_tokens] = @open_ai_params.delete(:max...
# A engine is a container for a single tool to run. # @param name [String] The name of the engine. Defaults to "OpenAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prompts [A...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/openai.rb#L29-L39
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Openai.check_response
def check_response(response, must_haves: %w[choices]) if response['error'] code = response.dig('error', 'code') msg = response.dig('error', 'message') || 'unknown error' raise KeyError, "OPENAI_ACCESS_TOKEN not valid" if code == 'invalid_api_key' raise ValueError, "OpenAI error: #...
# make sure we got a valid response # @param response [Hash] The response to check. # @param must_haves [Array<String>] The keys that must be in the response. Defaults to %w[choices]. # @raise [KeyError] if there is an issue with the access token. # @raise [ValueError] if the response is not valid.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/openai.rb#L109-L121
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.Perplexityai.initialize
def initialize(name: DEFAULT_PER_NAME, description: DEFAULT_PER_DESCRIPTION, prompts: [], batch_size: 20, **kwargs) @perplexity_params = DEFAULT_PER_PARAMS.merge(kwargs) @prompts = prompts @batch_size = batch_size super(description: description, name: name) end
# A engine is a container for a single tool to run. # @param name [String] The name of the engine. Defaults to "PerplexityAI engine". # @param description [String] A description of the engine. Defaults to: # useful for when you need to use AI to answer questions. You should ask targeted questions". # @param prom...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/engine/perplexityai.rb#L27-L32
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.TrainAction.initialize
def initialize(boxcar:, log:, boxcar_input: nil) @boxcar_input = boxcar_input @boxcar = boxcar @log = log end
# record for a train action # @param boxcar [String] The boxcar to run. # @param log [String] The log of the action. # @param boxcar_input [String] The input to the boxcar. # @return [Boxcars::TrainAction] The train action.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/train/train_action.rb#L13-L17
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.ZeroShot.extract_boxcar_and_input
def extract_boxcar_and_input(text) get_action_and_input(engine_output: text) rescue StandardError => e [:error, e.message] end
# Extract the boxcar and input from the engine output. # @param text [String] The output from the engine. # @return [Array<Boxcars::Boxcar, String>] The boxcar and input.
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/train/zero_shot.rb#L30-L34
9a294a13e96cbb628adb542807464e81a94d6535
boxcars
github_2023
BoxcarsAI
ruby
Boxcars.VectorStore.InMemory.BuildFromFiles.initialize
def initialize(params) @split_chunk_size = params[:split_chunk_size] || 2000 @training_data_path = File.absolute_path(params[:training_data_path]) @embedding_tool = params[:embedding_tool] || :openai validate_params(embedding_tool, training_data_path) @memory_vectors =...
# initialize the vector store with the following parameters: # @param params [Hash] A Hash containing the initial configuration. # @option params [Symbol] :embedding_tool The embedding tool to use. # @option params [String] :training_data_path The path to the training data files. # @option params [Integer] :split_chunk...
https://github.com/BoxcarsAI/boxcars/blob/9a294a13e96cbb628adb542807464e81a94d6535/lib/boxcars/vector_store/in_memory/build_from_files.rb#L15-L22
9a294a13e96cbb628adb542807464e81a94d6535
GlobalSfMpy
github_2023
zhangganlin
ruby
set_distance_type!
def set_distance_type! distance_function Flann.send(:flann_set_distance_type, distance_function, get_distance_order) self end
# Set the distance function to use when computing distances between data points.
https://github.com/zhangganlin/GlobalSfMpy/blob/ac6a0564d84e1d6e9a4077195e384d379aa20492/thirdparty/TheiaSfM/libraries/flann/src/ruby/lib/flann.rb#L199-L202
ac6a0564d84e1d6e9a4077195e384d379aa20492
GlobalSfMpy
github_2023
zhangganlin
ruby
read_dataset
def read_dataset filename Dir.chdir("spec") do f = File.new(filename, 'r') n = NMatrix.new([65536, 3], dtype: :float32) i = 0 while line = f.gets line.chomp! fields = line.split n[i,:*] = fields.map { |field| field.to_f } i += 1 end n end end
# Helper function for reading a test dataset so we can test nearest neighbors # and radius search and such.
https://github.com/zhangganlin/GlobalSfMpy/blob/ac6a0564d84e1d6e9a4077195e384d379aa20492/thirdparty/TheiaSfM/libraries/flann/src/ruby/spec/spec_helper.rb#L35-L50
ac6a0564d84e1d6e9a4077195e384d379aa20492
by
github_2023
jeremyevans
ruby
By.Server.initialize
def initialize(socket_path: default_socket_path, argv: default_argv, debug: default_debug, daemonize: default_daemonize, daemon_args: default_daemon_args, worker_class: default_worker_class) @socket_path = socket_path @argv = argv @debug = debug if @daemoniz...
# Creates a new server. Arguments: # socket_path: The path to the UNIX socket to create and listen on. # argv: The arguments to the server, which are libraries to be required by default. # debug: If set, operations on an existing server socket will be logged. # If the value is <tt>'log'</tt>, <tt>$LOADED_FEATUR...
https://github.com/jeremyevans/by/blob/20a61981f559498b6a47ecfdb8e694880d42c9ec/lib/by/server.rb#L30-L40
20a61981f559498b6a47ecfdb8e694880d42c9ec
by
github_2023
jeremyevans
ruby
By.Server.print_loaded_features
def print_loaded_features puts $LOADED_FEATURES end
# Print <tt>$LOADED_FEATURES</tt> to stdout.
https://github.com/jeremyevans/by/blob/20a61981f559498b6a47ecfdb8e694880d42c9ec/lib/by/server.rb#L207-L209
20a61981f559498b6a47ecfdb8e694880d42c9ec
by
github_2023
jeremyevans
ruby
By.Worker.reopen_stdio
def reopen_stdio $stdin.reopen(@socket.recv_io(IO)) $stdout.reopen(@socket.recv_io(IO)) $stderr.reopen(@socket.recv_io(IO)) end
# Replace stdin, stdout, stderr with the IO values provided by the client.
https://github.com/jeremyevans/by/blob/20a61981f559498b6a47ecfdb8e694880d42c9ec/lib/by/worker.rb#L36-L40
20a61981f559498b6a47ecfdb8e694880d42c9ec
beyla
github_2023
grafana
ruby
UsersController.show
def show render json: @user end
# GET /users/1
https://github.com/grafana/beyla/blob/2f2517bd9e5824bcd315292e62102f361a216434/test/integration/components/rubytestserver/testapi/app/controllers/users_controller.rb#L12-L14
2f2517bd9e5824bcd315292e62102f361a216434
beyla
github_2023
grafana
ruby
UsersController.update
def update if @user.update(user_params) render json: @user else render json: @user.errors, status: :unprocessable_entity end end
# PATCH/PUT /users/1
https://github.com/grafana/beyla/blob/2f2517bd9e5824bcd315292e62102f361a216434/test/integration/components/rubytestserver/testapi/app/controllers/users_controller.rb#L28-L34
2f2517bd9e5824bcd315292e62102f361a216434
litestack
github_2023
oldmoe
ruby
random_str
def random_str(size) @db.get_first_value("select hex(randomblob(?))", size) end
# sqlite database for fast random string generation
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/bench/bench.rb#L28-L30
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
ActiveSupport.Cache.Litecache.read_entry
def read_entry(key, **options) deserialize_entry(@cache.get(key)) end
# Read an entry from the cache.
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/active_support/cache/litecache.rb#L80-L82
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
ActiveSupport.Cache.Litecache.delete_entry
def delete_entry(key, **options) @cache.delete(key) end
# Delete an entry from the cache.
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/active_support/cache/litecache.rb#L120-L122
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
Litecable.subscribe
def subscribe(channel, subscriber, success_callback = nil) @subscribers.acquire do |subs| subs[channel] = {} unless subs[channel] subs[channel][subscriber] = true end success_callback&.call capture(:subscribe, channel) end
# subscribe to a channel, optionally providing a success callback proc
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/litestack/litecable.rb#L40-L47
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
Litecache.increment
def increment(key, amount = 1, expires_in = nil) expires_in ||= @expires_in @conn.acquire { |cache| cache.stmts[:incrementer].execute!(key.to_s, amount, expires_in)[0][0] } end
# increment an integer value by amount, optionally add an expiry value (in seconds)
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/litestack/litecache.rb#L165-L168
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
Litesupport.Liteconnection.with_connection
def with_connection @conn.acquire do |conn| @checked_out_conn = conn yield conn ensure @checked_out_conn = nil end end
# this will force the other run_* methods to use the # checked out connection if one exists
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/litestack/liteconnection.rb#L132-L139
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf
litestack
github_2023
oldmoe
ruby
Litedb.transaction
def transaction(mode = :immediate) super(mode) end
# enforce immediate mode to avoid deadlocks for a small performance penalty
https://github.com/oldmoe/litestack/blob/e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf/lib/litestack/litedb.rb#L43-L45
e598e1b1f0d46f45df1e2c6213ff9b136b63d9bf