CombinedText stringlengths 4 3.42M |
|---|
class MainController < ApplicationController
include TopicsHelper
include MapsHelper
include UsersHelper
include SynapsesHelper
before_filter :require_user, only: [:invite]
respond_to :html, :js, :json
# home page
def home
@maps = Map.find_all_by_featured(true).shuffle!
@maps = @maps.slice(0,3)
respond_with(@maps)
end
# /request
def requestinvite
end
### SEARCHING ###
# get /search/topics?term=SOMETERM
def searchtopics
@current = current_user
term = params[:term]
user = params[:user] ? params[:user] : false
if term && !term.empty? && term.downcase[0..3] != "map:" && term.downcase[0..6] != "mapper:" && term.downcase != "topic:"
#remove "topic:" if appended at beginning
term = term[6..-1] if term.downcase[0..5] == "topic:"
#if desc: search desc instead
desc = false
if term.downcase[0..4] == "desc:"
term = term[5..-1]
desc = true
end
#if link: search link instead
link = false
if term.downcase[0..4] == "link:"
term = term[5..-1]
link = true
end
#check whether there's a filter by metacode as part of the query
filterByMetacode = false
Metacode.all.each do |m|
lOne = m.name.length+1
lTwo = m.name.length
if term.downcase[0..lTwo] == m.name.downcase + ":"
term = term[lOne..-1]
filterByMetacode = m
end
end
if filterByMetacode
# !connor : Shouldn't this be checked for all cases, not just metacodes?
if term == ""
@topics = []
else
# !connor add % to the frontof this one too? why not?
search = term.downcase + '%'
if !user
@topics = Topic.where('LOWER("name") like ?', search).where('metacode_id = ?', filterByMetacode.id).order('"name"')
#read this next line as 'delete a topic if its private and you're either 1. logged out or 2. logged in but not the topic creator
@topics.delete_if {|t| t.permission == "private" && (!authenticated? || (authenticated? && @current.id != t.user_id)) }
elsif user
@topics = Topic.where('LOWER("name") like ?', search).where('metacode_id = ? AND user_id = ?', filterByMetacode.id, user).order('"name"')
#read this next line as 'delete a topic if its private and you're either 1. logged out or 2. logged in but not the topic creator
@topics.delete_if {|t| t.permission == "private" && (!authenticated? || (authenticated? && @current.id != t.user_id)) }
end
end
elsif desc
search = '%' + term.downcase + '%'
if !user
@topics = Topic.where('LOWER("desc") like ?', search).order('"name"')
elsif user
@topics = Topic.where('LOWER("desc") like ?', search).where('user_id = ?', user).order('"name"')
end
elsif link
search = '%' + term.downcase + '%'
if !user
@topics = Topic.where('LOWER("link") like ?', search).order('"name"')
elsif user
@topics = Topic.where('LOWER("link") like ?', search).where('user_id = ?', user).order('"name"')
end
else #regular case, just search the name
# !connor : Definitely add the % out front here.
search = term.downcase + '%'
if !user
@topics = Topic.where('LOWER("name") like ?', search).order('"name"')
elsif user
@topics = Topic.where('LOWER("name") like ?', search).where('user_id = ?', user).order('"name"')
end
end
else
@topics = []
end
#read this next line as 'delete a topic if its private and you're either 1. logged out or 2. logged in but not the topic creator
@topics.delete_if {|t| t.permission == "private" && (!authenticated? || (authenticated? && @current.id != t.user_id)) }
render json: autocomplete_array_json(@topics)
end
# get /search/maps?term=SOMETERM
def searchmaps
@current = current_user
term = params[:term]
#!connor is nil the same as false? why is it done different here?
user = params[:user] ? params[:user] : nil
if term && !term.empty? && term.downcase[0..5] != "topic:" && term.downcase[0..6] != "mapper:" && term.downcase != "map:"
#remove "map:" if appended at beginning
term = term[4..-1] if term.downcase[0..3] == "map:"
#if desc: search desc instead
desc = false
if term.downcase[0..4] == "desc:"
term = term[5..-1]
desc = true
end
# !connor make the search always '%' : term.downcase + '%'
search = desc ? '%' + term.downcase + '%' : term.downcase + '%'
query = desc ? 'LOWER("desc") like ?' : 'LOWER("name") like ?'
if !user
# !connor why is the limit 5 done here and not above? also, why not limit after sorting alphabetically?
@maps = Map.where(query, search).limit(5).order('"name"')
elsif user
@maps = Map.where(query, search).where('user_id = ?', user).limit(5).order('"name"')
end
else
@maps = []
end
#read this next line as 'delete a map if its private and you're either 1. logged out or 2. logged in but not the map creator
@maps.delete_if {|m| m.permission == "private" && (!authenticated? || (authenticated? && @current.id != m.user_id)) }
render json: autocomplete_map_array_json(@maps)
end
# get /search/mappers?term=SOMETERM
def searchmappers
@current = current_user
term = params[:term]
if term && !term.empty? && term.downcase[0..3] != "map:" && term.downcase[0..5] != "topic:" && term.downcase != "mapper:"
#remove "mapper:" if appended at beginning
term = term[7..-1] if term.downcase[0..6] == "mapper:"
# !connor same question as above
@mappers = User.where('LOWER("name") like ?', term.downcase + '%').limit(5).order('"name"')
else
@mappers = []
end
render json: autocomplete_user_array_json(@mappers)
end
# get /search/synapses?term=SOMETERM OR
# get /search/synapses?topic1id=SOMEID&topic2id=SOMEID
def searchsynapses
@current = current_user
term = params[:term]
topic1id = params[:topic1id]
topic2id = params[:topic2id]
if term && !term.empty?
@synapses = Synapse.select('DISTINCT "desc"').
# !connor this should likely also have the preceeding %
where('LOWER("desc") like ?', term.downcase + '%').limit(5).order('"desc"')
render json: autocomplete_synapse_generic_json(@synapses)
elsif topic1id && !topic1id.empty?
@one = Synapse.where('node1_id = ? AND node2_id = ?', topic1id, topic2id)
@two = Synapse.where('node2_id = ? AND node1_id = ?', topic1id, topic2id)
@synapses = @one + @two
@synapses.sort! {|s1,s2| s1.desc <=> s2.desc }
#read this next line as 'delete a synapse if its private and you're either 1. logged out or 2. logged in but not the synapse creator
@synapses.delete_if {|s| s.permission == "private" && (!authenticated? || (authenticated? && @current.id != s.user_id)) }
render json: autocomplete_synapse_array_json(@synapses)
else
@synapses = []
render json: autocomplete_synapse_array_json(@synapses)
end
end
end
Update main_controller.rb
realized these lines we're duplicated
class MainController < ApplicationController
include TopicsHelper
include MapsHelper
include UsersHelper
include SynapsesHelper
before_filter :require_user, only: [:invite]
respond_to :html, :js, :json
# home page
def home
@maps = Map.find_all_by_featured(true).shuffle!
@maps = @maps.slice(0,3)
respond_with(@maps)
end
# /request
def requestinvite
end
### SEARCHING ###
# get /search/topics?term=SOMETERM
def searchtopics
@current = current_user
term = params[:term]
user = params[:user] ? params[:user] : false
if term && !term.empty? && term.downcase[0..3] != "map:" && term.downcase[0..6] != "mapper:" && term.downcase != "topic:"
#remove "topic:" if appended at beginning
term = term[6..-1] if term.downcase[0..5] == "topic:"
#if desc: search desc instead
desc = false
if term.downcase[0..4] == "desc:"
term = term[5..-1]
desc = true
end
#if link: search link instead
link = false
if term.downcase[0..4] == "link:"
term = term[5..-1]
link = true
end
#check whether there's a filter by metacode as part of the query
filterByMetacode = false
Metacode.all.each do |m|
lOne = m.name.length+1
lTwo = m.name.length
if term.downcase[0..lTwo] == m.name.downcase + ":"
term = term[lOne..-1]
filterByMetacode = m
end
end
if filterByMetacode
# !connor : Shouldn't this be checked for all cases, not just metacodes?
if term == ""
@topics = []
else
# !connor add % to the frontof this one too? why not?
search = term.downcase + '%'
if !user
@topics = Topic.where('LOWER("name") like ?', search).where('metacode_id = ?', filterByMetacode.id).order('"name"')
elsif user
@topics = Topic.where('LOWER("name") like ?', search).where('metacode_id = ? AND user_id = ?', filterByMetacode.id, user).order('"name"')
end
end
elsif desc
search = '%' + term.downcase + '%'
if !user
@topics = Topic.where('LOWER("desc") like ?', search).order('"name"')
elsif user
@topics = Topic.where('LOWER("desc") like ?', search).where('user_id = ?', user).order('"name"')
end
elsif link
search = '%' + term.downcase + '%'
if !user
@topics = Topic.where('LOWER("link") like ?', search).order('"name"')
elsif user
@topics = Topic.where('LOWER("link") like ?', search).where('user_id = ?', user).order('"name"')
end
else #regular case, just search the name
# !connor : Definitely add the % out front here.
search = term.downcase + '%'
if !user
@topics = Topic.where('LOWER("name") like ?', search).order('"name"')
elsif user
@topics = Topic.where('LOWER("name") like ?', search).where('user_id = ?', user).order('"name"')
end
end
else
@topics = []
end
#read this next line as 'delete a topic if its private and you're either 1. logged out or 2. logged in but not the topic creator
@topics.delete_if {|t| t.permission == "private" && (!authenticated? || (authenticated? && @current.id != t.user_id)) }
render json: autocomplete_array_json(@topics)
end
# get /search/maps?term=SOMETERM
def searchmaps
@current = current_user
term = params[:term]
#!connor is nil the same as false? why is it done different here?
user = params[:user] ? params[:user] : nil
if term && !term.empty? && term.downcase[0..5] != "topic:" && term.downcase[0..6] != "mapper:" && term.downcase != "map:"
#remove "map:" if appended at beginning
term = term[4..-1] if term.downcase[0..3] == "map:"
#if desc: search desc instead
desc = false
if term.downcase[0..4] == "desc:"
term = term[5..-1]
desc = true
end
# !connor make the search always '%' : term.downcase + '%'
search = desc ? '%' + term.downcase + '%' : term.downcase + '%'
query = desc ? 'LOWER("desc") like ?' : 'LOWER("name") like ?'
if !user
# !connor why is the limit 5 done here and not above? also, why not limit after sorting alphabetically?
@maps = Map.where(query, search).limit(5).order('"name"')
elsif user
@maps = Map.where(query, search).where('user_id = ?', user).limit(5).order('"name"')
end
else
@maps = []
end
#read this next line as 'delete a map if its private and you're either 1. logged out or 2. logged in but not the map creator
@maps.delete_if {|m| m.permission == "private" && (!authenticated? || (authenticated? && @current.id != m.user_id)) }
render json: autocomplete_map_array_json(@maps)
end
# get /search/mappers?term=SOMETERM
def searchmappers
@current = current_user
term = params[:term]
if term && !term.empty? && term.downcase[0..3] != "map:" && term.downcase[0..5] != "topic:" && term.downcase != "mapper:"
#remove "mapper:" if appended at beginning
term = term[7..-1] if term.downcase[0..6] == "mapper:"
# !connor same question as above
@mappers = User.where('LOWER("name") like ?', term.downcase + '%').limit(5).order('"name"')
else
@mappers = []
end
render json: autocomplete_user_array_json(@mappers)
end
# get /search/synapses?term=SOMETERM OR
# get /search/synapses?topic1id=SOMEID&topic2id=SOMEID
def searchsynapses
@current = current_user
term = params[:term]
topic1id = params[:topic1id]
topic2id = params[:topic2id]
if term && !term.empty?
@synapses = Synapse.select('DISTINCT "desc"').
# !connor this should likely also have the preceeding %
where('LOWER("desc") like ?', term.downcase + '%').limit(5).order('"desc"')
render json: autocomplete_synapse_generic_json(@synapses)
elsif topic1id && !topic1id.empty?
@one = Synapse.where('node1_id = ? AND node2_id = ?', topic1id, topic2id)
@two = Synapse.where('node2_id = ? AND node1_id = ?', topic1id, topic2id)
@synapses = @one + @two
@synapses.sort! {|s1,s2| s1.desc <=> s2.desc }
#read this next line as 'delete a synapse if its private and you're either 1. logged out or 2. logged in but not the synapse creator
@synapses.delete_if {|s| s.permission == "private" && (!authenticated? || (authenticated? && @current.id != s.user_id)) }
render json: autocomplete_synapse_array_json(@synapses)
else
@synapses = []
render json: autocomplete_synapse_array_json(@synapses)
end
end
end
|
# encoding: utf-8
#
# = Name Controller
#
# == Actions
# L = login required
# R = root required
# V = has view
# P = prefetching allowed
#
# index_name:: List of results of index/search.
# list_names:: Alphabetical list of all names, used or otherwise.
# observation_index:: Alphabetical list of names people have seen.
# names_by_user:: Alphabetical list of names created by given user.
# names_by_editor:: Alphabetical list of names edited by given user.
# name_search:: Seach for string in name, notes, etc.
# map:: Show distribution map.
# index_name_description:: List of results of index/search.
# list_name_descriptions:: Alphabetical list of all name_descriptions,
# used or otherwise.
# name_descriptions_by_author:: Alphabetical list of name_descriptions authored
# by given user.
# name_descriptions_by_editor:: Alphabetical list of name_descriptions edited
# by given user.
# show_name:: Show info about name.
# show_past_name:: Show past versions of name info.
# prev_name:: Show previous name in index.
# next_name:: Show next name in index.
# show_name_description:: Show info about name_description.
# show_past_name_description:: Show past versions of name_description info.
# prev_name_description:: Show previous name_description in index.
# next_name_description:: Show next name_description in index.
# create_name:: Create new name.
# edit_name:: Edit name.
# create_name_description:: Create new name_description.
# edit_name_description:: Edit name_description.
# destroy_name_description:: Destroy name_description.
# make_description_default:: Make a description the default one.
# merge_descriptions:: Merge a description with another.
# publish_description:: Publish a draft description.
# adjust_permissions:: Adjust permissions on a description.
# change_synonyms:: Change list of synonyms for a name.
# deprecate_name:: Deprecate name in favor of another.
# approve_name:: Flag given name as "accepted"
# (others could be, too).
# bulk_name_edit:: Create/synonymize/deprecate a list of names.
# names_for_mushroom_app:: Display list of most common names in plain text.
#
# ==== Helpers
# deprecate_synonym:: (used by change_synonyms)
# check_for_new_synonym:: (used by change_synonyms)
# dump_sorter:: Error diagnostics for change_synonyms.
#
################################################################################
class NameController < ApplicationController
include DescriptionControllerHelpers
before_action :login_required, except: [
:advanced_search,
:authored_names,
:eol,
:eol_preview,
:index_name,
:index_name_description,
:map,
:list_name_descriptions,
:list_names,
:name_search,
:name_descriptions_by_author,
:name_descriptions_by_editor,
:names_by_user,
:names_by_editor,
:needed_descriptions,
:next_name,
:next_name_description,
:observation_index,
:prev_name,
:prev_name_description,
:show_name,
:show_name_description,
:show_past_name,
:show_past_name_description,
:test_index
]
before_action :disable_link_prefetching, except: [
:approve_name,
:bulk_name_edit,
:change_synonyms,
:create_name,
:create_name_description,
:deprecate_name,
:edit_name,
:edit_name_description,
:show_name,
:show_name_description,
:show_past_name,
:show_past_name_description
]
##############################################################################
#
# :section: Indexes and Searches
#
##############################################################################
# Display list of names in last index/search query.
def index_name # :nologin: :norobots:
query = find_or_create_query(:Name, by: params[:by])
show_selected_names(query, id: params[:id].to_s, always_index: true)
end
# Display list of all (correctly-spelled) names in the database.
def list_names # :nologin:
query = create_query(:Name, :all, by: :name)
show_selected_names(query)
end
# Display list of names that have observations.
def observation_index # :nologin: :norobots:
query = create_query(:Name, :with_observations)
show_selected_names(query)
end
# Display list of names that have authors.
def authored_names # :nologin: :norobots:
query = create_query(:Name, :with_descriptions)
show_selected_names(query)
end
# Display list of names that a given user is author on.
def names_by_user # :nologin: :norobots:
if user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user
query = create_query(:Name, :by_user, user: user)
show_selected_names(query)
end
end
# This no longer makes sense, but is being requested by robots.
alias_method :names_by_author, :names_by_user
# Display list of names that a given user is editor on.
def names_by_editor # :nologin: :norobots:
if user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user
query = create_query(:Name, :by_editor, user: user)
show_selected_names(query)
end
end
# Display list of the most popular 100 names that don't have descriptions.
def needed_descriptions # :nologin: :norobots:
# NOTE!! -- all this extra info and help will be lost if user re-sorts.
data = Name.connection.select_rows %(
SELECT names.id, name_counts.count
FROM names LEFT OUTER JOIN name_descriptions ON names.id = name_descriptions.name_id,
(SELECT count(*) AS count, name_id
FROM observations group by name_id) AS name_counts
WHERE names.id = name_counts.name_id
AND names.rank = #{Name.ranks[:Species]}
AND name_counts.count > 1
AND name_descriptions.name_id IS NULL
AND CURRENT_TIMESTAMP - names.updated_at > #{1.week.to_i}
ORDER BY name_counts.count DESC, names.sort_name ASC
LIMIT 100
)
@help = :needed_descriptions_help
query = create_query(:Name, :in_set, ids: data.map(&:first),
title: :needed_descriptions_title.l)
show_selected_names(query, num_per_page: 100) do |name|
# Add number of observations (parenthetically).
row = data.find { |id, _count| id == name.id }
row ? "(#{count} #{:observations.t})" : ""
end
end
# Display list of names that match a string.
def name_search # :nologin: :norobots:
pattern = params[:pattern].to_s
if pattern.match(/^\d+$/) &&
(name = Name.safe_find(pattern))
redirect_to(action: "show_name", id: name.id)
else
query = create_query(:Name, :pattern_search, pattern: pattern)
@suggest_alternate_spellings = pattern
show_selected_names(query)
end
end
# Displays list of advanced search results.
def advanced_search # :nologin: :norobots:
query = find_query(:Name)
show_selected_names(query)
rescue => err
flash_error(err.to_s) unless err.blank?
redirect_to(controller: "observer", action: "advanced_search_form")
end
# Used to test pagination.
def test_index # :nologin: :norobots:
query = find_query(:Name) or fail "Missing query: #{params[:q]}"
if params[:test_anchor]
@test_pagination_args = { anchor: params[:test_anchor] }
end
show_selected_names(query, num_per_page: params[:num_per_page].to_i)
end
# Show selected search results as a list with 'list_names' template.
def show_selected_names(query, args = {})
store_query_in_session(query)
@links ||= []
args = {
action: "list_names",
letters: "names.sort_name",
num_per_page: (params[:letter].to_s.match(/^[a-z]/i) ? 500 : 50)
}.merge(args)
# Tired of not having an easy link to list_names.
if query.flavor == :with_observations
@links << [:all_objects.t(type: :name), { action: "list_names" }]
end
# Add some alternate sorting criteria.
args[:sorting_links] = [
["name", :sort_by_name.t],
["created_at", :sort_by_created_at.t],
[(query.flavor == :by_rss_log ? "rss_log" : "updated_at"),
:sort_by_updated_at.t],
["num_views", :sort_by_num_views.t]
]
# Add "show observations" link if this query can be coerced into an
# observation query.
if query.is_coercable?(:Observation)
@links << [:show_objects.t(type: :observation),
add_query_param({
controller: "observer", action: "index_observation"
}, query)]
end
# Add "show descriptions" link if this query can be coerced into a
# description query.
if query.is_coercable?(:NameDescription)
@links << [:show_objects.t(type: :description),
add_query_param({ action: "index_name_description" },
query)]
end
# Add some extra fields to the index for authored_names.
if query.flavor == :with_descriptions
show_index_of_objects(query, args) do |name|
if desc = name.description
[desc.authors.map(&:login).join(", "),
desc.note_status.map(&:to_s).join("/"),
:"review_#{desc.review_status}".t]
else
[]
end
end
else
show_index_of_objects(query, args)
end
end
##############################################################################
#
# :section: Description Indexes and Searches
#
##############################################################################
# Display list of names in last index/search query.
def index_name_description # :nologin: :norobots:
query = find_or_create_query(:NameDescription, by: params[:by])
show_selected_name_descriptions(query, id: params[:id].to_s,
always_index: true)
end
# Display list of all (correctly-spelled) name_descriptions in the database.
def list_name_descriptions # :nologin:
query = create_query(:NameDescription, :all, by: :name)
show_selected_name_descriptions(query)
end
# Display list of name_descriptions that a given user is author on.
def name_descriptions_by_author # :nologin: :norobots:
if user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user
query = create_query(:NameDescription, :by_author, user: user)
show_selected_name_descriptions(query)
end
end
# Display list of name_descriptions that a given user is editor on.
def name_descriptions_by_editor # :nologin: :norobots:
if user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user
query = create_query(:NameDescription, :by_editor, user: user)
show_selected_name_descriptions(query)
end
end
# Show selected search results as a list with 'list_names' template.
def show_selected_name_descriptions(query, args = {})
store_query_in_session(query)
@links ||= []
args = {
action: "list_name_descriptions",
num_per_page: 50
}.merge(args)
# Add some alternate sorting criteria.
args[:sorting_links] = [
["name", :sort_by_name.t],
["created_at", :sort_by_created_at.t],
["updated_at", :sort_by_updated_at.t],
["num_views", :sort_by_num_views.t]
]
# Add "show names" link if this query can be coerced into an
# observation query.
if query.is_coercable?(:Name)
@links << [:show_objects.t(type: :name),
add_query_param({ action: "index_name" }, query)]
end
show_index_of_objects(query, args)
end
################################################################################
#
# :section: Show Name
#
################################################################################
# Show a Name, one of its NameDescription's, associated taxa, and a bunch of
# relevant Observations.
def show_name # :nologin: :prefetch:
pass_query_params
store_location
clear_query_in_session
# Load Name and NameDescription along with a bunch of associated objects.
name_id = params[:id].to_s
desc_id = params[:desc]
if @name = find_or_goto_index(Name, name_id)
@canonical_url = "#{MO.http_domain}/name/show_name/#{@name.id}"
update_view_stats(@name)
# Tell robots the proper URL to use to index this content.
@canonical_url = "#{MO.http_domain}/name/show_name/#{@name.id}"
# Get a list of projects the user can create drafts for.
@projects = @user && @user.projects_member.select do |project|
!@name.descriptions.any? { |d| d.belongs_to_project?(project) }
end
# Get classification
@classification = @name.best_classification
@parents = nil
unless @classification
# Get list of immediate parents.
@parents = @name.parents
end
# Create query for immediate children.
@children_query = create_query(:Name, :of_children, name: @name)
# Create search queries for observation lists.
@consensus_query = create_query(:Observation, :of_name, name: @name,
by: :confidence)
@consensus2_query = create_query(:Observation, :of_name, name: @name,
synonyms: :all,
by: :confidence)
@synonym_query = create_query(:Observation, :of_name, name: @name,
synonyms: :exclusive,
by: :confidence)
@other_query = create_query(:Observation, :of_name, name: @name,
synonyms: :all, nonconsensus: :exclusive,
by: :confidence)
@obs_with_images_query = create_query(:Observation, :of_name, name: @name,
by: :confidence, has_images: :yes)
if @name.at_or_below_genus?
@subtaxa_query = create_query(:Observation, :of_children, name: @name,
all: true, by: :confidence)
end
# Determine which queries actually have results and instantiate the ones we'll use
@best_description = @name.best_brief_description
@first_four = @obs_with_images_query.results(limit: 4)
@first_child = @children_query.results(limit: 1)[0]
@first_consensus = @consensus_query.results(limit: 1)[0]
@has_consensus2 = @consensus2_query.select_count
@has_synonym = @synonym_query.select_count
@has_other = @other_query.select_count
@has_subtaxa = @subtaxa_query.select_count if @subtaxa_query
end
end
# Show just a NameDescription.
def show_name_description # :nologin: :prefetch:
store_location
pass_query_params
if @description = find_or_goto_index(NameDescription, params[:id].to_s)
@canonical_url = "#{MO.http_domain}/name/show_name_description/#{@description.id}"
# Tell robots the proper URL to use to index this content.
@canonical_url = "#{MO.http_domain}/name/show_name_description/#{@description.id}"
# Public or user has permission.
if @description.is_reader?(@user)
@name = @description.name
update_view_stats(@description)
# Get a list of projects the user can create drafts for.
@projects = @user && @user.projects_member.select do |project|
!@name.descriptions.any? { |d| d.belongs_to_project?(project) }
end
# User doesn't have permission to see this description.
else
if @description.source_type == :project
flash_error(:runtime_show_draft_denied.t)
if project = @description.project
redirect_to(controller: "project", action: "show_project",
id: project.id)
else
redirect_to(action: "show_name", id: @description.name_id)
end
else
flash_error(:runtime_show_description_denied.t)
redirect_to(action: "show_name", id: @description.name_id)
end
end
end
end
# Show past version of Name. Accessible only from show_name page.
def show_past_name # :nologin: :prefetch: :norobots:
pass_query_params
store_location
if @name = find_or_goto_index(Name, params[:id].to_s)
@name.revert_to(params[:version].to_i)
# Old correct spellings could have gotten merged with something else and no longer exist.
if @name.is_misspelling?
@correct_spelling = Name.connection.select_value %(
SELECT display_name FROM names WHERE id = #{@name.correct_spelling_id}
)
else
@correct_spelling = ""
end
end
end
# Show past version of NameDescription. Accessible only from
# show_name_description page.
def show_past_name_description # :nologin: :prefetch: :norobots:
pass_query_params
store_location
if @description = find_or_goto_index(NameDescription, params[:id].to_s)
@name = @description.name
if params[:merge_source_id].blank?
@description.revert_to(params[:version].to_i)
else
@merge_source_id = params[:merge_source_id]
version = NameDescription::Version.find(@merge_source_id)
@old_parent_id = version.name_description_id
subversion = params[:version]
if !subversion.blank? &&
(version.version != subversion.to_i)
version = NameDescription::Version.
find_by_version_and_name_description_id(params[:version], @old_parent_id)
end
@description.clone_versioned_model(version, @description)
end
end
end
# Go to next name: redirects to show_name.
def next_name # :nologin: :norobots:
redirect_to_next_object(:next, Name, params[:id].to_s)
end
# Go to previous name: redirects to show_name.
def prev_name # :nologin: :norobots:
redirect_to_next_object(:prev, Name, params[:id].to_s)
end
# Go to next name: redirects to show_name.
def next_name_description # :nologin: :norobots:
redirect_to_next_object(:next, NameDescription, params[:id].to_s)
end
# Go to previous name_description: redirects to show_name_description.
def prev_name_description # :nologin: :norobots:
redirect_to_next_object(:prev, NameDescription, params[:id].to_s)
end
# Callback to let reviewers change the review status of a Name from the
# show_name page.
def set_review_status # :norobots:
pass_query_params
id = params[:id].to_s
desc = NameDescription.find(id)
desc.update_review_status(params[:value]) if is_reviewer?
redirect_with_query(action: :show_name, id: desc.name_id)
end
##############################################################################
#
# :section: Create and Edit Names
#
##############################################################################
# Create a new name; accessible from name indexes.
def create_name # :prefetch: :norobots:
store_location
pass_query_params
if request.method != "POST"
init_create_name_form
else
@parse = parse_name
@name, @parents = find_or_create_name_and_parents
make_sure_name_doesnt_exist
create_new_name
redirect_to_show_name
end
rescue RuntimeError => err
reload_create_name_form_on_error(err)
end
# Make changes to name; accessible from show_name page.
def edit_name # :prefetch: :norobots:
store_location
pass_query_params
if @name = find_or_goto_index(Name, params[:id].to_s)
init_edit_name_form
if request.method == "POST"
@parse = parse_name
new_name, @parents = find_or_create_name_and_parents
if new_name.new_record? || new_name == @name
email_admin_name_change unless can_make_changes? || minor_name_change?
update_correct_spelling
any_changes = update_existing_name
unless redirect_to_approve_or_deprecate
flash_warning(:runtime_edit_name_no_change.t) unless any_changes
redirect_to_show_name
end
elsif is_in_admin_mode? || @name.mergeable? || new_name.mergeable?
merge_name_into(new_name)
redirect_to_show_name
else
send_name_merge_email(new_name)
redirect_to_show_name
end
end
end
rescue RuntimeError => err
reload_edit_name_form_on_error(err)
end
def init_create_name_form
@name = Name.new
@name.rank = :Species
@name_string = ""
end
def reload_create_name_form_on_error(err)
flash_error(err.to_s) unless err.blank?
flash_object_errors(@name)
init_create_name_form
@name.rank = params[:name][:rank]
@name.author = params[:name][:author]
@name.citation = params[:name][:citation]
@name.notes = params[:name][:notes]
@name_string = params[:name][:text_name]
end
def init_edit_name_form
if !params[:name]
@misspelling = @name.is_misspelling?
@correct_spelling = @misspelling ? @name.correct_spelling.real_search_name : ""
else
@misspelling = (params[:name][:misspelling] == "1")
@correct_spelling = params[:name][:correct_spelling].to_s.strip_squeeze
end
@name_string = @name.real_text_name
end
def reload_edit_name_form_on_error(err)
flash_error(err.to_s) unless err.blank?
flash_object_errors(@name)
@name.rank = params[:name][:rank]
@name.author = params[:name][:author]
@name.citation = params[:name][:citation]
@name.notes = params[:name][:notes]
@name.deprecated = (params[:name][:deprecated] == "true")
@name_string = params[:name][:text_name]
end
# Only allowed to make substantive changes to name if you own all the references to it.
def can_make_changes?
unless is_in_admin_mode?
for obj in @name.namings + @name.observations
return false if obj.user_id != @user.id
end
end
true
end
def minor_name_change?
old_name = @name.real_search_name
new_name = @parse.real_search_name
new_name.percent_match(old_name) > 0.9
end
def email_admin_name_change
unless @name.author.blank? && @parse.real_text_name == @name.real_text_name
content = :email_name_change.l(
user: @user.login,
old: @name.real_search_name,
new: @parse.real_search_name,
observations: @name.observations.length,
namings: @name.namings.length,
url: "#{MO.http_domain}/name/show_name/#{@name.id}"
)
WebmasterEmail.build(@user.email, content).deliver_now
NameControllerTest.report_email(content) if Rails.env == "test"
end
end
def parse_name
text_name = params[:name][:text_name]
text_name = @name.real_text_name if text_name.blank? && @name
author = params[:name][:author]
in_str = Name.clean_incoming_string("#{text_name} #{author}")
in_rank = params[:name][:rank].to_sym
old_deprecated = @name ? @name.deprecated : false
parse = Name.parse_name(in_str, in_rank, old_deprecated)
if !parse || parse.rank != in_rank
rank_tag = :"rank_#{in_rank.to_s.downcase}"
fail(:runtime_invalid_for_rank.t(rank: rank_tag, name: in_str))
end
parse
end
def find_or_create_name_and_parents
parents = Name.find_or_create_parsed_name_and_parents(@parse)
unless name = parents.pop
if params[:action] == "create_name"
fail(:create_name_multiple_names_match.t(str: @parse.real_search_name))
else
others = Name.where(text_name: @parse.text_name)
fail(:edit_name_multiple_names_match.t(str: @parse.real_search_name,
matches: others.map(&:search_name).join(" / ")))
end
end
[name, parents]
end
def make_sure_name_doesnt_exist
unless @name.new_record?
fail(:runtime_name_create_already_exists.t(name: @name.display_name))
end
end
def create_new_name
@name.attributes = @parse.params
@name.change_deprecated(true) if params[:name][:deprecated] == "true"
@name.citation = params[:name][:citation].to_s.strip_squeeze
@name.notes = params[:name][:notes].to_s.strip
for name in @parents + [@name]
name.save_with_log(:log_name_created_at) if name && name.new_record?
end
flash_notice(:runtime_create_name_success.t(name: @name.real_search_name))
end
def update_existing_name
@name.attributes = @parse.params
@name.citation = params[:name][:citation].to_s.strip_squeeze
@name.notes = params[:name][:notes].to_s.strip
if !@name.changed?
any_changes = false
elsif !@name.save_with_log(:log_name_updated)
fail(:runtime_unable_to_save_changes.t)
else
flash_notice(:runtime_edit_name_success.t(name: @name.real_search_name))
any_changes = true
end
# This name itself might have been a parent when we called
# find_or_create... last time(!)
for name in Name.find_or_create_parsed_name_and_parents(@parse)
name.save_with_log(:log_name_created_at) if name && name.new_record?
end
any_changes
end
def merge_name_into(new_name)
old_display_name_for_log = @name[:display_name]
# First update this name (without saving).
@name.attributes = @parse.params
@name.citation = params[:name][:citation].to_s.strip_squeeze
@name.notes = params[:name][:notes].to_s.strip
# Only change deprecation status if user explicity requested it.
if @name.deprecated != (params[:name][:deprecated] == "true")
change_deprecated = !@name.deprecated
end
# Automatically swap names if that's a safer merge.
if !@name.mergeable? && new_name.mergeable?
@name, new_name = new_name, @name
old_display_name_for_log = @name[:display_name]
end
# Fill in author if other has one.
if new_name.author.blank? && !@parse.author.blank?
new_name.change_author(@parse.author)
end
new_name.change_deprecated(change_deprecated) unless change_deprecated.nil?
@name.display_name = old_display_name_for_log
new_name.merge(@name)
flash_notice(:runtime_edit_name_merge_success.t(this: @name.real_search_name,
that: new_name.real_search_name))
@name = new_name
@name.save
end
def send_name_merge_email(new_name)
flash_warning(:runtime_merge_names_warning.t)
content = :email_name_merge.l(
user: @user.login,
this: "##{@name.id}: " + @name.real_search_name,
that: "##{new_name.id}: " + new_name.real_search_name,
this_url: "#{MO.http_domain}/name/show_name/#{@name.id}",
that_url: "#{MO.http_domain}/name/show_name/#{new_name.id}"
)
WebmasterEmail.build(@user.email, content).deliver_now
NameControllerTest.report_email(content) if Rails.env == "test"
end
# Chain on to approve/deprecate name if changed status.
def redirect_to_approve_or_deprecate
if params[:name][:deprecated].to_s == "true" && !@name.deprecated
redirect_with_query(action: :deprecate_name, id: @name.id)
return true
elsif params[:name][:deprecated].to_s == "false" && @name.deprecated
redirect_with_query(action: :approve_name, id: @name.id)
return true
else
false
end
end
def redirect_to_show_name
redirect_with_query(action: :show_name, id: @name.id)
end
# Update the misspelling status.
#
# @name:: Name whose status we're changing.
# @misspelling:: Boolean: is the "this is misspelt" box checked?
# @correct_spelling:: String: the correct name, as entered by the user.
#
# 1) If the checkbox is unchecked, and name used to be misspelt, then it
# clears correct_spelling_id.
# 2) Otherwise, if the text field is filled in it looks up the name and
# sets correct_spelling_id.
#
# All changes are made (but not saved) to +name+. It returns true if
# everything went well. If it couldn't recognize the correct name, it
# changes nothing and raises a RuntimeError.
#
def update_correct_spelling
if @name.is_misspelling? && (!@misspelling || @correct_spelling.blank?)
# Clear status if checkbox unchecked.
@name.correct_spelling = nil
elsif !@correct_spelling.blank?
# Set correct_spelling if one given.
name2 = Name.find_names_filling_in_authors(@correct_spelling).first
if !name2
fail(:runtime_form_names_misspelling_bad.t)
elsif name2.id == @name.id
fail(:runtime_form_names_misspelling_same.t)
else
@name.correct_spelling = name2
@name.merge_synonyms(name2)
@name.change_deprecated(true)
# Make sure the "correct" name isn't also a misspelled name!
if name2.is_misspelling?
name2.correct_spelling = nil
name2.save_with_log(:log_name_unmisspelled, other: @name.display_name)
end
end
end
end
##############################################################################
#
# :section: Create and Edit Name Descriptions
#
##############################################################################
def create_name_description # :prefetch: :norobots:
store_location
pass_query_params
@name = Name.find(params[:id].to_s)
@licenses = License.current_names_and_ids
# Render a blank form.
if request.method == "GET"
@description = NameDescription.new
@description.name = @name
initialize_description_source(@description)
# Create new description.
else
@description = NameDescription.new
@description.name = @name
@description.attributes = whitelisted_name_description_params
@description.source_type = @description.source_type.to_sym
if @description.valid?
initialize_description_permissions(@description)
@description.save
# Make this the "default" description if there isn't one and this is
# publicly readable.
if !@name.description &&
@description.public
@name.description = @description
end
# Keep the parent's classification cache up to date.
if (@name.description == @description) &&
(@name.classification != @description.classification)
@name.classification = @description.classification
end
# Log action in parent name.
@description.name.log(:log_description_created_at,
user: @user.login, touch: true,
name: @description.unique_partial_format_name)
# Save any changes to parent name.
@name.save if @name.changed?
flash_notice(:runtime_name_description_success.t(
id: @description.id))
redirect_to(action: "show_name_description",
id: @description.id)
else
flash_object_errors @description
end
end
end
def edit_name_description # :prefetch: :norobots:
store_location
pass_query_params
@description = NameDescription.find(params[:id].to_s)
@licenses = License.current_names_and_ids
if !check_description_edit_permission(@description, params[:description])
# already redirected
elsif request.method == "POST"
@description.attributes = whitelisted_name_description_params
@description.source_type = @description.source_type.to_sym
# Modify permissions based on changes to the two "public" checkboxes.
modify_description_permissions(@description)
# If substantive changes are made by a reviewer, call this act a
# "review", even though they haven't actually changed the review
# status. If it's a non-reviewer, this will revert it to "unreviewed".
if @description.save_version?
@description.update_review_status(@description.review_status)
end
# No changes made.
if !@description.changed?
flash_warning(:runtime_edit_name_description_no_change.t)
redirect_to(action: "show_name_description", id: @description.id)
# There were error(s).
elsif !@description.save
flash_object_errors(@description)
# Updated successfully.
else
flash_notice(:runtime_edit_name_description_success.t(
id: @description.id))
# Update name's classification cache.
name = @description.name
if (name.description == @description) &&
(name.classification != @description.classification)
name.classification = @description.classification
name.save
end
# Log action to parent name.
name.log(:log_description_updated, touch: true, user: @user.login,
name: @description.unique_partial_format_name)
# Delete old description after resolving conflicts of merge.
if (params[:delete_after] == "true") &&
(old_desc = NameDescription.safe_find(params[:old_desc_id]))
v = @description.versions.latest
v.merge_source_id = old_desc.versions.latest.id
v.save
if !old_desc.is_admin?(@user)
flash_warning(:runtime_description_merge_delete_denied.t)
else
flash_notice(:runtime_description_merge_deleted.
t(old: old_desc.partial_format_name))
name.log(:log_object_merged_by_user,
user: @user.login, touch: true,
from: old_desc.unique_partial_format_name,
to: @description.unique_partial_format_name)
old_desc.destroy
end
end
redirect_to(action: "show_name_description",
id: @description.id)
end
end
end
def destroy_name_description # :norobots:
pass_query_params
@description = NameDescription.find(params[:id].to_s)
if @description.is_admin?(@user)
flash_notice(:runtime_destroy_description_success.t)
@description.name.log(:log_description_destroyed,
user: @user.login, touch: true,
name: @description.unique_partial_format_name)
@description.destroy
redirect_with_query(action: "show_name", id: @description.name_id)
else
flash_error(:runtime_destroy_description_not_admin.t)
if @description.is_reader?(@user)
redirect_with_query(action: "show_name_description",
id: @description.id)
else
redirect_with_query(action: "show_name", id: @description.name_id)
end
end
end
private
# TODO: should public, public_write and source_type be removed from this list?
# They should be individually checked and set, since we
# don't want them to have arbitrary values
def whitelisted_name_description_params
params.required(:description).
permit(:classification, :gen_desc, :diag_desc, :distribution, :habitat,
:look_alikes, :uses, :refs, :notes, :source_name, :project_id,
:source_type, :public, :public_write)
end
public
################################################################################
#
# :section: Synonymy
#
################################################################################
# Form accessible from show_name that lets a user review all the synonyms
# of a name, removing others, writing in new, etc.
def change_synonyms # :prefetch: :norobots:
pass_query_params
if @name = find_or_goto_index(Name, params[:id].to_s)
@list_members = nil
@new_names = nil
@synonym_name_ids = []
@synonym_names = []
@deprecate_all = true
if request.method == "POST"
list = params[:synonym][:members].strip_squeeze
@deprecate_all = (params[:deprecate][:all] == "1")
# Create any new names that have been approved.
construct_approved_names(list, params[:approved_names], @deprecate_all)
# Parse the write-in list of names.
sorter = NameSorter.new
sorter.sort_names(list)
sorter.append_approved_synonyms(params[:approved_synonyms])
# Are any names unrecognized (only unapproved names will still be
# unrecognized at this point) or ambiguous?
if !sorter.only_single_names
dump_sorter(sorter)
# Has the user NOT had a chance to choose from among the synonyms of any
# names they've written in?
elsif !sorter.only_approved_synonyms
flash_notice :name_change_synonyms_confirm.t
else
now = Time.now
# Create synonym and add this name to it if this name not already
# associated with a synonym.
unless @name.synonym_id
@name.synonym = Synonym.create
@name.save
end
# Go through list of all synonyms for this name and written-in names.
# Exclude any names that have un-checked check-boxes: newly written-in
# names will not have a check-box yet, names written-in in previous
# attempt to submit this form will have checkboxes and therefore must
# be checked to proceed -- the default initial state.
proposed_synonyms = params[:proposed_synonyms] || {}
for n in sorter.all_synonyms
# Synonymize all names that have been checked, or that don't have
# checkboxes.
if proposed_synonyms[n.id.to_s] != "0"
@name.transfer_synonym(n) if n.synonym_id != @name.synonym_id
end
end
# De-synonymize any old synonyms in the "existing synonyms" list that
# have been unchecked. This creates a new synonym to connect them if
# there are multiple unchecked names -- that is, it splits this
# synonym into two synonyms, with checked names staying in this one,
# and unchecked names moving to the new one.
check_for_new_synonym(@name, @name.synonyms, params[:existing_synonyms] || {})
# Deprecate everything if that check-box has been marked.
success = true
if @deprecate_all
for n in sorter.all_names
unless deprecate_synonym(n)
# Already flashed error message.
success = false
end
end
end
if success
redirect_with_query(action: "show_name", id: @name.id)
else
flash_object_errors(@name)
flash_object_errors(@name.synonym)
end
end
@list_members = sorter.all_line_strs.join("\r\n")
@new_names = sorter.new_name_strs.uniq
@synonym_name_ids = sorter.all_synonyms.map(&:id)
@synonym_names = @synonym_name_ids.map { |id| Name.safe_find(id) }.reject(&:nil?)
end
end
end
# Form accessible from show_name that lets the user deprecate a name in favor
# of another name.
def deprecate_name # :prefetch: :norobots:
pass_query_params
# These parameters aren't always provided.
params[:proposed] ||= {}
params[:comment] ||= {}
params[:chosen_name] ||= {}
params[:is] ||= {}
if @name = find_or_goto_index(Name, params[:id].to_s)
@what = begin
params[:proposed][:name].to_s.strip_squeeze
rescue
""
end
@comment = begin
params[:comment][:comment].to_s.strip_squeeze
rescue
""
end
@list_members = nil
@new_names = []
@synonym_name_ids = []
@synonym_names = []
@deprecate_all = "1"
@names = []
@misspelling = (params[:is][:misspelling] == "1")
if request.method == "POST"
if @what.blank?
flash_error :runtime_name_deprecate_must_choose.t
else
# Find the chosen preferred name.
if params[:chosen_name][:name_id] &&
name = Name.safe_find(params[:chosen_name][:name_id])
@names = [name]
else
@names = Name.find_names_filling_in_authors(@what)
end
approved_name = params[:approved_name].to_s.strip_squeeze
if @names.empty? &&
(new_name = Name.create_needed_names(approved_name, @what))
@names = [new_name]
end
target_name = @names.first
# No matches: try to guess.
if @names.empty?
@valid_names = Name.suggest_alternate_spellings(@what)
@suggest_corrections = true
# If written-in name matches uniquely an existing name:
elsif target_name && @names.length == 1
now = Time.now
# Merge this name's synonyms with the preferred name's synonyms.
@name.merge_synonyms(target_name)
# Change target name to "undeprecated".
target_name.change_deprecated(false)
target_name.save_with_log(:log_name_approved, other: @name.real_search_name)
# Change this name to "deprecated", set correct spelling, add note.
@name.change_deprecated(true)
if @misspelling
@name.misspelling = true
@name.correct_spelling = target_name
end
@name.save_with_log(:log_name_deprecated, other: target_name.real_search_name)
post_comment(:deprecate, @name, @comment) unless @comment.blank?
redirect_with_query(action: "show_name", id: @name.id)
end
end # @what
end # "POST"
end
end
# Form accessible from show_name that lets a user make call this an accepted
# name, possibly deprecating its synonyms at the same time.
def approve_name # :prefetch: :norobots:
pass_query_params
if @name = find_or_goto_index(Name, params[:id].to_s)
@approved_names = @name.approved_synonyms
comment = begin
params[:comment][:comment]
rescue
""
end
comment = comment.strip_squeeze
if request.method == "POST"
# Deprecate others first.
others = []
if params[:deprecate][:others] == "1"
for n in @name.approved_synonyms
n.change_deprecated(true)
n.save_with_log(:log_name_deprecated, other: @name.real_search_name)
others << n.real_search_name
end
end
# Approve this now.
@name.change_deprecated(false)
tag = :log_approved_by
args = {}
if others != []
tag = :log_name_approved
args[:other] = others.join(", ")
end
@name.save_with_log(tag, args)
post_comment(:approve, @name, comment) unless comment.blank?
redirect_with_query(action: "show_name", id: @name.id)
end
end
end
# Helper used by change_synonyms. Deprecates a single name. Returns true
# if it worked. Flashes an error and returns false if it fails for whatever
# reason.
def deprecate_synonym(name)
result = true
unless name.deprecated
begin
name.change_deprecated(true)
result = name.save_with_log(:log_deprecated_by)
rescue RuntimeError => err
flash_error(err.to_s) unless err.blank?
result = false
end
end
result
end
# If changing the synonyms of a name that already has synonyms, the user is
# presented with a list of "existing synonyms". This is a list of check-
# boxes. They all start out checked. If the user unchecks one, then that
# name is removed from this synonym. If the user unchecks several, then a
# new synonym is created to synonymize all those names.
def check_for_new_synonym(name, candidates, checks)
new_synonym_members = []
# Gather all names with un-checked checkboxes.
for n in candidates
new_synonym_members.push(n) if (name != n) && (checks[n.id.to_s] == "0")
end
len = new_synonym_members.length
if len > 1
name = new_synonym_members.shift
name.synonym = new_synonym = Synonym.create
name.save
for n in new_synonym_members
name.transfer_synonym(n)
end
elsif len == 1
name = new_synonym_members.first
name.clear_synonym
end
end
def dump_sorter(sorter)
logger.warn("tranfer_synonyms: only_single_names or only_approved_synonyms is false")
logger.warn("New names:")
for n in sorter.new_line_strs
logger.warn(n)
end
logger.warn("\nSingle names:")
for n in sorter.single_line_strs
logger.warn(n)
end
logger.warn("\nMultiple names:")
for n in sorter.multiple_line_strs
logger.warn(n)
end
if sorter.chosen_names
logger.warn("\nChosen names:")
for n in sorter.chosen_names
logger.warn(n)
end
end
logger.warn("\nSynonym names:")
for n in sorter.all_synonyms.map(&:id)
logger.warn(n)
end
end
# Post a comment after approval or deprecation if the user entered one.
def post_comment(action, name, message)
summary = :"name_#{action}_comment_summary".l
comment = Comment.create!(
target: name,
summary: summary,
comment: message
)
end
##############################################################################
#
# :section: EOL Feed
#
##############################################################################
# Send stuff to eol.
def eol_old # :nologin: :norobots:
@max_secs = params[:max_secs] ? params[:max_secs].to_i : nil
@timer_start = Time.now
eol_data(NameDescription.review_statuses.values_at(:unvetted, :vetted))
render_xml(action: "eol", layout: false)
end
# Show the data getting sent to EOL
def eol_preview # :nologin: :norobots:
@timer_start = Time.now
eol_data(NameDescription.review_statuses.values_at(:unvetted, :vetted))
@timer_end = Time.now
end
def eol_description_conditions(review_status_list)
# name descriptions that are exportable.
rsl = review_status_list.join("', '")
"review_status IN ('#{rsl}') AND " \
"gen_desc IS NOT NULL AND " \
"ok_for_export = 1 AND " \
"public = 1"
end
# Show the data not getting sent to EOL
def eol_need_review # :norobots:
eol_data(NameDescription.review_statuses.values_at(unreviewed))
@title = :eol_need_review_title.t
render(action: "eol_preview")
end
# Gather data for EOL feed.
def eol_data(review_status_list)
@names = []
@descs = {} # name.id -> [NameDescription, NmeDescription, ...]
@image_data = {} # name.id -> [img.id, obs.id, user.id, lic.id, date]
@users = {} # user.id -> user.legal_name
@licenses = {} # license.id -> license.url
@authors = {} # desc.id -> "user.legal_name, user.legal_name, ..."
descs = NameDescription.where(
eol_description_conditions(review_status_list))
# Fill in @descs, @users, @authors, @licenses.
for desc in descs
name_id = desc.name_id.to_i
@descs[name_id] ||= []
@descs[name_id] << desc
authors = Name.connection.select_values(%(
SELECT user_id FROM name_descriptions_authors
WHERE name_description_id = #{desc.id}
)).map(&:to_i)
authors = [desc.user_id] if authors.empty?
for author in authors
@users[author.to_i] ||= User.find(author).legal_name
end
@authors[desc.id] = authors.map { |id| @users[id.to_i] }.join(", ")
@licenses[desc.license_id] ||= desc.license.url if desc.license_id
end
# Get corresponding names.
name_ids = @descs.keys.map(&:to_s).join(",")
@names = Name.where(id: name_ids).order(:sort_name, :author).to_a
# Get corresponding images.
image_data = Name.connection.select_all %(
SELECT name_id, image_id, observation_id, images.user_id,
images.license_id, images.created_at
FROM observations, images_observations, images
WHERE observations.name_id IN (#{name_ids})
AND observations.vote_cache >= 2.4
AND observations.id = images_observations.observation_id
AND images_observations.image_id = images.id
AND images.vote_cache >= 2
AND images.ok_for_export
ORDER BY observations.vote_cache
)
image_data = image_data.to_a
# Fill in @image_data, @users, and @licenses.
for row in image_data
name_id = row["name_id"].to_i
user_id = row["user_id"].to_i
license_id = row["license_id"].to_i
image_datum = row.values_at("image_id", "observation_id", "user_id",
"license_id", "created_at")
@image_data[name_id] ||= []
@image_data[name_id].push(image_datum)
@users[user_id] ||= User.find(user_id).legal_name
@licenses[license_id] ||= License.find(license_id).url
end
end
def eol_expanded_review
@timer_start = Time.now
@data = EolData.new
end
# TODO: Add ability to preview synonyms?
# TODO: List stuff that's almost ready.
# TODO: Add EOL logo on pages getting exported
# show_name and show_descriptions for description info
# show_name, show_observation and show_image for images
# EOL preview from Name page
# Improve the Name page
# Review unapproved descriptions
# Send stuff to eol.
def eol # :nologin: :norobots:
@max_secs = params[:max_secs] ? params[:max_secs].to_i : nil
@timer_start = Time.now
@data = EolData.new
render_xml(layout: false)
end
def refresh_links_to_eol
data = get_eol_collection_data
clear_eol_data
load_eol_data(data)
end
def eol_for_taxon
store_location
# need name_id and review_status_list
id = params[:id].to_s
@name = Name.find(id)
@layout = calc_layout_params
# Get corresponding images.
ids = Name.connection.select_values(%(
SELECT images.id
FROM observations, images_observations, images
WHERE observations.name_id = #{id}
AND observations.vote_cache >= 2.4
AND observations.id = images_observations.observation_id
AND images_observations.image_id = images.id
AND images.vote_cache >= 2
AND images.ok_for_export
ORDER BY images.vote_cache DESC
))
# @images = Image.find(:all, :conditions => ['images.id IN (?)', ids], :include => :image_votes) # Rails 3
@images = Image.includes(:image_votes).where(images.id => ids).to_a
ids = Name.connection.select_values(%(
SELECT images.id
FROM observations, images_observations, images
WHERE observations.name_id = #{id}
AND observations.vote_cache >= 2.4
AND observations.id = images_observations.observation_id
AND images_observations.image_id = images.id
AND images.vote_cache IS NULL
AND images.ok_for_export
ORDER BY observations.vote_cache
))
# @voteless_images = Image.find(:all, :conditions => ['images.id IN (?)', ids], :include => :image_votes) # Rails 3
@voteless_images = Image.includes(:image_votes).where(images.id => ids)
ids = Name.connection.select_values(%(
SELECT DISTINCT observations.id
FROM observations, images_observations, images
WHERE observations.name_id = #{id}
AND observations.vote_cache IS NULL
AND observations.id = images_observations.observation_id
AND images_observations.image_id = images.id
AND images.ok_for_export
ORDER BY observations.id
))
# @voteless_obs = Observation.find(:all, :conditions => ['id IN (?)', ids]) # Rails 3
@voteless_obs = Observation.where(images.id => ids).to_a
end
################################################################################
#
# :section: Other Stuff
#
################################################################################
# Utility accessible from a number of name pages (e.g. indexes and
# show_name?) that lets you enter a whole list of names, together with
# synonymy, and create them all in one blow.
def bulk_name_edit # :prefetch: :norobots:
@list_members = nil
@new_names = nil
if request.method == "POST"
list = begin
params[:list][:members].strip_squeeze
rescue
""
end
construct_approved_names(list, params[:approved_names])
sorter = NameSorter.new
sorter.sort_names(list)
if sorter.only_single_names
sorter.create_new_synonyms
flash_notice :name_bulk_success.t
redirect_to(controller: "observer", action: "list_rss_logs")
else
if sorter.new_name_strs != []
# This error message is no longer necessary.
flash_error "Unrecognized names given, including: #{sorter.new_name_strs[0].inspect}" if Rails.env == "test"
else
# Same with this one... err, no this is not reported anywhere.
flash_error "Ambiguous names given, including: #{sorter.multiple_line_strs[0].inspect}"
end
@list_members = sorter.all_line_strs.join("\r\n")
@new_names = sorter.new_name_strs.uniq.sort
end
end
end
# Draw a map of all the locations where this name has been observed.
def map # :nologin: :norobots:
pass_query_params
if @name = find_or_goto_index(Name, params[:id].to_s)
@query = create_query(:Observation, :of_name, name: @name)
@observations = @query.results.select { |o| o.lat || o.location }
end
end
# Form accessible from show_name that lets a user setup tracker notifications
# for a name.
def email_tracking # :norobots:
pass_query_params
name_id = params[:id].to_s
if @name = find_or_goto_index(Name, name_id)
flavor = Notification.flavors[:name]
@notification = Notification.find_by_flavor_and_obj_id_and_user_id(flavor, name_id, @user.id)
# Initialize form.
if request.method != "POST"
unless @name.at_or_below_genus?
flash_warning(:email_tracking_enabled_only_for.t(name: @name.display_name, rank: @name.rank))
end
if @notification
@note_template = @notification.note_template
else
mailing_address = @user.mailing_address.strip
mailing_address = ":mailing_address" if mailing_address.blank?
@note_template = :email_tracking_note_template.l(
species_name: @name.real_text_name,
mailing_address: mailing_address,
users_name: @user.legal_name
)
end
# Submit form.
else
case params[:commit]
when :ENABLE.l, :UPDATE.l
note_template = params[:notification][:note_template]
note_template = nil if note_template.blank?
if @notification.nil?
@notification = Notification.new(flavor: :name, user: @user,
obj_id: name_id, note_template: note_template)
flash_notice(:email_tracking_now_tracking.t(name: @name.display_name))
else
@notification.note_template = note_template
flash_notice(:email_tracking_updated_messages.t)
end
@notification.save
when :DISABLE.l
@notification.destroy
flash_notice(:email_tracking_no_longer_tracking.t(name: @name.display_name))
end
redirect_with_query(action: "show_name", id: name_id)
end
end
end
################################################################################
#
# :section: Stuff for Mushroom App
#
################################################################################
def names_for_mushroom_app # :nologin: :norobots:
number_of_names = params[:number_of_names].blank? ? 1000 : params[:number_of_names]
minimum_confidence = params[:minimum_confidence].blank? ? 1.5 : params[:minimum_confidence]
minimum_observations = params[:minimum_observations].blank? ? 5 : params[:minimum_observations]
rank_condition = params[:include_higher_taxa].blank? ?
"= #{Name.ranks[:Species]}" :
"NOT IN (#{Name.ranks.values_at(:Subspecies, :Variety, :Form, :Group).join(",")})"
data = Name.connection.select_rows(%(
SELECT y.name, y.rank, SUM(y.number)
FROM (
SELECT n.text_name AS name,
n.rank AS rank,
x.number AS number
FROM (
SELECT n.id AS name_id,
n.synonym_id AS synonym_id,
COUNT(o.id) AS number
FROM names n, observations o
WHERE o.name_id = n.id
AND o.vote_cache >= #{minimum_confidence}
GROUP BY IF(n.synonym_id IS NULL, n.id, -n.synonym_id)
) AS x
LEFT OUTER JOIN names n ON IF(x.synonym_id IS NULL, n.id = x.name_id, n.synonym_id = x.synonym_id)
WHERE n.deprecated = FALSE
AND x.number >= #{minimum_observations}
AND n.rank #{rank_condition}
GROUP BY IF(n.synonym_id IS NULL, n.id, -n.synonym_id)
) AS y
GROUP BY y.name
ORDER BY SUM(y.number) DESC
LIMIT #{number_of_names}
))
genera = data.map do |name, _rank, _number|
name.split(" ").first
end.uniq
families = {}
for genus, classification in Name.connection.select_rows(%(
SELECT text_name, classification FROM names
WHERE rank = #{Name.ranks[:Genus]}
AND COALESCE(classification,'') != ''
AND text_name IN ('#{genera.join("','")}')
))
for rank, name in Name.parse_classification(classification).reverse
if rank == :Family
families[genus] = name
break
end
end
end
report = CSV.generate(col_sep: "\t") do |csv|
csv << %w(name rank number_observations family)
data.each do |name, rank, number|
genus = name.split(" ").first
family = families[genus] || ""
csv << [name, rank, number.round.to_s, family]
end
end
send_data(report,
type: "text/csv",
charset: "UTF-8",
header: "present",
disposition: "attachment",
filename: "#{action_name}.csv"
)
rescue => e
render(text: e.to_s, layout: false, status: 500)
end
end
Prevent NameController from throwing error if user.mailing_address is nil.
# encoding: utf-8
#
# = Name Controller
#
# == Actions
# L = login required
# R = root required
# V = has view
# P = prefetching allowed
#
# index_name:: List of results of index/search.
# list_names:: Alphabetical list of all names, used or otherwise.
# observation_index:: Alphabetical list of names people have seen.
# names_by_user:: Alphabetical list of names created by given user.
# names_by_editor:: Alphabetical list of names edited by given user.
# name_search:: Seach for string in name, notes, etc.
# map:: Show distribution map.
# index_name_description:: List of results of index/search.
# list_name_descriptions:: Alphabetical list of all name_descriptions,
# used or otherwise.
# name_descriptions_by_author:: Alphabetical list of name_descriptions authored
# by given user.
# name_descriptions_by_editor:: Alphabetical list of name_descriptions edited
# by given user.
# show_name:: Show info about name.
# show_past_name:: Show past versions of name info.
# prev_name:: Show previous name in index.
# next_name:: Show next name in index.
# show_name_description:: Show info about name_description.
# show_past_name_description:: Show past versions of name_description info.
# prev_name_description:: Show previous name_description in index.
# next_name_description:: Show next name_description in index.
# create_name:: Create new name.
# edit_name:: Edit name.
# create_name_description:: Create new name_description.
# edit_name_description:: Edit name_description.
# destroy_name_description:: Destroy name_description.
# make_description_default:: Make a description the default one.
# merge_descriptions:: Merge a description with another.
# publish_description:: Publish a draft description.
# adjust_permissions:: Adjust permissions on a description.
# change_synonyms:: Change list of synonyms for a name.
# deprecate_name:: Deprecate name in favor of another.
# approve_name:: Flag given name as "accepted"
# (others could be, too).
# bulk_name_edit:: Create/synonymize/deprecate a list of names.
# names_for_mushroom_app:: Display list of most common names in plain text.
#
# ==== Helpers
# deprecate_synonym:: (used by change_synonyms)
# check_for_new_synonym:: (used by change_synonyms)
# dump_sorter:: Error diagnostics for change_synonyms.
#
################################################################################
class NameController < ApplicationController
include DescriptionControllerHelpers
before_action :login_required, except: [
:advanced_search,
:authored_names,
:eol,
:eol_preview,
:index_name,
:index_name_description,
:map,
:list_name_descriptions,
:list_names,
:name_search,
:name_descriptions_by_author,
:name_descriptions_by_editor,
:names_by_user,
:names_by_editor,
:needed_descriptions,
:next_name,
:next_name_description,
:observation_index,
:prev_name,
:prev_name_description,
:show_name,
:show_name_description,
:show_past_name,
:show_past_name_description,
:test_index
]
before_action :disable_link_prefetching, except: [
:approve_name,
:bulk_name_edit,
:change_synonyms,
:create_name,
:create_name_description,
:deprecate_name,
:edit_name,
:edit_name_description,
:show_name,
:show_name_description,
:show_past_name,
:show_past_name_description
]
##############################################################################
#
# :section: Indexes and Searches
#
##############################################################################
# Display list of names in last index/search query.
def index_name # :nologin: :norobots:
query = find_or_create_query(:Name, by: params[:by])
show_selected_names(query, id: params[:id].to_s, always_index: true)
end
# Display list of all (correctly-spelled) names in the database.
def list_names # :nologin:
query = create_query(:Name, :all, by: :name)
show_selected_names(query)
end
# Display list of names that have observations.
def observation_index # :nologin: :norobots:
query = create_query(:Name, :with_observations)
show_selected_names(query)
end
# Display list of names that have authors.
def authored_names # :nologin: :norobots:
query = create_query(:Name, :with_descriptions)
show_selected_names(query)
end
# Display list of names that a given user is author on.
def names_by_user # :nologin: :norobots:
if user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user
query = create_query(:Name, :by_user, user: user)
show_selected_names(query)
end
end
# This no longer makes sense, but is being requested by robots.
alias_method :names_by_author, :names_by_user
# Display list of names that a given user is editor on.
def names_by_editor # :nologin: :norobots:
if user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user
query = create_query(:Name, :by_editor, user: user)
show_selected_names(query)
end
end
# Display list of the most popular 100 names that don't have descriptions.
def needed_descriptions # :nologin: :norobots:
# NOTE!! -- all this extra info and help will be lost if user re-sorts.
data = Name.connection.select_rows %(
SELECT names.id, name_counts.count
FROM names LEFT OUTER JOIN name_descriptions ON names.id = name_descriptions.name_id,
(SELECT count(*) AS count, name_id
FROM observations group by name_id) AS name_counts
WHERE names.id = name_counts.name_id
AND names.rank = #{Name.ranks[:Species]}
AND name_counts.count > 1
AND name_descriptions.name_id IS NULL
AND CURRENT_TIMESTAMP - names.updated_at > #{1.week.to_i}
ORDER BY name_counts.count DESC, names.sort_name ASC
LIMIT 100
)
@help = :needed_descriptions_help
query = create_query(:Name, :in_set, ids: data.map(&:first),
title: :needed_descriptions_title.l)
show_selected_names(query, num_per_page: 100) do |name|
# Add number of observations (parenthetically).
row = data.find { |id, _count| id == name.id }
row ? "(#{count} #{:observations.t})" : ""
end
end
# Display list of names that match a string.
def name_search # :nologin: :norobots:
pattern = params[:pattern].to_s
if pattern.match(/^\d+$/) &&
(name = Name.safe_find(pattern))
redirect_to(action: "show_name", id: name.id)
else
query = create_query(:Name, :pattern_search, pattern: pattern)
@suggest_alternate_spellings = pattern
show_selected_names(query)
end
end
# Displays list of advanced search results.
def advanced_search # :nologin: :norobots:
query = find_query(:Name)
show_selected_names(query)
rescue => err
flash_error(err.to_s) unless err.blank?
redirect_to(controller: "observer", action: "advanced_search_form")
end
# Used to test pagination.
def test_index # :nologin: :norobots:
query = find_query(:Name) or fail "Missing query: #{params[:q]}"
if params[:test_anchor]
@test_pagination_args = { anchor: params[:test_anchor] }
end
show_selected_names(query, num_per_page: params[:num_per_page].to_i)
end
# Show selected search results as a list with 'list_names' template.
def show_selected_names(query, args = {})
store_query_in_session(query)
@links ||= []
args = {
action: "list_names",
letters: "names.sort_name",
num_per_page: (params[:letter].to_s.match(/^[a-z]/i) ? 500 : 50)
}.merge(args)
# Tired of not having an easy link to list_names.
if query.flavor == :with_observations
@links << [:all_objects.t(type: :name), { action: "list_names" }]
end
# Add some alternate sorting criteria.
args[:sorting_links] = [
["name", :sort_by_name.t],
["created_at", :sort_by_created_at.t],
[(query.flavor == :by_rss_log ? "rss_log" : "updated_at"),
:sort_by_updated_at.t],
["num_views", :sort_by_num_views.t]
]
# Add "show observations" link if this query can be coerced into an
# observation query.
if query.is_coercable?(:Observation)
@links << [:show_objects.t(type: :observation),
add_query_param({
controller: "observer", action: "index_observation"
}, query)]
end
# Add "show descriptions" link if this query can be coerced into a
# description query.
if query.is_coercable?(:NameDescription)
@links << [:show_objects.t(type: :description),
add_query_param({ action: "index_name_description" },
query)]
end
# Add some extra fields to the index for authored_names.
if query.flavor == :with_descriptions
show_index_of_objects(query, args) do |name|
if desc = name.description
[desc.authors.map(&:login).join(", "),
desc.note_status.map(&:to_s).join("/"),
:"review_#{desc.review_status}".t]
else
[]
end
end
else
show_index_of_objects(query, args)
end
end
##############################################################################
#
# :section: Description Indexes and Searches
#
##############################################################################
# Display list of names in last index/search query.
def index_name_description # :nologin: :norobots:
query = find_or_create_query(:NameDescription, by: params[:by])
show_selected_name_descriptions(query, id: params[:id].to_s,
always_index: true)
end
# Display list of all (correctly-spelled) name_descriptions in the database.
def list_name_descriptions # :nologin:
query = create_query(:NameDescription, :all, by: :name)
show_selected_name_descriptions(query)
end
# Display list of name_descriptions that a given user is author on.
def name_descriptions_by_author # :nologin: :norobots:
if user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user
query = create_query(:NameDescription, :by_author, user: user)
show_selected_name_descriptions(query)
end
end
# Display list of name_descriptions that a given user is editor on.
def name_descriptions_by_editor # :nologin: :norobots:
if user = params[:id] ? find_or_goto_index(User, params[:id].to_s) : @user
query = create_query(:NameDescription, :by_editor, user: user)
show_selected_name_descriptions(query)
end
end
# Show selected search results as a list with 'list_names' template.
def show_selected_name_descriptions(query, args = {})
store_query_in_session(query)
@links ||= []
args = {
action: "list_name_descriptions",
num_per_page: 50
}.merge(args)
# Add some alternate sorting criteria.
args[:sorting_links] = [
["name", :sort_by_name.t],
["created_at", :sort_by_created_at.t],
["updated_at", :sort_by_updated_at.t],
["num_views", :sort_by_num_views.t]
]
# Add "show names" link if this query can be coerced into an
# observation query.
if query.is_coercable?(:Name)
@links << [:show_objects.t(type: :name),
add_query_param({ action: "index_name" }, query)]
end
show_index_of_objects(query, args)
end
################################################################################
#
# :section: Show Name
#
################################################################################
# Show a Name, one of its NameDescription's, associated taxa, and a bunch of
# relevant Observations.
def show_name # :nologin: :prefetch:
pass_query_params
store_location
clear_query_in_session
# Load Name and NameDescription along with a bunch of associated objects.
name_id = params[:id].to_s
desc_id = params[:desc]
if @name = find_or_goto_index(Name, name_id)
@canonical_url = "#{MO.http_domain}/name/show_name/#{@name.id}"
update_view_stats(@name)
# Tell robots the proper URL to use to index this content.
@canonical_url = "#{MO.http_domain}/name/show_name/#{@name.id}"
# Get a list of projects the user can create drafts for.
@projects = @user && @user.projects_member.select do |project|
!@name.descriptions.any? { |d| d.belongs_to_project?(project) }
end
# Get classification
@classification = @name.best_classification
@parents = nil
unless @classification
# Get list of immediate parents.
@parents = @name.parents
end
# Create query for immediate children.
@children_query = create_query(:Name, :of_children, name: @name)
# Create search queries for observation lists.
@consensus_query = create_query(:Observation, :of_name, name: @name,
by: :confidence)
@consensus2_query = create_query(:Observation, :of_name, name: @name,
synonyms: :all,
by: :confidence)
@synonym_query = create_query(:Observation, :of_name, name: @name,
synonyms: :exclusive,
by: :confidence)
@other_query = create_query(:Observation, :of_name, name: @name,
synonyms: :all, nonconsensus: :exclusive,
by: :confidence)
@obs_with_images_query = create_query(:Observation, :of_name, name: @name,
by: :confidence, has_images: :yes)
if @name.at_or_below_genus?
@subtaxa_query = create_query(:Observation, :of_children, name: @name,
all: true, by: :confidence)
end
# Determine which queries actually have results and instantiate the ones we'll use
@best_description = @name.best_brief_description
@first_four = @obs_with_images_query.results(limit: 4)
@first_child = @children_query.results(limit: 1)[0]
@first_consensus = @consensus_query.results(limit: 1)[0]
@has_consensus2 = @consensus2_query.select_count
@has_synonym = @synonym_query.select_count
@has_other = @other_query.select_count
@has_subtaxa = @subtaxa_query.select_count if @subtaxa_query
end
end
# Show just a NameDescription.
def show_name_description # :nologin: :prefetch:
store_location
pass_query_params
if @description = find_or_goto_index(NameDescription, params[:id].to_s)
@canonical_url = "#{MO.http_domain}/name/show_name_description/#{@description.id}"
# Tell robots the proper URL to use to index this content.
@canonical_url = "#{MO.http_domain}/name/show_name_description/#{@description.id}"
# Public or user has permission.
if @description.is_reader?(@user)
@name = @description.name
update_view_stats(@description)
# Get a list of projects the user can create drafts for.
@projects = @user && @user.projects_member.select do |project|
!@name.descriptions.any? { |d| d.belongs_to_project?(project) }
end
# User doesn't have permission to see this description.
else
if @description.source_type == :project
flash_error(:runtime_show_draft_denied.t)
if project = @description.project
redirect_to(controller: "project", action: "show_project",
id: project.id)
else
redirect_to(action: "show_name", id: @description.name_id)
end
else
flash_error(:runtime_show_description_denied.t)
redirect_to(action: "show_name", id: @description.name_id)
end
end
end
end
# Show past version of Name. Accessible only from show_name page.
def show_past_name # :nologin: :prefetch: :norobots:
pass_query_params
store_location
if @name = find_or_goto_index(Name, params[:id].to_s)
@name.revert_to(params[:version].to_i)
# Old correct spellings could have gotten merged with something else and no longer exist.
if @name.is_misspelling?
@correct_spelling = Name.connection.select_value %(
SELECT display_name FROM names WHERE id = #{@name.correct_spelling_id}
)
else
@correct_spelling = ""
end
end
end
# Show past version of NameDescription. Accessible only from
# show_name_description page.
def show_past_name_description # :nologin: :prefetch: :norobots:
pass_query_params
store_location
if @description = find_or_goto_index(NameDescription, params[:id].to_s)
@name = @description.name
if params[:merge_source_id].blank?
@description.revert_to(params[:version].to_i)
else
@merge_source_id = params[:merge_source_id]
version = NameDescription::Version.find(@merge_source_id)
@old_parent_id = version.name_description_id
subversion = params[:version]
if !subversion.blank? &&
(version.version != subversion.to_i)
version = NameDescription::Version.
find_by_version_and_name_description_id(params[:version], @old_parent_id)
end
@description.clone_versioned_model(version, @description)
end
end
end
# Go to next name: redirects to show_name.
def next_name # :nologin: :norobots:
redirect_to_next_object(:next, Name, params[:id].to_s)
end
# Go to previous name: redirects to show_name.
def prev_name # :nologin: :norobots:
redirect_to_next_object(:prev, Name, params[:id].to_s)
end
# Go to next name: redirects to show_name.
def next_name_description # :nologin: :norobots:
redirect_to_next_object(:next, NameDescription, params[:id].to_s)
end
# Go to previous name_description: redirects to show_name_description.
def prev_name_description # :nologin: :norobots:
redirect_to_next_object(:prev, NameDescription, params[:id].to_s)
end
# Callback to let reviewers change the review status of a Name from the
# show_name page.
def set_review_status # :norobots:
pass_query_params
id = params[:id].to_s
desc = NameDescription.find(id)
desc.update_review_status(params[:value]) if is_reviewer?
redirect_with_query(action: :show_name, id: desc.name_id)
end
##############################################################################
#
# :section: Create and Edit Names
#
##############################################################################
# Create a new name; accessible from name indexes.
def create_name # :prefetch: :norobots:
store_location
pass_query_params
if request.method != "POST"
init_create_name_form
else
@parse = parse_name
@name, @parents = find_or_create_name_and_parents
make_sure_name_doesnt_exist
create_new_name
redirect_to_show_name
end
rescue RuntimeError => err
reload_create_name_form_on_error(err)
end
# Make changes to name; accessible from show_name page.
def edit_name # :prefetch: :norobots:
store_location
pass_query_params
if @name = find_or_goto_index(Name, params[:id].to_s)
init_edit_name_form
if request.method == "POST"
@parse = parse_name
new_name, @parents = find_or_create_name_and_parents
if new_name.new_record? || new_name == @name
email_admin_name_change unless can_make_changes? || minor_name_change?
update_correct_spelling
any_changes = update_existing_name
unless redirect_to_approve_or_deprecate
flash_warning(:runtime_edit_name_no_change.t) unless any_changes
redirect_to_show_name
end
elsif is_in_admin_mode? || @name.mergeable? || new_name.mergeable?
merge_name_into(new_name)
redirect_to_show_name
else
send_name_merge_email(new_name)
redirect_to_show_name
end
end
end
rescue RuntimeError => err
reload_edit_name_form_on_error(err)
end
def init_create_name_form
@name = Name.new
@name.rank = :Species
@name_string = ""
end
def reload_create_name_form_on_error(err)
flash_error(err.to_s) unless err.blank?
flash_object_errors(@name)
init_create_name_form
@name.rank = params[:name][:rank]
@name.author = params[:name][:author]
@name.citation = params[:name][:citation]
@name.notes = params[:name][:notes]
@name_string = params[:name][:text_name]
end
def init_edit_name_form
if !params[:name]
@misspelling = @name.is_misspelling?
@correct_spelling = @misspelling ? @name.correct_spelling.real_search_name : ""
else
@misspelling = (params[:name][:misspelling] == "1")
@correct_spelling = params[:name][:correct_spelling].to_s.strip_squeeze
end
@name_string = @name.real_text_name
end
def reload_edit_name_form_on_error(err)
flash_error(err.to_s) unless err.blank?
flash_object_errors(@name)
@name.rank = params[:name][:rank]
@name.author = params[:name][:author]
@name.citation = params[:name][:citation]
@name.notes = params[:name][:notes]
@name.deprecated = (params[:name][:deprecated] == "true")
@name_string = params[:name][:text_name]
end
# Only allowed to make substantive changes to name if you own all the references to it.
def can_make_changes?
unless is_in_admin_mode?
for obj in @name.namings + @name.observations
return false if obj.user_id != @user.id
end
end
true
end
def minor_name_change?
old_name = @name.real_search_name
new_name = @parse.real_search_name
new_name.percent_match(old_name) > 0.9
end
def email_admin_name_change
unless @name.author.blank? && @parse.real_text_name == @name.real_text_name
content = :email_name_change.l(
user: @user.login,
old: @name.real_search_name,
new: @parse.real_search_name,
observations: @name.observations.length,
namings: @name.namings.length,
url: "#{MO.http_domain}/name/show_name/#{@name.id}"
)
WebmasterEmail.build(@user.email, content).deliver_now
NameControllerTest.report_email(content) if Rails.env == "test"
end
end
def parse_name
text_name = params[:name][:text_name]
text_name = @name.real_text_name if text_name.blank? && @name
author = params[:name][:author]
in_str = Name.clean_incoming_string("#{text_name} #{author}")
in_rank = params[:name][:rank].to_sym
old_deprecated = @name ? @name.deprecated : false
parse = Name.parse_name(in_str, in_rank, old_deprecated)
if !parse || parse.rank != in_rank
rank_tag = :"rank_#{in_rank.to_s.downcase}"
fail(:runtime_invalid_for_rank.t(rank: rank_tag, name: in_str))
end
parse
end
def find_or_create_name_and_parents
parents = Name.find_or_create_parsed_name_and_parents(@parse)
unless name = parents.pop
if params[:action] == "create_name"
fail(:create_name_multiple_names_match.t(str: @parse.real_search_name))
else
others = Name.where(text_name: @parse.text_name)
fail(:edit_name_multiple_names_match.t(str: @parse.real_search_name,
matches: others.map(&:search_name).join(" / ")))
end
end
[name, parents]
end
def make_sure_name_doesnt_exist
unless @name.new_record?
fail(:runtime_name_create_already_exists.t(name: @name.display_name))
end
end
def create_new_name
@name.attributes = @parse.params
@name.change_deprecated(true) if params[:name][:deprecated] == "true"
@name.citation = params[:name][:citation].to_s.strip_squeeze
@name.notes = params[:name][:notes].to_s.strip
for name in @parents + [@name]
name.save_with_log(:log_name_created_at) if name && name.new_record?
end
flash_notice(:runtime_create_name_success.t(name: @name.real_search_name))
end
def update_existing_name
@name.attributes = @parse.params
@name.citation = params[:name][:citation].to_s.strip_squeeze
@name.notes = params[:name][:notes].to_s.strip
if !@name.changed?
any_changes = false
elsif !@name.save_with_log(:log_name_updated)
fail(:runtime_unable_to_save_changes.t)
else
flash_notice(:runtime_edit_name_success.t(name: @name.real_search_name))
any_changes = true
end
# This name itself might have been a parent when we called
# find_or_create... last time(!)
for name in Name.find_or_create_parsed_name_and_parents(@parse)
name.save_with_log(:log_name_created_at) if name && name.new_record?
end
any_changes
end
def merge_name_into(new_name)
old_display_name_for_log = @name[:display_name]
# First update this name (without saving).
@name.attributes = @parse.params
@name.citation = params[:name][:citation].to_s.strip_squeeze
@name.notes = params[:name][:notes].to_s.strip
# Only change deprecation status if user explicity requested it.
if @name.deprecated != (params[:name][:deprecated] == "true")
change_deprecated = !@name.deprecated
end
# Automatically swap names if that's a safer merge.
if !@name.mergeable? && new_name.mergeable?
@name, new_name = new_name, @name
old_display_name_for_log = @name[:display_name]
end
# Fill in author if other has one.
if new_name.author.blank? && !@parse.author.blank?
new_name.change_author(@parse.author)
end
new_name.change_deprecated(change_deprecated) unless change_deprecated.nil?
@name.display_name = old_display_name_for_log
new_name.merge(@name)
flash_notice(:runtime_edit_name_merge_success.t(this: @name.real_search_name,
that: new_name.real_search_name))
@name = new_name
@name.save
end
def send_name_merge_email(new_name)
flash_warning(:runtime_merge_names_warning.t)
content = :email_name_merge.l(
user: @user.login,
this: "##{@name.id}: " + @name.real_search_name,
that: "##{new_name.id}: " + new_name.real_search_name,
this_url: "#{MO.http_domain}/name/show_name/#{@name.id}",
that_url: "#{MO.http_domain}/name/show_name/#{new_name.id}"
)
WebmasterEmail.build(@user.email, content).deliver_now
NameControllerTest.report_email(content) if Rails.env == "test"
end
# Chain on to approve/deprecate name if changed status.
def redirect_to_approve_or_deprecate
if params[:name][:deprecated].to_s == "true" && !@name.deprecated
redirect_with_query(action: :deprecate_name, id: @name.id)
return true
elsif params[:name][:deprecated].to_s == "false" && @name.deprecated
redirect_with_query(action: :approve_name, id: @name.id)
return true
else
false
end
end
def redirect_to_show_name
redirect_with_query(action: :show_name, id: @name.id)
end
# Update the misspelling status.
#
# @name:: Name whose status we're changing.
# @misspelling:: Boolean: is the "this is misspelt" box checked?
# @correct_spelling:: String: the correct name, as entered by the user.
#
# 1) If the checkbox is unchecked, and name used to be misspelt, then it
# clears correct_spelling_id.
# 2) Otherwise, if the text field is filled in it looks up the name and
# sets correct_spelling_id.
#
# All changes are made (but not saved) to +name+. It returns true if
# everything went well. If it couldn't recognize the correct name, it
# changes nothing and raises a RuntimeError.
#
def update_correct_spelling
if @name.is_misspelling? && (!@misspelling || @correct_spelling.blank?)
# Clear status if checkbox unchecked.
@name.correct_spelling = nil
elsif !@correct_spelling.blank?
# Set correct_spelling if one given.
name2 = Name.find_names_filling_in_authors(@correct_spelling).first
if !name2
fail(:runtime_form_names_misspelling_bad.t)
elsif name2.id == @name.id
fail(:runtime_form_names_misspelling_same.t)
else
@name.correct_spelling = name2
@name.merge_synonyms(name2)
@name.change_deprecated(true)
# Make sure the "correct" name isn't also a misspelled name!
if name2.is_misspelling?
name2.correct_spelling = nil
name2.save_with_log(:log_name_unmisspelled, other: @name.display_name)
end
end
end
end
##############################################################################
#
# :section: Create and Edit Name Descriptions
#
##############################################################################
def create_name_description # :prefetch: :norobots:
store_location
pass_query_params
@name = Name.find(params[:id].to_s)
@licenses = License.current_names_and_ids
# Render a blank form.
if request.method == "GET"
@description = NameDescription.new
@description.name = @name
initialize_description_source(@description)
# Create new description.
else
@description = NameDescription.new
@description.name = @name
@description.attributes = whitelisted_name_description_params
@description.source_type = @description.source_type.to_sym
if @description.valid?
initialize_description_permissions(@description)
@description.save
# Make this the "default" description if there isn't one and this is
# publicly readable.
if !@name.description &&
@description.public
@name.description = @description
end
# Keep the parent's classification cache up to date.
if (@name.description == @description) &&
(@name.classification != @description.classification)
@name.classification = @description.classification
end
# Log action in parent name.
@description.name.log(:log_description_created_at,
user: @user.login, touch: true,
name: @description.unique_partial_format_name)
# Save any changes to parent name.
@name.save if @name.changed?
flash_notice(:runtime_name_description_success.t(
id: @description.id))
redirect_to(action: "show_name_description",
id: @description.id)
else
flash_object_errors @description
end
end
end
def edit_name_description # :prefetch: :norobots:
store_location
pass_query_params
@description = NameDescription.find(params[:id].to_s)
@licenses = License.current_names_and_ids
if !check_description_edit_permission(@description, params[:description])
# already redirected
elsif request.method == "POST"
@description.attributes = whitelisted_name_description_params
@description.source_type = @description.source_type.to_sym
# Modify permissions based on changes to the two "public" checkboxes.
modify_description_permissions(@description)
# If substantive changes are made by a reviewer, call this act a
# "review", even though they haven't actually changed the review
# status. If it's a non-reviewer, this will revert it to "unreviewed".
if @description.save_version?
@description.update_review_status(@description.review_status)
end
# No changes made.
if !@description.changed?
flash_warning(:runtime_edit_name_description_no_change.t)
redirect_to(action: "show_name_description", id: @description.id)
# There were error(s).
elsif !@description.save
flash_object_errors(@description)
# Updated successfully.
else
flash_notice(:runtime_edit_name_description_success.t(
id: @description.id))
# Update name's classification cache.
name = @description.name
if (name.description == @description) &&
(name.classification != @description.classification)
name.classification = @description.classification
name.save
end
# Log action to parent name.
name.log(:log_description_updated, touch: true, user: @user.login,
name: @description.unique_partial_format_name)
# Delete old description after resolving conflicts of merge.
if (params[:delete_after] == "true") &&
(old_desc = NameDescription.safe_find(params[:old_desc_id]))
v = @description.versions.latest
v.merge_source_id = old_desc.versions.latest.id
v.save
if !old_desc.is_admin?(@user)
flash_warning(:runtime_description_merge_delete_denied.t)
else
flash_notice(:runtime_description_merge_deleted.
t(old: old_desc.partial_format_name))
name.log(:log_object_merged_by_user,
user: @user.login, touch: true,
from: old_desc.unique_partial_format_name,
to: @description.unique_partial_format_name)
old_desc.destroy
end
end
redirect_to(action: "show_name_description",
id: @description.id)
end
end
end
def destroy_name_description # :norobots:
pass_query_params
@description = NameDescription.find(params[:id].to_s)
if @description.is_admin?(@user)
flash_notice(:runtime_destroy_description_success.t)
@description.name.log(:log_description_destroyed,
user: @user.login, touch: true,
name: @description.unique_partial_format_name)
@description.destroy
redirect_with_query(action: "show_name", id: @description.name_id)
else
flash_error(:runtime_destroy_description_not_admin.t)
if @description.is_reader?(@user)
redirect_with_query(action: "show_name_description",
id: @description.id)
else
redirect_with_query(action: "show_name", id: @description.name_id)
end
end
end
private
# TODO: should public, public_write and source_type be removed from this list?
# They should be individually checked and set, since we
# don't want them to have arbitrary values
def whitelisted_name_description_params
params.required(:description).
permit(:classification, :gen_desc, :diag_desc, :distribution, :habitat,
:look_alikes, :uses, :refs, :notes, :source_name, :project_id,
:source_type, :public, :public_write)
end
public
################################################################################
#
# :section: Synonymy
#
################################################################################
# Form accessible from show_name that lets a user review all the synonyms
# of a name, removing others, writing in new, etc.
def change_synonyms # :prefetch: :norobots:
pass_query_params
if @name = find_or_goto_index(Name, params[:id].to_s)
@list_members = nil
@new_names = nil
@synonym_name_ids = []
@synonym_names = []
@deprecate_all = true
if request.method == "POST"
list = params[:synonym][:members].strip_squeeze
@deprecate_all = (params[:deprecate][:all] == "1")
# Create any new names that have been approved.
construct_approved_names(list, params[:approved_names], @deprecate_all)
# Parse the write-in list of names.
sorter = NameSorter.new
sorter.sort_names(list)
sorter.append_approved_synonyms(params[:approved_synonyms])
# Are any names unrecognized (only unapproved names will still be
# unrecognized at this point) or ambiguous?
if !sorter.only_single_names
dump_sorter(sorter)
# Has the user NOT had a chance to choose from among the synonyms of any
# names they've written in?
elsif !sorter.only_approved_synonyms
flash_notice :name_change_synonyms_confirm.t
else
now = Time.now
# Create synonym and add this name to it if this name not already
# associated with a synonym.
unless @name.synonym_id
@name.synonym = Synonym.create
@name.save
end
# Go through list of all synonyms for this name and written-in names.
# Exclude any names that have un-checked check-boxes: newly written-in
# names will not have a check-box yet, names written-in in previous
# attempt to submit this form will have checkboxes and therefore must
# be checked to proceed -- the default initial state.
proposed_synonyms = params[:proposed_synonyms] || {}
for n in sorter.all_synonyms
# Synonymize all names that have been checked, or that don't have
# checkboxes.
if proposed_synonyms[n.id.to_s] != "0"
@name.transfer_synonym(n) if n.synonym_id != @name.synonym_id
end
end
# De-synonymize any old synonyms in the "existing synonyms" list that
# have been unchecked. This creates a new synonym to connect them if
# there are multiple unchecked names -- that is, it splits this
# synonym into two synonyms, with checked names staying in this one,
# and unchecked names moving to the new one.
check_for_new_synonym(@name, @name.synonyms, params[:existing_synonyms] || {})
# Deprecate everything if that check-box has been marked.
success = true
if @deprecate_all
for n in sorter.all_names
unless deprecate_synonym(n)
# Already flashed error message.
success = false
end
end
end
if success
redirect_with_query(action: "show_name", id: @name.id)
else
flash_object_errors(@name)
flash_object_errors(@name.synonym)
end
end
@list_members = sorter.all_line_strs.join("\r\n")
@new_names = sorter.new_name_strs.uniq
@synonym_name_ids = sorter.all_synonyms.map(&:id)
@synonym_names = @synonym_name_ids.map { |id| Name.safe_find(id) }.reject(&:nil?)
end
end
end
# Form accessible from show_name that lets the user deprecate a name in favor
# of another name.
def deprecate_name # :prefetch: :norobots:
pass_query_params
# These parameters aren't always provided.
params[:proposed] ||= {}
params[:comment] ||= {}
params[:chosen_name] ||= {}
params[:is] ||= {}
if @name = find_or_goto_index(Name, params[:id].to_s)
@what = begin
params[:proposed][:name].to_s.strip_squeeze
rescue
""
end
@comment = begin
params[:comment][:comment].to_s.strip_squeeze
rescue
""
end
@list_members = nil
@new_names = []
@synonym_name_ids = []
@synonym_names = []
@deprecate_all = "1"
@names = []
@misspelling = (params[:is][:misspelling] == "1")
if request.method == "POST"
if @what.blank?
flash_error :runtime_name_deprecate_must_choose.t
else
# Find the chosen preferred name.
if params[:chosen_name][:name_id] &&
name = Name.safe_find(params[:chosen_name][:name_id])
@names = [name]
else
@names = Name.find_names_filling_in_authors(@what)
end
approved_name = params[:approved_name].to_s.strip_squeeze
if @names.empty? &&
(new_name = Name.create_needed_names(approved_name, @what))
@names = [new_name]
end
target_name = @names.first
# No matches: try to guess.
if @names.empty?
@valid_names = Name.suggest_alternate_spellings(@what)
@suggest_corrections = true
# If written-in name matches uniquely an existing name:
elsif target_name && @names.length == 1
now = Time.now
# Merge this name's synonyms with the preferred name's synonyms.
@name.merge_synonyms(target_name)
# Change target name to "undeprecated".
target_name.change_deprecated(false)
target_name.save_with_log(:log_name_approved, other: @name.real_search_name)
# Change this name to "deprecated", set correct spelling, add note.
@name.change_deprecated(true)
if @misspelling
@name.misspelling = true
@name.correct_spelling = target_name
end
@name.save_with_log(:log_name_deprecated, other: target_name.real_search_name)
post_comment(:deprecate, @name, @comment) unless @comment.blank?
redirect_with_query(action: "show_name", id: @name.id)
end
end # @what
end # "POST"
end
end
# Form accessible from show_name that lets a user make call this an accepted
# name, possibly deprecating its synonyms at the same time.
def approve_name # :prefetch: :norobots:
pass_query_params
if @name = find_or_goto_index(Name, params[:id].to_s)
@approved_names = @name.approved_synonyms
comment = begin
params[:comment][:comment]
rescue
""
end
comment = comment.strip_squeeze
if request.method == "POST"
# Deprecate others first.
others = []
if params[:deprecate][:others] == "1"
for n in @name.approved_synonyms
n.change_deprecated(true)
n.save_with_log(:log_name_deprecated, other: @name.real_search_name)
others << n.real_search_name
end
end
# Approve this now.
@name.change_deprecated(false)
tag = :log_approved_by
args = {}
if others != []
tag = :log_name_approved
args[:other] = others.join(", ")
end
@name.save_with_log(tag, args)
post_comment(:approve, @name, comment) unless comment.blank?
redirect_with_query(action: "show_name", id: @name.id)
end
end
end
# Helper used by change_synonyms. Deprecates a single name. Returns true
# if it worked. Flashes an error and returns false if it fails for whatever
# reason.
def deprecate_synonym(name)
result = true
unless name.deprecated
begin
name.change_deprecated(true)
result = name.save_with_log(:log_deprecated_by)
rescue RuntimeError => err
flash_error(err.to_s) unless err.blank?
result = false
end
end
result
end
# If changing the synonyms of a name that already has synonyms, the user is
# presented with a list of "existing synonyms". This is a list of check-
# boxes. They all start out checked. If the user unchecks one, then that
# name is removed from this synonym. If the user unchecks several, then a
# new synonym is created to synonymize all those names.
def check_for_new_synonym(name, candidates, checks)
new_synonym_members = []
# Gather all names with un-checked checkboxes.
for n in candidates
new_synonym_members.push(n) if (name != n) && (checks[n.id.to_s] == "0")
end
len = new_synonym_members.length
if len > 1
name = new_synonym_members.shift
name.synonym = new_synonym = Synonym.create
name.save
for n in new_synonym_members
name.transfer_synonym(n)
end
elsif len == 1
name = new_synonym_members.first
name.clear_synonym
end
end
def dump_sorter(sorter)
logger.warn("tranfer_synonyms: only_single_names or only_approved_synonyms is false")
logger.warn("New names:")
for n in sorter.new_line_strs
logger.warn(n)
end
logger.warn("\nSingle names:")
for n in sorter.single_line_strs
logger.warn(n)
end
logger.warn("\nMultiple names:")
for n in sorter.multiple_line_strs
logger.warn(n)
end
if sorter.chosen_names
logger.warn("\nChosen names:")
for n in sorter.chosen_names
logger.warn(n)
end
end
logger.warn("\nSynonym names:")
for n in sorter.all_synonyms.map(&:id)
logger.warn(n)
end
end
# Post a comment after approval or deprecation if the user entered one.
def post_comment(action, name, message)
summary = :"name_#{action}_comment_summary".l
comment = Comment.create!(
target: name,
summary: summary,
comment: message
)
end
##############################################################################
#
# :section: EOL Feed
#
##############################################################################
# Send stuff to eol.
def eol_old # :nologin: :norobots:
@max_secs = params[:max_secs] ? params[:max_secs].to_i : nil
@timer_start = Time.now
eol_data(NameDescription.review_statuses.values_at(:unvetted, :vetted))
render_xml(action: "eol", layout: false)
end
# Show the data getting sent to EOL
def eol_preview # :nologin: :norobots:
@timer_start = Time.now
eol_data(NameDescription.review_statuses.values_at(:unvetted, :vetted))
@timer_end = Time.now
end
def eol_description_conditions(review_status_list)
# name descriptions that are exportable.
rsl = review_status_list.join("', '")
"review_status IN ('#{rsl}') AND " \
"gen_desc IS NOT NULL AND " \
"ok_for_export = 1 AND " \
"public = 1"
end
# Show the data not getting sent to EOL
def eol_need_review # :norobots:
eol_data(NameDescription.review_statuses.values_at(unreviewed))
@title = :eol_need_review_title.t
render(action: "eol_preview")
end
# Gather data for EOL feed.
def eol_data(review_status_list)
@names = []
@descs = {} # name.id -> [NameDescription, NmeDescription, ...]
@image_data = {} # name.id -> [img.id, obs.id, user.id, lic.id, date]
@users = {} # user.id -> user.legal_name
@licenses = {} # license.id -> license.url
@authors = {} # desc.id -> "user.legal_name, user.legal_name, ..."
descs = NameDescription.where(
eol_description_conditions(review_status_list))
# Fill in @descs, @users, @authors, @licenses.
for desc in descs
name_id = desc.name_id.to_i
@descs[name_id] ||= []
@descs[name_id] << desc
authors = Name.connection.select_values(%(
SELECT user_id FROM name_descriptions_authors
WHERE name_description_id = #{desc.id}
)).map(&:to_i)
authors = [desc.user_id] if authors.empty?
for author in authors
@users[author.to_i] ||= User.find(author).legal_name
end
@authors[desc.id] = authors.map { |id| @users[id.to_i] }.join(", ")
@licenses[desc.license_id] ||= desc.license.url if desc.license_id
end
# Get corresponding names.
name_ids = @descs.keys.map(&:to_s).join(",")
@names = Name.where(id: name_ids).order(:sort_name, :author).to_a
# Get corresponding images.
image_data = Name.connection.select_all %(
SELECT name_id, image_id, observation_id, images.user_id,
images.license_id, images.created_at
FROM observations, images_observations, images
WHERE observations.name_id IN (#{name_ids})
AND observations.vote_cache >= 2.4
AND observations.id = images_observations.observation_id
AND images_observations.image_id = images.id
AND images.vote_cache >= 2
AND images.ok_for_export
ORDER BY observations.vote_cache
)
image_data = image_data.to_a
# Fill in @image_data, @users, and @licenses.
for row in image_data
name_id = row["name_id"].to_i
user_id = row["user_id"].to_i
license_id = row["license_id"].to_i
image_datum = row.values_at("image_id", "observation_id", "user_id",
"license_id", "created_at")
@image_data[name_id] ||= []
@image_data[name_id].push(image_datum)
@users[user_id] ||= User.find(user_id).legal_name
@licenses[license_id] ||= License.find(license_id).url
end
end
def eol_expanded_review
@timer_start = Time.now
@data = EolData.new
end
# TODO: Add ability to preview synonyms?
# TODO: List stuff that's almost ready.
# TODO: Add EOL logo on pages getting exported
# show_name and show_descriptions for description info
# show_name, show_observation and show_image for images
# EOL preview from Name page
# Improve the Name page
# Review unapproved descriptions
# Send stuff to eol.
def eol # :nologin: :norobots:
@max_secs = params[:max_secs] ? params[:max_secs].to_i : nil
@timer_start = Time.now
@data = EolData.new
render_xml(layout: false)
end
def refresh_links_to_eol
data = get_eol_collection_data
clear_eol_data
load_eol_data(data)
end
def eol_for_taxon
store_location
# need name_id and review_status_list
id = params[:id].to_s
@name = Name.find(id)
@layout = calc_layout_params
# Get corresponding images.
ids = Name.connection.select_values(%(
SELECT images.id
FROM observations, images_observations, images
WHERE observations.name_id = #{id}
AND observations.vote_cache >= 2.4
AND observations.id = images_observations.observation_id
AND images_observations.image_id = images.id
AND images.vote_cache >= 2
AND images.ok_for_export
ORDER BY images.vote_cache DESC
))
# @images = Image.find(:all, :conditions => ['images.id IN (?)', ids], :include => :image_votes) # Rails 3
@images = Image.includes(:image_votes).where(images.id => ids).to_a
ids = Name.connection.select_values(%(
SELECT images.id
FROM observations, images_observations, images
WHERE observations.name_id = #{id}
AND observations.vote_cache >= 2.4
AND observations.id = images_observations.observation_id
AND images_observations.image_id = images.id
AND images.vote_cache IS NULL
AND images.ok_for_export
ORDER BY observations.vote_cache
))
# @voteless_images = Image.find(:all, :conditions => ['images.id IN (?)', ids], :include => :image_votes) # Rails 3
@voteless_images = Image.includes(:image_votes).where(images.id => ids)
ids = Name.connection.select_values(%(
SELECT DISTINCT observations.id
FROM observations, images_observations, images
WHERE observations.name_id = #{id}
AND observations.vote_cache IS NULL
AND observations.id = images_observations.observation_id
AND images_observations.image_id = images.id
AND images.ok_for_export
ORDER BY observations.id
))
# @voteless_obs = Observation.find(:all, :conditions => ['id IN (?)', ids]) # Rails 3
@voteless_obs = Observation.where(images.id => ids).to_a
end
################################################################################
#
# :section: Other Stuff
#
################################################################################
# Utility accessible from a number of name pages (e.g. indexes and
# show_name?) that lets you enter a whole list of names, together with
# synonymy, and create them all in one blow.
def bulk_name_edit # :prefetch: :norobots:
@list_members = nil
@new_names = nil
if request.method == "POST"
list = begin
params[:list][:members].strip_squeeze
rescue
""
end
construct_approved_names(list, params[:approved_names])
sorter = NameSorter.new
sorter.sort_names(list)
if sorter.only_single_names
sorter.create_new_synonyms
flash_notice :name_bulk_success.t
redirect_to(controller: "observer", action: "list_rss_logs")
else
if sorter.new_name_strs != []
# This error message is no longer necessary.
flash_error "Unrecognized names given, including: #{sorter.new_name_strs[0].inspect}" if Rails.env == "test"
else
# Same with this one... err, no this is not reported anywhere.
flash_error "Ambiguous names given, including: #{sorter.multiple_line_strs[0].inspect}"
end
@list_members = sorter.all_line_strs.join("\r\n")
@new_names = sorter.new_name_strs.uniq.sort
end
end
end
# Draw a map of all the locations where this name has been observed.
def map # :nologin: :norobots:
pass_query_params
if @name = find_or_goto_index(Name, params[:id].to_s)
@query = create_query(:Observation, :of_name, name: @name)
@observations = @query.results.select { |o| o.lat || o.location }
end
end
# Form accessible from show_name that lets a user setup tracker notifications
# for a name.
def email_tracking # :norobots:
pass_query_params
name_id = params[:id].to_s
if @name = find_or_goto_index(Name, name_id)
flavor = Notification.flavors[:name]
@notification = Notification.find_by_flavor_and_obj_id_and_user_id(flavor, name_id, @user.id)
# Initialize form.
if request.method != "POST"
unless @name.at_or_below_genus?
flash_warning(:email_tracking_enabled_only_for.t(name: @name.display_name, rank: @name.rank))
end
if @notification
@note_template = @notification.note_template
else
mailing_address = @user.mailing_address.strip if @user.mailing_address
mailing_address = ":mailing_address" if mailing_address.blank?
@note_template = :email_tracking_note_template.l(
species_name: @name.real_text_name,
mailing_address: mailing_address,
users_name: @user.legal_name
)
end
# Submit form.
else
case params[:commit]
when :ENABLE.l, :UPDATE.l
note_template = params[:notification][:note_template]
note_template = nil if note_template.blank?
if @notification.nil?
@notification = Notification.new(flavor: :name, user: @user,
obj_id: name_id, note_template: note_template)
flash_notice(:email_tracking_now_tracking.t(name: @name.display_name))
else
@notification.note_template = note_template
flash_notice(:email_tracking_updated_messages.t)
end
@notification.save
when :DISABLE.l
@notification.destroy
flash_notice(:email_tracking_no_longer_tracking.t(name: @name.display_name))
end
redirect_with_query(action: "show_name", id: name_id)
end
end
end
################################################################################
#
# :section: Stuff for Mushroom App
#
################################################################################
def names_for_mushroom_app # :nologin: :norobots:
number_of_names = params[:number_of_names].blank? ? 1000 : params[:number_of_names]
minimum_confidence = params[:minimum_confidence].blank? ? 1.5 : params[:minimum_confidence]
minimum_observations = params[:minimum_observations].blank? ? 5 : params[:minimum_observations]
rank_condition = params[:include_higher_taxa].blank? ?
"= #{Name.ranks[:Species]}" :
"NOT IN (#{Name.ranks.values_at(:Subspecies, :Variety, :Form, :Group).join(",")})"
data = Name.connection.select_rows(%(
SELECT y.name, y.rank, SUM(y.number)
FROM (
SELECT n.text_name AS name,
n.rank AS rank,
x.number AS number
FROM (
SELECT n.id AS name_id,
n.synonym_id AS synonym_id,
COUNT(o.id) AS number
FROM names n, observations o
WHERE o.name_id = n.id
AND o.vote_cache >= #{minimum_confidence}
GROUP BY IF(n.synonym_id IS NULL, n.id, -n.synonym_id)
) AS x
LEFT OUTER JOIN names n ON IF(x.synonym_id IS NULL, n.id = x.name_id, n.synonym_id = x.synonym_id)
WHERE n.deprecated = FALSE
AND x.number >= #{minimum_observations}
AND n.rank #{rank_condition}
GROUP BY IF(n.synonym_id IS NULL, n.id, -n.synonym_id)
) AS y
GROUP BY y.name
ORDER BY SUM(y.number) DESC
LIMIT #{number_of_names}
))
genera = data.map do |name, _rank, _number|
name.split(" ").first
end.uniq
families = {}
for genus, classification in Name.connection.select_rows(%(
SELECT text_name, classification FROM names
WHERE rank = #{Name.ranks[:Genus]}
AND COALESCE(classification,'') != ''
AND text_name IN ('#{genera.join("','")}')
))
for rank, name in Name.parse_classification(classification).reverse
if rank == :Family
families[genus] = name
break
end
end
end
report = CSV.generate(col_sep: "\t") do |csv|
csv << %w(name rank number_observations family)
data.each do |name, rank, number|
genus = name.split(" ").first
family = families[genus] || ""
csv << [name, rank, number.round.to_s, family]
end
end
send_data(report,
type: "text/csv",
charset: "UTF-8",
header: "present",
disposition: "attachment",
filename: "#{action_name}.csv"
)
rescue => e
render(text: e.to_s, layout: false, status: 500)
end
end
|
# Copyright (c) 2008 Nathan Wilson
# Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
################################################################################
#
# Views:
# name_index Alphabetical list of all names, used or otherwise.
# observation_index Alphabetical list of names people have seen.
# show_name Show info about name.
# show_past_name Show past versions of name info.
# edit_name Edit name info.
# change_synonyms
# deprecate_name
# approve_name
# bulk_name_edit Create/synonymize/deprecate a list of names.
# map Show distribution map.
#
# Admin Tools:
# cleanup_versions
# do_maintenance
#
# Helpers:
# name_locs(name_id) List of locs where name has been observed.
# find_target_names(...) (used by edit_name)
# deprecate_synonym(name, user) (used by change_synonyms)
# check_for_new_synonym(...) (used by change_synonyms)
# dump_sorter(sorter) Error diagnostics for change_synonyms.
#
################################################################################
class NameController < ApplicationController
before_filter :login_required, :except => [
:auto_complete_for_proposed_name,
:map,
:name_index,
:name_search,
:observation_index,
:show_name,
:show_past_name
]
# Paginate and select name index data in prep for name_index view.
# Input: params['page'], params['letter'], @name_data
# Outputs: @letter, @letters, @name_data, @name_subset, @page, @pages
def name_index_helper
@letter = params[:letter]
@page = params[:page]
# Gather hash of letters that actually have names.
@letters = {}
for d in @name_data
match = d['display_name'].match(/([A-Z])/)
if match
l = d['first_letter'] = match[1]
@letters[l] = true
end
end
# If user's clicked on a letter, remove all names above that letter.
if @letter
@name_data = @name_data.select {|d| d['first_letter'][0] >= @letter[0]}
end
# Paginate the remaining names_.
@pages, @name_subset = paginate_array(@name_data, 100)
end
# List all the names
def name_index
store_location
session[:list_members] = nil
session[:new_names] = nil
session[:checklist_source] = :all_names
@title = "Name Index"
@name_data = Name.connection.select_all %(
SELECT id, display_name
FROM names
ORDER BY text_name asc, author asc
)
name_index_helper
end
# Just list the names that have observations
def observation_index
store_location
session[:list_members] = nil
session[:new_names] = nil
session[:checklist_source] = :all_observations
@title = "Observation Index"
@name_data = Name.connection.select_all %(
SELECT distinct names.id, names.display_name
FROM names, observations
WHERE observations.name_id = names.id
ORDER BY names.text_name asc, author asc
)
name_index_helper
render :action => 'name_index'
end
# Searches name, author, notes, and citation.
# Redirected from: pattern_search (search bar)
# View: name_index
# Inputs:
# session[:pattern]
# session['user']
# Only one match: redirects to show_name.
# Multiple matches: sets @name_data and renders name_index.
def name_search
store_location
@user = session['user']
@layout = calc_layout_params
@pattern = session[:pattern]
@title = "Names matching '#{@pattern}'"
sql_pattern = "%#{@pattern.gsub(/[*']/,"%")}%"
conditions = field_search(["search_name", "notes", "citation"], sql_pattern)
session[:checklist_source] = :nothing
@name_data = Name.connection.select_all %(
SELECT distinct id, display_name
FROM names
WHERE #{conditions}
ORDER BY text_name asc, author asc
)
len = @name_data.length
if len == 1
redirect_to :action => 'show_name', :id => @name_data[0]['id']
else
if len == 0
flash_warning "No names matching '#{@pattern}' found."
end
name_index_helper
render :action => 'name_index'
end
end
# AJAX request used for autocompletion of "what" field in deprecate_name.
# View: none
# Inputs: params[:proposed][:name]
# Outputs: none
def auto_complete_for_proposed_name
auto_complete_name(:proposed, :name)
end
# show_name.rhtml
def show_name
# Rough testing showed implementation without synonyms takes .23-.39 secs.
# elapsed_time = Benchmark.realtime do
store_location
@name = Name.find(params[:id])
@past_name = PastName.find(:all, :conditions => "name_id = %s and version = %s" % [@name.id, @name.version - 1]).first
@children = @name.children
# Matches on consensus name, any vote.
consensus_query = %(
SELECT o.id, o.when, o.thumb_image_id, o.where, o.location_id,
u.name, u.login, o.user_id, n.observation_name, o.vote_cache
FROM observations o, users u, names n
WHERE o.name_id = %s and n.id = o.name_id and u.id = o.user_id
ORDER BY o.vote_cache desc, o.when desc
)
# Matches on consensus name, only non-negative votes.
synonym_query = %(
SELECT o.id, o.when, o.thumb_image_id, o.where, o.location_id,
u.name, u.login, o.user_id, n.observation_name, o.vote_cache
FROM observations o, users u, names n
WHERE o.name_id = %s and n.id = o.name_id and u.id = o.user_id and
(o.vote_cache >= 0 || o.vote_cache is null)
ORDER BY o.vote_cache desc, o.when desc
)
# Matches on non-consensus namings, any vote.
other_query = %(
SELECT o.id, o.when, o.thumb_image_id, o.where, o.location_id,
u.name, u.login, o.user_id, n.observation_name, g.vote_cache
FROM observations o, users u, names n, namings g
WHERE g.name_id = %s and o.id = g.observation_id and
n.id = o.name_id and u.id = o.user_id and
o.name_id != g.name_id
ORDER BY g.vote_cache desc, o.when desc
)
# Get list of observations matching on consensus: these are "reliable".
@consensus_data = Observation.connection.select_all(consensus_query % params[:id])
# Get list of observations matching on other names: "look-alikes".
@other_data = Observation.connection.select_all(other_query % params[:id])
# Get list of observations matching any of its synonyms.
@synonym_data = []
synonym = @name.synonym
if synonym
for n in synonym.names
if n != @name
data = Observation.connection.select_all(synonym_query % n.id)
@synonym_data += data
end
end
end
# Remove duplicates. (Select block sets seen[id] to true and returns true
# for the first occurrance of an id, else implicitly returns false.)
seen = {}
@consensus_data = @consensus_data.select {|d|
seen[d["id"]] = true if !seen[d["id"]] }
@synonym_data = @synonym_data.select {|d|
seen[d["id"]] = true if !seen[d["id"]] }
@other_data = @other_data.select {|d|
seen[d["id"]] = true if !seen[d["id"]] }
# Gather full list of IDs for the prev/next buttons to cycle through.
observation_ids = []
@user = session['user']
for d in @consensus_data + @synonym_data + @other_data
observation_ids.push(d["id"].to_i)
end
# Paginate the two sections independently.
per_page = 12
@consensus_page = params['consensus_page']
@consensus_page = 1 if !@consensus_page
@synonym_page = params['synonym_page']
@synonym_page = 1 if !@synonym_page
@other_page = params['other_page']
@other_page = 1 if !@other_page
@consensus_pages, @consensus_data =
paginate_array(@consensus_data, per_page, @consensus_page)
@synonym_pages, @synonym_data =
paginate_array(@synonym_data, per_page, @synonym_page)
@other_pages, @other_data =
paginate_array(@other_data, per_page, @other_page)
@consensus_data = [] if !@consensus_data
@synonym_data = [] if !@synonym_data
@other_data = [] if !@other_data
# By default we query the consensus name above, but if the user
# is logged in we need to redo it and calc the preferred name for each.
# Note that there's no reason to do duplicate observations. (Note, only
# need to do this to subset on the page we can actually see.)
if @user = session['user']
for d in @consensus_data + @synonym_data + @other_data
d["observation_name"] = Observation.find(d["id"].to_i).preferred_name(@user).observation_name
end
end
session[:checklist_source] = :observation_ids
session[:observation_ids] = observation_ids
session[:image_ids] = nil
# end
# logger.warn("show_name took %s\n" % elapsed_time)
end
def show_past_name
store_location
@past_name = PastName.find(params[:id])
@other_versions = PastName.find(:all, :conditions => "name_id = %s" % @past_name.name_id, :order => "version desc")
end
# show_name.rhtml -> edit_name.rhtml
# Updates modified and saves changes
def edit_name
@user = session['user']
if verify_user()
@name = Name.find(params[:id])
@can_make_changes = true
if @user.id != 0
for obs in @name.observations
if obs.user.id != @user.id
@can_make_changes = false
break
end
end
end
if request.method == :post
text_name = (params[:name][:text_name] || '').strip
author = (params[:name][:author] || '').strip
begin
notes = params[:name][:notes]
(@name, old_name) = find_target_names(params[:id], text_name, author, notes)
if text_name == ''
text_name = @name.text_name
end
# Don't allow author to be cleared by using any author you can find...
if author == ''
author = @name.author || ''
if author == '' && old_name
author = old_name.author || ''
end
end
old_search_name = @name.search_name
count = 0
current_time = Time.now
@name.modified = current_time
count += 1
alt_ids = @name.change_text_name(text_name, author, params[:name][:rank])
@name.citation = params[:name][:citation]
if notes == '' && old_name # no new notes given and merge happened
notes = @name.notes # @name's notes
if notes.nil? or (notes == '')
notes = old_name.notes # try old_name's notes
end
end
@name.notes = notes
unless PastName.check_for_past_name(@name, @user, "Name updated by #{@user.login}")
unless @name.id
raise "Update_name called on a name that doesn't exist."
end
end
if old_name # merge happened
for o in old_name.observations
o.name = @name
o.modified = current_time
o.save
end
for g in old_name.namings
g.name = @name
g.modified = current_time
g.save
end
if @user.id != 0
old_name.log("#{old_search_name} merged with #{@name.search_name}")
end
old_name.destroy
end
rescue RuntimeError => err
flash_error err.to_s
flash_object_errors(@name)
else
redirect_to :action => 'show_name', :id => @name
end
end
end
end
# change_synonyms.rhtml -> transfer_synonyms -> show_name.rhtml
def change_synonyms
if verify_user()
@user = session['user']
@name = Name.find(params[:id])
@list_members = nil
@new_names = nil
@synonym_name_ids = []
@synonym_names = []
@deprecate_all = "checked"
if request.method == :post
list = params[:synonym][:members].squeeze(" ") # Get rid of extra whitespace while we're at it
deprecate = (params[:deprecate][:all] == "checked")
construct_approved_names(list, params[:approved_names], @user, deprecate)
sorter = NameSorter.new
sorter.sort_names(list)
sorter.append_approved_synonyms(params[:approved_synonyms])
# When does this fail??
if !sorter.only_single_names
dump_sorter(sorter)
elsif !sorter.only_approved_synonyms
flash_notice("Please confirm that this is what you intended.")
else
timestamp = Time.now
synonym = @name.synonym
if synonym.nil?
synonym = Synonym.new
synonym.created = timestamp
@name.synonym = synonym
@name.modified = timestamp # Change timestamp, but not modifier
@name.save # Not creating a PastName since they don't track synonyms
end
proposed_synonyms = params[:proposed_synonyms] || {}
for n in sorter.all_names
if proposed_synonyms[n.id.to_s] != '0'
synonym.transfer(n)
end
end
for name_id in sorter.proposed_synonym_ids
n = Name.find(name_id)
if proposed_synonyms[name_id.to_s] != '0'
synonym.transfer(n)
end
end
check_for_new_synonym(@name, synonym.names, params[:existing_synonyms] || {})
synonym.modified = timestamp
synonym.save
success = true
if deprecate
for n in sorter.all_names
success = false if !deprecate_synonym(n, @user)
end
end
if success
redirect_to :action => 'show_name', :id => @name
else
flash_object_errors(@name)
flash_object_errors(@name.synonym)
end
end
@list_members = sorter.all_line_strs.join("\r\n")
@new_names = sorter.new_name_strs.uniq
@synonym_name_ids = sorter.proposed_synonym_ids.uniq
@synonym_names = @synonym_name_ids.map {|id| Name.find(id)}
@deprecate_all = params[:deprecate][:all]
end
end
end
def deprecate_name
if verify_user()
@user = session['user']
@name = Name.find(params[:id])
@what = (params[:proposed] && params[:proposed][:name] ? params[:proposed][:name] : '').strip
@comment = (params[:comment] && params[:comment][:comment] ? params[:comment][:comment] : '').strip
@list_members = nil
@new_names = []
@synonym_name_ids = []
@synonym_names = []
@deprecate_all = "checked"
@names = []
if request.method == :post
if @what == ''
flash_error "Must choose a preferred name."
else
if params[:chosen_name] && params[:chosen_name][:name_id]
new_names = [Name.find(params[:chosen_name][:name_id])]
else
new_names = Name.find_names(@what)
end
if new_names.length == 0
new_names = [create_needed_names(params[:approved_name], @what, @user)]
end
target_name = new_names.first
if target_name
@names = new_names
if new_names.length == 1
@name.merge_synonyms(target_name)
target_name.change_deprecated(false)
current_time = Time.now
PastName.check_for_past_name(target_name, @user, "Preferred over #{@name.search_name} by #{@user.login}.")
@name.change_deprecated(true)
PastName.check_for_past_name(@name, @user, "Deprecated in favor of #{target_name.search_name} by #{@user.login}.")
comment_join = @comment == "" ? "." : ":\n"
@name.prepend_notes("Deprecated in favor of" +
" #{target_name.search_name} by #{@user.login} on " +
Time.now.to_formatted_s(:db) + comment_join + @comment)
redirect_to :action => 'show_name', :id => @name
end
end
end
end
end
end
def approve_name
if verify_user()
@user = session['user']
@name = Name.find(params[:id])
@approved_names = @name.approved_synonyms
if request.method == :post
if params[:deprecate][:others] == '1'
for n in @name.approved_synonyms
n.change_deprecated(true)
PastName.check_for_past_name(n, @user, "Deprecated in favor of #{@name.search_name} by #{@user.login}")
end
end
# @name.version = @name.version + 1
@name.change_deprecated(false)
PastName.check_for_past_name(@name, @user, "Approved by #{@user.login}")
comment = (params[:comment] && params[:comment][:comment] ?
params[:comment][:comment] : "").strip
comment_join = comment == "" ? "." : ":\n"
@name.prepend_notes("Approved by #{@user.login} on " +
Time.now.to_formatted_s(:db) + comment_join + comment)
redirect_to :action => 'show_name', :id => @name
end
end
end
# name_index/create_species_list -> bulk_name_edit
def bulk_name_edit
if verify_user()
@user = session['user']
@list_members = nil
@new_names = nil
if request.method == :post
list = params[:list][:members].squeeze(" ") # Get rid of extra whitespace while we're at it
construct_approved_names(list, params[:approved_names], @user)
sorter = setup_sorter(params, nil, list)
if sorter.only_single_names
sorter.create_new_synonyms()
flash_notice "All names are now in the database."
redirect_to :controller => 'observer', :action => 'list_rss_logs'
else
if sorter.new_name_strs != []
# This error message is no longer necessary.
# flash_error "Unrecognized names including #{sorter.new_name_strs[0]} given."
else
# Same with this one.
# flash_error "Ambiguous names including #{sorter.multiple_line_strs[0]} given."
end
@list_members = sorter.all_line_strs.join("\r\n")
@new_names = sorter.new_name_strs.uniq.sort
end
end
end
end
def map
name_id = params[:id]
@name = Name.find(name_id)
locs = name_locs(name_id)
@synonym_data = []
synonym = @name.synonym
if synonym
for n in synonym.names
if n != @name
syn_locs = name_locs(n.id)
for l in syn_locs
unless locs.member?(l)
locs.push(l)
end
end
end
end
end
@map = nil
@header = nil
if locs.length > 0
@map = make_map(locs)
@header = "#{GMap.header}\n#{finish_map(@map)}"
end
end
def cleanup_versions
if check_permission(1)
id = params[:id]
name = Name.find(id)
past_names = PastName.find(:all, :conditions => ["name_id = ?", id], :order => "version desc")
v = past_names.length
name.version = v
name.user_id = 1
name.save
v -= 1
for pn in past_names
pn.version = v
pn.save
v -= 1
end
end
redirect_to :action => 'show_name', :id => id
end
def do_maintenance
if check_permission(0)
@data = []
@users = {}
for n in Name.find(:all)
eldest_obs = nil
for o in n.observations
if eldest_obs.nil? or (o.created < eldest_obs.created)
eldest_obs = o
end
end
if eldest_obs
user = eldest_obs.user
if n.user != user
found_user = false
for p in n.past_names
if p.user == user
found_user = true
end
end
unless found_user
if @users[user.login]
@users[user.login] += 1
else
@users[user.login] = 1
end
@data.push({:name => n.display_name, :id => n.id, :login => user.login})
pn = PastName.make_past_name(n)
pn.user = user
pn.save
n.version += 1
n.save
end
end
end
end
else
flash_error "Maintenance operations can only be done by the admin user."
redirect_to :controller => "observer", :action => "list_rss_logs"
end
end
################################################################################
# Finds the intended name and if another name matching name exists,
# then ensure it is mergable. Returns [target_name, other_name]
def find_target_names(id_str, text_name, author, notes)
id = id_str.to_i
page_name = Name.find(id)
other_name = nil
matches = []
if author != ''
matches = Name.find(:all, :conditions => "text_name = '%s' and author = '%s'" % [text_name, author])
else
matches = Name.find(:all, :conditions => "text_name = '%s'" % text_name)
end
for m in matches
if m.id != id
other_name = m # Just take the first one
break
end
end
result = [page_name, other_name] # Default
if other_name # Is there a reason to prefer other_name?
if other_name.has_notes?
# If other_name's notes are going to get overwritten throw an error
if notes && (notes != '') && (other_name.notes != notes)
raise "The name, %s, is already in use and %s has notes" % [text_name, other_name.search_name]
end
result = [other_name, page_name]
elsif !page_name.has_notes?
# Neither has notes, so we need another criterion
if page_name.deprecated and !other_name.deprecated # Prefer valid names
result = [other_name, page_name]
elsif (other_name.deprecated == page_name.deprecated) and (other_name.version >= page_name.version)
result = [other_name, page_name]
end
end
end
result
end
def deprecate_synonym(name, user)
unless name.deprecated
begin
count = 0
name.change_deprecated(true)
PastName.check_for_past_name(name, user, "Name deprecated by #{user.login}.")
rescue RuntimeError => err
flash_error err.to_s
return false
end
end
return true
end
def dump_sorter(sorter)
logger.warn("tranfer_synonyms: only_single_names or only_approved_synonyms is false")
logger.warn("New names:")
for n in sorter.new_line_strs
logger.warn(n)
end
logger.warn("\nSingle names:")
for n in sorter.single_line_strs
logger.warn(n)
end
logger.warn("\nMultiple names:")
for n in sorter.multiple_line_strs
logger.warn(n)
end
if sorter.chosen_names
logger.warn("\nChosen names:")
for n in sorter.chosen_names
logger.warn(n)
end
end
logger.warn("\nSynonym name ids:")
for n in sorter.proposed_synonym_ids.uniq
logger.warn(n)
end
end
# Look through the candidates for names that are not marked in checks.
# If there are more than 1, then create a new synonym containing those taxa.
# If there is only one then remove it from any synonym it belongs to
def check_for_new_synonym(name, candidates, checks)
new_synonym_members = []
for n in candidates
if (name != n) && (checks[n.id.to_s] == "0")
new_synonym_members.push(n)
end
end
len = new_synonym_members.length
if len > 1
new_synonym = Synonym.new
new_synonym.created = Time.now
new_synonym.save
for n in new_synonym_members
new_synonym.transfer(n)
end
elsif len == 1
new_synonym_members[0].clear_synonym
end
end
def name_locs(name_id)
Location.find(:all, {
:include => :observations,
:conditions => ["observations.name_id = ? and
observations.is_collection_location = true and
observations.vote_cache >= 0", name_id]
})
end
end
Fixed mapping so that observations with no votes show up.
# Copyright (c) 2008 Nathan Wilson
# Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
################################################################################
#
# Views:
# name_index Alphabetical list of all names, used or otherwise.
# observation_index Alphabetical list of names people have seen.
# show_name Show info about name.
# show_past_name Show past versions of name info.
# edit_name Edit name info.
# change_synonyms
# deprecate_name
# approve_name
# bulk_name_edit Create/synonymize/deprecate a list of names.
# map Show distribution map.
#
# Admin Tools:
# cleanup_versions
# do_maintenance
#
# Helpers:
# name_locs(name_id) List of locs where name has been observed.
# find_target_names(...) (used by edit_name)
# deprecate_synonym(name, user) (used by change_synonyms)
# check_for_new_synonym(...) (used by change_synonyms)
# dump_sorter(sorter) Error diagnostics for change_synonyms.
#
################################################################################
class NameController < ApplicationController
before_filter :login_required, :except => [
:auto_complete_for_proposed_name,
:map,
:name_index,
:name_search,
:observation_index,
:show_name,
:show_past_name
]
# Paginate and select name index data in prep for name_index view.
# Input: params['page'], params['letter'], @name_data
# Outputs: @letter, @letters, @name_data, @name_subset, @page, @pages
def name_index_helper
@letter = params[:letter]
@page = params[:page]
# Gather hash of letters that actually have names.
@letters = {}
for d in @name_data
match = d['display_name'].match(/([A-Z])/)
if match
l = d['first_letter'] = match[1]
@letters[l] = true
end
end
# If user's clicked on a letter, remove all names above that letter.
if @letter
@name_data = @name_data.select {|d| d['first_letter'][0] >= @letter[0]}
end
# Paginate the remaining names_.
@pages, @name_subset = paginate_array(@name_data, 100)
end
# List all the names
def name_index
store_location
session[:list_members] = nil
session[:new_names] = nil
session[:checklist_source] = :all_names
@title = "Name Index"
@name_data = Name.connection.select_all %(
SELECT id, display_name
FROM names
ORDER BY text_name asc, author asc
)
name_index_helper
end
# Just list the names that have observations
def observation_index
store_location
session[:list_members] = nil
session[:new_names] = nil
session[:checklist_source] = :all_observations
@title = "Observation Index"
@name_data = Name.connection.select_all %(
SELECT distinct names.id, names.display_name
FROM names, observations
WHERE observations.name_id = names.id
ORDER BY names.text_name asc, author asc
)
name_index_helper
render :action => 'name_index'
end
# Searches name, author, notes, and citation.
# Redirected from: pattern_search (search bar)
# View: name_index
# Inputs:
# session[:pattern]
# session['user']
# Only one match: redirects to show_name.
# Multiple matches: sets @name_data and renders name_index.
def name_search
store_location
@user = session['user']
@layout = calc_layout_params
@pattern = session[:pattern]
@title = "Names matching '#{@pattern}'"
sql_pattern = "%#{@pattern.gsub(/[*']/,"%")}%"
conditions = field_search(["search_name", "notes", "citation"], sql_pattern)
session[:checklist_source] = :nothing
@name_data = Name.connection.select_all %(
SELECT distinct id, display_name
FROM names
WHERE #{conditions}
ORDER BY text_name asc, author asc
)
len = @name_data.length
if len == 1
redirect_to :action => 'show_name', :id => @name_data[0]['id']
else
if len == 0
flash_warning "No names matching '#{@pattern}' found."
end
name_index_helper
render :action => 'name_index'
end
end
# AJAX request used for autocompletion of "what" field in deprecate_name.
# View: none
# Inputs: params[:proposed][:name]
# Outputs: none
def auto_complete_for_proposed_name
auto_complete_name(:proposed, :name)
end
# show_name.rhtml
def show_name
# Rough testing showed implementation without synonyms takes .23-.39 secs.
# elapsed_time = Benchmark.realtime do
store_location
@name = Name.find(params[:id])
@past_name = PastName.find(:all, :conditions => "name_id = %s and version = %s" % [@name.id, @name.version - 1]).first
@children = @name.children
# Matches on consensus name, any vote.
consensus_query = %(
SELECT o.id, o.when, o.thumb_image_id, o.where, o.location_id,
u.name, u.login, o.user_id, n.observation_name, o.vote_cache
FROM observations o, users u, names n
WHERE o.name_id = %s and n.id = o.name_id and u.id = o.user_id
ORDER BY o.vote_cache desc, o.when desc
)
# Matches on consensus name, only non-negative votes.
synonym_query = %(
SELECT o.id, o.when, o.thumb_image_id, o.where, o.location_id,
u.name, u.login, o.user_id, n.observation_name, o.vote_cache
FROM observations o, users u, names n
WHERE o.name_id = %s and n.id = o.name_id and u.id = o.user_id and
(o.vote_cache >= 0 || o.vote_cache is null)
ORDER BY o.vote_cache desc, o.when desc
)
# Matches on non-consensus namings, any vote.
other_query = %(
SELECT o.id, o.when, o.thumb_image_id, o.where, o.location_id,
u.name, u.login, o.user_id, n.observation_name, g.vote_cache
FROM observations o, users u, names n, namings g
WHERE g.name_id = %s and o.id = g.observation_id and
n.id = o.name_id and u.id = o.user_id and
o.name_id != g.name_id
ORDER BY g.vote_cache desc, o.when desc
)
# Get list of observations matching on consensus: these are "reliable".
@consensus_data = Observation.connection.select_all(consensus_query % params[:id])
# Get list of observations matching on other names: "look-alikes".
@other_data = Observation.connection.select_all(other_query % params[:id])
# Get list of observations matching any of its synonyms.
@synonym_data = []
synonym = @name.synonym
if synonym
for n in synonym.names
if n != @name
data = Observation.connection.select_all(synonym_query % n.id)
@synonym_data += data
end
end
end
# Remove duplicates. (Select block sets seen[id] to true and returns true
# for the first occurrance of an id, else implicitly returns false.)
seen = {}
@consensus_data = @consensus_data.select {|d|
seen[d["id"]] = true if !seen[d["id"]] }
@synonym_data = @synonym_data.select {|d|
seen[d["id"]] = true if !seen[d["id"]] }
@other_data = @other_data.select {|d|
seen[d["id"]] = true if !seen[d["id"]] }
# Gather full list of IDs for the prev/next buttons to cycle through.
observation_ids = []
@user = session['user']
for d in @consensus_data + @synonym_data + @other_data
observation_ids.push(d["id"].to_i)
end
# Paginate the two sections independently.
per_page = 12
@consensus_page = params['consensus_page']
@consensus_page = 1 if !@consensus_page
@synonym_page = params['synonym_page']
@synonym_page = 1 if !@synonym_page
@other_page = params['other_page']
@other_page = 1 if !@other_page
@consensus_pages, @consensus_data =
paginate_array(@consensus_data, per_page, @consensus_page)
@synonym_pages, @synonym_data =
paginate_array(@synonym_data, per_page, @synonym_page)
@other_pages, @other_data =
paginate_array(@other_data, per_page, @other_page)
@consensus_data = [] if !@consensus_data
@synonym_data = [] if !@synonym_data
@other_data = [] if !@other_data
# By default we query the consensus name above, but if the user
# is logged in we need to redo it and calc the preferred name for each.
# Note that there's no reason to do duplicate observations. (Note, only
# need to do this to subset on the page we can actually see.)
if @user = session['user']
for d in @consensus_data + @synonym_data + @other_data
d["observation_name"] = Observation.find(d["id"].to_i).preferred_name(@user).observation_name
end
end
session[:checklist_source] = :observation_ids
session[:observation_ids] = observation_ids
session[:image_ids] = nil
# end
# logger.warn("show_name took %s\n" % elapsed_time)
end
def show_past_name
store_location
@past_name = PastName.find(params[:id])
@other_versions = PastName.find(:all, :conditions => "name_id = %s" % @past_name.name_id, :order => "version desc")
end
# show_name.rhtml -> edit_name.rhtml
# Updates modified and saves changes
def edit_name
@user = session['user']
if verify_user()
@name = Name.find(params[:id])
@can_make_changes = true
if @user.id != 0
for obs in @name.observations
if obs.user.id != @user.id
@can_make_changes = false
break
end
end
end
if request.method == :post
text_name = (params[:name][:text_name] || '').strip
author = (params[:name][:author] || '').strip
begin
notes = params[:name][:notes]
(@name, old_name) = find_target_names(params[:id], text_name, author, notes)
if text_name == ''
text_name = @name.text_name
end
# Don't allow author to be cleared by using any author you can find...
if author == ''
author = @name.author || ''
if author == '' && old_name
author = old_name.author || ''
end
end
old_search_name = @name.search_name
count = 0
current_time = Time.now
@name.modified = current_time
count += 1
alt_ids = @name.change_text_name(text_name, author, params[:name][:rank])
@name.citation = params[:name][:citation]
if notes == '' && old_name # no new notes given and merge happened
notes = @name.notes # @name's notes
if notes.nil? or (notes == '')
notes = old_name.notes # try old_name's notes
end
end
@name.notes = notes
unless PastName.check_for_past_name(@name, @user, "Name updated by #{@user.login}")
unless @name.id
raise "Update_name called on a name that doesn't exist."
end
end
if old_name # merge happened
for o in old_name.observations
o.name = @name
o.modified = current_time
o.save
end
for g in old_name.namings
g.name = @name
g.modified = current_time
g.save
end
if @user.id != 0
old_name.log("#{old_search_name} merged with #{@name.search_name}")
end
old_name.destroy
end
rescue RuntimeError => err
flash_error err.to_s
flash_object_errors(@name)
else
redirect_to :action => 'show_name', :id => @name
end
end
end
end
# change_synonyms.rhtml -> transfer_synonyms -> show_name.rhtml
def change_synonyms
if verify_user()
@user = session['user']
@name = Name.find(params[:id])
@list_members = nil
@new_names = nil
@synonym_name_ids = []
@synonym_names = []
@deprecate_all = "checked"
if request.method == :post
list = params[:synonym][:members].squeeze(" ") # Get rid of extra whitespace while we're at it
deprecate = (params[:deprecate][:all] == "checked")
construct_approved_names(list, params[:approved_names], @user, deprecate)
sorter = NameSorter.new
sorter.sort_names(list)
sorter.append_approved_synonyms(params[:approved_synonyms])
# When does this fail??
if !sorter.only_single_names
dump_sorter(sorter)
elsif !sorter.only_approved_synonyms
flash_notice("Please confirm that this is what you intended.")
else
timestamp = Time.now
synonym = @name.synonym
if synonym.nil?
synonym = Synonym.new
synonym.created = timestamp
@name.synonym = synonym
@name.modified = timestamp # Change timestamp, but not modifier
@name.save # Not creating a PastName since they don't track synonyms
end
proposed_synonyms = params[:proposed_synonyms] || {}
for n in sorter.all_names
if proposed_synonyms[n.id.to_s] != '0'
synonym.transfer(n)
end
end
for name_id in sorter.proposed_synonym_ids
n = Name.find(name_id)
if proposed_synonyms[name_id.to_s] != '0'
synonym.transfer(n)
end
end
check_for_new_synonym(@name, synonym.names, params[:existing_synonyms] || {})
synonym.modified = timestamp
synonym.save
success = true
if deprecate
for n in sorter.all_names
success = false if !deprecate_synonym(n, @user)
end
end
if success
redirect_to :action => 'show_name', :id => @name
else
flash_object_errors(@name)
flash_object_errors(@name.synonym)
end
end
@list_members = sorter.all_line_strs.join("\r\n")
@new_names = sorter.new_name_strs.uniq
@synonym_name_ids = sorter.proposed_synonym_ids.uniq
@synonym_names = @synonym_name_ids.map {|id| Name.find(id)}
@deprecate_all = params[:deprecate][:all]
end
end
end
def deprecate_name
if verify_user()
@user = session['user']
@name = Name.find(params[:id])
@what = (params[:proposed] && params[:proposed][:name] ? params[:proposed][:name] : '').strip
@comment = (params[:comment] && params[:comment][:comment] ? params[:comment][:comment] : '').strip
@list_members = nil
@new_names = []
@synonym_name_ids = []
@synonym_names = []
@deprecate_all = "checked"
@names = []
if request.method == :post
if @what == ''
flash_error "Must choose a preferred name."
else
if params[:chosen_name] && params[:chosen_name][:name_id]
new_names = [Name.find(params[:chosen_name][:name_id])]
else
new_names = Name.find_names(@what)
end
if new_names.length == 0
new_names = [create_needed_names(params[:approved_name], @what, @user)]
end
target_name = new_names.first
if target_name
@names = new_names
if new_names.length == 1
@name.merge_synonyms(target_name)
target_name.change_deprecated(false)
current_time = Time.now
PastName.check_for_past_name(target_name, @user, "Preferred over #{@name.search_name} by #{@user.login}.")
@name.change_deprecated(true)
PastName.check_for_past_name(@name, @user, "Deprecated in favor of #{target_name.search_name} by #{@user.login}.")
comment_join = @comment == "" ? "." : ":\n"
@name.prepend_notes("Deprecated in favor of" +
" #{target_name.search_name} by #{@user.login} on " +
Time.now.to_formatted_s(:db) + comment_join + @comment)
redirect_to :action => 'show_name', :id => @name
end
end
end
end
end
end
def approve_name
if verify_user()
@user = session['user']
@name = Name.find(params[:id])
@approved_names = @name.approved_synonyms
if request.method == :post
if params[:deprecate][:others] == '1'
for n in @name.approved_synonyms
n.change_deprecated(true)
PastName.check_for_past_name(n, @user, "Deprecated in favor of #{@name.search_name} by #{@user.login}")
end
end
# @name.version = @name.version + 1
@name.change_deprecated(false)
PastName.check_for_past_name(@name, @user, "Approved by #{@user.login}")
comment = (params[:comment] && params[:comment][:comment] ?
params[:comment][:comment] : "").strip
comment_join = comment == "" ? "." : ":\n"
@name.prepend_notes("Approved by #{@user.login} on " +
Time.now.to_formatted_s(:db) + comment_join + comment)
redirect_to :action => 'show_name', :id => @name
end
end
end
# name_index/create_species_list -> bulk_name_edit
def bulk_name_edit
if verify_user()
@user = session['user']
@list_members = nil
@new_names = nil
if request.method == :post
list = params[:list][:members].squeeze(" ") # Get rid of extra whitespace while we're at it
construct_approved_names(list, params[:approved_names], @user)
sorter = setup_sorter(params, nil, list)
if sorter.only_single_names
sorter.create_new_synonyms()
flash_notice "All names are now in the database."
redirect_to :controller => 'observer', :action => 'list_rss_logs'
else
if sorter.new_name_strs != []
# This error message is no longer necessary.
# flash_error "Unrecognized names including #{sorter.new_name_strs[0]} given."
else
# Same with this one.
# flash_error "Ambiguous names including #{sorter.multiple_line_strs[0]} given."
end
@list_members = sorter.all_line_strs.join("\r\n")
@new_names = sorter.new_name_strs.uniq.sort
end
end
end
end
def map
name_id = params[:id]
@name = Name.find(name_id)
locs = name_locs(name_id)
print "NameController.map:locs.length: #{locs.length}\n"
@synonym_data = []
synonym = @name.synonym
if synonym
print "NameController.map:locs.length: have synonym\n"
for n in synonym.names
if n != @name
syn_locs = name_locs(n.id)
print "NameController.map:syn_locs.length: #{syn_locs.length}\n"
for l in syn_locs
unless locs.member?(l)
locs.push(l)
end
end
end
end
end
print "NameController.map:locs.length 2: #{locs.length}\n"
@map = nil
@header = nil
if locs.length > 0
@map = make_map(locs)
@header = "#{GMap.header}\n#{finish_map(@map)}"
end
end
def cleanup_versions
if check_permission(1)
id = params[:id]
name = Name.find(id)
past_names = PastName.find(:all, :conditions => ["name_id = ?", id], :order => "version desc")
v = past_names.length
name.version = v
name.user_id = 1
name.save
v -= 1
for pn in past_names
pn.version = v
pn.save
v -= 1
end
end
redirect_to :action => 'show_name', :id => id
end
def do_maintenance
if check_permission(0)
@data = []
@users = {}
for n in Name.find(:all)
eldest_obs = nil
for o in n.observations
if eldest_obs.nil? or (o.created < eldest_obs.created)
eldest_obs = o
end
end
if eldest_obs
user = eldest_obs.user
if n.user != user
found_user = false
for p in n.past_names
if p.user == user
found_user = true
end
end
unless found_user
if @users[user.login]
@users[user.login] += 1
else
@users[user.login] = 1
end
@data.push({:name => n.display_name, :id => n.id, :login => user.login})
pn = PastName.make_past_name(n)
pn.user = user
pn.save
n.version += 1
n.save
end
end
end
end
else
flash_error "Maintenance operations can only be done by the admin user."
redirect_to :controller => "observer", :action => "list_rss_logs"
end
end
################################################################################
# Finds the intended name and if another name matching name exists,
# then ensure it is mergable. Returns [target_name, other_name]
def find_target_names(id_str, text_name, author, notes)
id = id_str.to_i
page_name = Name.find(id)
other_name = nil
matches = []
if author != ''
matches = Name.find(:all, :conditions => "text_name = '%s' and author = '%s'" % [text_name, author])
else
matches = Name.find(:all, :conditions => "text_name = '%s'" % text_name)
end
for m in matches
if m.id != id
other_name = m # Just take the first one
break
end
end
result = [page_name, other_name] # Default
if other_name # Is there a reason to prefer other_name?
if other_name.has_notes?
# If other_name's notes are going to get overwritten throw an error
if notes && (notes != '') && (other_name.notes != notes)
raise "The name, %s, is already in use and %s has notes" % [text_name, other_name.search_name]
end
result = [other_name, page_name]
elsif !page_name.has_notes?
# Neither has notes, so we need another criterion
if page_name.deprecated and !other_name.deprecated # Prefer valid names
result = [other_name, page_name]
elsif (other_name.deprecated == page_name.deprecated) and (other_name.version >= page_name.version)
result = [other_name, page_name]
end
end
end
result
end
def deprecate_synonym(name, user)
unless name.deprecated
begin
count = 0
name.change_deprecated(true)
PastName.check_for_past_name(name, user, "Name deprecated by #{user.login}.")
rescue RuntimeError => err
flash_error err.to_s
return false
end
end
return true
end
def dump_sorter(sorter)
logger.warn("tranfer_synonyms: only_single_names or only_approved_synonyms is false")
logger.warn("New names:")
for n in sorter.new_line_strs
logger.warn(n)
end
logger.warn("\nSingle names:")
for n in sorter.single_line_strs
logger.warn(n)
end
logger.warn("\nMultiple names:")
for n in sorter.multiple_line_strs
logger.warn(n)
end
if sorter.chosen_names
logger.warn("\nChosen names:")
for n in sorter.chosen_names
logger.warn(n)
end
end
logger.warn("\nSynonym name ids:")
for n in sorter.proposed_synonym_ids.uniq
logger.warn(n)
end
end
# Look through the candidates for names that are not marked in checks.
# If there are more than 1, then create a new synonym containing those taxa.
# If there is only one then remove it from any synonym it belongs to
def check_for_new_synonym(name, candidates, checks)
new_synonym_members = []
for n in candidates
if (name != n) && (checks[n.id.to_s] == "0")
new_synonym_members.push(n)
end
end
len = new_synonym_members.length
if len > 1
new_synonym = Synonym.new
new_synonym.created = Time.now
new_synonym.save
for n in new_synonym_members
new_synonym.transfer(n)
end
elsif len == 1
new_synonym_members[0].clear_synonym
end
end
def name_locs(name_id)
Location.find(:all, {
:include => :observations,
:conditions => ["observations.name_id = ? and
observations.is_collection_location = true and
(observations.vote_cache >= 0 or observations.vote_cache is NULL)", name_id]
})
end
end
|
cask 'abyss-web-server' do
version '2.11.8'
sha256 '1df93374340a939c9bdb34e39eef06a317c7c1240d119784f5f75773f3e9da4c'
url 'https://aprelium.com/data/abwsx1.dmg'
appcast 'https://aprelium.com/abyssws/download.php'
name 'Abyss Web Server'
homepage 'https://aprelium.com/abyssws/'
app 'Abyss Web Server/Abyss Web Server.app'
preflight do
set_permissions "#{staged_path}/Abyss Web Server/Abyss Web Server.app", '0755'
end
end
Update abyss-web-server to 2.12 (#57032)
cask 'abyss-web-server' do
version '2.12'
sha256 'f93ae42987bc01817fef41a051e7fcc65ac13560a971f4e6f9e7301c3fcd4c37'
url 'https://aprelium.com/data/abwsx1.dmg'
appcast 'https://aprelium.com/abyssws/download.php'
name 'Abyss Web Server'
homepage 'https://aprelium.com/abyssws/'
app 'Abyss Web Server/Abyss Web Server.app'
preflight do
set_permissions "#{staged_path}/Abyss Web Server/Abyss Web Server.app", '0755'
end
end
|
class PinsController < ApplicationController
def index
@pins = Pin.all
if request.xhr?
respond_to do |format|
format.json { render json: @pins }
end
end
end
def new
@pin = Pin.new
end
def create
@user = User.find(params[:id])
@pin = Pin.new(song_id: params[:song_id], user: @user.id, latitude: params[:lat], longitude: params[:lng], song_id: params[:song_id])
redirect_to "pins/_form"
end
def show
@friend_pins = Pin.where(user_id: params[:user_id])
if request.xhr?
respond_to do |format|
format.json { render json: @friend_pins }
end
end
end
end
Fix controller create method with local variables
class PinsController < ApplicationController
def index
@pins = Pin.all
if request.xhr?
respond_to do |format|
format.json { render json: @pins }
end
end
end
def new
@pin = Pin.new
end
def create
user = User.find(params[:id])
@pin = Pin.new(song_id: params[:song_id], user: user.id, latitude: params[:lat], longitude: params[:lng], song_id: params[:song_id])
redirect_to "pins/_form"
end
def show
@friend_pins = Pin.where(user_id: params[:user_id])
if request.xhr?
respond_to do |format|
format.json { render json: @friend_pins }
end
end
end
end
|
cask "beekeeper-studio" do
version "3.0.9"
sha256 "887831b017e5975763a59b90c4b9e2609c39b9397a7d0156ef8fa243193ac6e2"
url "https://github.com/beekeeper-studio/beekeeper-studio/releases/download/v#{version}/Beekeeper-Studio-#{version}.dmg",
verified: "github.com/beekeeper-studio/beekeeper-studio/"
name "Beekeeper Studio"
desc "Cross platform SQL editor and database management app"
homepage "https://www.beekeeperstudio.io/"
livecheck do
url :url
strategy :github_latest
end
auto_updates true
app "Beekeeper Studio.app"
zap trash: [
"~/Library/Application Support/beekeeper-studio",
"~/Library/Application Support/Caches/beekeeper-studio-updater",
"~/Library/Caches/io.beekeeperstudio.desktop.ShipIt",
"~/Library/Caches/io.beekeeperstudio.desktop",
"~/Library/Preferences/ByHost/io.beekeeperstudio.desktop.ShipIt.*.plist",
"~/Library/Preferences/io.beekeeperstudio.desktop.plist",
"~/Library/Saved Application State/io.beekeeperstudio.desktop.savedState",
]
end
Update beekeeper-studio from 3.0.9 to 3.0.11 (#117454)
cask "beekeeper-studio" do
version "3.0.11"
sha256 "83d6b371c308f8706deacd6a0307ad4fafbf044f233dde570a87289d362d57e8"
url "https://github.com/beekeeper-studio/beekeeper-studio/releases/download/v#{version}/Beekeeper-Studio-#{version}.dmg",
verified: "github.com/beekeeper-studio/beekeeper-studio/"
name "Beekeeper Studio"
desc "Cross platform SQL editor and database management app"
homepage "https://www.beekeeperstudio.io/"
livecheck do
url :url
strategy :github_latest
end
auto_updates true
app "Beekeeper Studio.app"
zap trash: [
"~/Library/Application Support/beekeeper-studio",
"~/Library/Application Support/Caches/beekeeper-studio-updater",
"~/Library/Caches/io.beekeeperstudio.desktop.ShipIt",
"~/Library/Caches/io.beekeeperstudio.desktop",
"~/Library/Preferences/ByHost/io.beekeeperstudio.desktop.ShipIt.*.plist",
"~/Library/Preferences/io.beekeeperstudio.desktop.plist",
"~/Library/Saved Application State/io.beekeeperstudio.desktop.savedState",
]
end
|
require 'elo'
class PongController < ActionController::Base
layout 'application'
def feed
end
def leaderboard
if params[:club] == nil
redirect_to '/clubs'
end
end
def about
end
def clubs
@clubs = Club.all.map do |club|
{
name: club.name,
country: club.country.downcase,
resource_name: club.name.downcase.gsub(/ /, '-'),
player_count: Club.members_in_club(club.id)
}
end
@clubs.sort_by! do |item| item[:player_count] end
@clubs.reverse!
end
def feeddata
if params[:club] == nil
redirect_to '/clubs'
else
render json: Match.all.to_json
end
end
def leaderboarddata
players = {}
if params[:club] == nil
redirect_to '/clubs'
else
formatted_club_name = format_club_name params[:club]
matches = Match.joins(:club).where('lower(clubs.name) = ?', 'pivotal denver').order(created_at: 'desc')
matches.each do |match|
winner = match['winner']
loser = match['loser']
if (!players.has_key? winner)
players[winner] = Elo::Player.new
end
if (!players.has_key? loser)
players[loser] = Elo::Player.new
end
players[winner].wins_from(players[loser])
end
end
sorted_players = players.sort_by { |name, player| player.rating}.reverse!
render json: sorted_players.map { |arr| {name: arr[0], rating: arr[1].rating}}
end
def format_club_name(club_name)
formatted_club_name = club_name.gsub(/[ \.\/]/, '-').gsub(/[-]+/, '-').downcase
formatted_club_name[0...-1] if formatted_club_name[-1, 1] == '-' # Remove last character if -
end
end
Fixes issue #21 - leaderboard and feed relevant to correct club
require 'elo'
class PongController < ActionController::Base
layout 'application'
def feed
end
def leaderboard
if params[:club] == nil
redirect_to '/clubs'
end
end
def about
end
def clubs
@clubs = Club.all.map do |club|
{
name: club.name,
country: club.country.downcase,
resource_name: club.name.downcase.gsub(/ /, '-'),
player_count: Club.members_in_club(club.id)
}
end
@clubs.sort_by! do |item| item[:player_count] end
@clubs.reverse!
end
def feeddata
if params[:club] == nil
redirect_to '/clubs'
else
formatted_club_name = params[:club].gsub(/-/, ' ')
render json: Match.joins(:club).where('lower(clubs.name) = ?', formatted_club_name).to_json
end
end
def leaderboarddata
players = {}
if params[:club] == nil
redirect_to '/clubs'
else
formatted_club_name = params[:club].gsub(/-/, ' ')
matches = Match.joins(:club).where('lower(clubs.name) = ?', formatted_club_name).order(created_at: 'desc')
matches.each do |match|
winner = match['winner']
loser = match['loser']
if (!players.has_key? winner)
players[winner] = Elo::Player.new
end
if (!players.has_key? loser)
players[loser] = Elo::Player.new
end
players[winner].wins_from(players[loser])
end
end
sorted_players = players.sort_by { |name, player| player.rating}.reverse!
render json: sorted_players.map { |arr| {name: arr[0], rating: arr[1].rating}}
end
end
|
cask :v1 => 'cloudfoundry-cli' do
version '6.11.3'
sha256 'a8534a3e4dcc285f127d7d32d62ebcf8dd03ed9003c80bf0c4633d0b72faec07'
# amazonaws.com is the official download host per the vendor homepage
url "http://go-cli.s3-website-us-east-1.amazonaws.com/releases/v#{version}/installer-osx-amd64.pkg"
name 'Cloud Foundry CLI'
homepage 'https://github.com/cloudfoundry/cli'
license :apache
pkg 'installer-osx-amd64.pkg'
uninstall :pkgutil => 'com.pivotal.cloudfoundry.pkg'
caveats do
files_in_usr_local
end
end
Upgrade cloudfoundry-cli to v6.12.1
Should close issue https://github.com/caskroom/homebrew-cask/issues/12504
https://github.com/cloudfoundry/cli/releases
cask :v1 => 'cloudfoundry-cli' do
version '6.12.1'
sha256 '4810c0dc3427db8f1c81c3f658dd5e6265120ae109ea438d1969ba7b96b6db84'
# amazonaws.com is the official download host per the vendor homepage
url "http://go-cli.s3-website-us-east-1.amazonaws.com/releases/v#{version}/installer-osx-amd64.pkg"
name 'Cloud Foundry CLI'
homepage 'https://github.com/cloudfoundry/cli'
license :apache
pkg 'installer-osx-amd64.pkg'
uninstall :pkgutil => 'com.pivotal.cloudfoundry.pkg'
caveats do
files_in_usr_local
end
end
|
#
# This controller is in charge of rendering the root url.
#
class RootController < ApplicationController
helper :groups, :account, :wiki, :page
stylesheet 'wiki_edit'
javascript :wiki, :action => :index
permissions 'root','groups/base'
before_filter :login_required, :except => ['index']
before_filter :fetch_network
def index
if !logged_in?
login_page
elsif current_site.network
site_home
else
redirect_to me_url
end
end
##
## TAB CONTENT, PULLED BY AJAX
##
def featured
update_page_list('featured_panel',
:pages => paginate('featured_by', @group.id, 'descending', 'updated_at'),
:expanded => true
)
end
def most_viewed
update_page_list("most_viewed_panel",
:pages => pages_for_timespan('most_views'),
:columns => [:views, :icon, :title, :last_updated],
:sortable => false,
:heading_partial => 'root/time_links',
:pagination_options => {:params => {:time_span => params[:time_span]}}
)
end
def most_active
update_page_list("most_active_panel",
:pages => pages_for_timespan('most_edits'),
:columns => [:contributors, :icon, :title, :last_updated],
:sortable => false,
:heading_partial => 'root/time_links',
:pagination_options => {:params => {:time_span => params[:time_span]}}
)
end
def most_stars
update_page_list("most_stars_panel",
:pages => pages_for_timespan('most_stars'),
:columns => [:stars, :icon, :title, :last_updated],
:sortable => false,
:heading_partial => 'root/time_links',
:pagination_options => {:params => {:time_span => params[:time_span]}}
)
end
def announcements
update_page_list('announcements_panel',
:pages => paginate('descending','created_at', :flow => :announcement)
)
end
def recent_pages
if params[:type]
page = paginate('descending', 'updated_at', 'type', params[:type])
else
page = paginate('descending', 'updated_at')
end
update_page_list('recent_pages_panel',
:pages => page,
:columns => [:stars, :icon, :title, :last_updated],
:heading_partial => 'root/type_links',
:sortable => false,
:show_time_dividers => true,
:pagination_options => {:params => {:type => params[:type]}}
)
end
protected
def pages_for_timespan(filter_by)
time_span = params[:time_span] || 'all_time'
case time_span
when 'today' then
paginate(filter_by, '24', 'hours')
when 'this_week' then
paginate(filter_by, '7', 'days')
when 'this_month' then
paginate(filter_by, '30', 'days')
when 'all_time' then
case filter_by
when 'most_views' then
paginate('descending','views_count')
when 'most_edits' then
paginate('descending', 'contributors_count', 'contributed') #TODO: contributors count does not seem to get updated
when 'most_stars' then
paginate('descending', 'stars_count', 'starred')
end
end
end
def authorized?
true
end
def site_home
@active_tab = :home
@group.profiles.public.create_wiki unless @group.profiles.public.wiki
@announcements = Page.find_by_path('limit/3/descending/created_at',
options_for_group(@group, :flow => :announcement))
@show_featured = Page.count_by_path(['featured_by', @group.id], options_for_group(@group, :limit => 1)) > 0
render :template => 'root/site_home'
end
def login_page
@stylesheet = 'account'
@active_tab = :home
render :template => 'account/index'
end
def fetch_network
@group = current_site.network if current_site and current_site.network
end
def paginate(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
Page.paginate_by_path(args, options_for_group(@group, {:page => params[:page]}.merge(options)))
end
def update_page_list(target, locals)
render :update do |page|
if locals[:expanded]
page.replace_html target, :partial => 'pages/list_expanded', :locals => locals
else
page.replace_html target, :partial => 'pages/list', :locals => locals
end
end
end
##
## lists of active groups and users. used by the view.
##
helper_method :most_active_groups
def most_active_groups
Group.only_groups.most_visits.find(:all, :limit => 5)
end
helper_method :recently_active_groups
def recently_active_groups
Group.only_groups.recent_visits.find(:all, :limit => 10)
end
helper_method :most_active_users
def most_active_users
User.most_active_on(current_site, nil).not_inactive.find(:all, :limit => 5)
end
helper_method :recently_active_users
def recently_active_users
User.most_active_on(current_site, Time.now - 30.days).not_inactive.find(:all, :limit => 10)
end
end
fixes #1796 - list 15 most active things in site home sidebar feeds
#
# This controller is in charge of rendering the root url.
#
class RootController < ApplicationController
helper :groups, :account, :wiki, :page
stylesheet 'wiki_edit'
javascript :wiki, :action => :index
permissions 'root','groups/base'
before_filter :login_required, :except => ['index']
before_filter :fetch_network
def index
if !logged_in?
login_page
elsif current_site.network
site_home
else
redirect_to me_url
end
end
##
## TAB CONTENT, PULLED BY AJAX
##
def featured
update_page_list('featured_panel',
:pages => paginate('featured_by', @group.id, 'descending', 'updated_at'),
:expanded => true
)
end
def most_viewed
update_page_list("most_viewed_panel",
:pages => pages_for_timespan('most_views'),
:columns => [:views, :icon, :title, :last_updated],
:sortable => false,
:heading_partial => 'root/time_links',
:pagination_options => {:params => {:time_span => params[:time_span]}}
)
end
def most_active
update_page_list("most_active_panel",
:pages => pages_for_timespan('most_edits'),
:columns => [:contributors, :icon, :title, :last_updated],
:sortable => false,
:heading_partial => 'root/time_links',
:pagination_options => {:params => {:time_span => params[:time_span]}}
)
end
def most_stars
update_page_list("most_stars_panel",
:pages => pages_for_timespan('most_stars'),
:columns => [:stars, :icon, :title, :last_updated],
:sortable => false,
:heading_partial => 'root/time_links',
:pagination_options => {:params => {:time_span => params[:time_span]}}
)
end
def announcements
update_page_list('announcements_panel',
:pages => paginate('descending','created_at', :flow => :announcement)
)
end
def recent_pages
if params[:type]
page = paginate('descending', 'updated_at', 'type', params[:type])
else
page = paginate('descending', 'updated_at')
end
update_page_list('recent_pages_panel',
:pages => page,
:columns => [:stars, :icon, :title, :last_updated],
:heading_partial => 'root/type_links',
:sortable => false,
:show_time_dividers => true,
:pagination_options => {:params => {:type => params[:type]}}
)
end
protected
def pages_for_timespan(filter_by)
time_span = params[:time_span] || 'all_time'
case time_span
when 'today' then
paginate(filter_by, '24', 'hours')
when 'this_week' then
paginate(filter_by, '7', 'days')
when 'this_month' then
paginate(filter_by, '30', 'days')
when 'all_time' then
case filter_by
when 'most_views' then
paginate('descending','views_count')
when 'most_edits' then
paginate('descending', 'contributors_count', 'contributed') #TODO: contributors count does not seem to get updated
when 'most_stars' then
paginate('descending', 'stars_count', 'starred')
end
end
end
def authorized?
true
end
def site_home
@active_tab = :home
@group.profiles.public.create_wiki unless @group.profiles.public.wiki
@announcements = Page.find_by_path('limit/3/descending/created_at',
options_for_group(@group, :flow => :announcement))
@show_featured = Page.count_by_path(['featured_by', @group.id], options_for_group(@group, :limit => 1)) > 0
render :template => 'root/site_home'
end
def login_page
@stylesheet = 'account'
@active_tab = :home
render :template => 'account/index'
end
def fetch_network
@group = current_site.network if current_site and current_site.network
end
def paginate(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
Page.paginate_by_path(args, options_for_group(@group, {:page => params[:page]}.merge(options)))
end
def update_page_list(target, locals)
render :update do |page|
if locals[:expanded]
page.replace_html target, :partial => 'pages/list_expanded', :locals => locals
else
page.replace_html target, :partial => 'pages/list', :locals => locals
end
end
end
##
## lists of active groups and users. used by the view.
##
helper_method :most_active_groups
def most_active_groups
Group.only_groups.most_visits.find(:all, :limit => 15)
end
helper_method :recently_active_groups
def recently_active_groups
Group.only_groups.recent_visits.find(:all, :limit => 10)
end
helper_method :most_active_users
def most_active_users
User.most_active_on(current_site, nil).not_inactive.find(:all, :limit => 15)
end
helper_method :recently_active_users
def recently_active_users
User.most_active_on(current_site, Time.now - 30.days).not_inactive.find(:all, :limit => 10)
end
end
|
cask "daedalus-testnet" do
version "4.4.1,19369"
sha256 "4bf65f233a9d7b37e97bfc79c843a05d867446a141d81c99e5a997ea41f65dda"
url "https://updates-cardano-testnet.s3.amazonaws.com/daedalus-#{version.before_comma}-testnet-#{version.after_comma}.pkg",
verified: "updates-cardano-testnet.s3.amazonaws.com/"
name "Daedalus Testnet"
desc "Cryptocurrency wallet for test ada on the Cardano Testnet blockchain"
homepage "https://developers.cardano.org/en/testnets/cardano/get-started/wallet/"
livecheck do
url "https://updates-cardano-testnet.s3.amazonaws.com/daedalus-latest-version.json"
strategy :page_match do |page|
version = page.match(/"version":"(.+?)"/)[1]
build = page.match(/-(\d+(?:\.\d+)*)\.pkg/)[1]
"#{version},#{build}"
end
end
auto_updates true
depends_on macos: ">= :high_sierra"
pkg "daedalus-#{version.before_comma}-testnet-#{version.after_comma}.pkg"
uninstall pkgutil: "org.Daedalustestnet.pkg"
zap trash: [
"~/Library/Application Support/Daedalus Testnet",
"~/Library/Preferences/com.electron.daedalus-testnet.plist",
"~/Library/Saved Application State/com.electron.daedalus-testnet.savedState",
]
end
Update daedalus-testnet from 4.4.1 to 4.5.1 (#114680)
* Update daedalus-testnet from 4.4.1 to 4.5.1
* Update daedalus-testnet.rb
Co-authored-by: Miccal Matthews <a53b0df86fcdccc56e90f3003dd9230c49f140c6@gmail.com>
cask "daedalus-testnet" do
version "4.5.1,19747"
sha256 "521606e0ebc3b51e29f2a5d112c1db823247a8efa2687e0756a1a8769239f398"
url "https://updates-cardano-testnet.s3.amazonaws.com/daedalus-#{version.before_comma}-testnet-#{version.after_comma}.pkg",
verified: "updates-cardano-testnet.s3.amazonaws.com/"
name "Daedalus Testnet"
desc "Cryptocurrency wallet for test ada on the Cardano Testnet blockchain"
homepage "https://developers.cardano.org/en/testnets/cardano/get-started/wallet/"
livecheck do
url "https://updates-cardano-testnet.s3.amazonaws.com/daedalus-latest-version.json"
strategy :page_match do |page|
version = page.match(/"version":"(\d+(?:\.\d+)+)"/)[1]
build = page.match(/(\d+(?:\.\d+)*)\.pkg/)[1]
"#{version},#{build}"
end
end
auto_updates true
depends_on macos: ">= :high_sierra"
pkg "daedalus-#{version.before_comma}-testnet-#{version.after_comma}.pkg"
uninstall pkgutil: "org.Daedalustestnet.pkg"
zap trash: [
"~/Library/Application Support/Daedalus Testnet",
"~/Library/Preferences/com.electron.daedalus-testnet.plist",
"~/Library/Saved Application State/com.electron.daedalus-testnet.savedState",
]
end
|
require './commands/command'
require 'net/http'
class Meme < Command
def respond(client, room, time=nil, nick=nil, text=nil)
# Meme ID's come from https://api.imgflip.com/caption_image
# This should probably be more robust and stored in the db,
# but I'm kinda lazy right now...
@memes = {
:interesting_man => 61532,
:yodawg => 101716,
:takemoney => 176908,
:notsure => 61520,
:onedoesnot => 61579,
:matrix => 100947,
:onlyone => 259680,
:notime => 442575
}
meme_url = nil
post_data = {
:template_id => nil,
:text0 => nil,
:text1 => nil,
:username => nil,
:password => nil
}
case text.downcase
when /i don't always (.*) but when i do (.*)/
post_data[:template_id] = @memes[:interesting_man]
post_data[:text0] = "I don't always #{$1}"
post_data[:text1] = "but when I do, #{$2}"
when /yo dawg (.*) so (.*)/
post_data[:template_id] = @memes[:yodawg]
post_data[:text0] = "Yo Dawg, #{$1}"
post_data[:text1] = "so #{$2}"
when /one does not simply (.*)/
post_data[:template_id] = @memes[:onedoesnot]
post_data[:text0] = 'One does not simply'
post_data[:text1] = $1
when /take my money/
post_data[:template_id] = @memes[:takemoney]
when /not sure if (.*) or (.*)/
post_data[:template_id] = @memes[:notsure]
post_data[:text0] = "Not sure if #{$1}"
post_data[:text1] = "or #{$2}"
when /what if i told you (.*)/
post_data[:template_id] = @memes[:matrix]
post_data[:text0] = "What if I told you"
post_data[:text1] = $1
when /am i then only one around here (.*)/
post_data[:template_id] = @memes[:onlyone]
post_data[:text0] = 'Am I the only one around here'
post_data[:text1] = $1
when /(.*) ain't nobody got time for that/
post_data[:template_id] = @memes[:notime]
post_data[:text0] = $1
post_data[:text1] = "Ain't nobody got time for that!"
end
url = client.config['meme']['post_url']
post_data[:username] = client.config['meme']['username']
post_data[:password] = client.config['meme']['password']
uri = URI.parse(url)
response = Net::HTTP.post_form(uri, post_data)
if response.code == '200'
data = JSON.parse(response.body)
if data['success']
meme_url = data['data']['url']
else
client.log.error("Tried to make meme, but got error: #{data['error_message']}")
end
else
client.log.error("Tried to make meme, but got response: #{response.code}")
end
if meme_url
client.send(room, meme_url)
else
client.send(room, "Sorry, I couldn't generate a meme for that.")
end
end
end
fix one
require './commands/command'
require 'net/http'
class Meme < Command
def respond(client, room, time=nil, nick=nil, text=nil)
# Meme ID's come from https://api.imgflip.com/caption_image
# This should probably be more robust and stored in the db,
# but I'm kinda lazy right now...
@memes = {
:interesting_man => 61532,
:yodawg => 101716,
:takemoney => 176908,
:notsure => 61520,
:onedoesnot => 61579,
:matrix => 100947,
:onlyone => 259680,
:notime => 442575
}
meme_url = nil
post_data = {
:template_id => nil,
:text0 => nil,
:text1 => nil,
:username => nil,
:password => nil
}
case text.downcase
when /i don't always (.*) but when i do (.*)/
post_data[:template_id] = @memes[:interesting_man]
post_data[:text0] = "I don't always #{$1}"
post_data[:text1] = "but when I do, #{$2}"
when /yo dawg (.*) so (.*)/
post_data[:template_id] = @memes[:yodawg]
post_data[:text0] = "Yo Dawg, #{$1}"
post_data[:text1] = "so #{$2}"
when /one does not simply (.*)/
post_data[:template_id] = @memes[:onedoesnot]
post_data[:text0] = 'One does not simply'
post_data[:text1] = $1
when /take my money/
post_data[:template_id] = @memes[:takemoney]
post_data[:text0] = 'Shut up and'
post_data[:text1] = 'take my money!'
when /not sure if (.*) or (.*)/
post_data[:template_id] = @memes[:notsure]
post_data[:text0] = "Not sure if #{$1}"
post_data[:text1] = "or #{$2}"
when /what if i told you (.*)/
post_data[:template_id] = @memes[:matrix]
post_data[:text0] = "What if I told you"
post_data[:text1] = $1
when /am i then only one around here (.*)/
post_data[:template_id] = @memes[:onlyone]
post_data[:text0] = 'Am I the only one around here'
post_data[:text1] = $1
when /(.*) ain't nobody got time for that/
post_data[:template_id] = @memes[:notime]
post_data[:text0] = $1
post_data[:text1] = "Ain't nobody got time for that!"
end
url = client.config['meme']['post_url']
post_data[:username] = client.config['meme']['username']
post_data[:password] = client.config['meme']['password']
uri = URI.parse(url)
response = Net::HTTP.post_form(uri, post_data)
if response.code == '200'
data = JSON.parse(response.body)
if data['success']
meme_url = data['data']['url']
else
client.log.error("Tried to make meme, but got error: #{data['error_message']}")
end
else
client.log.error("Tried to make meme, but got response: #{response.code}")
end
if meme_url
client.send(room, meme_url)
else
client.send(room, "Sorry, I couldn't generate a meme for that.")
end
end
end
|
require 'htmlentities'
class RunsController < ApplicationController
def search
if params[:term].present?
redirect_to "/search/#{params[:term]}"
end
end
def results
@term = params[:term]
@runs = (Game.search(@term).map(&:categories).flatten.map(&:runs).flatten | Category.search(@term).map(&:runs).flatten).sort_by(&:hits)
end
def create
splits = params[:file]
@run = Run.create
@run.file = splits.read
if @run.parses
@run.user = current_user
@run.image_url = params[:image_url]
game = Game.find_by(name: @run.parsed.game) || Game.create(name: @run.parsed.game)
@run.category = Category.find_by(game: game, name: @run.parsed.category) || game.categories.new(game: game, name: @run.parsed.category)
@run.save
respond_to do |format|
format.html { redirect_to run_path(@run.nick) }
format.json { render json: {url: request.protocol + request.host_with_port + run_path(@run.nick)} }
end
else
@run.destroy
respond_to do |format|
format.html { redirect_to cant_parse_path }
format.json { render json: {url: cant_parse_path } }
end
end
end
def show
@random = session[:random] or false
session[:random] = false
@run = Run.find_by nick: params[:run]
render :bad_url and return if @run.try(:file).nil?
@run.user = current_user if @run.hits == 0 && user_signed_in?
@run.hits += 1
@run.save
if @run.parses
respond_to do |format|
format.html { render :show }
format.json { render json: @run }
end
else
if @run.hits > 1 then render :cant_parse
else @run.destroy and redirect_to(cant_parse_path) end
end
end
def download
@run = Run.find_by nick: params[:run]
if @run.nil?
render(:bad_url) and return
end
@run.hits += 1 and @run.save
if @run.present?
file_extension = params[:program] == 'livesplit' ? 'lss' : params[:program]
if params[:program].to_sym == @run.program # If the original program was requested, serve the original file
send_data(HTMLEntities.new.decode(@run.file), filename: "#{@run.nick}.#{file_extension}", layout: false)
else
send_data(HTMLEntities.new.decode(render_to_string(params[:program], layout: false)), filename: "#{@run.nick}.#{file_extension}", layout: false)
end
else
if @run.hits > 1 then render(:cant_parse)
else @run.destroy and redirect_to(cant_parse_path) end
end
end
def random
# Find a random run. If we can't parse it, find another, and so on.
run = nil
if request.env["HTTP_REFERER"].present?
# Don't use the run that we just came from (i.e. we're spam clicking random)
last_run = URI.parse(URI.encode request.env["HTTP_REFERER"].strip).path
last_run.slice! 0 # Remove initial '/'
else
last_run = nil
end
run = Run.all.sample(1).first
if run.nil?
redirect_to root_path, alert: 'There are no runs yet!' and return
end
session[:random] = true
redirect_to run_path(run.nick)
end
def disown
@run = Run.find_by(nick: params[:run])
if @run.user.present? && current_user == @run.user
@run.user = nil
@run.save and redirect_to(root_path)
else
redirect_to(run_path(@run.nick))
end
end
def delete
@run = Run.find_by(nick: params[:run])
if @run.user.present? && current_user == @run.user
@run.destroy and redirect_to(root_path)
else
redirect_to(run_path(@run.nick))
end
end
end
Make `/random` wayyyy faster lol
I didn't even realize what I was doing
require 'htmlentities'
class RunsController < ApplicationController
def search
if params[:term].present?
redirect_to "/search/#{params[:term]}"
end
end
def results
@term = params[:term]
@runs = (Game.search(@term).map(&:categories).flatten.map(&:runs).flatten | Category.search(@term).map(&:runs).flatten).sort_by(&:hits)
end
def create
splits = params[:file]
@run = Run.create
@run.file = splits.read
if @run.parses
@run.user = current_user
@run.image_url = params[:image_url]
game = Game.find_by(name: @run.parsed.game) || Game.create(name: @run.parsed.game)
@run.category = Category.find_by(game: game, name: @run.parsed.category) || game.categories.new(game: game, name: @run.parsed.category)
@run.save
respond_to do |format|
format.html { redirect_to run_path(@run.nick) }
format.json { render json: {url: request.protocol + request.host_with_port + run_path(@run.nick)} }
end
else
@run.destroy
respond_to do |format|
format.html { redirect_to cant_parse_path }
format.json { render json: {url: cant_parse_path } }
end
end
end
def show
@random = session[:random] or false
session[:random] = false
@run = Run.find_by nick: params[:run]
render :bad_url and return if @run.try(:file).nil?
@run.user = current_user if @run.hits == 0 && user_signed_in?
@run.hits += 1
@run.save
if @run.parses
respond_to do |format|
format.html { render :show }
format.json { render json: @run }
end
else
if @run.hits > 1 then render :cant_parse
else @run.destroy and redirect_to(cant_parse_path) end
end
end
def download
@run = Run.find_by nick: params[:run]
if @run.nil?
render(:bad_url) and return
end
@run.hits += 1 and @run.save
if @run.present?
file_extension = params[:program] == 'livesplit' ? 'lss' : params[:program]
if params[:program].to_sym == @run.program # If the original program was requested, serve the original file
send_data(HTMLEntities.new.decode(@run.file), filename: "#{@run.nick}.#{file_extension}", layout: false)
else
send_data(HTMLEntities.new.decode(render_to_string(params[:program], layout: false)), filename: "#{@run.nick}.#{file_extension}", layout: false)
end
else
if @run.hits > 1 then render(:cant_parse)
else @run.destroy and redirect_to(cant_parse_path) end
end
end
def random
# Find a random run. If we can't parse it, find another, and so on.
run = nil
if request.env["HTTP_REFERER"].present?
# Don't use the run that we just came from (i.e. we're spam clicking random)
last_run = URI.parse(URI.encode request.env["HTTP_REFERER"].strip).path
last_run.slice! 0 # Remove initial '/'
else
last_run = nil
end
run = Run.offset(rand(Run.count)).first
if run.nil?
redirect_to root_path, alert: 'There are no runs yet!' and return
end
session[:random] = true
redirect_to run_path(run.nick)
end
def disown
@run = Run.find_by(nick: params[:run])
if @run.user.present? && current_user == @run.user
@run.user = nil
@run.save and redirect_to(root_path)
else
redirect_to(run_path(@run.nick))
end
end
def delete
@run = Run.find_by(nick: params[:run])
if @run.user.present? && current_user == @run.user
@run.destroy and redirect_to(root_path)
else
redirect_to(run_path(@run.nick))
end
end
end
|
cask :v1 => 'fivedetails-flow' do
version :latest
sha256 :no_check
url 'http://fivedetails.com/flow/download'
appcast 'http://extendmac.com/flow/updates/update.php'
homepage 'http://fivedetails.com'
license :unknown
app 'Flow.app'
end
license todo comment in fivedetails-flow
cask :v1 => 'fivedetails-flow' do
version :latest
sha256 :no_check
url 'http://fivedetails.com/flow/download'
appcast 'http://extendmac.com/flow/updates/update.php'
homepage 'http://fivedetails.com'
license :unknown # todo: improve this machine-generated value
app 'Flow.app'
end
|
class EditableMachineForm
include ActiveModel::Model
include ActiveModel::Validations
def self.model_name
ActiveModel::Name.new(Machine)
end
delegate :fqdn, :arch, :ram, :cores, :vmhost, :description,
:os, :os_release, :serialnumber,
:switch_url, :mrtg_url, :config_instructions, :device_type_name,
:sw_characteristics, :business_purpose, to: :machine
delegate :nics, :aliases, to: :machine
attr_reader :machine
delegate :name, :new_record?, to: :machine
validate do |form|
unless @parms["nics"].blank?
@parms["nics"].each do |nic|
next if nic["name"].blank?
index = form.machine.nics.find_index{|n| n.name == nic["name"]}
nic_obj = nil
unless index.nil?
nic_obj = form.machine.nics[index]
end
if nic["ip_address"]["addr"].blank?
form.errors.add(nic_obj.name, 'ip address missing')
end
if nic["ip_address"]["netmask"].blank?
form.errors.add(nic_obj.name, 'netmask missing')
end
end
end
end
def initialize(machine)
@machine = machine
@show_errors = false
end
def show_errors?
!!@show_errors
end
def update(params)
klass = Machine.device_type_by_name(params["device_type_name"])
if klass
@machine.becomes!(klass)
end
params.permit! if params.is_a? ActionController::Parameters
@parms = params.to_h.clone
params = params.to_h
nics = params.delete(:nics)
nics = recursive_symbolize_keys(nics) || Array.new
aliases = params.delete(:aliases) || Array.new
aliases = recursive_symbolize_keys(aliases)
nics_changed = false
# if nic parameters are presented delete all nics and create them from scratch
@machine.nics.destroy_all if nics.size > 0
params.keys.each do |key|
next unless machine.respond_to?("#{key}=")
machine.public_send("#{key}=", params[key])
end
nics.each do |data|
next if data[:name].blank?
ip_address = data.delete(:ip_address)
next if data[:remove] # NIC has been marked to remove, ignore its params
nic = nic_for(data)
return false unless nic
nic.update(mac: data[:mac])
nics_changed = true
nic.ip_address || nic.build_ip_address(family: 'inet')
nic.ip_address.update(ip_address) if ip_address
end
aliases.each do |data|
next if data[:name].blank?
aliass = alias_for(data)
next if aliass.destroyed?
end
begin
changed_attributes = machine.changed_attributes
if valid? && machine.save
changed_attributes.empty? ? {} : changed_attributes
else
@show_errors = true
nil
end
rescue ActiveRecord::RecordNotUnique => error
@show_errors = true
str = $!.message
# extract the alias from the MySQL message "Duplicate entry 'xyz' for"
self.errors.add('Alias', 'already exists: '+str[str.index("entry '")+7, str.index("' for")-(str.index("entry '")+7)])
false
end
end
def nic_for(data)
return if data.nil? || data[:name].blank?
nic = machine.nics.where(name: data[:name]).first
machine.nics.build(data)
end
def alias_for(data)
remove = data.delete(:remove)
aliass = machine.aliases.where(name: data[:name]).first
if aliass
# Destroy the alias if the remove flag has been set.
remove ? aliass.destroy : aliass
else
machine.aliases.build(data)
end
end
def arch_list
%w(amd64 i386)
end
def core_collection
[1] + 2.step(48, 2).to_a # Show even number of cores.
end
def vmhost_list
Machine.where(type: nil).pluck(:fqdn).sort
end
def os_list
(
Machine.select(:os).distinct.map(&:os).compact + os_other
).sort
end
def os_release_list
(
Machine.select(:os_release).distinct.map(&:os_release).compact + os_release_other
).sort
end
def to_model
machine
end
def mrtg_url
machine.mrtg_url ? machine.mrtg_url : IDB.config.mrtg.base_url
end
private
def os_other
IDB.config.machine_details.os
end
def os_release_other
IDB.config.machine_details.os_release
end
def recursive_symbolize_keys(my_hash)
case my_hash
when Hash
Hash[
my_hash.map do |key, value|
[ key.respond_to?(:to_sym) ? key.to_sym : key, recursive_symbolize_keys(value) ]
end
]
when Enumerable
my_hash.map { |value| recursive_symbolize_keys(value) }
else
my_hash
end
end
end
also list type "Machine" in vmhost list and lowercase before sorting
class EditableMachineForm
include ActiveModel::Model
include ActiveModel::Validations
def self.model_name
ActiveModel::Name.new(Machine)
end
delegate :fqdn, :arch, :ram, :cores, :vmhost, :description,
:os, :os_release, :serialnumber,
:switch_url, :mrtg_url, :config_instructions, :device_type_name,
:sw_characteristics, :business_purpose, to: :machine
delegate :nics, :aliases, to: :machine
attr_reader :machine
delegate :name, :new_record?, to: :machine
validate do |form|
unless @parms["nics"].blank?
@parms["nics"].each do |nic|
next if nic["name"].blank?
index = form.machine.nics.find_index{|n| n.name == nic["name"]}
nic_obj = nil
unless index.nil?
nic_obj = form.machine.nics[index]
end
if nic["ip_address"]["addr"].blank?
form.errors.add(nic_obj.name, 'ip address missing')
end
if nic["ip_address"]["netmask"].blank?
form.errors.add(nic_obj.name, 'netmask missing')
end
end
end
end
def initialize(machine)
@machine = machine
@show_errors = false
end
def show_errors?
!!@show_errors
end
def update(params)
klass = Machine.device_type_by_name(params["device_type_name"])
if klass
@machine.becomes!(klass)
end
params.permit! if params.is_a? ActionController::Parameters
@parms = params.to_h.clone
params = params.to_h
nics = params.delete(:nics)
nics = recursive_symbolize_keys(nics) || Array.new
aliases = params.delete(:aliases) || Array.new
aliases = recursive_symbolize_keys(aliases)
nics_changed = false
# if nic parameters are presented delete all nics and create them from scratch
@machine.nics.destroy_all if nics.size > 0
params.keys.each do |key|
next unless machine.respond_to?("#{key}=")
machine.public_send("#{key}=", params[key])
end
nics.each do |data|
next if data[:name].blank?
ip_address = data.delete(:ip_address)
next if data[:remove] # NIC has been marked to remove, ignore its params
nic = nic_for(data)
return false unless nic
nic.update(mac: data[:mac])
nics_changed = true
nic.ip_address || nic.build_ip_address(family: 'inet')
nic.ip_address.update(ip_address) if ip_address
end
aliases.each do |data|
next if data[:name].blank?
aliass = alias_for(data)
next if aliass.destroyed?
end
begin
changed_attributes = machine.changed_attributes
if valid? && machine.save
changed_attributes.empty? ? {} : changed_attributes
else
@show_errors = true
nil
end
rescue ActiveRecord::RecordNotUnique => error
@show_errors = true
str = $!.message
# extract the alias from the MySQL message "Duplicate entry 'xyz' for"
self.errors.add('Alias', 'already exists: '+str[str.index("entry '")+7, str.index("' for")-(str.index("entry '")+7)])
false
end
end
def nic_for(data)
return if data.nil? || data[:name].blank?
nic = machine.nics.where(name: data[:name]).first
machine.nics.build(data)
end
def alias_for(data)
remove = data.delete(:remove)
aliass = machine.aliases.where(name: data[:name]).first
if aliass
# Destroy the alias if the remove flag has been set.
remove ? aliass.destroy : aliass
else
machine.aliases.build(data)
end
end
def arch_list
%w(amd64 i386)
end
def core_collection
[1] + 2.step(48, 2).to_a # Show even number of cores.
end
def vmhost_list
Machine.where(type: "Machine").or(Machine.where(type: nil)).pluck(:fqdn).map(&:downcase).sort
end
def os_list
(
Machine.select(:os).distinct.map(&:os).compact + os_other
).sort
end
def os_release_list
(
Machine.select(:os_release).distinct.map(&:os_release).compact + os_release_other
).sort
end
def to_model
machine
end
def mrtg_url
machine.mrtg_url ? machine.mrtg_url : IDB.config.mrtg.base_url
end
private
def os_other
IDB.config.machine_details.os
end
def os_release_other
IDB.config.machine_details.os_release
end
def recursive_symbolize_keys(my_hash)
case my_hash
when Hash
Hash[
my_hash.map do |key, value|
[ key.respond_to?(:to_sym) ? key.to_sym : key, recursive_symbolize_keys(value) ]
end
]
when Enumerable
my_hash.map { |value| recursive_symbolize_keys(value) }
else
my_hash
end
end
end
|
require 'htmlentities'
require 'uri'
class RunsController < ApplicationController
before_action :set_run, only: [:show, :download, :disown, :delete]
before_action :increment_hits, only: [:show, :download]
def show
@random = session[:random] || false
session[:random] = false
@run.user = current_user if @run.hits == 1 && user_signed_in?
if @run.parses?
respond_to do |format|
format.html { render :show }
format.json { render json: @run }
end
else
if @run.new?
@run.destroy
redirect_to cant_parse_path
else
render :cant_parse
end
end
end
def upload
splits = params[:file]
@run = Run.create
@run.file = splits.read
if @run.parses?
@run.user = current_user
@run.image_url = params[:image_url]
game = Game.find_by(name: @run.parse.game) || Game.create(name: @run.parse.game)
@run.category = Category.find_by(game: game, name: @run.parse.category) || game.categories.new(name: @run.parse.category)
@run.save
respond_to do |format|
format.html { redirect_to run_path(@run.nick) }
format.json { render json: { url: request.protocol + request.host_with_port + run_path(@run.nick) } }
end
else
@run.destroy
respond_to do |format|
format.html { redirect_to cant_parse_path }
format.json { render json: { url: cant_parse_path } }
end
end
if request.xhr?
client = 'drag and drop'
elsif request.env['HTTP_USER_AGENT'] =~ /LiveSplit/i
client = request.env['HTTP_USER_AGENT']
elsif request.referer =~ /\/upload/i
client = 'form'
end
mixpanel.track(current_user.try(:id), 'run uploaded', @run.tracking_info.merge({'Client' => client}))
end
def download
if @run.present?
file_extension = params[:program] == 'livesplit' ? 'lss' : params[:program]
if params[:program].to_sym == @run.program # If the original program was requested, serve the original file
send_data(HTMLEntities.new.decode(@run.file), filename: "#{@run.nick}.#{file_extension}", layout: false)
else
send_data(HTMLEntities.new.decode(render_to_string(params[:program], layout: false)), filename: "#{@run.nick}.#{file_extension}", layout: false)
end
else
if @run.new?
@run.destroy
redirect_to cant_parse_path
else
render :cant_parse
end
end
end
def random
if Run.count == 0
redirect_to root_path, alert: 'There are no runs yet!'
else
session[:random] = true
@run = Run.offset(rand(Run.count)).first
redirect_to(run_path(@run.nick))
end
end
def disown
if @run.belongs_to?(current_user)
@run.disown
@run.save
redirect_to root_path
else
redirect_to run_path(@run.nick)
end
end
def delete
if @run.belongs_to?(current_user)
@run.destroy
redirect_to root_path
else
redirect_to run_path(@run.nick)
end
end
protected
def set_run
@run = Run.find_by(nick: params[:run])
if @run.try(:file).nil?
render :bad_url
return false
end
end
def increment_hits
@run.hit
@run.save
end
end
Fix a `null` being reported as Client of run uploads
require 'htmlentities'
require 'uri'
class RunsController < ApplicationController
before_action :set_run, only: [:show, :download, :disown, :delete]
before_action :increment_hits, only: [:show, :download]
def show
@random = session[:random] || false
session[:random] = false
@run.user = current_user if @run.hits == 1 && user_signed_in?
if @run.parses?
respond_to do |format|
format.html { render :show }
format.json { render json: @run }
end
else
if @run.new?
@run.destroy
redirect_to cant_parse_path
else
render :cant_parse
end
end
end
def upload
splits = params[:file]
@run = Run.create
@run.file = splits.read
if @run.parses?
@run.user = current_user
@run.image_url = params[:image_url]
game = Game.find_by(name: @run.parse.game) || Game.create(name: @run.parse.game)
@run.category = Category.find_by(game: game, name: @run.parse.category) || game.categories.new(name: @run.parse.category)
@run.save
respond_to do |format|
format.html { redirect_to run_path(@run.nick) }
format.json { render json: { url: request.protocol + request.host_with_port + run_path(@run.nick) } }
end
else
@run.destroy
respond_to do |format|
format.html { redirect_to cant_parse_path }
format.json { render json: { url: cant_parse_path } }
end
end
params = {}
if request.xhr?
params['Client'] = 'drag and drop'
elsif request.env['HTTP_USER_AGENT'] =~ /LiveSplit/i
params['Client'] = request.env['HTTP_USER_AGENT']
elsif request.referer =~ /\/upload/i
params['Client'] = 'form'
end
mixpanel.track(current_user.try(:id), 'run uploaded', @run.tracking_info.merge(params))
end
def download
if @run.present?
file_extension = params[:program] == 'livesplit' ? 'lss' : params[:program]
if params[:program].to_sym == @run.program # If the original program was requested, serve the original file
send_data(HTMLEntities.new.decode(@run.file), filename: "#{@run.nick}.#{file_extension}", layout: false)
else
send_data(HTMLEntities.new.decode(render_to_string(params[:program], layout: false)), filename: "#{@run.nick}.#{file_extension}", layout: false)
end
else
if @run.new?
@run.destroy
redirect_to cant_parse_path
else
render :cant_parse
end
end
end
def random
if Run.count == 0
redirect_to root_path, alert: 'There are no runs yet!'
else
session[:random] = true
@run = Run.offset(rand(Run.count)).first
redirect_to(run_path(@run.nick))
end
end
def disown
if @run.belongs_to?(current_user)
@run.disown
@run.save
redirect_to root_path
else
redirect_to run_path(@run.nick)
end
end
def delete
if @run.belongs_to?(current_user)
@run.destroy
redirect_to root_path
else
redirect_to run_path(@run.nick)
end
end
protected
def set_run
@run = Run.find_by(nick: params[:run])
if @run.try(:file).nil?
render :bad_url
return false
end
end
def increment_hits
@run.hit
@run.save
end
end
|
Add folder-colorizer (#116074)
* Create folder-colorizer
* Add zap
* Auto updates true
* Add livecheck
* Update folder-colorizer.rb
Co-authored-by: Bevan Kay <a88b7dcd1a9e3e17770bbaa6d7515b31a2d7e85d@bevankay.me>
cask "folder-colorizer" do
version "4.0.0"
sha256 "4f9ff6d49b34b01f874e88af6c83138dc198f8444113a28c3780c78c73868806"
url "https://ushining.softorino.com/shine_uploads/foldercolorizermac_#{version}.dmg"
name "Folder Colorizer"
desc "Folder icon editor & manager"
homepage "https://softorino.com/folder-colorizer-mac/"
livecheck do
url "https://ushining.softorino.com/appcast.php?abbr=fcm"
strategy :sparkle
end
auto_updates true
app "Folder Colorizer.app"
zap trash: [
"/Users/Shared/Folder Colorizer",
"~/Library/Application Support/Folder Colorizer",
"~/Library/Preferences/com.softorino.foldercolorizer.plist",
"~/Library/Saved Application State/com.softorino.foldercolorizer.savedState",
]
end
|
# frozen_string_literal: true
module Util
class GraphqlPolicy
RULES = {
#################
# Mutations
#################
Types::MutationType => {
### Guideline
createGuideline: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
deleteGuideline: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Guideline.find(args[:guidelineId]).team
current_user.admin? || current_user.admin_of?(team)
end,
updateGuideline: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Guideline.find(args[:guidelineId]).team
current_user.admin? || current_user.admin_of?(team)
end,
### Goal
createGoal: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = KudosMeter.find(args[:kudosMeterId]).team
current_user.admin? || current_user.admin_of?(team)
end,
deleteGoal: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Goal.find(args[:goalId]).kudos_meter.team
current_user.admin? || current_user.admin_of?(team)
end,
updateGoal: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Goal.find(args[:goalId]).kudos_meter.team
current_user.admin? || current_user.admin_of?(team)
end,
### KudosMeter
createKudosMeter: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
deleteKudosMeter: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = KudosMeter.find(args[:kudosMeterId]).team
current_user.admin? || current_user.admin_of?(team)
end,
updateKudosMeter: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = KudosMeter.find(args[:kudosMeterId]).team
current_user.admin? || current_user.admin_of?(team)
end,
### Post
createPost: ->(_obj, args, ctx) do
team = Team.find(args[:teamId])
current_user = ctx[:current_user]
return false unless current_user.present?
current_user.admin? || current_user.member_of?(team)
end,
deletePost: ->(_obj, args, ctx) do
post = Post.find(args[:id])
current_user = ctx[:current_user]
return false unless current_user.present?
if current_user == post.sender || current_user.admin_of?(post.team) || current_user.admin?
if post.created_at < Post.editable_time
current_user.admin? || current_user.admin_of?(post.team)
else
true
end
end
end,
### Team
createTeam: ->(_obj, _args, ctx) { ctx[:current_user].present? },
updateTeam: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
### TeamInvite
createTeamInvite: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
deleteTeamInvite: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = TeamInvite.find(args[:teamInviteId]).team
current_user.admin? || current_user.admin_of?(team)
end,
acceptTeamInvite: ->(_obj, args, ctx) do
team_invite = TeamInvite.find(args[:teamInviteId])
current_user = ctx[:current_user]
return false unless current_user.present?
current_user.admin? || team_invite.email == current_user.email
end,
declineTeamInvite: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team_invite = TeamInvite.find(args[:teamInviteId])
current_user.admin? || team_invite.email == current_user.email
end,
### TeamMember
deleteTeamMember: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = TeamMember.find(args[:id]).team
current_user.admin? || current_user.admin_of?(team)
end,
updateTeamMemberRole: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
### User
resetPassword: ->(_obj, _args, ctx) { ctx[:current_user].present? },
### Vote
toggleLikePost: ->(_obj, args, ctx) do
team = Post.find(args[:postId]).team
current_user = ctx[:current_user]
return false unless current_user.present?
current_user.admin? || current_user.member_of?(team)
end
},
#################
# Team Type
#################
Types::TeamType => {
'*': ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team = obj.object
current_user.member_of?(team) ||
current_user.admin?
end,
id: ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team = obj.object
TeamInvite.where(team: team, email: current_user.email).any? ||
current_user.member_of?(team) ||
current_user.admin?
end,
name: ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team = obj.object
TeamInvite.where(team: team, email: current_user.email).any? ||
current_user.member_of?(team) ||
current_user.admin?
end
},
#################
# TeamInvite Type
#################
Types::TeamInviteType => {
'*': ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team_invite = obj.object
current_user.email == team_invite.email ||
current_user.admin_of?(team_invite.team) ||
current_user.admin?
end
},
#################
# Post Type
#################
Types::PostType => {
'*': ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team = obj.object.team
current_user.member_of?(team) ||
current_user.admin?
end
},
#################
# User Type
#################
Types::UserType => {
'email': ->(obj, _args, ctx) do
current_user = ctx[:current_user]
user = obj.object
current_user.id == user.id ||
current_user.admin?
end
}
}.freeze
def self.guard(type, field)
RULES.dig(type.metadata[:type_class], field)
end
end
end
Added team admin permissions to user's email
# frozen_string_literal: true
module Util
class GraphqlPolicy
RULES = {
#################
# Mutations
#################
Types::MutationType => {
### Guideline
createGuideline: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
deleteGuideline: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Guideline.find(args[:guidelineId]).team
current_user.admin? || current_user.admin_of?(team)
end,
updateGuideline: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Guideline.find(args[:guidelineId]).team
current_user.admin? || current_user.admin_of?(team)
end,
### Goal
createGoal: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = KudosMeter.find(args[:kudosMeterId]).team
current_user.admin? || current_user.admin_of?(team)
end,
deleteGoal: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Goal.find(args[:goalId]).kudos_meter.team
current_user.admin? || current_user.admin_of?(team)
end,
updateGoal: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Goal.find(args[:goalId]).kudos_meter.team
current_user.admin? || current_user.admin_of?(team)
end,
### KudosMeter
createKudosMeter: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
deleteKudosMeter: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = KudosMeter.find(args[:kudosMeterId]).team
current_user.admin? || current_user.admin_of?(team)
end,
updateKudosMeter: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = KudosMeter.find(args[:kudosMeterId]).team
current_user.admin? || current_user.admin_of?(team)
end,
### Post
createPost: ->(_obj, args, ctx) do
team = Team.find(args[:teamId])
current_user = ctx[:current_user]
return false unless current_user.present?
current_user.admin? || current_user.member_of?(team)
end,
deletePost: ->(_obj, args, ctx) do
post = Post.find(args[:id])
current_user = ctx[:current_user]
return false unless current_user.present?
if current_user == post.sender || current_user.admin_of?(post.team) || current_user.admin?
if post.created_at < Post.editable_time
current_user.admin? || current_user.admin_of?(post.team)
else
true
end
end
end,
### Team
createTeam: ->(_obj, _args, ctx) { ctx[:current_user].present? },
updateTeam: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
### TeamInvite
createTeamInvite: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
deleteTeamInvite: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = TeamInvite.find(args[:teamInviteId]).team
current_user.admin? || current_user.admin_of?(team)
end,
acceptTeamInvite: ->(_obj, args, ctx) do
team_invite = TeamInvite.find(args[:teamInviteId])
current_user = ctx[:current_user]
return false unless current_user.present?
current_user.admin? || team_invite.email == current_user.email
end,
declineTeamInvite: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team_invite = TeamInvite.find(args[:teamInviteId])
current_user.admin? || team_invite.email == current_user.email
end,
### TeamMember
deleteTeamMember: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = TeamMember.find(args[:id]).team
current_user.admin? || current_user.admin_of?(team)
end,
updateTeamMemberRole: ->(_obj, args, ctx) do
current_user = ctx[:current_user]
return false unless current_user.present?
team = Team.find(args[:teamId])
current_user.admin? || current_user.admin_of?(team)
end,
### User
resetPassword: ->(_obj, _args, ctx) { ctx[:current_user].present? },
### Vote
toggleLikePost: ->(_obj, args, ctx) do
team = Post.find(args[:postId]).team
current_user = ctx[:current_user]
return false unless current_user.present?
current_user.admin? || current_user.member_of?(team)
end
},
#################
# Team Type
#################
Types::TeamType => {
'*': ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team = obj.object
current_user.member_of?(team) ||
current_user.admin?
end,
id: ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team = obj.object
TeamInvite.where(team: team, email: current_user.email).any? ||
current_user.member_of?(team) ||
current_user.admin?
end,
name: ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team = obj.object
TeamInvite.where(team: team, email: current_user.email).any? ||
current_user.member_of?(team) ||
current_user.admin?
end
},
#################
# TeamInvite Type
#################
Types::TeamInviteType => {
'*': ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team_invite = obj.object
current_user.email == team_invite.email ||
current_user.admin_of?(team_invite.team) ||
current_user.admin?
end
},
#################
# Post Type
#################
Types::PostType => {
'*': ->(obj, _args, ctx) do
current_user = ctx[:current_user]
team = obj.object.team
current_user.member_of?(team) ||
current_user.admin?
end
},
#################
# User Type
#################
Types::UserType => {
'email': ->(obj, _args, ctx) do
current_user = ctx[:current_user]
user = obj.object
same_teams = (user.teams && current_user.teams)
if same_teams.any?
same_teams.each { |team| current_user.admin_of?(team) }
else
current_user.id == user.id || current_user.admin?
end
end
}
}.freeze
def self.guard(type, field)
RULES.dig(type.metadata[:type_class], field)
end
end
end |
class FontCutiveMono < Cask
version '1.002'
sha256 'ef9633aae944f29d936f5da3d757fa6b00cad4948fe8891a093788c2f3524bba'
url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/cutivemono/CutiveMono-Regular.ttf'
homepage 'http://www.google.com/fonts/specimen/Cutive%20Mono'
license :ofl
font 'CutiveMono-Regular.ttf'
end
new-style header in font-cutive-mono
cask :v1 => 'font-cutive-mono' do
version '1.002'
sha256 'ef9633aae944f29d936f5da3d757fa6b00cad4948fe8891a093788c2f3524bba'
url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/cutivemono/CutiveMono-Regular.ttf'
homepage 'http://www.google.com/fonts/specimen/Cutive%20Mono'
license :ofl
font 'CutiveMono-Regular.ttf'
end
|
SAML controller
# -*- coding: utf-8 -*-
class SamlController < ApplicationController
# Create a SAML request and send the user to the IdP
def new
request = Onelogin::Saml::Authrequest.new
redirect_to(request.create(saml_settings))
end
# Parse the SAML response from the IdP and authenticate the user
def consume
response = Onelogin::Saml::Response.new(params[:SAMLResponse])
response.settings = saml_settings
if response.is_valid?
@user = User.where(username: response.attributes[APP_CONFIG["saml"]["username_key"].to_sym]).first
if @user
session[:user_id] = @user.id
redirect_to root_url
else
# TODO: Skapa användaren
render text: "User not in dashboard"
end
else
error_page("500", "Ett fel uppstod med Portwise.")
end
end
def metadata
meta = Onelogin::Saml::Metadata.new
render :xml => meta.generate(saml_settings)
end
private
def saml_settings
sc = APP_CONFIG["saml"]
s = Onelogin::Saml::Settings.new
s.issuer = sc["issuer"]
s.idp_sso_target_url = sc["idp_sso_target_url"]
s.assertion_consumer_service_url = sc["assertion_consumer_service_url"]
s.idp_cert_fingerprint = sc["idp_cert_fingerprint"]
s.name_identifier_format = sc["name_identifier_format"]
s.authn_context = sc["authn_context"]
s
end
end
|
class FontEmblemaOne < Cask
version '1.003'
sha256 '068ab584fb9868c299776adb871cf693b21123ccfb6ed5fab98ff861d1d42bee'
url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/emblemaone/EmblemaOne-Regular.ttf'
homepage 'http://www.google.com/fonts/specimen/Emblema%20One'
font 'EmblemaOne-Regular.ttf'
end
add license stanza, font-emblema-one
class FontEmblemaOne < Cask
version '1.003'
sha256 '068ab584fb9868c299776adb871cf693b21123ccfb6ed5fab98ff861d1d42bee'
url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/emblemaone/EmblemaOne-Regular.ttf'
homepage 'http://www.google.com/fonts/specimen/Emblema%20One'
license :ofl
font 'EmblemaOne-Regular.ttf'
end
|
module Pano
module ElementHelper
def element(element, html_options = {}, &block)
element.render(html_options, &block)
end
end
end
Pass string to render rather than block
module Pano
module ElementHelper
def element(element, html_options = {}, &block)
block_content = ''
block_content += capture(&block) if block_given?
element.render(html_options, block_content)
end
end
end |
module FelyneBot
module Commands
module Raid
extend Discordrb::Commands::CommandContainer
command(:raid, description: 'Displays raid schedule.') do |event, list|
now = Time.now
now = now.to_i
name1=IO.readlines("bot/raid1")[0]
name2=IO.readlines("bot/raid2")[0]
name3=IO.readlines("bot/raid3")[0]
name4=IO.readlines("bot/raid4")[0]
name5=IO.readlines("bot/raid5")[0]
if name1.to_s == ''
raid1 = "```Raid 1: Nothing set up"
else
name1=name1.gsub("\n","")
time1=IO.readlines("bot/raid1")[1].to_i
timediff1 = time1 - now - 3600
if time1 < now
raid1 = "```Raid 1: In process or Completed"
else
raid1 = "```Raid 1: #{name1} in #{Time.at(timediff1).strftime('%H hours %M minutes %S seconds')}"
end
end
if name2.to_s == ''
raid2 = "Raid 2: Nothing set up"
else
name2=name2.gsub("\n","")
time2=IO.readlines("bot/raid2")[1].to_i
timediff2 = time2 - now - 3600
if time2 < now
raid2 = "Raid 2: In process or Completed"
else
raid2 = "Raid 2: #{name2} in #{Time.at(timediff2).strftime('%H hours %M minutes %S seconds')}"
end
end
if name3.to_s == ''
raid3 = "Raid 3: Nothing set up"
else
name3=name3.gsub("\n","")
time3=IO.readlines("bot/raid3")[1].to_i
timediff3 = time3 - now - 3600
if time3 < now
raid3 = "Raid 3: In process or Completed"
else
raid3 = "Raid 3: #{name3} in #{Time.at(timediff3).strftime('%H hours %M minutes %S seconds')}"
end
end
if name4.to_s == ''
raid4 = "Raid 4: Nothing set up"
else
name4=name4.gsub("\n","")
time4=IO.readlines("bot/raid4")[1].to_i
timediff4 = time4 - now - 3600
if time4 < now
raid4 = "Raid 4: In process or Completed"
else
raid4 = "Raid 4: #{name4} in #{Time.at(timediff4).strftime('%H hours %M minutes %S seconds')}"
end
end
if name5.to_s == ''
raid5 = "Raid 5: Nothing set up```"
else
name5=name5.gsub("\n","")
time5=IO.readlines("bot/raid5")[1].to_i
timediff5 = time5 - now - 3600
if time5 < now
raid5 = "Raid 5: In process or Completed```"
else
raid5 = "Raid 5: #{name5} in #{Time.at(timediff5).strftime('%H hours %M minutes %S seconds')}```"
end
end
event << "#{raid1}\n#{raid2}\n#{raid3}\n#{raid4}\n#{raid5}"
if list == 'ready'
role = event.server.roles.find { |role| role.name == "RaidReady" }.id
raidready = event.server.members.select { |m| m.role?(role) }
i=0
raidusers = ""
while i < raidready.length
raidusers << "**#{raidready[i].username}**\n"
i+=1
end
event << raidusers
event << raidready.length
end
end
end
end
end
edited text
module FelyneBot
module Commands
module Raid
extend Discordrb::Commands::CommandContainer
command(:raid, description: 'Displays raid schedule.') do |event, list|
now = Time.now
now = now.to_i
name1=IO.readlines("bot/raid1")[0]
name2=IO.readlines("bot/raid2")[0]
name3=IO.readlines("bot/raid3")[0]
name4=IO.readlines("bot/raid4")[0]
name5=IO.readlines("bot/raid5")[0]
if name1.to_s == ''
raid1 = "```Raid 1: Nothing set up"
else
name1=name1.gsub("\n","")
time1=IO.readlines("bot/raid1")[1].to_i
timediff1 = time1 - now - 3600
if time1 < now
raid1 = "```Raid 1: In process or Completed"
else
raid1 = "```Raid 1: #{name1} in #{Time.at(timediff1).strftime('%H hours %M minutes %S seconds')}"
end
end
if name2.to_s == ''
raid2 = "Raid 2: Nothing set up"
else
name2=name2.gsub("\n","")
time2=IO.readlines("bot/raid2")[1].to_i
timediff2 = time2 - now - 3600
if time2 < now
raid2 = "Raid 2: In process or Completed"
else
raid2 = "Raid 2: #{name2} in #{Time.at(timediff2).strftime('%H hours %M minutes %S seconds')}"
end
end
if name3.to_s == ''
raid3 = "Raid 3: Nothing set up"
else
name3=name3.gsub("\n","")
time3=IO.readlines("bot/raid3")[1].to_i
timediff3 = time3 - now - 3600
if time3 < now
raid3 = "Raid 3: In process or Completed"
else
raid3 = "Raid 3: #{name3} in #{Time.at(timediff3).strftime('%H hours %M minutes %S seconds')}"
end
end
if name4.to_s == ''
raid4 = "Raid 4: Nothing set up"
else
name4=name4.gsub("\n","")
time4=IO.readlines("bot/raid4")[1].to_i
timediff4 = time4 - now - 3600
if time4 < now
raid4 = "Raid 4: In process or Completed"
else
raid4 = "Raid 4: #{name4} in #{Time.at(timediff4).strftime('%H hours %M minutes %S seconds')}"
end
end
if name5.to_s == ''
raid5 = "Raid 5: Nothing set up```"
else
name5=name5.gsub("\n","")
time5=IO.readlines("bot/raid5")[1].to_i
timediff5 = time5 - now - 3600
if time5 < now
raid5 = "Raid 5: In process or Completed```"
else
raid5 = "Raid 5: #{name5} in #{Time.at(timediff5).strftime('%H hours %M minutes %S seconds')}```"
end
end
event << "#{raid1}\n#{raid2}\n#{raid3}\n#{raid4}\n#{raid5}"
if list == 'ready'
role = event.server.roles.find { |role| role.name == "RaidReady" }.id
raidready = event.server.members.select { |m| m.role?(role) }
i=0
raidusers = ""
while i < raidready.length
raidusers << "**#{raidready[i].username}**\n"
i+=1
end
event << raidusers
event << "#{raidready.length} users are ready to raid"
end
end
end
end
end |
Init version of SLAs.
class SlasController < ApplicationController
before_filter :authentication_check
=begin
Format:
JSON
Example:
{
"id":1,
"name":"some sla",
"condition":{"c_a":1,"c_b":2},
"data":{"o_a":1,"o_b":2},
"updated_at":"2012-09-14T17:51:53Z",
"created_at":"2012-09-14T17:51:53Z",
"updated_by_id":2.
"created_by_id":2,
}
=end
=begin
Resource:
GET /api/slas.json
Response:
[
{
"id": 1,
"name": "some_name1",
...
},
{
"id": 2,
"name": "some_name2",
...
}
]
Test:
curl http://localhost/api/slas.json -v -u #{login}:#{password}
=end
def index
model_index_render(Sla, params)
end
=begin
Resource:
GET /api/slas/#{id}.json
Response:
{
"id": 1,
"name": "name_1",
...
}
Test:
curl http://localhost/api/slas/#{id}.json -v -u #{login}:#{password}
=end
def show
model_show_render(Sla, params)
end
=begin
Resource:
POST /api/slas.json
Payload:
{
"name":"some sla",
"condition":{"c_a":1,"c_b":2},
"data":{"o_a":1,"o_b":2},
}
Response:
{
"id": 1,
"name": "some_name",
...
}
Test:
curl http://localhost/api/slas.json -v -u #{login}:#{password} -H "Content-Type: application/json" -X POST -d '{"name": "some_name","active": true, "note": "some note"}'
=end
def create
model_create_render(Sla, params)
end
=begin
Resource:
PUT /api/slas/{id}.json
Payload:
{
"name":"some sla",
"condition":{"c_a":1,"c_b":2},
"data":{"o_a":1,"o_b":2},
}
Response:
{
"id": 1,
"name": "some_name",
...
}
Test:
curl http://localhost/api/slas.json -v -u #{login}:#{password} -H "Content-Type: application/json" -X PUT -d '{"name": "some_name","active": true, "note": "some note"}'
=end
def update
model_update_render(Sla, params)
end
=begin
Resource:
DELETE /api/slas/{id}.json
Response:
{}
Test:
curl http://localhost/api/slas.json -v -u #{login}:#{password} -H "Content-Type: application/json" -X DELETE
=end
def destroy
model_destory_render(Sla, params)
end
end
|
class FontLifeSavers < Cask
url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/lifesavers',
:using => :svn,
:revision => '50',
:trust_cert => true
homepage 'http://www.google.com/fonts/specimen/Life%20Savers'
version '2.001'
sha256 :no_check
font 'LifeSavers-Bold.ttf'
font 'LifeSavers-Regular.ttf'
end
standard Cask layout for font-life-savers.rb
class FontLifeSavers < Cask
version '2.001'
sha256 :no_check
url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/lifesavers',
:using => :svn,
:revision => '50',
:trust_cert => true
homepage 'http://www.google.com/fonts/specimen/Life%20Savers'
font 'LifeSavers-Bold.ttf'
font 'LifeSavers-Regular.ttf'
end
|
class Abook < Formula
desc "Address book with mutt support"
homepage "https://abook.sourceforge.io/"
url "https://downloads.sourceforge.net/project/abook/abook/0.5.6/abook-0.5.6.tar.gz"
sha256 "0646f6311a94ad3341812a4de12a5a940a7a44d5cb6e9da5b0930aae9f44756e"
revision 1
head "git://git.code.sf.net/p/abook/git"
bottle do
sha256 "e32cff277928e0b5cd24f201b1b5f94faf5469f263856b48c78f85b539018c86" => :sierra
sha256 "fc5e09a73519a20dbe90258d6779bfddb1a02b2fc277fd54b4cd8c80c378539d" => :el_capitan
sha256 "2f3a8d37fd17ecdda801f8de53e4048f19d824748e11a34c6f9abca0aae06c3b" => :yosemite
end
devel do
url "http://abook.sourceforge.net/devel/abook-0.6.0pre2.tar.gz"
sha256 "59d444504109dd96816e003b3023175981ae179af479349c34fa70bc12f6d385"
version "0.6.0pre2"
# Remove `inline` from function implementation for clang compatibility
patch :DATA
end
depends_on "readline"
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--mandir=#{man}"
system "make", "install"
end
test do
system "#{bin}/abook", "--formats"
end
end
__END__
diff --git a/database.c b/database.c
index 7c47ab6..53bdb9f 100644
--- a/database.c
+++ b/database.c
@@ -762,7 +762,7 @@ item_duplicate(list_item dest, list_item src)
*/
/* quick lookup by "standard" field number */
-inline int
+int
field_id(int i)
{
assert((i >= 0) && (i < ITEM_FIELDS));
abook: use secure head url
class Abook < Formula
desc "Address book with mutt support"
homepage "https://abook.sourceforge.io/"
url "https://downloads.sourceforge.net/project/abook/abook/0.5.6/abook-0.5.6.tar.gz"
sha256 "0646f6311a94ad3341812a4de12a5a940a7a44d5cb6e9da5b0930aae9f44756e"
revision 1
head "https://git.code.sf.net/p/abook/git.git"
bottle do
sha256 "e32cff277928e0b5cd24f201b1b5f94faf5469f263856b48c78f85b539018c86" => :sierra
sha256 "fc5e09a73519a20dbe90258d6779bfddb1a02b2fc277fd54b4cd8c80c378539d" => :el_capitan
sha256 "2f3a8d37fd17ecdda801f8de53e4048f19d824748e11a34c6f9abca0aae06c3b" => :yosemite
end
devel do
url "https://abook.sourceforge.io/devel/abook-0.6.0pre2.tar.gz"
sha256 "59d444504109dd96816e003b3023175981ae179af479349c34fa70bc12f6d385"
version "0.6.0pre2"
# Remove `inline` from function implementation for clang compatibility
patch :DATA
end
depends_on "readline"
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--mandir=#{man}"
system "make", "install"
end
test do
system "#{bin}/abook", "--formats"
end
end
__END__
diff --git a/database.c b/database.c
index 7c47ab6..53bdb9f 100644
--- a/database.c
+++ b/database.c
@@ -762,7 +762,7 @@ item_duplicate(list_item dest, list_item src)
*/
/* quick lookup by "standard" field number */
-inline int
+int
field_id(int i)
{
assert((i >= 0) && (i < ITEM_FIELDS));
|
class SrpmController < ApplicationController
# caches_page :main, :changelog, :rawspec, :patches, :sources, :download, :gear, :bugs, :allbugs, :repocop
def main
branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch_id => branch.id },
:include => [:packages, :group, :branch, :leader, :packager]
if @srpm != nil
# @allsrpms = Srpm.find :all,
# :conditions => { :name => params[:name] }\
# @allsrpms = Srpm.find_by_sql ["SELECT srpms.name, srpms.version,
# srpms.release, branches.name,
# branches.order_id
# FROM srpms, branches
# WHERE srpms.branch_id = branches.id
# AND srpms.name = ?
# ORDER BY branches.order_id ASC", params[:name]]
if params[:branch] == 'Sisyphus' or
params[:branch] == '5.1' or
params[:branch] == '5.0' or
params[:branch] == '4.1' or
params[:branch] == '4.0'
# @packages = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => ["noarch", "i586"] },
# :order => 'name ASC'
# @leader = Leader.first :conditions => {
# :branch_id => branch.id,
# :package => params[:name] }
# @packager = Packager.first :conditions => { :login => @leader.login }
elsif params[:branch] == 'SisyphusARM'
# @packages = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => ["noarch", "arm"] },
# :order => 'name ASC'
elsif params[:branch] == 'Platform5'
# @packages = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => ["noarch", "i586"] },
# :order => 'name ASC'
end
else
render :status => 404, :action => "nosuchpackage"
end
end
def changelog
branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch_id => branch.id },
:include => [:group, :branch]
if @srpm == nil
render :status => 404, :action => "nosuchpackage"
end
end
def rawspec
branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch_id => branch.id },
:include => [:branch, :group]
if @srpm == nil
render :status => 404, :action => "nosuchpackage"
end
end
def download
branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch_id => branch.id },
:include => [:group, :branch, :packages]
if @srpm != nil
# @allsrpms = Srpm.find_by_sql ["SELECT srpms.name, srpms.version,
# srpms.release, srpms.branch,
# order_id
# FROM srpms, branches
# WHERE srpms.branch = branches.name
# AND srpms.name = ?
# ORDER BY branches.order_id ASC", params[:name]]
# @i586 = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => 'i586' },
# :order => 'name ASC'
# @noarch = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => 'noarch' },
# :order => 'name ASC'
# @x86_64 = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => 'x86_64' },
# :order => 'name ASC'
else
render :status => 404, :action => "nosuchpackage"
end
end
def gear
@branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch => @branch.name,
:vendor => @branch.vendor }
if @srpm != nil
@gitrepos = Gitrepo.all :conditions => { :repo => @srpm.name },
:order => 'lastchange DESC'
else
render :status => 404, :action => "nosuchpackage"
end
end
def bugs
@branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@bugs = Bug.all :conditions => {
:component => params[:name],
:product => params[:branch],
:bug_status => ["NEW", "ASSIGNED", "VERIFIED", "REOPENED"]},
:order => "bug_id DESC"
@allbugs = Bug.all :conditions => {
:component => params[:name],
:product => params[:branch] },
:order => "bug_id DESC"
end
def allbugs
@branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@bugs = Bug.all :conditions => {
:component => params[:name],
:product => params[:branch],
:bug_status => ["NEW", "ASSIGNED", "VERIFIED", "REOPENED"]},
:order => "bug_id DESC"
@allbugs = Bug.all :conditions => {
:component => params[:name],
:product => params[:branch] },
:order => "bug_id DESC"
end
def repocop
@branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch => @branch.name,
:vendor => @branch.vendor }
if @srpm != nil
@repocops = Repocop.all :conditions => {
:srcname => @srpm.name,
:srcversion => @srpm.version,
:srcrel => @srpm.release }
# if @srpm == nil
else
render :status => 404, :action => "nosuchpackage"
end
end
def nosuchpackage
end
end
fix srpm controller
class SrpmController < ApplicationController
# caches_page :main, :changelog, :rawspec, :patches, :sources, :download, :gear, :bugs, :allbugs, :repocop
def main
branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch_id => branch.id },
:include => [:packages, :group, :branch, :leader]
if @srpm != nil
# @allsrpms = Srpm.find :all,
# :conditions => { :name => params[:name] }\
# @allsrpms = Srpm.find_by_sql ["SELECT srpms.name, srpms.version,
# srpms.release, branches.name,
# branches.order_id
# FROM srpms, branches
# WHERE srpms.branch_id = branches.id
# AND srpms.name = ?
# ORDER BY branches.order_id ASC", params[:name]]
if params[:branch] == 'Sisyphus' or
params[:branch] == '5.1' or
params[:branch] == '5.0' or
params[:branch] == '4.1' or
params[:branch] == '4.0'
# @packages = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => ["noarch", "i586"] },
# :order => 'name ASC'
# @leader = Leader.first :conditions => {
# :branch_id => branch.id,
# :package => params[:name] }
# @packager = Packager.first :conditions => { :login => @leader.login }
elsif params[:branch] == 'SisyphusARM'
# @packages = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => ["noarch", "arm"] },
# :order => 'name ASC'
elsif params[:branch] == 'Platform5'
# @packages = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => ["noarch", "i586"] },
# :order => 'name ASC'
end
else
render :status => 404, :action => "nosuchpackage"
end
end
def changelog
branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch_id => branch.id },
:include => [:group, :branch]
if @srpm == nil
render :status => 404, :action => "nosuchpackage"
end
end
def rawspec
branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch_id => branch.id },
:include => [:branch, :group]
if @srpm == nil
render :status => 404, :action => "nosuchpackage"
end
end
def download
branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch_id => branch.id },
:include => [:group, :branch, :packages]
if @srpm != nil
# @allsrpms = Srpm.find_by_sql ["SELECT srpms.name, srpms.version,
# srpms.release, srpms.branch,
# order_id
# FROM srpms, branches
# WHERE srpms.branch = branches.name
# AND srpms.name = ?
# ORDER BY branches.order_id ASC", params[:name]]
# @i586 = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => 'i586' },
# :order => 'name ASC'
# @noarch = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => 'noarch' },
# :order => 'name ASC'
# @x86_64 = Package.all :conditions => {
# :branch => @branch.name,
# :vendor => @branch.vendor,
# :sourcepackage => @srpm.filename,
# :arch => 'x86_64' },
# :order => 'name ASC'
else
render :status => 404, :action => "nosuchpackage"
end
end
def gear
@branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch => @branch.name,
:vendor => @branch.vendor }
if @srpm != nil
@gitrepos = Gitrepo.all :conditions => { :repo => @srpm.name },
:order => 'lastchange DESC'
else
render :status => 404, :action => "nosuchpackage"
end
end
def bugs
@branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@bugs = Bug.all :conditions => {
:component => params[:name],
:product => params[:branch],
:bug_status => ["NEW", "ASSIGNED", "VERIFIED", "REOPENED"]},
:order => "bug_id DESC"
@allbugs = Bug.all :conditions => {
:component => params[:name],
:product => params[:branch] },
:order => "bug_id DESC"
end
def allbugs
@branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@bugs = Bug.all :conditions => {
:component => params[:name],
:product => params[:branch],
:bug_status => ["NEW", "ASSIGNED", "VERIFIED", "REOPENED"]},
:order => "bug_id DESC"
@allbugs = Bug.all :conditions => {
:component => params[:name],
:product => params[:branch] },
:order => "bug_id DESC"
end
def repocop
@branch = Branch.first :conditions => { :vendor => 'ALT Linux', :name => params[:branch] }
@srpm = Srpm.first :conditions => {
:name => params[:name],
:branch => @branch.name,
:vendor => @branch.vendor }
if @srpm != nil
@repocops = Repocop.all :conditions => {
:srcname => @srpm.name,
:srcversion => @srpm.version,
:srcrel => @srpm.release }
# if @srpm == nil
else
render :status => 404, :action => "nosuchpackage"
end
end
def nosuchpackage
end
end |
add font Digohweli Old DO
class FontMasinahikan < Cask
version 'latest'
sha256 :no_check
# version '1.000'
# sha256 '15b64154923017c85c0da6563479b1bd5bc6fe78d729ba085168ca3f208ccd4c'
url 'http://www.languagegeek.com/font/Masinahikan.zip'
homepage 'http://www.languagegeek.com/font/fontdownload.html'
font 'Masinahikan_h.ttf'
font 'Masinahikan_h_Bold.ttf'
font 'Masinahikan_h_Semi.ttf'
end
|
class Abyss < Formula
desc "Genome sequence assembler for short reads"
homepage "https://www.bcgsc.ca/resources/software/abyss"
url "https://github.com/bcgsc/abyss/releases/download/2.2.5/abyss-2.2.5.tar.gz"
sha256 "38e886f455074c76b32dd549e94cc345f46cb1d33ab11ad3e8e1f5214fc65521"
license all_of: ["GPL-3.0-only", "LGPL-2.1-or-later", "MIT", "BSD-3-Clause"]
livecheck do
url :stable
strategy :github_latest
end
bottle do
cellar :any
sha256 "9fe0e2f711647eda6cfc6f4dc8ff0259f6fa96534fa1bfa9f895cfc2b62830b6" => :big_sur
sha256 "521a584ab5f11e69de3b4b2362bdcf89cf3b541b32694c30eec6e71d334c8232" => :catalina
sha256 "8c473ad4f6d9c3b786069c1d933d1ee8e72fb117f1ddbef65b0696163cf34292" => :mojave
sha256 "7fbea49ff3c1cdf2867ceac467be40d16a37cf104ef7fcd478faf0cfdd726eea" => :high_sierra
end
head do
url "https://github.com/bcgsc/abyss.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "multimarkdown" => :build
end
depends_on "boost" => :build
depends_on "google-sparsehash" => :build
depends_on "gcc"
depends_on "open-mpi"
fails_with :clang # no OpenMP support
resource("testdata") do
url "https://www.bcgsc.ca/sites/default/files/bioinformatics/software/abyss/releases/1.3.4/test-data.tar.gz"
sha256 "28f8592203daf2d7c3b90887f9344ea54fda39451464a306ef0226224e5f4f0e"
end
def install
ENV.delete("HOMEBREW_SDKROOT") if MacOS.version >= :mojave && MacOS::CLT.installed?
system "./autogen.sh" if build.head?
system "./configure", "--enable-maxk=128",
"--prefix=#{prefix}",
"--with-boost=#{Formula["boost"].include}",
"--with-mpi=#{Formula["open-mpi"].prefix}",
"--with-sparsehash=#{Formula["google-sparsehash"].prefix}",
"--disable-dependency-tracking",
"--disable-silent-rules"
system "make", "install"
end
test do
testpath.install resource("testdata")
system "#{bin}/abyss-pe", "k=25", "name=ts", "in=reads1.fastq reads2.fastq"
system "#{bin}/abyss-fac", "ts-unitigs.fa"
end
end
abyss: update 2.2.5 bottle.
class Abyss < Formula
desc "Genome sequence assembler for short reads"
homepage "https://www.bcgsc.ca/resources/software/abyss"
url "https://github.com/bcgsc/abyss/releases/download/2.2.5/abyss-2.2.5.tar.gz"
sha256 "38e886f455074c76b32dd549e94cc345f46cb1d33ab11ad3e8e1f5214fc65521"
license all_of: ["GPL-3.0-only", "LGPL-2.1-or-later", "MIT", "BSD-3-Clause"]
livecheck do
url :stable
strategy :github_latest
end
bottle do
cellar :any
sha256 "9fe0e2f711647eda6cfc6f4dc8ff0259f6fa96534fa1bfa9f895cfc2b62830b6" => :big_sur
sha256 "4f653f5b026d1ed8c2b0ced4f47a13bf13cbef542ca1c14d9ef4a9ac2feca90b" => :arm64_big_sur
sha256 "521a584ab5f11e69de3b4b2362bdcf89cf3b541b32694c30eec6e71d334c8232" => :catalina
sha256 "8c473ad4f6d9c3b786069c1d933d1ee8e72fb117f1ddbef65b0696163cf34292" => :mojave
sha256 "7fbea49ff3c1cdf2867ceac467be40d16a37cf104ef7fcd478faf0cfdd726eea" => :high_sierra
end
head do
url "https://github.com/bcgsc/abyss.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "multimarkdown" => :build
end
depends_on "boost" => :build
depends_on "google-sparsehash" => :build
depends_on "gcc"
depends_on "open-mpi"
fails_with :clang # no OpenMP support
resource("testdata") do
url "https://www.bcgsc.ca/sites/default/files/bioinformatics/software/abyss/releases/1.3.4/test-data.tar.gz"
sha256 "28f8592203daf2d7c3b90887f9344ea54fda39451464a306ef0226224e5f4f0e"
end
def install
ENV.delete("HOMEBREW_SDKROOT") if MacOS.version >= :mojave && MacOS::CLT.installed?
system "./autogen.sh" if build.head?
system "./configure", "--enable-maxk=128",
"--prefix=#{prefix}",
"--with-boost=#{Formula["boost"].include}",
"--with-mpi=#{Formula["open-mpi"].prefix}",
"--with-sparsehash=#{Formula["google-sparsehash"].prefix}",
"--disable-dependency-tracking",
"--disable-silent-rules"
system "make", "install"
end
test do
testpath.install resource("testdata")
system "#{bin}/abyss-pe", "k=25", "name=ts", "in=reads1.fastq reads2.fastq"
system "#{bin}/abyss-fac", "ts-unitigs.fa"
end
end
|
Add tags controller.
class TagsController < ApplicationController
def index
@tags = ActsAsTaggableOn::Tag.all
end
def show
@tag_name = params[:tag_name]
@lists = List.tagged_with(@tag_name)
end
end
|
cask 'font-sansita-one' do
version :latest
sha256 :no_check
# github.com/google/fonts was verified as official when first introduced to the cask
url 'https://github.com/google/fonts/raw/master/ofl/sansitaone/SansitaOne.ttf'
name 'Sansita One'
homepage 'http://www.google.com/fonts/specimen/Sansita+One'
font 'SansitaOne.ttf'
end
Update font-sansita-one to latest (#1399)
cask 'font-sansita-one' do
version :latest
sha256 :no_check
# github.com/google/fonts was verified as official when first introduced to the cask
url 'https://github.com/google/fonts/raw/master/ofl/sansitaone/SansitaOne-Regular.ttf'
name 'Sansita One'
homepage 'https://www.google.com/fonts/specimen/Sansita+One'
font 'SansitaOne-Regular.ttf'
end
|
class Aften < Formula
desc "Audio encoder which generates ATSC A/52 compressed audio streams"
homepage "http://aften.sourceforge.net/"
url "https://downloads.sourceforge.net/aften/aften-0.0.8.tar.bz2"
sha256 "87cc847233bb92fbd5bed49e2cdd6932bb58504aeaefbfd20ecfbeb9532f0c0a"
bottle do
cellar :any
sha256 "535ef47b08163c8d1d7a66ffda7d3f280c0569a74d9feedbcfc93cd3c55194ca" => :sierra
sha256 "68b4983cc843e2d57854a263038a965a2dd6c473c98111f482ec1c69d09ace83" => :el_capitan
sha256 "4f785f04a3bbde677452f2c5d1c04f77605e156b4020294c5799c85d0b8586d3" => :yosemite
sha256 "b7acaf77ece8e6b51493ce69e713990a4ce13bc5b9d5ad6914cc86c0f745c9d0" => :mavericks
end
depends_on "cmake" => :build
resource "sample_wav" do
url "http://www.mediacollege.com/audio/tone/files/1kHz_44100Hz_16bit_05sec.wav"
sha256 "949dd8ef74db1793ac6174b8d38b1c8e4c4e10fb3ffe7a15b4941fa0f1fbdc20"
end
def install
mkdir "default" do
system "cmake", "-DSHARED=ON", "..", *std_cmake_args
system "make", "install"
end
end
test do
resource("sample_wav").stage testpath
system "#{bin}/aften", "#{testpath}/1kHz_44100Hz_16bit_05sec.wav", "sample.ac3"
end
end
aften: fix audit --warning
class Aften < Formula
desc "Audio encoder which generates ATSC A/52 compressed audio streams"
homepage "https://aften.sourceforge.io/"
url "https://downloads.sourceforge.net/aften/aften-0.0.8.tar.bz2"
sha256 "87cc847233bb92fbd5bed49e2cdd6932bb58504aeaefbfd20ecfbeb9532f0c0a"
bottle do
cellar :any
sha256 "535ef47b08163c8d1d7a66ffda7d3f280c0569a74d9feedbcfc93cd3c55194ca" => :sierra
sha256 "68b4983cc843e2d57854a263038a965a2dd6c473c98111f482ec1c69d09ace83" => :el_capitan
sha256 "4f785f04a3bbde677452f2c5d1c04f77605e156b4020294c5799c85d0b8586d3" => :yosemite
sha256 "b7acaf77ece8e6b51493ce69e713990a4ce13bc5b9d5ad6914cc86c0f745c9d0" => :mavericks
end
depends_on "cmake" => :build
resource "sample_wav" do
url "http://www.mediacollege.com/audio/tone/files/1kHz_44100Hz_16bit_05sec.wav"
sha256 "949dd8ef74db1793ac6174b8d38b1c8e4c4e10fb3ffe7a15b4941fa0f1fbdc20"
end
def install
mkdir "default" do
system "cmake", "-DSHARED=ON", "..", *std_cmake_args
system "make", "install"
end
end
test do
resource("sample_wav").stage testpath
system "#{bin}/aften", "#{testpath}/1kHz_44100Hz_16bit_05sec.wav", "sample.ac3"
end
end
|
# Controller to deal with tagging
class TagsController < ApplicationController
before_filter :require_login, :only => [:new, :create, :edit, :update, :destroy]
def index
@tags = Tag.find(:all)
end
def create
@node = Node.find(params[:node_id])
@new_tagged_nodes = [ ]
@html = '';
params[:new_tag].each_with_index do |tag_name, index|
next if tag_name.blank? or tag_name == 'tag name'
comment = params[:new_comment][index].strip
tag = Tag.find_or_create_by_name(tag_name.downcase.strip, :person_id => @person.id)
tn = TaggedNode.find_or_create_by_tag_id_and_person_id_and_node_id(tag.id,
@person.id,
@node.id,
:comment => comment)
if tn.created_at < 1.minute.ago
@new_tagged_nodes << tn
notification_recipients = @node.people.reject { |person| person == @person}
if notification_recipients.empty?
logger.warn "No recipients; not sending the notification"
else
logger.warn "Notification recipients = '#{notification_recipients}'"
Notifications.deliver_applied_tag(notification_recipients, tn.tag)
end
end
@html += render_to_string(:partial => 'one_tag.html', :locals => { :tm => tn})
end
respond_to do |format|
format.html do
render :text => @html;
end
format.json do
render :json => {:success => true, :html => @html, :message => '' + params[:new_tag].length + ' tags added'}
end
end
end
def one_tag
tag_id = params[:id]
if tag_id.blank?
flash[:notice] = "No tag ID was provided; can't view this tag."
redirect_to :back
return
end
@tag = Tag.find(tag_id)
end
def follow
@tag = Tag.find(params[:id])
@tagged_nodes = @tag.tagged_nodes.sort_by { |tn| tn.created_at }
respond_to do |format|
format.atom { @tagged_nodes }
end
end
def complete_tags
# Parameters: {"timestamp"=>"1235989842305", "q"=>"ab", "limit"=>"150"}
query = params[:q].downcase
limit = params[:limit].to_i
render :text => Tag.search(query)[0..limit].map { |tag| tag.name}.join("\n")
end
def destroy
tn = TaggedNode.find(params[:id])
model = tn.node
if tn.person == @person or @person.administrator?
tn.destroy
render :json => {:success => true, :message => "Tag '#{tn.tag.name}' removed from the '#{model.name}' model"}
else
render :json => {:success => false, :message => "You are not authorized to remove this tag"}
end
end
def download
tag = Tag.find(params[:id])
send_file(tag.create_zipfile(@person), :filename => tag.zipfile_name, :type => 'application/zip', :disposition => "inline")
end
def image
num_to_fetch_from_db = 10 #limit number of tagged nodes to fetch from db to increase speed
tag = Tag.find(params[:id])
nodes = tag.tagged_nodes.all(:order => 'updated_at DESC', :limit => num_to_fetch_from_db).map{|tn| tn.node}.select{|node| node.visible_to_user?(@person) && !node.preview.blank?}[0..3]
size = 152
list = Magick::ImageList.new
if nodes.length > 0
nodes.each do |model|
if !model.preview.blank?
list.from_blob(model.preview.contents.to_s)
end
if list.length >= 4
break
end
end
end
if list.length == 4
list.each do |image|
image.resize_to_fill!(size/2, size/2, Magick::CenterGravity)
end
m = list.montage {
self.geometry = "#{size/2}x#{size/2}+0+0"
self.tile = '2x2'
} .first
elsif list.length == 3
list[0..1].each { |image|
image.resize_to_fill!(size/2, size/2, Magick::CenterGravity)
}
top = list[0..1].montage {
self.geometry = "#{size/2}x#{size/2}+0+0"
self.tile = '2x1'
} .first
bottom = list[2]
bottom.resize_to_fill!(size, size/2, Magick::CenterGravity)
list = Magick::ImageList.new
list.push(top)
list.push(bottom)
m = list.montage {
self.geometry = "#{size}x#{size/2}+0+0"
self.tile = '1x2'
} .first
elsif list.length == 2
list.each do |image|
image.resize_to_fill!(size, size/2, Magick::CenterGravity)
end
m = list.montage {
self.geometry = "#{size}x#{size/2}+0+0"
self.tile = '1x2'
} .first
elsif list.length == 1
m = list.first.resize_to_fill!(size, size, Magick::CenterGravity)
else
m = Magick::Image.new(1,1) {
self.background_color = 'rgba(255, 255, 255, 0)'
}
end
m.format = 'png'
send_data(m.to_blob, :type => 'image/png', :disposition => 'inline')
#render :json => {:count => list.length}
end
end
Added require to the top of the tags controller
Former-commit-id: 0c23f59c6f3d09281dc47e9a74f86cd9afbf17f0
# Controller to deal with tagging
require 'rmagick'
class TagsController < ApplicationController
before_filter :require_login, :only => [:new, :create, :edit, :update, :destroy]
def index
@tags = Tag.find(:all)
end
def create
@node = Node.find(params[:node_id])
@new_tagged_nodes = [ ]
@html = '';
params[:new_tag].each_with_index do |tag_name, index|
next if tag_name.blank? or tag_name == 'tag name'
comment = params[:new_comment][index].strip
tag = Tag.find_or_create_by_name(tag_name.downcase.strip, :person_id => @person.id)
tn = TaggedNode.find_or_create_by_tag_id_and_person_id_and_node_id(tag.id,
@person.id,
@node.id,
:comment => comment)
if tn.created_at < 1.minute.ago
@new_tagged_nodes << tn
notification_recipients = @node.people.reject { |person| person == @person}
if notification_recipients.empty?
logger.warn "No recipients; not sending the notification"
else
logger.warn "Notification recipients = '#{notification_recipients}'"
Notifications.deliver_applied_tag(notification_recipients, tn.tag)
end
end
@html += render_to_string(:partial => 'one_tag.html', :locals => { :tm => tn})
end
respond_to do |format|
format.html do
render :text => @html;
end
format.json do
render :json => {:success => true, :html => @html, :message => '' + params[:new_tag].length + ' tags added'}
end
end
end
def one_tag
tag_id = params[:id]
if tag_id.blank?
flash[:notice] = "No tag ID was provided; can't view this tag."
redirect_to :back
return
end
@tag = Tag.find(tag_id)
end
def follow
@tag = Tag.find(params[:id])
@tagged_nodes = @tag.tagged_nodes.sort_by { |tn| tn.created_at }
respond_to do |format|
format.atom { @tagged_nodes }
end
end
def complete_tags
# Parameters: {"timestamp"=>"1235989842305", "q"=>"ab", "limit"=>"150"}
query = params[:q].downcase
limit = params[:limit].to_i
render :text => Tag.search(query)[0..limit].map { |tag| tag.name}.join("\n")
end
def destroy
tn = TaggedNode.find(params[:id])
model = tn.node
if tn.person == @person or @person.administrator?
tn.destroy
render :json => {:success => true, :message => "Tag '#{tn.tag.name}' removed from the '#{model.name}' model"}
else
render :json => {:success => false, :message => "You are not authorized to remove this tag"}
end
end
def download
tag = Tag.find(params[:id])
send_file(tag.create_zipfile(@person), :filename => tag.zipfile_name, :type => 'application/zip', :disposition => "inline")
end
def image
num_to_fetch_from_db = 10 #limit number of tagged nodes to fetch from db to increase speed
tag = Tag.find(params[:id])
nodes = tag.tagged_nodes.all(:order => 'updated_at DESC', :limit => num_to_fetch_from_db).map{|tn| tn.node}.select{|node| node.visible_to_user?(@person) && !node.preview.blank?}[0..3]
size = 152
list = Magick::ImageList.new
if nodes.length > 0
nodes.each do |model|
if !model.preview.blank?
list.from_blob(model.preview.contents.to_s)
end
if list.length >= 4
break
end
end
end
if list.length == 4
list.each do |image|
image.resize_to_fill!(size/2, size/2, Magick::CenterGravity)
end
m = list.montage {
self.geometry = "#{size/2}x#{size/2}+0+0"
self.tile = '2x2'
} .first
elsif list.length == 3
list[0..1].each { |image|
image.resize_to_fill!(size/2, size/2, Magick::CenterGravity)
}
top = list[0..1].montage {
self.geometry = "#{size/2}x#{size/2}+0+0"
self.tile = '2x1'
} .first
bottom = list[2]
bottom.resize_to_fill!(size, size/2, Magick::CenterGravity)
list = Magick::ImageList.new
list.push(top)
list.push(bottom)
m = list.montage {
self.geometry = "#{size}x#{size/2}+0+0"
self.tile = '1x2'
} .first
elsif list.length == 2
list.each do |image|
image.resize_to_fill!(size, size/2, Magick::CenterGravity)
end
m = list.montage {
self.geometry = "#{size}x#{size/2}+0+0"
self.tile = '1x2'
} .first
elsif list.length == 1
m = list.first.resize_to_fill!(size, size, Magick::CenterGravity)
else
m = Magick::Image.new(1,1) {
self.background_color = 'rgba(255, 255, 255, 0)'
}
end
m.format = 'png'
send_data(m.to_blob, :type => 'image/png', :disposition => 'inline')
#render :json => {:count => list.length}
end
end
|
cask :v1 => 'google-earth-pro' do
version :latest
sha256 :no_check
url 'https://dl.google.com/earth/client/advanced/current/GoogleEarthProMac-Intel.dmg'
name 'Google Earth Pro'
homepage 'https://www.google.com/earth/'
license :gratis
tags :vendor => 'Google'
app 'Google Earth Pro.app'
zap :delete => [
'~/Library/Application Support/Google Earth',
'~/Library/Caches/Google Earth',
'~/Library/Caches/com.Google.GoogleEarthPro',
]
caveats <<-EOS.undent
Using #{token} requires a license key. If you do not have a key, use your
email address and the key GEPFREE to sign in.
EOS
end
Change install to pkg in Google Earth Pro Cask
cask :v1 => 'google-earth-pro' do
version :latest
sha256 :no_check
url 'https://dl.google.com/earth/client/advanced/current/GoogleEarthProMac-Intel.dmg'
name 'Google Earth Pro'
homepage 'https://www.google.com/earth/'
license :gratis
tags :vendor => 'Google'
pkg 'Install Google Earth.pkg'
uninstall :pkgutil => 'com.Google.GoogleEarthPro'
zap :delete => [
'~/Library/Application Support/Google Earth',
'~/Library/Caches/Google Earth',
'~/Library/Caches/com.Google.GoogleEarthPro',
]
caveats <<-EOS.undent
Using #{token} requires a license key. If you do not have a key, use your
email address and the key GEPFREE to sign in.
EOS
end
|
class Annie < Formula
desc "Fast, simple and clean video downloader"
homepage "https://github.com/iawia002/annie"
url "https://github.com/iawia002/annie/archive/0.9.6.tar.gz"
sha256 "e5e505ff7c7363fed6dbeed7ccefb3af726312ae19fd290b3179f5d41cb63d22"
bottle do
cellar :any_skip_relocation
sha256 "6560d04f09c28d7cb8b5013eb62a569e30eb59462375f30575b15f73cd6b9171" => :catalina
sha256 "3897252d4dcd0f100215ce986dee661b2caae620690b5db9237a8fe64b8e02e3" => :mojave
sha256 "a00211a682f61543f119bf5c5c1a8c540e88318ba42b82f815179be941a34d1c" => :high_sierra
end
depends_on "go" => :build
def install
system "go", "build", "-o", bin/"annie"
prefix.install_metafiles
end
test do
system bin/"annie", "-i", "https://www.bilibili.com/video/av20203945"
end
end
annie: update 0.9.6 bottle.
class Annie < Formula
desc "Fast, simple and clean video downloader"
homepage "https://github.com/iawia002/annie"
url "https://github.com/iawia002/annie/archive/0.9.6.tar.gz"
sha256 "e5e505ff7c7363fed6dbeed7ccefb3af726312ae19fd290b3179f5d41cb63d22"
bottle do
cellar :any_skip_relocation
rebuild 1
sha256 "26f0634743808cb254fccef6bb2bf1aaddb47d6afefc5833b9fa73c0ab8ba118" => :catalina
sha256 "1cf5f2033c1bcdc77780f0c7ae5e84522470928bbbd1ccd927d2916a82ba515d" => :mojave
sha256 "fc64e3d49a0e499f5e5323a42a15d12820556f8ada2560fa4047ed32a578c962" => :high_sierra
end
depends_on "go" => :build
def install
system "go", "build", "-o", bin/"annie"
prefix.install_metafiles
end
test do
system bin/"annie", "-i", "https://www.bilibili.com/video/av20203945"
end
end
|
# frozen_string_literal: true
class TagsController < ApplicationController
before_action :login_required, except: [:index, :show]
before_action :find_tag, except: :index
before_action :permission_required, except: [:index, :show]
def index
@page_title = "Tags"
if params[:view].present?
unless Tag::TYPES.include?(params[:view])
flash[:error] = "Invalid filter"
redirect_to tags_path and return
end
@view = params[:view]
end
@tags = Tag.order('type desc, LOWER(name) asc').select('tags.*')
if @view.present?
@tags = @tags.where(type: @view)
else
@tags = @tags.where.not(type: 'GalleryGroup')
end
@tags = @tags.with_item_counts.paginate(per_page: 25, page: page)
end
def show
@posts = posts_from_relation(@tag.posts)
@characters = @tag.characters.includes(:user)
@galleries = @tag.galleries.with_icon_count.order('name asc')
@page_title = @tag.name.to_s
use_javascript('galleries/expander') if @tag.is_a?(GalleryGroup)
end
def edit
@page_title = "Edit Tag: #{@tag.name}"
build_editor
end
def update
unless @tag.update_attributes(tag_params)
flash.now[:error] = {}
flash.now[:error][:message] = "Tag could not be saved because of the following problems:"
flash.now[:error][:array] = @tag.errors.full_messages
@page_title = "Edit Tag: #{@tag.name}"
build_editor
render action: :edit and return
end
flash[:success] = "Tag saved!"
redirect_to tag_path(@tag)
end
def destroy
@tag.destroy
flash[:success] = "Tag deleted."
redirect_to tags_path
end
private
def find_tag
unless (@tag = Tag.find_by_id(params[:id]))
flash[:error] = "Tag could not be found."
redirect_to tags_path
end
end
def permission_required
unless @tag.editable_by?(current_user)
flash[:error] = "You do not have permission to edit this tag."
redirect_to tag_path(@tag)
end
end
def build_editor
# n.b. this method is unsafe for unpersisted tags (in case we ever add tags#new)
return unless @tag.is_a?(Setting)
@canons = @tag.canons.order('tag_tags.id asc') || []
use_javascript('tags/edit')
end
def tag_params
permitted = [:type, :description, canon_ids: []]
permitted.insert(0, :name) if current_user.admin?
permitted.insert(0, :user_id) if current_user.admin? || @tag.user == current_user
params.fetch(:tag, {}).permit(permitted)
end
end
Allow editing owned field
# frozen_string_literal: true
class TagsController < ApplicationController
before_action :login_required, except: [:index, :show]
before_action :find_tag, except: :index
before_action :permission_required, except: [:index, :show]
def index
@page_title = "Tags"
if params[:view].present?
unless Tag::TYPES.include?(params[:view])
flash[:error] = "Invalid filter"
redirect_to tags_path and return
end
@view = params[:view]
end
@tags = Tag.order('type desc, LOWER(name) asc').select('tags.*')
if @view.present?
@tags = @tags.where(type: @view)
else
@tags = @tags.where.not(type: 'GalleryGroup')
end
@tags = @tags.with_item_counts.paginate(per_page: 25, page: page)
end
def show
@posts = posts_from_relation(@tag.posts)
@characters = @tag.characters.includes(:user)
@galleries = @tag.galleries.with_icon_count.order('name asc')
@page_title = @tag.name.to_s
use_javascript('galleries/expander') if @tag.is_a?(GalleryGroup)
end
def edit
@page_title = "Edit Tag: #{@tag.name}"
build_editor
end
def update
unless @tag.update_attributes(tag_params)
flash.now[:error] = {}
flash.now[:error][:message] = "Tag could not be saved because of the following problems:"
flash.now[:error][:array] = @tag.errors.full_messages
@page_title = "Edit Tag: #{@tag.name}"
build_editor
render action: :edit and return
end
flash[:success] = "Tag saved!"
redirect_to tag_path(@tag)
end
def destroy
@tag.destroy
flash[:success] = "Tag deleted."
redirect_to tags_path
end
private
def find_tag
unless (@tag = Tag.find_by_id(params[:id]))
flash[:error] = "Tag could not be found."
redirect_to tags_path
end
end
def permission_required
unless @tag.editable_by?(current_user)
flash[:error] = "You do not have permission to edit this tag."
redirect_to tag_path(@tag)
end
end
def build_editor
# n.b. this method is unsafe for unpersisted tags (in case we ever add tags#new)
return unless @tag.is_a?(Setting)
@canons = @tag.canons.order('tag_tags.id asc') || []
use_javascript('tags/edit')
end
def tag_params
permitted = [:type, :description, :owned, canon_ids: []]
permitted.insert(0, :name) if current_user.admin?
permitted.insert(0, :user_id) if current_user.admin? || @tag.user == current_user
params.fetch(:tag, {}).permit(permitted)
end
end
|
cask 'intellij-idea-ce' do
version '2016.2.3'
sha256 '3a180ff30a8c9b7bf8bf38f6297fcd9ec6d8994e2b0489b97bfbeead362fb3b8'
url "https://download.jetbrains.com/idea/ideaIC-#{version}.dmg"
name 'IntelliJ IDEA Community Edition'
name 'IntelliJ IDEA CE'
homepage 'https://www.jetbrains.com/idea/'
license :apache
auto_updates true
app 'IntelliJ IDEA CE.app'
uninstall delete: '/usr/local/bin/idea'
zap delete: [
"~/Library/Application Support/IdeaIC#{version.major_minor}",
"~/Library/Preferences/IdeaIC#{version.major_minor}",
"~/Library/Caches/IdeaIC#{version.major_minor}",
"~/Library/Logs/IdeaIC#{version.major_minor}",
]
end
Update IntelliJ IDEA CE to 2016.2.4
cask 'intellij-idea-ce' do
version '2016.2.4'
sha256 '36d7aaf6a10a5c3ac7899c8482449fbe7617d23c4a635086d48b4190551b921b'
url "https://download.jetbrains.com/idea/ideaIC-#{version}.dmg"
name 'IntelliJ IDEA Community Edition'
name 'IntelliJ IDEA CE'
homepage 'https://www.jetbrains.com/idea/'
license :apache
auto_updates true
app 'IntelliJ IDEA CE.app'
uninstall delete: '/usr/local/bin/idea'
zap delete: [
"~/Library/Application Support/IdeaIC#{version.major_minor}",
"~/Library/Preferences/IdeaIC#{version.major_minor}",
"~/Library/Caches/IdeaIC#{version.major_minor}",
"~/Library/Logs/IdeaIC#{version.major_minor}",
]
end
|
require 'formula'
class Aria2 < Formula
url 'http://downloads.sourceforge.net/project/aria2/stable/aria2-1.12.0/aria2-1.12.0.tar.bz2'
md5 '3611fd4d63821162aa47ae113a7858b2'
homepage 'http://aria2.sourceforge.net/'
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
end
end
aria2 1.12.1
Signed-off-by: Jack Nagel <43386ce32af96f5c56f2a88e458cb94cebee3751@gmail.com>
require 'formula'
class Aria2 < Formula
url 'http://downloads.sourceforge.net/project/aria2/stable/aria2-1.12.1/aria2-1.12.1.tar.bz2'
md5 '9f3bf96d92bc8b70b74817ed10c2c7e7'
homepage 'http://aria2.sourceforge.net/'
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make install"
end
end
|
=begin
RailsCollab
-----------
Copyright (C) 2007 James S Urquhart (jamesu at gmail.com)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
=end
class TaskController < ApplicationController
layout 'project_website'
verify :method => :post,
:only => [ :delete_list, :delete_task, :open_task, :complete_task ],
:add_flash => { :flash_error => "Invalid request" },
:redirect_to => { :controller => 'project' }
before_filter :login_required
before_filter :process_session
after_filter :user_track, :only => [:index, :view_list]
def index
@open_task_lists = @active_project.open_task_lists
@completed_task_lists = @active_project.completed_task_lists
@content_for_sidebar = 'index_sidebar'
end
# Task lists
def view_list
begin
@task_list = ProjectTaskList.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task list"
redirect_back_or_default :controller => 'task', :action => 'index'
return
end
if not @task_list.can_be_seen_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task', :action => 'index'
return
end
@open_task_lists = @active_project.open_task_lists
@completed_task_lists = @active_project.completed_task_lists
@content_for_sidebar = 'index_sidebar'
end
def add_list
if not ProjectTaskList.can_be_created_by(@logged_user, @active_project)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
@task_list = ProjectTaskList.new
case request.method
when :get
begin
@task_list.project_milestone = ProjectMilestone.find(params[:milestone_id])
@task_list.is_private = @task_list.project_milestone.is_private
rescue ActiveRecord::RecordNotFound
@task_list.milestone_id = 0
@task_list.is_private = false
end
when :post
task_attribs = params[:task_list]
@task_list.update_attributes(task_attribs)
@task_list.created_by = @logged_user
@task_list.project = @active_project
@task_list.is_private = task_attribs[:is_private] if @logged_user.member_of_owner?
if @task_list.save
ApplicationLog::new_log(@task_list, @logged_user, :add, @task_list.is_private)
@task_list.tags = task_attribs[:tags]
flash[:flash_success] = "Successfully added task"
redirect_back_or_default :controller => 'task'
end
end
end
def edit_list
begin
@task_list = ProjectTaskList.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task_list.can_be_changed_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
case request.method
when :post
task_attribs = params[:task_list]
@task_list.update_attributes(task_attribs)
@task_list.updated_by = @logged_user
@task_list.tags = task_attribs[:tags]
@task_list.is_private = task_attribs[:is_private] if @logged_user.member_of_owner?
if @task_list.save
ApplicationLog::new_log(@task_list, @logged_user, :edit, @task_list.is_private)
flash[:flash_success] = "Successfully modified task"
redirect_back_or_default :controller => 'task'
end
end
end
def delete_list
begin
@task_list = ProjectTaskList.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task_list.can_be_deleted_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
ApplicationLog::new_log(@task_list, @logged_user, :delete, @task_list.is_private)
@task_list.destroy
flash[:flash_success] = "Successfully deleted task"
redirect_back_or_default :controller => 'milestone'
end
def reorder_tasks
end
# Tasks
def add_task
begin
@task_list = ProjectTaskList.find(params[:task_list_id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task list"
if params[:partial]
render :text => '403 Invalid', :status => 403
else
redirect_back_or_default :controller => 'task'
end
return
end
if not ProjectTask.can_be_created_by(@logged_user, @task_list.project)
flash[:flash_error] = "Insufficient permissions"
if params[:partial]
render :text => '403 Invalid', :status => 403
else
redirect_back_or_default :controller => 'task'
end
return
end
@task = ProjectTask.new
case request.method
when :post
task_attribs = params[:task]
@task.update_attributes(task_attribs)
@task.created_by = @logged_user
@task.task_list = @task_list
if @task.save
ApplicationLog::new_log(@task, @logged_user, :add, @task_list.is_private, @active_project)
flash[:flash_success] = "Successfully added task"
if params[:partial]
puts "RENDERING PARTIAL!!!"
render :partial => 'task/task_item', :collection => [@task]
else
redirect_back_or_default :controller => 'task'
end
elsif params[:partial]
render :text => 'Validation failed', :status => 400
end
end
end
def edit_task
begin
@task = ProjectTask.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task.can_be_changed_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
case request.method
when :post
task_attribs = params[:task]
@task.update_attributes(task_attribs)
@task.updated_by = @logged_user
if @task.save
ApplicationLog::new_log(@task, @logged_user, :edit, @task.task_list.is_private, @active_project)
flash[:flash_success] = "Successfully modified task"
redirect_back_or_default :controller => 'task'
end
end
end
def delete_task
begin
@task = ProjectTask.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task.can_be_deleted_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
ApplicationLog::new_log(@task, @logged_user, :delete, @task.task_list.is_private, @active_project)
@task.destroy
flash[:flash_success] = "Successfully deleted task"
redirect_back_or_default :controller => 'milestone'
end
def complete_task
begin
@task = ProjectTask.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task.can_be_changed_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
if not @task.completed_by.nil?
flash[:flash_error] = "Task already completed"
redirect_back_or_default :controller => 'task'
return
end
@task.completed_on = Time.now.utc
@task.completed_by = @logged_user
if @task.valid?
ApplicationLog::new_log(@task, @logged_user, :close, @task.task_list.is_private, @active_project)
end
if not @task.save
flash[:flash_error] = "Error saving"
else
# add a log entry for the task list
if @task.task_list.finished_all_tasks?
ApplicationLog::new_log(@task.task_list, @task.completed_by, :close, false)
end
end
redirect_back_or_default :controller => 'task'
end
def open_task
begin
@task = ProjectTask.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task.can_be_changed_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
if @task.completed_by.nil?
flash[:flash_error] = "Task already open"
redirect_back_or_default :controller => 'task'
return
end
@task.completed_on = 0
@task.completed_by = nil
if not @task.save
flash[:flash_error] = "Error saving"
else
if not @task.task_list.finished_all_tasks?
ApplicationLog::new_log(@task.task_list, @logged_user, :open, @task.task_list.is_private)
end
ApplicationLog::new_log(@task, @logged_user, :open, @task.task_list.is_private, @active_project)
end
redirect_back_or_default :controller => 'task'
end
end
- Remove silly debug print
git-svn-id: c56bb3f9cb1c9468aec8fd62c717d587012de106@143 1e8d30c7-b1cd-4b0d-952e-12ddc4cacc65
=begin
RailsCollab
-----------
Copyright (C) 2007 James S Urquhart (jamesu at gmail.com)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
=end
class TaskController < ApplicationController
layout 'project_website'
verify :method => :post,
:only => [ :delete_list, :delete_task, :open_task, :complete_task ],
:add_flash => { :flash_error => "Invalid request" },
:redirect_to => { :controller => 'project' }
before_filter :login_required
before_filter :process_session
after_filter :user_track, :only => [:index, :view_list]
def index
@open_task_lists = @active_project.open_task_lists
@completed_task_lists = @active_project.completed_task_lists
@content_for_sidebar = 'index_sidebar'
end
# Task lists
def view_list
begin
@task_list = ProjectTaskList.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task list"
redirect_back_or_default :controller => 'task', :action => 'index'
return
end
if not @task_list.can_be_seen_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task', :action => 'index'
return
end
@open_task_lists = @active_project.open_task_lists
@completed_task_lists = @active_project.completed_task_lists
@content_for_sidebar = 'index_sidebar'
end
def add_list
if not ProjectTaskList.can_be_created_by(@logged_user, @active_project)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
@task_list = ProjectTaskList.new
case request.method
when :get
begin
@task_list.project_milestone = ProjectMilestone.find(params[:milestone_id])
@task_list.is_private = @task_list.project_milestone.is_private
rescue ActiveRecord::RecordNotFound
@task_list.milestone_id = 0
@task_list.is_private = false
end
when :post
task_attribs = params[:task_list]
@task_list.update_attributes(task_attribs)
@task_list.created_by = @logged_user
@task_list.project = @active_project
@task_list.is_private = task_attribs[:is_private] if @logged_user.member_of_owner?
if @task_list.save
ApplicationLog::new_log(@task_list, @logged_user, :add, @task_list.is_private)
@task_list.tags = task_attribs[:tags]
flash[:flash_success] = "Successfully added task"
redirect_back_or_default :controller => 'task'
end
end
end
def edit_list
begin
@task_list = ProjectTaskList.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task_list.can_be_changed_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
case request.method
when :post
task_attribs = params[:task_list]
@task_list.update_attributes(task_attribs)
@task_list.updated_by = @logged_user
@task_list.tags = task_attribs[:tags]
@task_list.is_private = task_attribs[:is_private] if @logged_user.member_of_owner?
if @task_list.save
ApplicationLog::new_log(@task_list, @logged_user, :edit, @task_list.is_private)
flash[:flash_success] = "Successfully modified task"
redirect_back_or_default :controller => 'task'
end
end
end
def delete_list
begin
@task_list = ProjectTaskList.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task_list.can_be_deleted_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
ApplicationLog::new_log(@task_list, @logged_user, :delete, @task_list.is_private)
@task_list.destroy
flash[:flash_success] = "Successfully deleted task"
redirect_back_or_default :controller => 'milestone'
end
def reorder_tasks
end
# Tasks
def add_task
begin
@task_list = ProjectTaskList.find(params[:task_list_id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task list"
if params[:partial]
render :text => '403 Invalid', :status => 403
else
redirect_back_or_default :controller => 'task'
end
return
end
if not ProjectTask.can_be_created_by(@logged_user, @task_list.project)
flash[:flash_error] = "Insufficient permissions"
if params[:partial]
render :text => '403 Invalid', :status => 403
else
redirect_back_or_default :controller => 'task'
end
return
end
@task = ProjectTask.new
case request.method
when :post
task_attribs = params[:task]
@task.update_attributes(task_attribs)
@task.created_by = @logged_user
@task.task_list = @task_list
if @task.save
ApplicationLog::new_log(@task, @logged_user, :add, @task_list.is_private, @active_project)
flash[:flash_success] = "Successfully added task"
if params[:partial]
render :partial => 'task/task_item', :collection => [@task]
else
redirect_back_or_default :controller => 'task'
end
elsif params[:partial]
render :text => 'Validation failed', :status => 400
end
end
end
def edit_task
begin
@task = ProjectTask.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task.can_be_changed_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
case request.method
when :post
task_attribs = params[:task]
@task.update_attributes(task_attribs)
@task.updated_by = @logged_user
if @task.save
ApplicationLog::new_log(@task, @logged_user, :edit, @task.task_list.is_private, @active_project)
flash[:flash_success] = "Successfully modified task"
redirect_back_or_default :controller => 'task'
end
end
end
def delete_task
begin
@task = ProjectTask.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task.can_be_deleted_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
ApplicationLog::new_log(@task, @logged_user, :delete, @task.task_list.is_private, @active_project)
@task.destroy
flash[:flash_success] = "Successfully deleted task"
redirect_back_or_default :controller => 'milestone'
end
def complete_task
begin
@task = ProjectTask.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task.can_be_changed_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
if not @task.completed_by.nil?
flash[:flash_error] = "Task already completed"
redirect_back_or_default :controller => 'task'
return
end
@task.completed_on = Time.now.utc
@task.completed_by = @logged_user
if @task.valid?
ApplicationLog::new_log(@task, @logged_user, :close, @task.task_list.is_private, @active_project)
end
if not @task.save
flash[:flash_error] = "Error saving"
else
# add a log entry for the task list
if @task.task_list.finished_all_tasks?
ApplicationLog::new_log(@task.task_list, @task.completed_by, :close, false)
end
end
redirect_back_or_default :controller => 'task'
end
def open_task
begin
@task = ProjectTask.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:flash_error] = "Invalid task"
redirect_back_or_default :controller => 'task'
return
end
if not @task.can_be_changed_by(@logged_user)
flash[:flash_error] = "Insufficient permissions"
redirect_back_or_default :controller => 'task'
return
end
if @task.completed_by.nil?
flash[:flash_error] = "Task already open"
redirect_back_or_default :controller => 'task'
return
end
@task.completed_on = 0
@task.completed_by = nil
if not @task.save
flash[:flash_error] = "Error saving"
else
if not @task.task_list.finished_all_tasks?
ApplicationLog::new_log(@task.task_list, @logged_user, :open, @task.task_list.is_private)
end
ApplicationLog::new_log(@task, @logged_user, :open, @task.task_list.is_private, @active_project)
end
redirect_back_or_default :controller => 'task'
end
end
|
cask 'logitech-options' do
version '7.00.554'
sha256 'cd3467a7147640fbdd07958ca7e3039c75c092cb9b1118dc4304f0e363d06c58'
url "https://www.logitech.com/pub/techsupport/options/Options_#{version}.zip"
name 'Logitech Options'
homepage 'https://support.logitech.com/en_us/software/options'
auto_updates true
depends_on macos: '>= :el_capitan'
pkg "LogiMgr Installer #{version}.app/Contents/Resources/LogiMgr.mpkg"
uninstall script: {
executable: '/Applications/Utilities/LogiMgr Uninstaller.app/Contents/Resources/Uninstaller',
},
pkgutil: [
'com.logitech.manager.pkg',
'com.Logitech.signedKext.pkg',
],
launchctl: 'com.logitech.manager.daemon'
caveats do
reboot
end
end
Update logitech-options to 7.10.5 (#687)
cask 'logitech-options' do
version '7.10.5'
sha256 '23b90c5f6c232fa80b5e48e85815eb94ad873c92285f6b24066eeb28251b6660'
url "https://www.logitech.com/pub/techsupport/options/Options_#{version}.zip"
name 'Logitech Options'
homepage 'https://support.logitech.com/en_us/software/options'
auto_updates true
depends_on macos: '>= :el_capitan'
pkg "LogiMgr Installer #{version}.app/Contents/Resources/LogiMgr.mpkg"
uninstall script: {
executable: '/Applications/Utilities/LogiMgr Uninstaller.app/Contents/Resources/Uninstaller',
},
pkgutil: [
'com.logitech.manager.pkg',
'com.Logitech.signedKext.pkg',
],
launchctl: 'com.logitech.manager.daemon'
caveats do
reboot
end
end
|
class Atmos < Formula
desc "Universal Tool for DevOps and Cloud Automation"
homepage "https://github.com/cloudposse/atmos"
url "https://github.com/cloudposse/atmos/archive/v1.12.2.tar.gz"
sha256 "d2eed4ff679eb6386ca2cdd3bd8c74c3b6ac513da7c8af15e5f8147648081107"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_ventura: "bfbddf0e8711c7b1ac442111220063df043f0de98d7b8cdd7096087b7f8df3e9"
sha256 cellar: :any_skip_relocation, arm64_monterey: "c35fbbe19dac1551ce7ed71bda363ce23d373c2faad39bf2afe5b4fe7269cd3f"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "090c015034eafc00d7bc33467d1acf1df7f17922c6fc9f8d712e61e1093140af"
sha256 cellar: :any_skip_relocation, monterey: "ea2282c3f4149a6dd595f760acbc97fe26d088a8837238bb0e1afb7ac4a0e3ef"
sha256 cellar: :any_skip_relocation, big_sur: "b3ce0d4a066a1c1eac19cbd62f564768e8bb0f56d50432c684a791b8c5fb72e7"
sha256 cellar: :any_skip_relocation, catalina: "aa80205593422d5754bd18eaf8124ec081207023c9571503bdd657eb6467be5e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "0e13eb032fda14e7e84b92c0adfc87a5eeca15538fc3a9279aaf0a1d48b898b1"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args(ldflags: "-s -w -X 'github.com/cloudposse/atmos/cmd.Version=#{version}'")
generate_completions_from_executable(bin/"atmos", "completion")
end
test do
# create basic atmos.yaml
(testpath/"atmos.yaml").write <<~EOT
components:
terraform:
base_path: "./components/terraform"
apply_auto_approve: false
deploy_run_init: true
auto_generate_backend_file: false
helmfile:
base_path: "./components/helmfile"
kubeconfig_path: "/dev/shm"
helm_aws_profile_pattern: "{namespace}-{tenant}-gbl-{stage}-helm"
cluster_name_pattern: "{namespace}-{tenant}-{environment}-{stage}-eks-cluster"
stacks:
base_path: "./stacks"
included_paths:
- "**/*"
excluded_paths:
- "globals/**/*"
- "catalog/**/*"
- "**/*globals*"
name_pattern: "{tenant}-{environment}-{stage}"
logs:
verbose: false
colors: true
EOT
# create scaffold
mkdir_p testpath/"stacks"
mkdir_p testpath/"components/terraform/top-level-component1"
(testpath/"stacks/tenant1-ue2-dev.yaml").write <<~EOT
terraform:
backend_type: s3 # s3, remote, vault, static, etc.
backend:
s3:
encrypt: true
bucket: "eg-ue2-root-tfstate"
key: "terraform.tfstate"
dynamodb_table: "eg-ue2-root-tfstate-lock"
acl: "bucket-owner-full-control"
region: "us-east-2"
role_arn: null
remote:
vault:
vars:
tenant: tenant1
region: us-east-2
environment: ue2
stage: dev
components:
terraform:
top-level-component1: {}
EOT
# create expected file
(testpath/"backend.tf.json").write <<~EOT
{
"terraform": {
"backend": {
"s3": {
"workspace_key_prefix": "top-level-component1",
"acl": "bucket-owner-full-control",
"bucket": "eg-ue2-root-tfstate",
"dynamodb_table": "eg-ue2-root-tfstate-lock",
"encrypt": true,
"key": "terraform.tfstate",
"region": "us-east-2",
"role_arn": null
}
}
}
}
EOT
system bin/"atmos", "terraform", "generate", "backend", "top-level-component1", "--stack", "tenant1-ue2-dev"
actual_json = JSON.parse(File.read(testpath/"components/terraform/top-level-component1/backend.tf.json"))
expected_json = JSON.parse(File.read(testpath/"backend.tf.json"))
assert_equal expected_json["terraform"].to_set, actual_json["terraform"].to_set
end
end
atmos 1.13.1
Created by https://github.com/mislav/bump-homebrew-formula-action
Closes #115500.
Signed-off-by: Rui Chen <907c7afd57be493757f13ccd1dd45dddf02db069@chenrui.dev>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Atmos < Formula
desc "Universal Tool for DevOps and Cloud Automation"
homepage "https://github.com/cloudposse/atmos"
url "https://github.com/cloudposse/atmos/archive/v1.13.1.tar.gz"
sha256 "1061067d1469b6d48d3cdce3a64139e7f9b6198012ff5f773cdf084beb619084"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_ventura: "bfbddf0e8711c7b1ac442111220063df043f0de98d7b8cdd7096087b7f8df3e9"
sha256 cellar: :any_skip_relocation, arm64_monterey: "c35fbbe19dac1551ce7ed71bda363ce23d373c2faad39bf2afe5b4fe7269cd3f"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "090c015034eafc00d7bc33467d1acf1df7f17922c6fc9f8d712e61e1093140af"
sha256 cellar: :any_skip_relocation, monterey: "ea2282c3f4149a6dd595f760acbc97fe26d088a8837238bb0e1afb7ac4a0e3ef"
sha256 cellar: :any_skip_relocation, big_sur: "b3ce0d4a066a1c1eac19cbd62f564768e8bb0f56d50432c684a791b8c5fb72e7"
sha256 cellar: :any_skip_relocation, catalina: "aa80205593422d5754bd18eaf8124ec081207023c9571503bdd657eb6467be5e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "0e13eb032fda14e7e84b92c0adfc87a5eeca15538fc3a9279aaf0a1d48b898b1"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args(ldflags: "-s -w -X 'github.com/cloudposse/atmos/cmd.Version=#{version}'")
generate_completions_from_executable(bin/"atmos", "completion")
end
test do
# create basic atmos.yaml
(testpath/"atmos.yaml").write <<~EOT
components:
terraform:
base_path: "./components/terraform"
apply_auto_approve: false
deploy_run_init: true
auto_generate_backend_file: false
helmfile:
base_path: "./components/helmfile"
kubeconfig_path: "/dev/shm"
helm_aws_profile_pattern: "{namespace}-{tenant}-gbl-{stage}-helm"
cluster_name_pattern: "{namespace}-{tenant}-{environment}-{stage}-eks-cluster"
stacks:
base_path: "./stacks"
included_paths:
- "**/*"
excluded_paths:
- "globals/**/*"
- "catalog/**/*"
- "**/*globals*"
name_pattern: "{tenant}-{environment}-{stage}"
logs:
verbose: false
colors: true
EOT
# create scaffold
mkdir_p testpath/"stacks"
mkdir_p testpath/"components/terraform/top-level-component1"
(testpath/"stacks/tenant1-ue2-dev.yaml").write <<~EOT
terraform:
backend_type: s3 # s3, remote, vault, static, etc.
backend:
s3:
encrypt: true
bucket: "eg-ue2-root-tfstate"
key: "terraform.tfstate"
dynamodb_table: "eg-ue2-root-tfstate-lock"
acl: "bucket-owner-full-control"
region: "us-east-2"
role_arn: null
remote:
vault:
vars:
tenant: tenant1
region: us-east-2
environment: ue2
stage: dev
components:
terraform:
top-level-component1: {}
EOT
# create expected file
(testpath/"backend.tf.json").write <<~EOT
{
"terraform": {
"backend": {
"s3": {
"workspace_key_prefix": "top-level-component1",
"acl": "bucket-owner-full-control",
"bucket": "eg-ue2-root-tfstate",
"dynamodb_table": "eg-ue2-root-tfstate-lock",
"encrypt": true,
"key": "terraform.tfstate",
"region": "us-east-2",
"role_arn": null
}
}
}
}
EOT
system bin/"atmos", "terraform", "generate", "backend", "top-level-component1", "--stack", "tenant1-ue2-dev"
actual_json = JSON.parse(File.read(testpath/"components/terraform/top-level-component1/backend.tf.json"))
expected_json = JSON.parse(File.read(testpath/"backend.tf.json"))
assert_equal expected_json["terraform"].to_set, actual_json["terraform"].to_set
end
end
|
class UserController < ApplicationController
before_action :user_logged?
def index
@user = User.find(session[:user_id])
@exams = exams_belonging_user
@completed_exam = CompletedExam.where(user_id: @user.id)
end
def user_exam
@exam = Exam.find(params[:id])
@video = @exam.video_id
@questions = @exam.questions
end
def user_exam_save
puts "*"*100, params
exam = Exam.find(params[:id])
delete_old_completed_exam exam.id
score = calculate_score params
new_completed_exam exam, score
redirect_to user_path
end
def change_password
@user = User.find(session[:user_id])
end
def update_password
@user = User.find(session[:user_id])
if can_change_password?
@user.password_digest = params[:new_password]
@user.save
end
redirect_to user_edit_info_path
end
def user_edit_info
@user = User.find(session[:user_id])
@genders = User.genders
end
def user_update_info
@user = User.find(session[:user_id])
if @user.id.to_s == params[:id]
@user.name = params[:user][:name]
@user.gender = params[:user][:gender]
@user.save
end
redirect_to user_path
end
private
def can_change_password?
old_password_is_right? and new_password_is_right?
end
def new_password_is_right?
params[:new_password] == params[:repeat_new_password]
end
def old_password_is_right?
@user.password_digest == params[:old_password]
end
def calculate_score params
score = 0
params.each do | key, value |
if key.to_i != 0
answer = Answer.find(value.to_i)
score += 1 if answer.right == '1'
end
end
score
end
def delete_old_completed_exam exam_id
old_completed_exam = CompletedExam.where(user_id: session[:user_id]).where(exam_id: exam_id)
old_completed_exam.first.destroy unless old_completed_exam.empty?
end
def new_completed_exam exam, score
completed_exam = CompletedExam.new({
:user_id => session[:user_id],
:questions => exam.questions.count,
:score => score,
:exam_id => exam.id
})
completed_exam.save
end
def user_logged?
redirect_to signin_path unless session[:user_id]
end
def exams_belonging_user
level = @user.level.to_i
exams = []
Exam.order_by_position.each do |exam|
exams << exam if exam.level.to_i <= level
end
exams
end
end
Removed ramdom puts ;P
class UserController < ApplicationController
before_action :user_logged?
def index
@user = User.find(session[:user_id])
@exams = exams_belonging_user
@completed_exam = CompletedExam.where(user_id: @user.id)
end
def user_exam
@exam = Exam.find(params[:id])
@video = @exam.video_id
@questions = @exam.questions
end
def user_exam_save
exam = Exam.find(params[:id])
delete_old_completed_exam exam.id
score = calculate_score params
new_completed_exam exam, score
redirect_to user_path
end
def change_password
@user = User.find(session[:user_id])
end
def update_password
@user = User.find(session[:user_id])
if can_change_password?
@user.password_digest = params[:new_password]
@user.save
end
redirect_to user_edit_info_path
end
def user_edit_info
@user = User.find(session[:user_id])
@genders = User.genders
end
def user_update_info
@user = User.find(session[:user_id])
if @user.id.to_s == params[:id]
@user.name = params[:user][:name]
@user.gender = params[:user][:gender]
@user.save
end
redirect_to user_path
end
private
def can_change_password?
old_password_is_right? and new_password_is_right?
end
def new_password_is_right?
params[:new_password] == params[:repeat_new_password]
end
def old_password_is_right?
@user.password_digest == params[:old_password]
end
def calculate_score params
score = 0
params.each do | key, value |
if key.to_i != 0
answer = Answer.find(value.to_i)
score += 1 if answer.right == '1'
end
end
score
end
def delete_old_completed_exam exam_id
old_completed_exam = CompletedExam.where(user_id: session[:user_id]).where(exam_id: exam_id)
old_completed_exam.first.destroy unless old_completed_exam.empty?
end
def new_completed_exam exam, score
completed_exam = CompletedExam.new({
:user_id => session[:user_id],
:questions => exam.questions.count,
:score => score,
:exam_id => exam.id
})
completed_exam.save
end
def user_logged?
redirect_to signin_path unless session[:user_id]
end
def exams_belonging_user
level = @user.level.to_i
exams = []
Exam.order_by_position.each do |exam|
exams << exam if exam.level.to_i <= level
end
exams
end
end
|
cask "macloggerdx-beta" do
version "6.43b30"
sha256 :no_check
url "https://www.dogparksoftware.com/files/MacLoggerDX.beta.dmg"
name "MacLoggerDX"
desc "Ham radio logging and rig control software"
homepage "https://www.dogparksoftware.com/MacLoggerDX.html"
livecheck do
url :homepage
regex(/Download:\s*v?(\d+(?:\.\d+)+b\d+)/i)
end
conflicts_with cask: "macloggerdx"
depends_on macos: ">= :high_sierra"
app "MacLoggerDX.app"
zap trash: [
"~/Library/Caches/com.apple.helpd/Generated/MacLoggerDX Help*",
"~/Library/Caches/com.dogparksoftware.MacLoggerDX",
"~/Library/HTTPStorages/com.dogparksoftware.MacLoggerDX",
"~/Library/Preferences/com.dogparksoftware.MacLoggerDX*.plist",
]
end
Update macloggerdx-beta from 6.43b30 to 6.43b31 (#14972)
Co-authored-by: Eric Macauley <0a53f2a8ec306b66af9534c7d256540499e07db9@users.noreply.github.com>
cask "macloggerdx-beta" do
version "6.43b31"
sha256 :no_check
url "https://www.dogparksoftware.com/files/MacLoggerDX.beta.dmg"
name "MacLoggerDX"
desc "Ham radio logging and rig control software"
homepage "https://www.dogparksoftware.com/MacLoggerDX.html"
livecheck do
url :homepage
regex(/Download:\s*v?(\d+(?:\.\d+)+b\d+)/i)
end
conflicts_with cask: "macloggerdx"
depends_on macos: ">= :high_sierra"
app "MacLoggerDX.app"
zap trash: [
"~/Library/Caches/com.apple.helpd/Generated/MacLoggerDX Help*",
"~/Library/Caches/com.dogparksoftware.MacLoggerDX",
"~/Library/HTTPStorages/com.dogparksoftware.MacLoggerDX",
"~/Library/Preferences/com.dogparksoftware.MacLoggerDX*.plist",
]
end
|
class Atmos < Formula
desc "Universal Tool for DevOps and Cloud Automation"
homepage "https://github.com/cloudposse/atmos"
url "https://github.com/cloudposse/atmos/archive/v1.4.8.tar.gz"
sha256 "40b141f835fe53321b1a7696fade046c3d21b0b8c14518a0249b1b655a042dbc"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "d8924d613f715700c084349af5eb0cf5488261c6f820fbe91b1fd753492f4ba4"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "b1f20daf91cada69d5786850c7a21936a8f3468c2c4571e3e8ffb08dcbeaa2dc"
sha256 cellar: :any_skip_relocation, monterey: "7279253467d9b62a2f7267280f6bfb4d9efc38a8c3be161ad976e7ba0200b027"
sha256 cellar: :any_skip_relocation, big_sur: "2492a64f7ebad97b70b7cb6b20637cc2513e9a38d2ffa055fa5d9c2bc9de07d1"
sha256 cellar: :any_skip_relocation, catalina: "fa9d96c2151392b84175231e559583b3c164a508e2e172de665d36b47b851ccf"
sha256 cellar: :any_skip_relocation, x86_64_linux: "5c60bb20e265bb04ccf8dcd1c2a1a36cf5b7f1b74c229dc1be8a6802f95f040f"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args(ldflags: "-s -w -X 'github.com/cloudposse/atmos/cmd.Version=#{version}'")
end
test do
# create basic atmos.yaml
(testpath/"atmos.yaml").write <<~EOT
components:
terraform:
base_path: "./components/terraform"
apply_auto_approve: false
deploy_run_init: true
auto_generate_backend_file: false
helmfile:
base_path: "./components/helmfile"
kubeconfig_path: "/dev/shm"
helm_aws_profile_pattern: "{namespace}-{tenant}-gbl-{stage}-helm"
cluster_name_pattern: "{namespace}-{tenant}-{environment}-{stage}-eks-cluster"
stacks:
base_path: "./stacks"
included_paths:
- "**/*"
excluded_paths:
- "globals/**/*"
- "catalog/**/*"
- "**/*globals*"
name_pattern: "{tenant}-{environment}-{stage}"
logs:
verbose: false
colors: true
EOT
# create scaffold
mkdir_p testpath/"stacks"
mkdir_p testpath/"components/terraform/top-level-component1"
(testpath/"stacks/tenant1-ue2-dev.yaml").write <<~EOT
terraform:
backend_type: s3 # s3, remote, vault, static, etc.
backend:
s3:
encrypt: true
bucket: "eg-ue2-root-tfstate"
key: "terraform.tfstate"
dynamodb_table: "eg-ue2-root-tfstate-lock"
acl: "bucket-owner-full-control"
region: "us-east-2"
role_arn: null
remote:
vault:
vars:
tenant: tenant1
region: us-east-2
environment: ue2
stage: dev
components:
terraform:
top-level-component1: {}
EOT
# create expected file
(testpath/"backend.tf.json").write <<~EOT
{
"terraform": {
"backend": {
"s3": {
"workspace_key_prefix": "top-level-component1",
"acl": "bucket-owner-full-control",
"bucket": "eg-ue2-root-tfstate",
"dynamodb_table": "eg-ue2-root-tfstate-lock",
"encrypt": true,
"key": "terraform.tfstate",
"region": "us-east-2",
"role_arn": null
}
}
}
}
EOT
system bin/"atmos", "terraform", "generate", "backend", "top-level-component1", "--stack", "tenant1-ue2-dev"
actual_json = JSON.parse(File.read(testpath/"components/terraform/top-level-component1/backend.tf.json"))
expected_json = JSON.parse(File.read(testpath/"backend.tf.json"))
assert_equal expected_json["terraform"].to_set, actual_json["terraform"].to_set
end
end
atmos: update 1.4.8 bottle.
class Atmos < Formula
desc "Universal Tool for DevOps and Cloud Automation"
homepage "https://github.com/cloudposse/atmos"
url "https://github.com/cloudposse/atmos/archive/v1.4.8.tar.gz"
sha256 "40b141f835fe53321b1a7696fade046c3d21b0b8c14518a0249b1b655a042dbc"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "26f311e2e549e7df8e06e6bf4add0c9a80dee22ac2c29315bbdfa4d5d9ea73d5"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "2c0e323c7d07345a4566c337821cc6e76c9eba5d529e66953f332b03e4ed811e"
sha256 cellar: :any_skip_relocation, monterey: "58e439c9d448ab1b2b32e8064ff22d80bd433f71472971a62b3e998fc4ca779c"
sha256 cellar: :any_skip_relocation, big_sur: "307e2fe67a999319dc5f580e18cea1cd4f2a1408ea8e56c15bc57cc1a1302de6"
sha256 cellar: :any_skip_relocation, catalina: "0e41df43e35ee99cb28c7966a9f4367bfbd23b3e5756787ee7cb1d5ee0e1a96b"
sha256 cellar: :any_skip_relocation, x86_64_linux: "398c298513f96010481a5d2f860e67deadeb55a2c4ceaefcb23dede35bcebef0"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args(ldflags: "-s -w -X 'github.com/cloudposse/atmos/cmd.Version=#{version}'")
end
test do
# create basic atmos.yaml
(testpath/"atmos.yaml").write <<~EOT
components:
terraform:
base_path: "./components/terraform"
apply_auto_approve: false
deploy_run_init: true
auto_generate_backend_file: false
helmfile:
base_path: "./components/helmfile"
kubeconfig_path: "/dev/shm"
helm_aws_profile_pattern: "{namespace}-{tenant}-gbl-{stage}-helm"
cluster_name_pattern: "{namespace}-{tenant}-{environment}-{stage}-eks-cluster"
stacks:
base_path: "./stacks"
included_paths:
- "**/*"
excluded_paths:
- "globals/**/*"
- "catalog/**/*"
- "**/*globals*"
name_pattern: "{tenant}-{environment}-{stage}"
logs:
verbose: false
colors: true
EOT
# create scaffold
mkdir_p testpath/"stacks"
mkdir_p testpath/"components/terraform/top-level-component1"
(testpath/"stacks/tenant1-ue2-dev.yaml").write <<~EOT
terraform:
backend_type: s3 # s3, remote, vault, static, etc.
backend:
s3:
encrypt: true
bucket: "eg-ue2-root-tfstate"
key: "terraform.tfstate"
dynamodb_table: "eg-ue2-root-tfstate-lock"
acl: "bucket-owner-full-control"
region: "us-east-2"
role_arn: null
remote:
vault:
vars:
tenant: tenant1
region: us-east-2
environment: ue2
stage: dev
components:
terraform:
top-level-component1: {}
EOT
# create expected file
(testpath/"backend.tf.json").write <<~EOT
{
"terraform": {
"backend": {
"s3": {
"workspace_key_prefix": "top-level-component1",
"acl": "bucket-owner-full-control",
"bucket": "eg-ue2-root-tfstate",
"dynamodb_table": "eg-ue2-root-tfstate-lock",
"encrypt": true,
"key": "terraform.tfstate",
"region": "us-east-2",
"role_arn": null
}
}
}
}
EOT
system bin/"atmos", "terraform", "generate", "backend", "top-level-component1", "--stack", "tenant1-ue2-dev"
actual_json = JSON.parse(File.read(testpath/"components/terraform/top-level-component1/backend.tf.json"))
expected_json = JSON.parse(File.read(testpath/"backend.tf.json"))
assert_equal expected_json["terraform"].to_set, actual_json["terraform"].to_set
end
end
|
cask :v1 => 'mendeley-desktop' do
version '1.13.5'
sha256 '99cc040095b198c984f8193eb7b5da4c39bbf77ac1b715161b4036ca7d55db35'
url "http://desktop-download.mendeley.com/download/Mendeley-Desktop-#{version}-OSX-Universal.dmg"
name 'Mendeley'
homepage 'http://www.mendeley.com/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Mendeley Desktop.app'
end
Upgrade Mendeley Desktop to v1.13.6
cask :v1 => 'mendeley-desktop' do
version '1.13.6'
sha256 '77eef115c488662494b2fcdcbbddcdde63bfe7d81800e5445a02228a0630160e'
url "http://desktop-download.mendeley.com/download/Mendeley-Desktop-#{version}-OSX-Universal.dmg"
name 'Mendeley'
homepage 'http://www.mendeley.com/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Mendeley Desktop.app'
end
|
class Atool < Formula
desc "Archival front-end"
homepage "https://savannah.nongnu.org/projects/atool/"
url "https://savannah.nongnu.org/download/atool/atool-0.39.0.tar.gz"
sha256 "aaf60095884abb872e25f8e919a8a63d0dabaeca46faeba87d12812d6efc703b"
bottle do
cellar :any_skip_relocation
revision 2
sha256 "dcfdcb720aa3704b9103aa01bb8efac42d24327bc8664baa420a9a69d75a98b6" => :el_capitan
sha256 "efdeeb165e146f4a76477417d2af9c60e2f776d06081bb579ff73ceb296a899d" => :yosemite
sha256 "4eed286344a3a1d4fc6efc908b34062b5cc7c7fdf2449cf85b7767168585fc7a" => :mavericks
end
def install
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
mkdir "apple_juice"
cd testpath/"apple_juice" do
touch "example.txt"
touch "example2.txt"
system bin/"apack", "test.tar.gz", "example.txt", "example2.txt"
end
output = shell_output("#{bin}/als #{testpath}/apple_juice/test.tar.gz")
assert_match "example.txt", output
assert_match "example2.txt", output
end
end
atool: Build a bottle for Linuxbrew
Closes Linuxbrew/homebrew-core#420.
Signed-off-by: Bob W. Hogg <c772a964fd55352a3510e5d535dd9ccc9ac30168@linux.com>
# atool: Build a bottle for Linuxbrew
class Atool < Formula
desc "Archival front-end"
homepage "https://savannah.nongnu.org/projects/atool/"
url "https://savannah.nongnu.org/download/atool/atool-0.39.0.tar.gz"
sha256 "aaf60095884abb872e25f8e919a8a63d0dabaeca46faeba87d12812d6efc703b"
bottle do
cellar :any_skip_relocation
revision 2
sha256 "dcfdcb720aa3704b9103aa01bb8efac42d24327bc8664baa420a9a69d75a98b6" => :el_capitan
sha256 "efdeeb165e146f4a76477417d2af9c60e2f776d06081bb579ff73ceb296a899d" => :yosemite
sha256 "4eed286344a3a1d4fc6efc908b34062b5cc7c7fdf2449cf85b7767168585fc7a" => :mavericks
end
def install
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
mkdir "apple_juice"
cd testpath/"apple_juice" do
touch "example.txt"
touch "example2.txt"
system bin/"apack", "test.tar.gz", "example.txt", "example2.txt"
end
output = shell_output("#{bin}/als #{testpath}/apple_juice/test.tar.gz")
assert_match "example.txt", output
assert_match "example2.txt", output
end
end
|
#Use for loading xml based metadata for a dataset. Can be used to reload metadata file
#even if the database already has variables for that survey. Change the survey_id to
#match the appropriate year and the parser to load the correct xml file
require 'rubygems'
require 'rake'
require 'model_execution'
require 'active_record/fixtures'
require 'xml'
namespace :obesity do
desc "load metadata from xml"
task :load_single_metadata => :environment do
parser = XML::Parser.file('/Users/Ian/scratch/hse_xml_metadata/hse2007.xml')
doc = parser.parse
survey_id = 16
survey = Survey.find(survey_id)
datasets = survey.datasets
datasets.each do |dataset|
puts "DATASET: " + dataset.name
dataset_id=dataset.id
nodes = doc.find('//metadata/variable')
nodes.each do |node|
namenode = node.find('child::name')
namecontent = namenode.first.content
print " NAME: " + namecontent
variable_name = namecontent
descnode = node.find('child::description')
desccontent = descnode.first.content
print " DESC: " + desccontent
variable_value = desccontent
catnode = node.find('child::category')
catcontent = catnode.first.content
print " CAT: " + catcontent
variable_category = catcontent
dernode = node.find('child::derivation')
dercontent = dernode.first
dertype = dercontent.find('child::type')
if dertype.first != nil
dertypecontent = dertype.first.content
variable_dertype = dertypecontent
print " TYPE: " + dertypecontent
else
print "TYPE: NIL"
end
dermethod = dercontent.find('child::method')
if dermethod.first != nil
dermethodcontent = dermethod.first.content
variable_dermethod = dermethodcontent
page = dermethod[0].[]("page")
document = dermethod[0].[]("document")
print "METHOD: " + dermethodcontent
if page != nil
print " page: " + page + " document: " + document
end
else
print "METHOD: NIL"
end
infonode = node.find('child::information')
infocontent = infonode.first.content
variable_info = infocontent
print "INFO: " + infocontent
v = Variable.find(:all,:conditions=> "dataset_id=" + dataset_id.to_s + " and name='" + variable_name+"'")
if (v[0]!= nil)
puts "Found Variable " + v[0].name
# v[0].value= variable_value
# v[0].dertype = variable_dertype
# v[0].dermethod = variable_dermethod
# v[0].info = variable_info
# v[0].category = variable_category
# v[0].save
if v[0].update_attributes(:value=>variable_value, :dertype=>variable_dertype, :dermethod=>variable_dermethod, :info=>variable_info,:category=>variable_category, :page=>page, :document=>document)
puts "Update success"
else
v[0].errors.full_messages.to_sentence
end
else
puts "Could not find " + variable_name + " in " + dataset.name
# variable = Variable.new
# variable.name = variable_name
# variable.value= variable_value
# variable.dertype = variable_dertype
# variable.dermethod = variable_dermethod
# variable.info = variable_info
# variable.category = variable_category
# variable.survey_id = survey_id;
# variable.save
end
# infonode = node.find('child::information')
# if infonode.length>=1
# infochildren = infonode[0].find('child::info')
# infochildren.each do |childnode|
# valnode = childnode.first
# valvalue = valnode.first.content
# labelnode = valnode.next
# labelvalue = labelnode.first.content
# print valvalue
# print labelvalue
# end
# end
end
end
end
end
now adds new variables that were not in the database
#Use for loading xml based metadata for a dataset. Can be used to reload metadata file
#even if the database already has variables for that survey. Change the survey_id to
#match the appropriate year and the parser to load the correct xml file
require 'rubygems'
require 'rake'
require 'model_execution'
require 'active_record/fixtures'
require 'xml'
namespace :obesity do
desc "load metadata from xml"
task :load_single_metadata => :environment do
parser = XML::Parser.file('/Users/Ian/Downloads/output/HSE-2001-hse01ai--2010-06-30.xml')
doc = parser.parse
missing_vars = []
# survey_id = 17
# survey = Survey.find(survey_id)
# datasets = survey.datasets
# datasets.each do |dataset|
#puts "DATASET: " + dataset.name
dataset_id=22
nodes = doc.find('//metadata/variable')
nodes.each do |node|
namenode = node.find('child::name')
namecontent = namenode.first.content
print " NAME: " + namecontent
variable_name = namecontent
descnode = node.find('child::description')
desccontent = descnode.first.content
print " DESC: " + desccontent
variable_value = desccontent
catnode = node.find('child::category')
catcontent = catnode.first.content
print " CAT: " + catcontent
variable_category = catcontent
dernode = node.find('child::derivation')
dercontent = dernode.first
dertype = dercontent.find('child::type')
if dertype.first != nil
dertypecontent = dertype.first.content
variable_dertype = dertypecontent
print " TYPE: " + dertypecontent
else
print "TYPE: NIL"
end
dermethod = dercontent.find('child::method')
if dermethod.first != nil
dermethodcontent = dermethod.first.content
variable_dermethod = dermethodcontent
page = dermethod[0].[]("page")
document = dermethod[0].[]("document")
print "METHOD: " + dermethodcontent
if page != nil
print " page: " + page + " document: " + document
end
else
print "METHOD: NIL"
end
infonode = node.find('child::information')
infocontent = infonode.first.content
variable_info = infocontent
print "INFO: " + infocontent
v = Variable.find(:all,:conditions=> "dataset_id=" + dataset_id.to_s + " and name='" + variable_name+"'")
if (v[0]!= nil)
puts "Found Variable " + v[0].name
# v[0].value= variable_value
# v[0].dertype = variable_dertype
# v[0].dermethod = variable_dermethod
# v[0].info = variable_info
# v[0].category = variable_category
# v[0].save
if v[0].update_attributes(:value=>variable_value, :dertype=>variable_dertype, :dermethod=>variable_dermethod, :info=>variable_info,:category=>variable_category, :page=>page, :document=>document)
puts "Update success"
else
v[0].errors.full_messages.to_sentence
end
else
missing_vars.push(variable_name)
puts "Could not find " + variable_name
variable = Variable.new
variable.name = variable_name
variable.value= variable_value
variable.dertype = variable_dertype
variable.dermethod = variable_dermethod
variable.info = variable_info
variable.category = variable_category
variable.dataset_id = dataset_id;
variable.page = page
variable.document = document
variable.save
end
# infonode = node.find('child::information')
# if infonode.length>=1
# infochildren = infonode[0].find('child::info')
# infochildren.each do |childnode|
# valnode = childnode.first
# valvalue = valnode.first.content
# labelnode = valnode.next
# labelvalue = labelnode.first.content
# print valvalue
# print labelvalue
# end
# end
# end
end
puts "missing/new variables"
missing_vars.each {|missing_var| puts missing_var}
end
end
|
cask "mockuuups-studio" do
version "3.1.0"
sha256 "5935dea82713be5ec18c7ff81bd0b6f7b69503b1c365e91a54ffccbfa9b767f8"
url "https://binaries.mockuuups.com/Mockuuups%20Studio-#{version}-mac.zip",
verified: "mockuuups.com/"
name "Mockuuups Studio"
desc "Allows designers and marketers to drag and drop visuals into scenes"
homepage "https://mockuuups.studio/"
livecheck do
url "https://mockuuups.studio/download/mac/"
strategy :header_match
end
app "Mockuuups Studio.app"
zap trash: [
"~/Library/Application Support/Mockuuups Studio",
"~/Library/Caches/com.mockuuups.studio-app",
"~/Library/Caches/com.mockuuups.studio-app.ShipIt",
"~/Library/Cookies/com.mockuuups.studio-app.binarycookies",
"~/Library/Preferences/com.mockuuups.studio-app.helper.plist",
"~/Library/Preferences/com.mockuuups.studio-app.plist",
"~/Library/Saved Application State/com.mockuuups.studio-app.savedState",
]
end
Update mockuuups-studio from 3.1.0 to 3.1.1 (#105900)
cask "mockuuups-studio" do
version "3.1.1"
sha256 "634d6a55eb9398f12c5bbb1cc2aec604cf0bb78913ecc1dd9582e8543dc5592e"
url "https://binaries.mockuuups.com/Mockuuups%20Studio-#{version}-mac.zip",
verified: "mockuuups.com/"
name "Mockuuups Studio"
desc "Allows designers and marketers to drag and drop visuals into scenes"
homepage "https://mockuuups.studio/"
livecheck do
url "https://mockuuups.studio/download/mac/"
strategy :header_match
end
app "Mockuuups Studio.app"
zap trash: [
"~/Library/Application Support/Mockuuups Studio",
"~/Library/Caches/com.mockuuups.studio-app",
"~/Library/Caches/com.mockuuups.studio-app.ShipIt",
"~/Library/Cookies/com.mockuuups.studio-app.binarycookies",
"~/Library/Preferences/com.mockuuups.studio-app.helper.plist",
"~/Library/Preferences/com.mockuuups.studio-app.plist",
"~/Library/Saved Application State/com.mockuuups.studio-app.savedState",
]
end
|
class Aubio < Formula
desc "Extract annotations from audio signals"
homepage "https://github.com/aubio/aubio"
url "http://sources.buildroot.net/aubio/aubio-0.4.9.tar.bz2"
sha256 "d48282ae4dab83b3dc94c16cf011bcb63835c1c02b515490e1883049c3d1f3da"
revision 3
livecheck do
url "https://aubio.org/pub/"
regex(/href=.*?aubio[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 cellar: :any, arm64_monterey: "24480a57c922ecce159a8c51c7b6cbd888534ad071f8e6e44c2673d9af3cc123"
sha256 cellar: :any, arm64_big_sur: "1109fc08328664e84eff65a547737b1ac602e23519e6a88855fbd9a25a341a2c"
sha256 cellar: :any, monterey: "81bde2bc55939b498d263f6486f80f2c29b67ef6927db247ace8345ae34b2357"
sha256 cellar: :any, big_sur: "ce2477e78e0ddf5c3d2801c571c65e73a73a33967650aa067a94d49695a144d4"
sha256 cellar: :any, catalina: "3a0a2bcf355eef8bb66385c5bda82105569c2a7f999182626ca0b417d44e6255"
sha256 cellar: :any_skip_relocation, x86_64_linux: "741a3b0b3f1230f381b0ba5aef3815c8c6d1f437ccec04b95b70dad388cc0e33"
end
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "numpy"
depends_on "python@3.10"
on_linux do
depends_on "libsndfile"
end
resource "aiff" do
url "https://archive.org/download/TestAifAiffFile/02DayIsDone.aif"
sha256 "bca81e8d13f3f6526cd54110ec1196afd5bda6c93b16a7ba5023e474901e050d"
end
def install
# Needed due to issue with recent clang (-fno-fused-madd))
ENV.refurbish_args
python = "python3.10"
system python, "./waf", "configure", "--prefix=#{prefix}"
system python, "./waf", "build"
system python, "./waf", "install"
system python, *Language::Python.setup_install_args(prefix, python)
end
test do
testpath.install resource("aiff")
system bin/"aubiocut", "--verbose", "02DayIsDone.aif"
system bin/"aubioonset", "--verbose", "02DayIsDone.aif"
end
end
aubio: update 0.4.9_3 bottle.
class Aubio < Formula
desc "Extract annotations from audio signals"
homepage "https://github.com/aubio/aubio"
url "http://sources.buildroot.net/aubio/aubio-0.4.9.tar.bz2"
sha256 "d48282ae4dab83b3dc94c16cf011bcb63835c1c02b515490e1883049c3d1f3da"
revision 3
livecheck do
url "https://aubio.org/pub/"
regex(/href=.*?aubio[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 cellar: :any, arm64_ventura: "0a4511d273dd660c733a50e0368575fb71f21e1720fe35a3e40e0c02f61b20a7"
sha256 cellar: :any, arm64_monterey: "24480a57c922ecce159a8c51c7b6cbd888534ad071f8e6e44c2673d9af3cc123"
sha256 cellar: :any, arm64_big_sur: "1109fc08328664e84eff65a547737b1ac602e23519e6a88855fbd9a25a341a2c"
sha256 cellar: :any, monterey: "81bde2bc55939b498d263f6486f80f2c29b67ef6927db247ace8345ae34b2357"
sha256 cellar: :any, big_sur: "ce2477e78e0ddf5c3d2801c571c65e73a73a33967650aa067a94d49695a144d4"
sha256 cellar: :any, catalina: "3a0a2bcf355eef8bb66385c5bda82105569c2a7f999182626ca0b417d44e6255"
sha256 cellar: :any_skip_relocation, x86_64_linux: "741a3b0b3f1230f381b0ba5aef3815c8c6d1f437ccec04b95b70dad388cc0e33"
end
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "numpy"
depends_on "python@3.10"
on_linux do
depends_on "libsndfile"
end
resource "aiff" do
url "https://archive.org/download/TestAifAiffFile/02DayIsDone.aif"
sha256 "bca81e8d13f3f6526cd54110ec1196afd5bda6c93b16a7ba5023e474901e050d"
end
def install
# Needed due to issue with recent clang (-fno-fused-madd))
ENV.refurbish_args
python = "python3.10"
system python, "./waf", "configure", "--prefix=#{prefix}"
system python, "./waf", "build"
system python, "./waf", "install"
system python, *Language::Python.setup_install_args(prefix, python)
end
test do
testpath.install resource("aiff")
system bin/"aubiocut", "--verbose", "02DayIsDone.aif"
system bin/"aubioonset", "--verbose", "02DayIsDone.aif"
end
end
|
require 'webrick'
require 'middleman-core/meta_pages'
require 'middleman-core/logger'
# rubocop:disable GlobalVars
module Middleman
module PreviewServer
DEFAULT_PORT = 4567
class << self
extend Forwardable
attr_reader :app, :host, :port
def_delegator :app, :logger
# Start an instance of Middleman::Application
# @return [void]
def start(opts={})
@options = opts
@host = @options[:host] || '0.0.0.0'
@port = @options[:port] || DEFAULT_PORT
mount_instance(new_app)
logger.info "== The Middleman is standing watch at #{uri}"
logger.info "== Inspect your site configuration at #{uri + '__middleman'}"
@initialized ||= false
return if @initialized
@initialized = true
register_signal_handlers
# Save the last-used @options so it may be re-used when
# reloading later on.
::Middleman::Profiling.report('server_start')
loop do
@webrick.start
# $mm_shutdown is set by the signal handler
if $mm_shutdown
shutdown
exit
elsif $mm_reload
$mm_reload = false
reload
end
end
end
# Detach the current Middleman::Application instance
# @return [void]
def stop
begin
logger.info '== The Middleman is shutting down'
rescue
# if the user closed their terminal STDOUT/STDERR won't exist
end
if @listener
@listener.stop
@listener = nil
end
unmount_instance
end
# Simply stop, then start the server
# @return [void]
def reload
logger.info '== The Middleman is reloading'
begin
app = new_app
rescue => e
logger.error "Error reloading Middleman: #{e}\n#{e.backtrace.join("\n")}"
logger.info '== The Middleman is still running the application from before the error'
return
end
unmount_instance
mount_instance(app)
logger.info '== The Middleman has reloaded'
end
# Stop the current instance, exit Webrick
# @return [void]
def shutdown
stop
@webrick.shutdown
end
private
def new_app
opts = @options.dup
::Middleman::Logger.singleton(
opts[:debug] ? 0 : 1,
opts[:instrumenting] || false
)
server = ::Middleman::Application.server
# Add in the meta pages application
meta_app = Middleman::MetaPages::Application.new(server)
server.map '/__middleman' do
run meta_app
end
@app = server.inst do
config[:environment] = opts[:environment].to_sym if opts[:environment]
end
end
def start_file_watcher
return if @listener || @options[:disable_watcher]
# Watcher Library
require 'listen'
options = { force_polling: @options[:force_polling] }
options[:latency] = @options[:latency] if @options[:latency]
@listener = Listen.to(Dir.pwd, options) do |modified, added, removed|
added_and_modified = (modified + added)
# See if the changed file is config.rb or lib/*.rb
if needs_to_reload?(added_and_modified + removed)
@mm_reload = true
@webrick.stop
else
added_and_modified.each do |path|
relative_path = Pathname(path).relative_path_from(Pathname(Dir.pwd)).to_s
next if app.files.ignored?(relative_path)
app.files.did_change(relative_path)
end
removed.each do |path|
relative_path = Pathname(path).relative_path_from(Pathname(Dir.pwd)).to_s
next if app.files.ignored?(relative_path)
app.files.did_delete(relative_path)
end
end
end
# Don't block this thread
@listener.start
end
# Trap some interupt signals and shut down smoothly
# @return [void]
def register_signal_handlers
%w(INT HUP TERM QUIT).each do |sig|
next unless Signal.list[sig]
Signal.trap(sig) do
# Do as little work as possible in the signal context
$mm_shutdown = true
@webrick.stop
end
end
end
# Initialize webrick
# @return [void]
def setup_webrick(is_logging)
http_opts = {
BindAddress: host,
Port: port,
AccessLog: [],
DoNotReverseLookup: true
}
if is_logging
http_opts[:Logger] = FilteredWebrickLog.new
else
http_opts[:Logger] = ::WEBrick::Log.new(nil, 0)
end
begin
::WEBrick::HTTPServer.new(http_opts)
rescue Errno::EADDRINUSE
logger.error "== Port #{port} is unavailable. Either close the instance of Middleman already running on #{port} or start this Middleman on a new port with: --port=#{port.to_i + 1}"
exit(1)
end
end
# Attach a new Middleman::Application instance
# @param [Middleman::Application] app
# @return [void]
def mount_instance(app)
@app = app
@webrick ||= setup_webrick(@options[:debug] || false)
start_file_watcher
rack_app = app.class.to_rack_app
@webrick.mount '/', ::Rack::Handler::WEBrick, rack_app
end
# Detach the current Middleman::Application instance
# @return [void]
def unmount_instance
@webrick.unmount '/'
@app = nil
end
# Whether the passed files are config.rb, lib/*.rb or helpers
# @param [Array<String>] paths Array of paths to check
# @return [Boolean] Whether the server needs to reload
def needs_to_reload?(paths)
match_against = [
%r{^config\.rb},
%r{^lib/[^\.](.*)\.rb$},
%r{^helpers/[^\.](.*)\.rb$}
]
if @options[:reload_paths]
@options[:reload_paths].split(',').each do |part|
match_against << %r{^#{part}}
end
end
paths.any? do |path|
match_against.any? do |matcher|
path =~ matcher
end
end
end
# Returns the URI the preview server will run on
# @return [URI]
def uri
host = (@host == '0.0.0.0') ? 'localhost' : @host
URI("http://#{host}:#{@port}")
end
end
class FilteredWebrickLog < ::WEBrick::Log
def log(level, data)
super(level, data) unless data =~ %r{Could not determine content-length of response body.}
end
end
end
end
Reload MM on environment and helpers_dir changes. Closes #1274. Closes #1105
require 'webrick'
require 'middleman-core/meta_pages'
require 'middleman-core/logger'
# rubocop:disable GlobalVars
module Middleman
module PreviewServer
DEFAULT_PORT = 4567
class << self
extend Forwardable
attr_reader :app, :host, :port
def_delegator :app, :logger
# Start an instance of Middleman::Application
# @return [void]
def start(opts={})
@options = opts
@host = @options[:host] || '0.0.0.0'
@port = @options[:port] || DEFAULT_PORT
mount_instance(new_app)
logger.info "== The Middleman is standing watch at #{uri}"
logger.info "== Inspect your site configuration at #{uri + '__middleman'}"
@initialized ||= false
return if @initialized
@initialized = true
register_signal_handlers
# Save the last-used @options so it may be re-used when
# reloading later on.
::Middleman::Profiling.report('server_start')
loop do
@webrick.start
# $mm_shutdown is set by the signal handler
if $mm_shutdown
shutdown
exit
elsif $mm_reload
$mm_reload = false
reload
end
end
end
# Detach the current Middleman::Application instance
# @return [void]
def stop
begin
logger.info '== The Middleman is shutting down'
rescue
# if the user closed their terminal STDOUT/STDERR won't exist
end
if @listener
@listener.stop
@listener = nil
end
unmount_instance
end
# Simply stop, then start the server
# @return [void]
def reload
logger.info '== The Middleman is reloading'
begin
app = new_app
rescue => e
logger.error "Error reloading Middleman: #{e}\n#{e.backtrace.join("\n")}"
logger.info '== The Middleman is still running the application from before the error'
return
end
unmount_instance
mount_instance(app)
logger.info '== The Middleman has reloaded'
end
# Stop the current instance, exit Webrick
# @return [void]
def shutdown
stop
@webrick.shutdown
end
private
def new_app
opts = @options.dup
::Middleman::Logger.singleton(
opts[:debug] ? 0 : 1,
opts[:instrumenting] || false
)
server = ::Middleman::Application.server
# Add in the meta pages application
meta_app = Middleman::MetaPages::Application.new(server)
server.map '/__middleman' do
run meta_app
end
@app = server.inst do
config[:environment] = opts[:environment].to_sym if opts[:environment]
end
end
def start_file_watcher
return if @listener || @options[:disable_watcher]
# Watcher Library
require 'listen'
options = { force_polling: @options[:force_polling] }
options[:latency] = @options[:latency] if @options[:latency]
@listener = Listen.to(Dir.pwd, options) do |modified, added, removed|
added_and_modified = (modified + added)
# See if the changed file is config.rb or lib/*.rb
if needs_to_reload?(added_and_modified + removed)
$mm_reload = true
@webrick.stop
else
added_and_modified.each do |path|
relative_path = Pathname(path).relative_path_from(Pathname(Dir.pwd)).to_s
next if app.files.ignored?(relative_path)
app.files.did_change(relative_path)
end
removed.each do |path|
relative_path = Pathname(path).relative_path_from(Pathname(Dir.pwd)).to_s
next if app.files.ignored?(relative_path)
app.files.did_delete(relative_path)
end
end
end
# Don't block this thread
@listener.start
end
# Trap some interupt signals and shut down smoothly
# @return [void]
def register_signal_handlers
%w(INT HUP TERM QUIT).each do |sig|
next unless Signal.list[sig]
Signal.trap(sig) do
# Do as little work as possible in the signal context
$mm_shutdown = true
@webrick.stop
end
end
end
# Initialize webrick
# @return [void]
def setup_webrick(is_logging)
http_opts = {
BindAddress: host,
Port: port,
AccessLog: [],
DoNotReverseLookup: true
}
if is_logging
http_opts[:Logger] = FilteredWebrickLog.new
else
http_opts[:Logger] = ::WEBrick::Log.new(nil, 0)
end
begin
::WEBrick::HTTPServer.new(http_opts)
rescue Errno::EADDRINUSE
logger.error "== Port #{port} is unavailable. Either close the instance of Middleman already running on #{port} or start this Middleman on a new port with: --port=#{port.to_i + 1}"
exit(1)
end
end
# Attach a new Middleman::Application instance
# @param [Middleman::Application] app
# @return [void]
def mount_instance(app)
@app = app
@webrick ||= setup_webrick(@options[:debug] || false)
start_file_watcher
rack_app = app.class.to_rack_app
@webrick.mount '/', ::Rack::Handler::WEBrick, rack_app
end
# Detach the current Middleman::Application instance
# @return [void]
def unmount_instance
@webrick.unmount '/'
@app = nil
end
# Whether the passed files are config.rb, lib/*.rb or helpers
# @param [Array<String>] paths Array of paths to check
# @return [Boolean] Whether the server needs to reload
def needs_to_reload?(paths)
match_against = [
%r{^/config\.rb},
%r{^/environments/[^\.](.*)\.rb$},
%r{^/lib/[^\.](.*)\.rb$},
%r{^/#{@app.config[:helpers_dir]}/[^\.](.*)\.rb$}
]
if @options[:reload_paths]
@options[:reload_paths].split(',').each do |part|
match_against << %r{^#{part}}
end
end
paths.any? do |path|
match_against.any? do |matcher|
path.sub(@app.root, '').match matcher
end
end
end
# Returns the URI the preview server will run on
# @return [URI]
def uri
host = (@host == '0.0.0.0') ? 'localhost' : @host
URI("http://#{host}:#{@port}")
end
end
class FilteredWebrickLog < ::WEBrick::Log
def log(level, data)
super(level, data) unless data =~ %r{Could not determine content-length of response body.}
end
end
end
end
|
cask 'obinslab-starter' do
version '1.0.5'
sha256 'edf944898b64595cccc9dfaec98055b7cdac7857be98df01e5ba1672311aeeeb'
url "http://releases.obins.net/occ/darwin/x64/ObinslabStarter_#{version}.dmg"
name 'Obinslab Starter'
homepage 'http://en.obins.net/obinslab-starter'
app 'Obinslab Starter.app'
end
Update obinslab-starter to 1.0.7 (#60623)
cask 'obinslab-starter' do
version '1.0.7'
sha256 '322bbd28bb9dec1c5b60f6fe5c5bbe4a3238b5127ea1e8628bce1364929062a9'
url "http://releases.obins.net/occ/darwin/x64/ObinslabStarter_#{version}.dmg"
name 'Obinslab Starter'
homepage 'http://en.obins.net/obinslab-starter'
app 'Obinslab Starter.app'
end
|
class Aztfy < Formula
desc "Bring your existing Azure resources under the management of Terraform"
homepage "https://azure.github.io/aztfy"
url "https://github.com/Azure/aztfy.git",
tag: "v0.7.0",
revision: "071ef92a56ffb8b7a8ff208f00c58350d9925672"
license "MPL-2.0"
head "https://github.com/Azure/aztfy.git", branch: "main"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "3223262cffd36fd34b96828eaf60c6b91ea3296f7ca8a70a8bb97dc59d16a8d7"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "3223262cffd36fd34b96828eaf60c6b91ea3296f7ca8a70a8bb97dc59d16a8d7"
sha256 cellar: :any_skip_relocation, monterey: "248092b3e8792f4278eb9f981e8333a5c06410c4da6ed0c5379e784a9ce9329e"
sha256 cellar: :any_skip_relocation, big_sur: "248092b3e8792f4278eb9f981e8333a5c06410c4da6ed0c5379e784a9ce9329e"
sha256 cellar: :any_skip_relocation, catalina: "248092b3e8792f4278eb9f981e8333a5c06410c4da6ed0c5379e784a9ce9329e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "a5742042639aa27ef133d0c80061cf2ffb337e545367021d6931ad188c6e2a7c"
end
depends_on "go" => :build
def install
ENV["CGO_ENABLED"] = "0"
system "go", "build", *std_go_args(ldflags: "-s -w -X 'main.version=v#{version}' -X 'main.revision=#{Utils.git_short_head(length: 7)}'")
end
test do
version_output = shell_output("#{bin}/aztfy -v")
assert_match version.to_s, version_output
no_resource_group_specified_output = shell_output("#{bin}/aztfy rg 2>&1", 1)
assert_match("Error: No resource group specified", no_resource_group_specified_output)
end
end
aztfy 0.8.0
* aztfy 0.8.0
* Fix spec
Closes #112104.
Signed-off-by: Rui Chen <907c7afd57be493757f13ccd1dd45dddf02db069@chenrui.dev>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Aztfy < Formula
desc "Bring your existing Azure resources under the management of Terraform"
homepage "https://azure.github.io/aztfy"
url "https://github.com/Azure/aztfy.git",
tag: "v0.8.0",
revision: "a7c179f0a150fb5ad63206532ea891c1dc0c87f1"
license "MPL-2.0"
head "https://github.com/Azure/aztfy.git", branch: "main"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "3223262cffd36fd34b96828eaf60c6b91ea3296f7ca8a70a8bb97dc59d16a8d7"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "3223262cffd36fd34b96828eaf60c6b91ea3296f7ca8a70a8bb97dc59d16a8d7"
sha256 cellar: :any_skip_relocation, monterey: "248092b3e8792f4278eb9f981e8333a5c06410c4da6ed0c5379e784a9ce9329e"
sha256 cellar: :any_skip_relocation, big_sur: "248092b3e8792f4278eb9f981e8333a5c06410c4da6ed0c5379e784a9ce9329e"
sha256 cellar: :any_skip_relocation, catalina: "248092b3e8792f4278eb9f981e8333a5c06410c4da6ed0c5379e784a9ce9329e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "a5742042639aa27ef133d0c80061cf2ffb337e545367021d6931ad188c6e2a7c"
end
depends_on "go" => :build
def install
ENV["CGO_ENABLED"] = "0"
system "go", "build", *std_go_args(ldflags: "-s -w -X 'main.version=v#{version}' -X 'main.revision=#{Utils.git_short_head(length: 7)}'")
end
test do
version_output = shell_output("#{bin}/aztfy -v")
assert_match version.to_s, version_output
no_resource_group_specified_output = shell_output("#{bin}/aztfy rg 2>&1", 1)
assert_match("Error: retrieving subscription id from CLI", no_resource_group_specified_output)
end
end
|
class ParaviewNightly < Cask
version 'latest'
sha256 :no_check
url 'http://www.paraview.org/paraview-downloads/download.php?submit=Download&version=nightly&type=binary&os=osx&downloadFile=ParaView-Darwin-64bit-NIGHTLY.dmg'
homepage 'http://www.paraview.org/'
app 'paraview.app'
caveats <<-EOS.undent
This version of Paraview should be installed if your system Python
version is 2.7. If you are running OS X Lion (10.7) or Mountain
Lion (10.8) and your system Python version is 2.6, please instead
pkg paraview-nightly-lion-python27.
EOS
end
:latest as symbol, paraview-nightly
class ParaviewNightly < Cask
version :latest
sha256 :no_check
url 'http://www.paraview.org/paraview-downloads/download.php?submit=Download&version=nightly&type=binary&os=osx&downloadFile=ParaView-Darwin-64bit-NIGHTLY.dmg'
homepage 'http://www.paraview.org/'
app 'paraview.app'
caveats <<-EOS.undent
This version of Paraview should be installed if your system Python
version is 2.7. If you are running OS X Lion (10.7) or Mountain
Lion (10.8) and your system Python version is 2.6, please instead
pkg paraview-nightly-lion-python27.
EOS
end
|
require "language/node"
require "json"
class Babel < Formula
desc "Compiler for writing next generation JavaScript"
homepage "https://babeljs.io/"
url "https://registry.npmjs.org/@babel/core/-/core-7.8.6.tgz"
sha256 "2df1c0b546be24908cc60e4df52d51c726caf23986941e2a9997739f46e72ea0"
bottle do
sha256 "a8cce2b8d6fae4c2ca15f5b43fc341ee709d470b1d2b6ee2c1e9f51b57ebb811" => :catalina
sha256 "cbe3831e019e6c42793d76aacd7ef53e6e8e05c1ab57659973c29f42fa16a7bb" => :mojave
sha256 "2f0be893881e4262618b5ef50a9c4783862969421c75ea689e3e7321de7bc26a" => :high_sierra
end
depends_on "node"
resource "babel-cli" do
url "https://registry.npmjs.org/@babel/cli/-/cli-7.8.4.tgz"
sha256 "326e825e7aba32fc7d6f99152f5c8a821f215ff444ed54b48bdfefa1410c057a"
end
def install
(buildpath/"node_modules/@babel/core").install Dir["*"]
buildpath.install resource("babel-cli")
# declare babel-core as a bundledDependency of babel-cli
pkg_json = JSON.parse(IO.read("package.json"))
pkg_json["dependencies"]["@babel/core"] = version
pkg_json["bundledDependencies"] = ["@babel/core"]
IO.write("package.json", JSON.pretty_generate(pkg_json))
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
(testpath/"script.js").write <<~EOS
[1,2,3].map(n => n + 1);
EOS
system bin/"babel", "script.js", "--out-file", "script-compiled.js"
assert_predicate testpath/"script-compiled.js", :exist?, "script-compiled.js was not generated"
end
end
babel 7.8.7
Closes #51145.
Signed-off-by: Rui Chen <5fd29470147430022ff146db88de16ee91dea376@gmail.com>
require "language/node"
require "json"
class Babel < Formula
desc "Compiler for writing next generation JavaScript"
homepage "https://babeljs.io/"
url "https://registry.npmjs.org/@babel/core/-/core-7.8.7.tgz"
sha256 "e43c2bea6203f99e4964fc9bfac997d7b917fb43e24936db7dc425466c066ce0"
bottle do
sha256 "a8cce2b8d6fae4c2ca15f5b43fc341ee709d470b1d2b6ee2c1e9f51b57ebb811" => :catalina
sha256 "cbe3831e019e6c42793d76aacd7ef53e6e8e05c1ab57659973c29f42fa16a7bb" => :mojave
sha256 "2f0be893881e4262618b5ef50a9c4783862969421c75ea689e3e7321de7bc26a" => :high_sierra
end
depends_on "node"
resource "babel-cli" do
url "https://registry.npmjs.org/@babel/cli/-/cli-7.8.4.tgz"
sha256 "326e825e7aba32fc7d6f99152f5c8a821f215ff444ed54b48bdfefa1410c057a"
end
def install
(buildpath/"node_modules/@babel/core").install Dir["*"]
buildpath.install resource("babel-cli")
# declare babel-core as a bundledDependency of babel-cli
pkg_json = JSON.parse(IO.read("package.json"))
pkg_json["dependencies"]["@babel/core"] = version
pkg_json["bundledDependencies"] = ["@babel/core"]
IO.write("package.json", JSON.pretty_generate(pkg_json))
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
(testpath/"script.js").write <<~EOS
[1,2,3].map(n => n + 1);
EOS
system bin/"babel", "script.js", "--out-file", "script-compiled.js"
assert_predicate testpath/"script-compiled.js", :exist?, "script-compiled.js was not generated"
end
end
|
cask 'sqlpro-for-mssql' do
version '1.0.318'
sha256 '7c98cdacc92dc51e0810848485ed64e65be2a95b1c2a4c89a735cd7ddb183ff7'
# d3fwkemdw8spx3.cloudfront.net/mssql was verified as official when first introduced to the cask
url "https://d3fwkemdw8spx3.cloudfront.net/mssql/SQLProMSSQL.#{version}.app.zip"
name 'SQLPro for MSSQL'
homepage 'https://www.macsqlclient.com/'
app 'SQLPro for MSSQL.app'
zap trash: [
'~/Library/Containers/com.hankinsoft.osx.tinysqlstudio',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.hankinsoft.osx.tinysqlstudio.sfl*',
]
end
Update sqlpro-for-mssql from 1.0.318 to 1.0.465 (#62378)
cask 'sqlpro-for-mssql' do
version '1.0.465'
sha256 '476e454040170fff58b192ecafdddefc83cbb59c4fa1a7320a77d8bc777a2a5f'
# d3fwkemdw8spx3.cloudfront.net/mssql was verified as official when first introduced to the cask
url "https://d3fwkemdw8spx3.cloudfront.net/mssql/SQLProMSSQL.#{version}.app.zip"
name 'SQLPro for MSSQL'
homepage 'https://www.macsqlclient.com/'
app 'SQLPro for MSSQL.app'
zap trash: [
'~/Library/Containers/com.hankinsoft.osx.tinysqlstudio',
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.hankinsoft.osx.tinysqlstudio.sfl*',
]
end
|
require "language/node"
require "json"
class Babel < Formula
desc "Compiler for writing next generation JavaScript"
homepage "https://babeljs.io/"
url "https://registry.npmjs.org/@babel/core/-/core-7.19.1.tgz"
sha256 "a16a84e263a928bc9d11e2ebb9e500f1822269d979696846a797466a8e7a7409"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, all: "f04ed0067e42e64c59310280a4d3a2d6eb3f1bda0359d50a03e22b6c41b44e1d"
end
depends_on "node"
resource "babel-cli" do
url "https://registry.npmjs.org/@babel/cli/-/cli-7.18.10.tgz"
sha256 "9bda888e2b4feb37e343657b2a7eff5e0480c8fc1713d8919b368a24c8164f69"
end
def install
(buildpath/"node_modules/@babel/core").install Dir["*"]
buildpath.install resource("babel-cli")
cd buildpath/"node_modules/@babel/core" do
system "npm", "install", *Language::Node.local_npm_install_args, "--production"
end
# declare babel-core as a bundledDependency of babel-cli
pkg_json = JSON.parse(File.read("package.json"))
pkg_json["dependencies"]["@babel/core"] = version
pkg_json["bundleDependencies"] = ["@babel/core"]
File.write("package.json", JSON.pretty_generate(pkg_json))
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
(testpath/"script.js").write <<~EOS
[1,2,3].map(n => n + 1);
EOS
system bin/"babel", "script.js", "--out-file", "script-compiled.js"
assert_predicate testpath/"script-compiled.js", :exist?, "script-compiled.js was not generated"
end
end
babel: update 7.19.1 bottle.
require "language/node"
require "json"
class Babel < Formula
desc "Compiler for writing next generation JavaScript"
homepage "https://babeljs.io/"
url "https://registry.npmjs.org/@babel/core/-/core-7.19.1.tgz"
sha256 "a16a84e263a928bc9d11e2ebb9e500f1822269d979696846a797466a8e7a7409"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "b73bad5b901717c921d1fd97c4c116968cd25ebe9cb5fbc6980e3c453a7dc620"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "b73bad5b901717c921d1fd97c4c116968cd25ebe9cb5fbc6980e3c453a7dc620"
sha256 cellar: :any_skip_relocation, monterey: "8171b05dc83a6d695b87a16bedc43c739f796de0d44e445cc6bbc7a1ce55d6d0"
sha256 cellar: :any_skip_relocation, big_sur: "8171b05dc83a6d695b87a16bedc43c739f796de0d44e445cc6bbc7a1ce55d6d0"
sha256 cellar: :any_skip_relocation, catalina: "8171b05dc83a6d695b87a16bedc43c739f796de0d44e445cc6bbc7a1ce55d6d0"
sha256 cellar: :any_skip_relocation, x86_64_linux: "b73bad5b901717c921d1fd97c4c116968cd25ebe9cb5fbc6980e3c453a7dc620"
end
depends_on "node"
resource "babel-cli" do
url "https://registry.npmjs.org/@babel/cli/-/cli-7.18.10.tgz"
sha256 "9bda888e2b4feb37e343657b2a7eff5e0480c8fc1713d8919b368a24c8164f69"
end
def install
(buildpath/"node_modules/@babel/core").install Dir["*"]
buildpath.install resource("babel-cli")
cd buildpath/"node_modules/@babel/core" do
system "npm", "install", *Language::Node.local_npm_install_args, "--production"
end
# declare babel-core as a bundledDependency of babel-cli
pkg_json = JSON.parse(File.read("package.json"))
pkg_json["dependencies"]["@babel/core"] = version
pkg_json["bundleDependencies"] = ["@babel/core"]
File.write("package.json", JSON.pretty_generate(pkg_json))
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
(testpath/"script.js").write <<~EOS
[1,2,3].map(n => n + 1);
EOS
system bin/"babel", "script.js", "--out-file", "script-compiled.js"
assert_predicate testpath/"script-compiled.js", :exist?, "script-compiled.js was not generated"
end
end
|
cask 'teamspeak-client' do
version '3.5.3'
sha256 '6497d19e2f420da7866572f84db7123ff15c104b69cc70302ca9ee72fd19aa7d'
# files.teamspeak-services.com/releases/client/ was verified as official when first introduced to the cask
url "https://files.teamspeak-services.com/releases/client/#{version}/TeamSpeak#{version.major}-Client-macosx-#{version}.dmg"
appcast 'https://versions.teamspeak.com/ts3-client-2'
name 'TeamSpeak Client'
homepage 'https://www.teamspeak.com/'
auto_updates true
depends_on macos: '>= :sierra'
app "TeamSpeak #{version.major} Client.app"
end
teamspeak-client: fix RuboCop style.
See https://github.com/Homebrew/brew/pull/7867.
cask "teamspeak-client" do
version "3.5.3"
sha256 "6497d19e2f420da7866572f84db7123ff15c104b69cc70302ca9ee72fd19aa7d"
# files.teamspeak-services.com/releases/client/ was verified as official when first introduced to the cask
url "https://files.teamspeak-services.com/releases/client/#{version}/TeamSpeak#{version.major}-Client-macosx-#{version}.dmg"
appcast "https://versions.teamspeak.com/ts3-client-2"
name "TeamSpeak Client"
homepage "https://www.teamspeak.com/"
auto_updates true
depends_on macos: ">= :sierra"
app "TeamSpeak #{version.major} Client.app"
end
|
require 'formula'
class Bagit < Formula
homepage 'https://github.com/LibraryOfCongress/bagit-java'
url 'https://github.com/LibraryOfCongress/bagit-java/releases/download/bagit-4.8.1/bagit-4.8.1-bin.zip'
sha1 'a5f42372dcbe75f44d9181dd8edc8e6f18b68ec9'
def install
# put logs in var, not in the Cellar
(var/'log/bagit').mkpath
inreplace "conf/log4j.properties", "${app.home}/logs", "#{var}/log/bagit"
libexec.install Dir['*']
bin.install_symlink libexec/"bin/bag"
end
test do
system bin/'bag'
end
end
bagit 4.9.0
require 'formula'
class Bagit < Formula
homepage 'https://github.com/LibraryOfCongress/bagit-java'
url 'https://github.com/LibraryOfCongress/bagit-java/releases/download/bagit-4.9.0/bagit-4.9.0-bin.zip'
sha1 '6ca4c2a202ce6c975b130a180cd3bd2dcbe5a756'
def install
# put logs in var, not in the Cellar
(var/'log/bagit').mkpath
inreplace "conf/log4j.properties", "${app.home}/logs", "#{var}/log/bagit"
libexec.install Dir['*']
bin.install_symlink libexec/"bin/bag"
end
test do
system bin/'bag'
end
end
|
module ApplicationsHelper
Application::FLAGS.each do |flag|
define_method(:"display_#{flag}?") { not session[:"hide_#{flag}"] }
define_method(:"hide_#{flag}?") { session[:"hide_#{flag}"] }
end
def rating_classes_for(rating, user)
classes = []
classes << "pick" if rating.pick?
classes << 'own_rating' if rating.user == user
classes.join(' ')
end
def application_classes_for(application)
classes = [cycle(:even, :odd)]
classes << 'selected' if application.selected?
classes << 'volunteering_team' if application.volunteering_team?
classes.join(' ')
end
def formatted_application_data_value(key, value)
markdown_fields = %w(project_plan)
value = value.presence || 'n/a'
formatted = case
when markdown_fields.include?(key.to_s)
render_markdown value
when /project._id/ =~ key.to_s
project = Project.find_by_id value
link_to_if project, project.try(:name), project
else
auto_link simple_format(value)
end
content_tag :p, formatted.html_safe
end
def format_application_location(application)
country = country_for_application(application).to_s
location = location_for_application(application).to_s
location = location.gsub(country, '').gsub(%r(^\s*/\s*), '').gsub(/[\(\)]*/, '')
[location.strip, country.strip].select(&:present?).join('/')
end
def country_for_application(application)
country = application.country
country = 'US' if country == 'United States of America'
country = 'UK' if country == 'United Kingdom'
country
end
def location_for_application(application)
application.city.present? ? application.city : application.team.students.map(&:location).reject(&:blank?).join(', ')
end
def link_to_ordered(text, type)
link_to text, rating_applications_path(order: type)
end
def format_application_projects(application)
link_to_application_project(application) || links_to_application_projects(application)
end
def link_to_application_project(application)
if project = application.project
link_txt = project.name
link_txt += " (#{application.project_visibility})" if application.project_visibility
link_to link_txt, project
end
end
def format_application_flags(application)
flags = Application::FLAGS.select do |flag|
application.send(:"#{flag}?")
end
flags.map { |flag| flag.to_s.titleize }.join(', ')
end
def format_application_money(application)
money = application.application_data.
values_at('student0_application_money', 'student1_application_money').
reject(&:blank?)
safe_join(money.map{|m| number_to_currency m, precision: 0}, "\n")
end
private
def links_to_application_projects(application)
projects = Project.where id: application.application_data.values_at('project1_id', 'project2_id')
safe_join(projects.map{|p| link_to(p.name, p)}, "<br/>".html_safe)
end
end
Changed order of projects in the applications table
module ApplicationsHelper
Application::FLAGS.each do |flag|
define_method(:"display_#{flag}?") { not session[:"hide_#{flag}"] }
define_method(:"hide_#{flag}?") { session[:"hide_#{flag}"] }
end
def rating_classes_for(rating, user)
classes = []
classes << "pick" if rating.pick?
classes << 'own_rating' if rating.user == user
classes.join(' ')
end
def application_classes_for(application)
classes = [cycle(:even, :odd)]
classes << 'selected' if application.selected?
classes << 'volunteering_team' if application.volunteering_team?
classes.join(' ')
end
def formatted_application_data_value(key, value)
markdown_fields = %w(project_plan)
value = value.presence || 'n/a'
formatted = case
when markdown_fields.include?(key.to_s)
render_markdown value
when /project._id/ =~ key.to_s
project = Project.find_by_id value
link_to_if project, project.try(:name), project
else
auto_link simple_format(value)
end
content_tag :p, formatted.html_safe
end
def format_application_location(application)
country = country_for_application(application).to_s
location = location_for_application(application).to_s
location = location.gsub(country, '').gsub(%r(^\s*/\s*), '').gsub(/[\(\)]*/, '')
[location.strip, country.strip].select(&:present?).join('/')
end
def country_for_application(application)
country = application.country
country = 'US' if country == 'United States of America'
country = 'UK' if country == 'United Kingdom'
country
end
def location_for_application(application)
application.city.present? ? application.city : application.team.students.map(&:location).reject(&:blank?).join(', ')
end
def link_to_ordered(text, type)
link_to text, rating_applications_path(order: type)
end
def format_application_projects(application)
link_to_application_project(application) || links_to_application_projects(application)
end
def link_to_application_project(application)
if project = application.project
link_txt = project.name
link_txt += " (#{application.project_visibility})" if application.project_visibility
link_to link_txt, project
end
end
def format_application_flags(application)
flags = Application::FLAGS.select do |flag|
application.send(:"#{flag}?")
end
flags.map { |flag| flag.to_s.titleize }.join(', ')
end
def format_application_money(application)
money = application.application_data.
values_at('student0_application_money', 'student1_application_money').
reject(&:blank?)
safe_join(money.map{|m| number_to_currency m, precision: 0}, "\n")
end
private
def links_to_application_projects(application)
projects = Project.where id: application.application_data.values_at('project1_id')
projects += Project.where id: application.application_data.values_at('project2_id')
safe_join(projects.map{|p| link_to(p.name, p)}, "<br/>".html_safe)
end
end
|
cask :v1 => 'thirty-three-rpm' do
version :latest
sha256 :no_check
url 'http://www.edenwaith.com/downloads/33rpm.dmg'
homepage 'http://www.edenwaith.com/products/33rpm/'
license :unknown
app '33 RPM.app'
end
license todo comment in thirty-three-rpm
cask :v1 => 'thirty-three-rpm' do
version :latest
sha256 :no_check
url 'http://www.edenwaith.com/downloads/33rpm.dmg'
homepage 'http://www.edenwaith.com/products/33rpm/'
license :unknown # todo: improve this machine-generated value
app '33 RPM.app'
end
|
require "formula"
class Ruby19Dependency < Requirement
fatal true
default_formula "ruby"
satisfy do
`ruby --version` =~ /ruby (\d\.\d).\d/
$1.to_f >= 1.9
end
def message
"Betty requires Ruby 1.9 or better."
end
end
class Betty < Formula
homepage "https://github.com/pickhardt/betty"
url "https://github.com/pickhardt/betty/archive/v0.1.6.tar.gz"
sha1 "bd838caa8d596598f406209609f39a7bd5087ac1"
depends_on Ruby19Dependency
def install
libexec.install "lib", "main.rb" => "betty"
bin.write_exec_script libexec/"betty"
end
test do
system bin/"betty", "speech on"
system bin/"betty", "what is your name"
system bin/"betty", "version"
system bin/"betty", "speech off"
end
end
betty 0.1.7
require "formula"
class Ruby19Dependency < Requirement
fatal true
default_formula "ruby"
satisfy do
`ruby --version` =~ /ruby (\d\.\d).\d/
$1.to_f >= 1.9
end
def message
"Betty requires Ruby 1.9 or better."
end
end
class Betty < Formula
homepage "https://github.com/pickhardt/betty"
url "https://github.com/pickhardt/betty/archive/v0.1.7.tar.gz"
sha1 "ec21ec5541289a9902874c7897f8d521044daf27"
depends_on Ruby19Dependency
def install
libexec.install "lib", "main.rb" => "betty"
bin.write_exec_script libexec/"betty"
end
test do
system bin/"betty", "speech on"
system bin/"betty", "what is your name"
system bin/"betty", "version"
system bin/"betty", "speech off"
end
end
|
$:.push File.expand_path("../lib", __FILE__)
require "doorkeeper/version"
Gem::Specification.new do |s|
s.name = "doorkeeper"
s.version = Doorkeeper::VERSION
s.authors = ["Felipe Elias Philipp", "Tute Costa"]
s.email = %w(tutecosta@gmail.com)
s.homepage = "https://github.com/doorkeeper-gem/doorkeeper"
s.summary = "Doorkeeper is an OAuth 2 provider for Rails."
s.description = "Doorkeeper is an OAuth 2 provider for Rails."
s.license = 'MIT'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- test/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency "railties", ">= 3.2"
s.add_development_dependency "sqlite3", "~> 1.3.5"
s.add_development_dependency "rspec-rails", "~> 3.2.0"
s.add_development_dependency "capybara", "~> 2.3.0"
s.add_development_dependency "generator_spec", "~> 0.9.0"
s.add_development_dependency "factory_girl", "~> 4.5.0"
s.add_development_dependency "timecop", "~> 0.7.0"
s.add_development_dependency "database_cleaner", "~> 1.3.0"
s.add_development_dependency "rspec-activemodel-mocks", "~> 1.0.0"
s.add_development_dependency "bcrypt-ruby", "~> 3.0.1"
s.add_development_dependency "pry", "~> 0.10.0"
end
gemspec update
$:.push File.expand_path("../lib", __FILE__)
require "doorkeeper/version"
Gem::Specification.new do |s|
s.name = "doorkeeper"
s.version = Doorkeeper::VERSION
s.authors = ["Felipe Elias Philipp", "Tute Costa"]
s.email = %w(tutecosta@gmail.com)
s.homepage = "https://github.com/doorkeeper-gem/doorkeeper"
s.summary = "OAuth 2 provider for Rails and Grape"
s.description = "Doorkeeper is an OAuth 2 provider for Rails and Grape."
s.license = 'MIT'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency "railties", ">= 3.2"
s.add_development_dependency "sqlite3", "~> 1.3.5"
s.add_development_dependency "rspec-rails", "~> 3.2.0"
s.add_development_dependency "capybara", "~> 2.3.0"
s.add_development_dependency "generator_spec", "~> 0.9.0"
s.add_development_dependency "factory_girl", "~> 4.5.0"
s.add_development_dependency "timecop", "~> 0.7.0"
s.add_development_dependency "database_cleaner", "~> 1.3.0"
s.add_development_dependency "rspec-activemodel-mocks", "~> 1.0.0"
s.add_development_dependency "bcrypt-ruby", "~> 3.0.1"
s.add_development_dependency "pry", "~> 0.10.0"
end
|
cask 'tinymediamanager' do
version '3.0.1'
sha256 '67bf41198f4b2461f7985ddb9225d620fcc63842bb213a05cc4a8ece260ab5cc'
url "https://release.tinymediamanager.org/v#{version.major}/dist/tmm_#{version}_mac.zip"
appcast 'https://release.tinymediamanager.org/'
name 'tinyMediaManager'
homepage 'https://www.tinymediamanager.org/'
app 'tinyMediaManager.app'
caveats do
depends_on_java '8+'
end
end
Update tinymediamanager from 3.0.1 to 3.0.2 (#65410)
cask 'tinymediamanager' do
version '3.0.2'
sha256 'd43308948c5993237af5cc05cde1624eae2bdde26806e3b4c1f9397f1bf3c071'
url "https://release.tinymediamanager.org/v#{version.major}/dist/tmm_#{version}_mac.zip"
appcast 'https://release.tinymediamanager.org/'
name 'tinyMediaManager'
homepage 'https://www.tinymediamanager.org/'
app 'tinyMediaManager.app'
caveats do
depends_on_java '8+'
end
end
|
class Bmake < Formula
desc "Portable version of NetBSD make(1)"
homepage "https://www.crufty.net/help/sjg/bmake.html"
url "https://www.crufty.net/ftp/pub/sjg/bmake-20220612.tar.gz"
sha256 "e34bcc6375c75ae5b53551da0b1d6c1205cdee61e4f564e2cfe04081a5a682fa"
license "BSD-3-Clause"
livecheck do
url "https://www.crufty.net/ftp/pub/sjg/"
regex(/href=.*?bmake[._-]v?(\d{6,8})\.t/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "ea6d347e27b41d0fe9e672910c829123de6563da61b665b2d0f17a45d7f14994"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "801ad5c98a414c1efc6be2d83ffe15c2c25af0ef3d973421ea2a1ed6864856bc"
sha256 monterey: "cc70133aa230c37eca6973c9759b8d08ffcc1d3ffc9f147f8ac73cc978d075b9"
sha256 big_sur: "467fbaa19a541763345a973dc9041a2a88c6ad4eef1e31bf660814c32bdff409"
sha256 catalina: "a9d6f26a78e81862230f1cee75746431fb049235dd811028b032fe6f52716bec"
sha256 x86_64_linux: "e420bc8442cf5eb48296e98d142a9de2000baf2b600444c1f6cd1e4937f2725d"
end
def install
# Don't pre-roff cat pages.
inreplace "mk/man.mk", "MANTARGET?", "MANTARGET"
# -DWITHOUT_PROG_LINK means "don't symlink as bmake-VERSION."
# shell-ksh test segfaults since macOS 11.
args = ["--prefix=#{prefix}", "-DWITHOUT_PROG_LINK", "--install", "BROKEN_TESTS=shell-ksh"]
system "sh", "boot-strap", *args
man1.install "bmake.1"
end
test do
(testpath/"Makefile").write <<~EOS
all: hello
hello:
\t@echo 'Test successful.'
clean:
\trm -rf Makefile
EOS
system bin/"bmake"
system bin/"bmake", "clean"
end
end
bmake: update 20220612 bottle.
class Bmake < Formula
desc "Portable version of NetBSD make(1)"
homepage "https://www.crufty.net/help/sjg/bmake.html"
url "https://www.crufty.net/ftp/pub/sjg/bmake-20220612.tar.gz"
sha256 "e34bcc6375c75ae5b53551da0b1d6c1205cdee61e4f564e2cfe04081a5a682fa"
license "BSD-3-Clause"
livecheck do
url "https://www.crufty.net/ftp/pub/sjg/"
regex(/href=.*?bmake[._-]v?(\d{6,8})\.t/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "cf0f133f588f36936d923fb647cd92e9a4a1ecb07868b3ecebe32df7377930ef"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "33099f5ee54c088e6e534cf79b5ed6ce61f53ebb28f3f749ae5b6470abdc88bc"
sha256 monterey: "1152dc2e7c757d05890bce2f5d67cae877d6179eb228a969c6b1ab4e2f484a47"
sha256 big_sur: "ed16394880239ec8b6fd0214e02c5665ce05344e68b20474f28a098e1678b147"
sha256 catalina: "1b611932389043df5ac25f509a6503ebd5fddc879dbe59fce1ccf82f181c1664"
sha256 x86_64_linux: "7638ab6295ff1231bcb2072198f69aa24d944528b6186253112452dd0d00fc48"
end
def install
# Don't pre-roff cat pages.
inreplace "mk/man.mk", "MANTARGET?", "MANTARGET"
# -DWITHOUT_PROG_LINK means "don't symlink as bmake-VERSION."
# shell-ksh test segfaults since macOS 11.
args = ["--prefix=#{prefix}", "-DWITHOUT_PROG_LINK", "--install", "BROKEN_TESTS=shell-ksh"]
system "sh", "boot-strap", *args
man1.install "bmake.1"
end
test do
(testpath/"Makefile").write <<~EOS
all: hello
hello:
\t@echo 'Test successful.'
clean:
\trm -rf Makefile
EOS
system bin/"bmake"
system bin/"bmake", "clean"
end
end
|
$:.push File.expand_path("../lib", __FILE__)
require "doorkeeper/version"
Gem::Specification.new do |s|
s.name = "doorkeeper"
s.version = Doorkeeper::VERSION
s.authors = ["Felipe Elias Philipp", "Piotr Jakubowski"]
s.email = ["felipe@applicake.com", "piotr.jakubowski@applicake.com"]
s.homepage = "https://github.com/applicake/doorkeeper"
s.summary = "Doorkeeper is an OAuth 2 provider for Rails."
s.description = "Doorkeeper is an OAuth 2 provider for Rails."
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- test/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency "railties", ">= 3.1"
s.add_development_dependency "sqlite3", "~> 1.3.5"
s.add_development_dependency "rspec-rails", ">= 2.11.4"
s.add_development_dependency "capybara", "~> 1.1.2"
s.add_development_dependency "generator_spec", "~> 0.9.0"
s.add_development_dependency "factory_girl", "~> 2.6.4"
s.add_development_dependency "timecop", "~> 0.5.2"
s.add_development_dependency "database_cleaner", "~> 0.9.1"
s.add_development_dependency "bcrypt-ruby", "~> 3.0.1"
end
add jquery as gem dependency
$:.push File.expand_path("../lib", __FILE__)
require "doorkeeper/version"
Gem::Specification.new do |s|
s.name = "doorkeeper"
s.version = Doorkeeper::VERSION
s.authors = ["Felipe Elias Philipp", "Piotr Jakubowski"]
s.email = ["felipe@applicake.com", "piotr.jakubowski@applicake.com"]
s.homepage = "https://github.com/applicake/doorkeeper"
s.summary = "Doorkeeper is an OAuth 2 provider for Rails."
s.description = "Doorkeeper is an OAuth 2 provider for Rails."
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- test/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency "railties", ">= 3.1"
s.add_dependency "jquery-rails", "~> 3.0.4"
s.add_development_dependency "sqlite3", "~> 1.3.5"
s.add_development_dependency "rspec-rails", ">= 2.11.4"
s.add_development_dependency "capybara", "~> 1.1.2"
s.add_development_dependency "generator_spec", "~> 0.9.0"
s.add_development_dependency "factory_girl", "~> 2.6.4"
s.add_development_dependency "timecop", "~> 0.5.2"
s.add_development_dependency "database_cleaner", "~> 0.9.1"
s.add_development_dependency "bcrypt-ruby", "~> 3.0.1"
end
|
class ValentinaStudio < Cask
url 'http://www.valentina-db.com/download/release/mac_32/vstudio_5_mac.dmg'
homepage 'http://www.valentina-db.com/'
version 'latest'
sha256 :no_check
link 'Valentina Studio.app'
end
Reformat valentina-studio.rb according to readability conventions
class ValentinaStudio < Cask
version 'latest'
sha256 :no_check
url 'http://www.valentina-db.com/download/release/mac_32/vstudio_5_mac.dmg'
homepage 'http://www.valentina-db.com/'
link 'Valentina Studio.app'
end
|
require 'formula'
class UniversalPython < Requirement
satisfy(:build_env => false) { archs_for_command("python").universal? }
def message; <<-EOS.undent
A universal build was requested, but Python is not a universal build
Boost compiles against the Python it finds in the path; if this Python
is not a universal build then linking will likely fail.
EOS
end
end
class Boost < Formula
homepage 'http://www.boost.org'
url 'https://downloads.sourceforge.net/project/boost/boost/1.55.0/boost_1_55_0.tar.bz2'
sha1 'cef9a0cc7084b1d639e06cd3bc34e4251524c840'
revision 1
head 'https://github.com/boostorg/boost.git'
bottle do
cellar :any
sha1 "8febaa2cf64152663551ae34a30f3030a1c1c023" => :mavericks
sha1 "1567fbf688e212f0e5a24d246fa386ea99cab5ae" => :mountain_lion
sha1 "2ed8000a0abb993fdd2985383eae9126c4170f5e" => :lion
end
env :userpaths
option :universal
option 'with-icu', 'Build regexp engine with icu support'
option 'without-single', 'Disable building single-threading variant'
option 'without-static', 'Disable building static library variant'
option 'with-mpi', 'Build with MPI support'
option :cxx11
depends_on :python => :recommended
depends_on UniversalPython if build.universal? and build.with? "python"
if build.with? 'icu'
if build.cxx11?
depends_on 'icu4c' => 'c++11'
else
depends_on 'icu4c'
end
end
if build.with? 'mpi'
if build.cxx11?
depends_on 'open-mpi' => 'c++11'
else
depends_on :mpi => [:cc, :cxx, :optional]
end
end
odie 'boost: --with-c++11 has been renamed to --c++11' if build.with? 'c++11'
stable do
# Patches boost::atomic for LLVM 3.4 as it is used on OS X 10.9 with Xcode 5.1
# https://github.com/Homebrew/homebrew/issues/27396
# https://github.com/Homebrew/homebrew/pull/27436
patch :p2 do
url "https://github.com/boostorg/atomic/commit/6bb71fdd.patch"
sha1 "9ab8e6c041b4ecc291b2dd1a3c93e9b342d5e0e4"
end
patch :p2 do
url "https://github.com/boostorg/atomic/commit/e4bde20f.patch"
sha1 "f206e7261d00503788ae8ec3a0635ced8a816293"
end
end
fails_with :llvm do
build 2335
cause "Dropped arguments to functions when linking with boost"
end
def install
# https://svn.boost.org/trac/boost/ticket/8841
if build.with? 'mpi' and build.with? 'single'
raise <<-EOS.undent
Building MPI support for both single and multi-threaded flavors
is not supported. Please use '--with-mpi' together with
'--without-single'.
EOS
end
if build.cxx11? and build.with? 'mpi' and build.with? 'python'
raise <<-EOS.undent
Building MPI support for Python using C++11 mode results in
failure and hence disabled. Please don't use this combination
of options.
EOS
end
ENV.universal_binary if build.universal?
# Force boost to compile using the appropriate GCC version.
open("user-config.jam", "a") do |file|
file.write "using darwin : : #{ENV.cxx} ;\n"
file.write "using mpi ;\n" if build.with? 'mpi'
end
# we specify libdir too because the script is apparently broken
bargs = ["--prefix=#{prefix}", "--libdir=#{lib}"]
if build.with? 'icu'
icu4c_prefix = Formula['icu4c'].opt_prefix
bargs << "--with-icu=#{icu4c_prefix}"
else
bargs << '--without-icu'
end
# Handle libraries that will not be built.
without_libraries = []
# The context library is implemented as x86_64 ASM, so it
# won't build on PPC or 32-bit builds
# see https://github.com/Homebrew/homebrew/issues/17646
if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal?
without_libraries << "context"
# The coroutine library depends on the context library.
without_libraries << "coroutine"
end
# Boost.Log cannot be built using Apple GCC at the moment. Disabled
# on such systems.
without_libraries << "log" if ENV.compiler == :gcc || ENV.compiler == :llvm
without_libraries << "python" if build.without? 'python'
without_libraries << "mpi" if build.without? 'mpi'
bargs << "--without-libraries=#{without_libraries.join(',')}"
args = ["--prefix=#{prefix}",
"--libdir=#{lib}",
"-d2",
"-j#{ENV.make_jobs}",
"--layout=tagged",
"--user-config=user-config.jam",
"install"]
if build.with? "single"
args << "threading=multi,single"
else
args << "threading=multi"
end
if build.with? "static"
args << "link=shared,static"
else
args << "link=shared"
end
args << "address-model=32_64" << "architecture=x86" << "pch=off" if build.universal?
# Trunk starts using "clang++ -x c" to select C compiler which breaks C++11
# handling using ENV.cxx11. Using "cxxflags" and "linkflags" still works.
if build.cxx11?
args << "cxxflags=-std=c++11"
if ENV.compiler == :clang
args << "cxxflags=-stdlib=libc++" << "linkflags=-stdlib=libc++"
end
end
system "./bootstrap.sh", *bargs
system "./b2", *args
end
def caveats
s = ''
# ENV.compiler doesn't exist in caveats. Check library availability
# instead.
if Dir.glob("#{lib}/libboost_log*").empty?
s += <<-EOS.undent
Building of Boost.Log is disabled because it requires newer GCC or Clang.
EOS
end
if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal?
s += <<-EOS.undent
Building of Boost.Context and Boost.Coroutine is disabled as they are
only supported on x86_64.
EOS
end
s
end
end
boost: update patch sha1
Closes Homebrew/homebrew#28169.
Closes Homebrew/homebrew#28179.
Signed-off-by: Jack Nagel <43386ce32af96f5c56f2a88e458cb94cebee3751@gmail.com>
require 'formula'
class UniversalPython < Requirement
satisfy(:build_env => false) { archs_for_command("python").universal? }
def message; <<-EOS.undent
A universal build was requested, but Python is not a universal build
Boost compiles against the Python it finds in the path; if this Python
is not a universal build then linking will likely fail.
EOS
end
end
class Boost < Formula
homepage 'http://www.boost.org'
url 'https://downloads.sourceforge.net/project/boost/boost/1.55.0/boost_1_55_0.tar.bz2'
sha1 'cef9a0cc7084b1d639e06cd3bc34e4251524c840'
revision 1
head 'https://github.com/boostorg/boost.git'
bottle do
cellar :any
sha1 "8febaa2cf64152663551ae34a30f3030a1c1c023" => :mavericks
sha1 "1567fbf688e212f0e5a24d246fa386ea99cab5ae" => :mountain_lion
sha1 "2ed8000a0abb993fdd2985383eae9126c4170f5e" => :lion
end
env :userpaths
option :universal
option 'with-icu', 'Build regexp engine with icu support'
option 'without-single', 'Disable building single-threading variant'
option 'without-static', 'Disable building static library variant'
option 'with-mpi', 'Build with MPI support'
option :cxx11
depends_on :python => :recommended
depends_on UniversalPython if build.universal? and build.with? "python"
if build.with? 'icu'
if build.cxx11?
depends_on 'icu4c' => 'c++11'
else
depends_on 'icu4c'
end
end
if build.with? 'mpi'
if build.cxx11?
depends_on 'open-mpi' => 'c++11'
else
depends_on :mpi => [:cc, :cxx, :optional]
end
end
odie 'boost: --with-c++11 has been renamed to --c++11' if build.with? 'c++11'
stable do
# Patches boost::atomic for LLVM 3.4 as it is used on OS X 10.9 with Xcode 5.1
# https://github.com/Homebrew/homebrew/issues/27396
# https://github.com/Homebrew/homebrew/pull/27436
patch :p2 do
url "https://github.com/boostorg/atomic/commit/6bb71fdd.patch"
sha1 "8dfaf4d123f1161c83fff91d4ef70b8f95a4ef94"
end
patch :p2 do
url "https://github.com/boostorg/atomic/commit/e4bde20f.patch"
sha1 "f206e7261d00503788ae8ec3a0635ced8a816293"
end
end
fails_with :llvm do
build 2335
cause "Dropped arguments to functions when linking with boost"
end
def install
# https://svn.boost.org/trac/boost/ticket/8841
if build.with? 'mpi' and build.with? 'single'
raise <<-EOS.undent
Building MPI support for both single and multi-threaded flavors
is not supported. Please use '--with-mpi' together with
'--without-single'.
EOS
end
if build.cxx11? and build.with? 'mpi' and build.with? 'python'
raise <<-EOS.undent
Building MPI support for Python using C++11 mode results in
failure and hence disabled. Please don't use this combination
of options.
EOS
end
ENV.universal_binary if build.universal?
# Force boost to compile using the appropriate GCC version.
open("user-config.jam", "a") do |file|
file.write "using darwin : : #{ENV.cxx} ;\n"
file.write "using mpi ;\n" if build.with? 'mpi'
end
# we specify libdir too because the script is apparently broken
bargs = ["--prefix=#{prefix}", "--libdir=#{lib}"]
if build.with? 'icu'
icu4c_prefix = Formula['icu4c'].opt_prefix
bargs << "--with-icu=#{icu4c_prefix}"
else
bargs << '--without-icu'
end
# Handle libraries that will not be built.
without_libraries = []
# The context library is implemented as x86_64 ASM, so it
# won't build on PPC or 32-bit builds
# see https://github.com/Homebrew/homebrew/issues/17646
if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal?
without_libraries << "context"
# The coroutine library depends on the context library.
without_libraries << "coroutine"
end
# Boost.Log cannot be built using Apple GCC at the moment. Disabled
# on such systems.
without_libraries << "log" if ENV.compiler == :gcc || ENV.compiler == :llvm
without_libraries << "python" if build.without? 'python'
without_libraries << "mpi" if build.without? 'mpi'
bargs << "--without-libraries=#{without_libraries.join(',')}"
args = ["--prefix=#{prefix}",
"--libdir=#{lib}",
"-d2",
"-j#{ENV.make_jobs}",
"--layout=tagged",
"--user-config=user-config.jam",
"install"]
if build.with? "single"
args << "threading=multi,single"
else
args << "threading=multi"
end
if build.with? "static"
args << "link=shared,static"
else
args << "link=shared"
end
args << "address-model=32_64" << "architecture=x86" << "pch=off" if build.universal?
# Trunk starts using "clang++ -x c" to select C compiler which breaks C++11
# handling using ENV.cxx11. Using "cxxflags" and "linkflags" still works.
if build.cxx11?
args << "cxxflags=-std=c++11"
if ENV.compiler == :clang
args << "cxxflags=-stdlib=libc++" << "linkflags=-stdlib=libc++"
end
end
system "./bootstrap.sh", *bargs
system "./b2", *args
end
def caveats
s = ''
# ENV.compiler doesn't exist in caveats. Check library availability
# instead.
if Dir.glob("#{lib}/libboost_log*").empty?
s += <<-EOS.undent
Building of Boost.Log is disabled because it requires newer GCC or Clang.
EOS
end
if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal?
s += <<-EOS.undent
Building of Boost.Context and Boost.Coroutine is disabled as they are
only supported on x86_64.
EOS
end
s
end
end
|
require 'net/http'
module ServiceChangeNotifier
def notify_services_of_changes
Service.all.each do |s|
next if s.url.nil?
request = Net::HTTP.post_form(URI(s.url),
'services' =>
Service.all.to_json(include: :models))
if request.nil?
Net::HTTP.post_form(URI(s.url),
'error' => 'Request is nil')
elsif request == Net::HTTPSuccess
else
send_mail(s, status)
request.retry
end
end
end
end
Use service url instead of service
require 'net/http'
module ServiceChangeNotifier
def notify_services_of_changes
Service.all.each do |s|
next if s.url.nil?
request = Net::HTTP.post_form(URI(s.url),
'services' =>
Service.all.to_json(include: :models))
if request.nil?
Net::HTTP.post_form(URI(s.url),
'error' => 'Request is nil')
elsif request == Net::HTTPSuccess
else
send_mail(s.url, status)
request.retry
end
end
end
end
|
require 'formula'
class Botan < Formula
homepage 'http://botan.randombit.net/'
url 'http://botan.randombit.net/files/Botan-1.10.8.tbz'
sha1 'a7ba0be11629143043da078a4c044eac3369b4ec'
option 'enable-debug', 'Enable debug build of Botan'
# upstream ticket: https://bugs.randombit.net/show_bug.cgi?id=267
patch :DATA
def install
args = %W[
--prefix=#{prefix}
--docdir=#{share}/doc
--cpu=#{MacOS.preferred_arch}
--cc=#{ENV.compiler}
--os=darwin
--with-openssl
--with-zlib
--with-bzip2
]
args << "--enable-debug" if build.include? "enable-debug"
system "./configure.py", *args
# A hack to force them use our CFLAGS. MACH_OPT is empty in the Makefile
# but used for each call to cc/ld.
system "make", "install", "MACH_OPT=#{ENV.cflags}"
end
end
__END__
--- a/src/build-data/makefile/unix_shr.in
+++ b/src/build-data/makefile/unix_shr.in
@@ -57,8 +57,8 @@
LIBNAME = %{lib_prefix}libbotan
STATIC_LIB = $(LIBNAME)-$(SERIES).a
-SONAME = $(LIBNAME)-$(SERIES).%{so_suffix}.%{so_abi_rev}
-SHARED_LIB = $(SONAME).%{version_patch}
+SONAME = $(LIBNAME)-$(SERIES).%{so_abi_rev}.%{so_suffix}
+SHARED_LIB = $(LIBNAME)-$(SERIES).%{so_abi_rev}.%{version_patch}.%{so_suffix}
SYMLINK = $(LIBNAME)-$(SERIES).%{so_suffix}
botan: additional openssl dependency
Added OpenSSL dependency and double quotes everywhere. The download location has also moved upstream. Any attempt to use the old one just gets a redirect to the new one, so I’ve just switched it. For some reason the checksum has changed, but the pgp signature for the download file was verified fine.
require "formula"
class Botan < Formula
homepage "http://botan.randombit.net/"
url "http://files.randombit.net/botan/Botan-1.10.8.tgz"
sha1 "078fcb03c9ef0691621eda3ca312ebf08b3890cc"
revision 1
option "enable-debug", "Enable debug build of Botan"
depends_on "pkg-config" => :build
depends_on "openssl"
# upstream ticket: https://bugs.randombit.net/show_bug.cgi?id=267
patch :DATA
def install
args = %W[
--prefix=#{prefix}
--docdir=#{share}/doc
--cpu=#{MacOS.preferred_arch}
--cc=#{ENV.compiler}
--os=darwin
--with-openssl
--with-zlib
--with-bzip2
]
args << "--enable-debug" if build.include? "enable-debug"
system "./configure.py", *args
# A hack to force them use our CFLAGS. MACH_OPT is empty in the Makefile
# but used for each call to cc/ld.
system "make", "install", "MACH_OPT=#{ENV.cflags}"
end
end
__END__
--- a/src/build-data/makefile/unix_shr.in
+++ b/src/build-data/makefile/unix_shr.in
@@ -57,8 +57,8 @@
LIBNAME = %{lib_prefix}libbotan
STATIC_LIB = $(LIBNAME)-$(SERIES).a
-SONAME = $(LIBNAME)-$(SERIES).%{so_suffix}.%{so_abi_rev}
-SHARED_LIB = $(SONAME).%{version_patch}
+SONAME = $(LIBNAME)-$(SERIES).%{so_abi_rev}.%{so_suffix}
+SHARED_LIB = $(LIBNAME)-$(SERIES).%{so_abi_rev}.%{version_patch}.%{so_suffix}
SYMLINK = $(LIBNAME)-$(SERIES).%{so_suffix}
|
class Botan < Formula
desc "Cryptographic algorithms and formats library in C++"
homepage "https://botan.randombit.net/"
url "https://botan.randombit.net/releases/Botan-2.12.1.tar.xz"
sha256 "7e035f142a51fca1359705792627a282456d49749bf62a37a8e48375d41baaa9"
head "https://github.com/randombit/botan.git"
bottle do
sha256 "f5a85f91c7f2b59ce8dd5344d2b92c29bc23d48f73b926249998ce3db8ccac2e" => :catalina
sha256 "2feb4965ddb22f39b381f287ec86b51d752d6372ce09061323f0de2784aad913" => :mojave
sha256 "39fd93ccbbcc9facce634ea568875b16bd3dc14e91b129575a65b8441af70289" => :high_sierra
sha256 "26a88637571802493479451b59aa3f101a545d4c35d00be583d87dab2845b825" => :sierra
end
depends_on "pkg-config" => :build
depends_on "openssl@1.1"
def install
ENV.cxx11
args = %W[
--prefix=#{prefix}
--docdir=share/doc
--cpu=#{MacOS.preferred_arch}
--cc=#{ENV.compiler}
--os=darwin
--with-openssl
--with-zlib
--with-bzip2
]
system "./configure.py", *args
system "make", "install"
end
test do
(testpath/"test.txt").write "Homebrew"
(testpath/"testout.txt").write Utils.popen_read("#{bin}/botan base64_enc test.txt")
assert_match "Homebrew", shell_output("#{bin}/botan base64_dec testout.txt")
end
end
botan: update 2.12.1 bottle.
class Botan < Formula
desc "Cryptographic algorithms and formats library in C++"
homepage "https://botan.randombit.net/"
url "https://botan.randombit.net/releases/Botan-2.12.1.tar.xz"
sha256 "7e035f142a51fca1359705792627a282456d49749bf62a37a8e48375d41baaa9"
head "https://github.com/randombit/botan.git"
bottle do
sha256 "6e014274755eea746204793b4f6a1bbe1e338af984c23f9eedf51f2d631d17eb" => :catalina
sha256 "b014bfa6f440a8d06d2da28261e575b68e15cd1c2a34d42ae37777e97ce15827" => :mojave
sha256 "605df5ce325dcea0c6cb00349cf016b154f122e90fb1f7fcb791de9e6b0e48ae" => :high_sierra
end
depends_on "pkg-config" => :build
depends_on "openssl@1.1"
def install
ENV.cxx11
args = %W[
--prefix=#{prefix}
--docdir=share/doc
--cpu=#{MacOS.preferred_arch}
--cc=#{ENV.compiler}
--os=darwin
--with-openssl
--with-zlib
--with-bzip2
]
system "./configure.py", *args
system "make", "install"
end
test do
(testpath/"test.txt").write "Homebrew"
(testpath/"testout.txt").write Utils.popen_read("#{bin}/botan base64_enc test.txt")
assert_match "Homebrew", shell_output("#{bin}/botan base64_dec testout.txt")
end
end
|
class Boxes < Formula
desc "Draw boxes around text"
homepage "http://boxes.thomasjensen.com/"
url "https://github.com/ascii-boxes/boxes/archive/v1.1.3.tar.gz"
sha256 "4087ca01413c0aa79d4b9dcaf917e0a91721e5de76e8f6a38d1a16234e8290bf"
head "https://github.com/ascii-boxes/boxes.git"
bottle do
sha256 "5715225d1b80a729ce073906aad9a785c03cb4df064dfde0683595dc2fceb51b" => :sierra
sha256 "b34022a6136281c73eec0d470cf6cf1c520e681ca50055b0a026ba2430542ab8" => :el_capitan
sha256 "6c7f30eb447ce1c54d073aa3b8aa16611671522d709a460a8a53d08063a68d6b" => :yosemite
end
def install
# distro uses /usr/share/boxes change to prefix
system "make", "GLOBALCONF=#{share}/boxes-config", "CC=#{ENV.cc}"
bin.install "src/boxes"
man1.install "doc/boxes.1"
share.install "boxes-config"
end
test do
assert_match "test brew", pipe_output("#{bin}/boxes", "test brew")
end
end
boxes 1.2
Closes #11225.
Signed-off-by: Tomasz Pajor <ea73344294b1c6e2cb529d7fc98a4971de7607ac@polishgeeks.com>
class Boxes < Formula
desc "Draw boxes around text"
homepage "http://boxes.thomasjensen.com/"
url "https://github.com/ascii-boxes/boxes/archive/v1.2.tar.gz"
sha256 "ba237f6d4936bdace133d5f370674fd4c63bf0d767999a104bada6460c5d1913"
head "https://github.com/ascii-boxes/boxes.git"
bottle do
sha256 "5715225d1b80a729ce073906aad9a785c03cb4df064dfde0683595dc2fceb51b" => :sierra
sha256 "b34022a6136281c73eec0d470cf6cf1c520e681ca50055b0a026ba2430542ab8" => :el_capitan
sha256 "6c7f30eb447ce1c54d073aa3b8aa16611671522d709a460a8a53d08063a68d6b" => :yosemite
end
def install
# distro uses /usr/share/boxes change to prefix
system "make", "GLOBALCONF=#{share}/boxes-config", "CC=#{ENV.cc}"
bin.install "src/boxes"
man1.install "doc/boxes.1"
share.install "boxes-config"
end
test do
assert_match "test brew", pipe_output("#{bin}/boxes", "test brew")
end
end
|
class Broot < Formula
desc "New way to see and navigate directory trees"
homepage "https://dystroy.org/broot"
url "https://github.com/Canop/broot/archive/v0.13.1.tar.gz"
sha256 "594130c1e985379ce60885aab1b961d2326d0e5b34816d1c3590cf5837493742"
head "https://github.com/Canop/broot.git"
bottle do
cellar :any_skip_relocation
sha256 "62bfe1e7e688633f6caba3ae146935539445691d81fe36bacd2edeed33ca1f4f" => :catalina
sha256 "d89134eaf0dedfddb05fc37c360f86931d8fa380f4cd5cee9a6648b440707c21" => :mojave
sha256 "f0c29f3bdf1abffd219ba0c7bb7e228703b74e5a04f5202cb4dc3044364cf2bf" => :high_sierra
end
depends_on "rust" => :build
uses_from_macos "zlib"
def install
system "cargo", "install", "--locked", "--root", prefix, "--path", "."
end
test do
assert_match version.to_s, shell_output("#{bin}/broot --version")
assert_match "BFS", shell_output("#{bin}/broot --help 2>&1")
return if !OS.mac? && ENV["CI"]
(testpath/"test.exp").write <<~EOS
spawn #{bin}/broot --cmd :pt --no-style --out #{testpath}/output.txt
send "n\r"
expect {
timeout { exit 1 }
eof
}
EOS
assert_match "New Configuration file written in", shell_output("expect -f test.exp 2>&1")
end
end
broot: update 0.13.1 bottle.
class Broot < Formula
desc "New way to see and navigate directory trees"
homepage "https://dystroy.org/broot"
url "https://github.com/Canop/broot/archive/v0.13.1.tar.gz"
sha256 "594130c1e985379ce60885aab1b961d2326d0e5b34816d1c3590cf5837493742"
head "https://github.com/Canop/broot.git"
bottle do
cellar :any_skip_relocation
sha256 "62bfe1e7e688633f6caba3ae146935539445691d81fe36bacd2edeed33ca1f4f" => :catalina
sha256 "d89134eaf0dedfddb05fc37c360f86931d8fa380f4cd5cee9a6648b440707c21" => :mojave
sha256 "f0c29f3bdf1abffd219ba0c7bb7e228703b74e5a04f5202cb4dc3044364cf2bf" => :high_sierra
sha256 "0f3f067d533da8e2e5428ca10bde5199ea8869e1c49f52cb961a55829000eba5" => :x86_64_linux
end
depends_on "rust" => :build
uses_from_macos "zlib"
def install
system "cargo", "install", "--locked", "--root", prefix, "--path", "."
end
test do
assert_match version.to_s, shell_output("#{bin}/broot --version")
assert_match "BFS", shell_output("#{bin}/broot --help 2>&1")
return if !OS.mac? && ENV["CI"]
(testpath/"test.exp").write <<~EOS
spawn #{bin}/broot --cmd :pt --no-style --out #{testpath}/output.txt
send "n\r"
expect {
timeout { exit 1 }
eof
}
EOS
assert_match "New Configuration file written in", shell_output("expect -f test.exp 2>&1")
end
end
|
class Broot < Formula
desc "New way to see and navigate directory trees"
homepage "https://dystroy.org/broot"
url "https://github.com/Canop/broot/archive/v0.10.2.tar.gz"
sha256 "05b520b7511d06d152395b8ea9da3f78fe3bdc7fb2e262a338a7176c9511f395"
head "https://github.com/Canop/broot.git"
bottle do
cellar :any_skip_relocation
sha256 "8f199956e05eb8c777ee6f8f5ecd573d0f67e4502724b6a2a24eef632b377b80" => :catalina
sha256 "e7e084cdb1904deeb0f46710c962fe35496f470c0538ff4582404c1c028de95f" => :mojave
sha256 "ce7d18614a5cc44c3f85e1717b6cd4d1efbb005f3aedae96ac6d398cd22b4f06" => :high_sierra
end
depends_on "rust" => :build
def install
system "cargo", "install", "--locked", "--root", prefix, "--path", "."
end
test do
# Errno::EIO: Input/output error @ io_fread - /dev/pts/0
return if ENV["CI"]
require "pty"
%w[a b c].each { |f| (testpath/"root"/f).write("") }
PTY.spawn("#{bin}/broot", "--cmd", ":pt", "--no-style", "--out", "#{testpath}/output.txt", testpath/"root") do |r, _w, _pid|
r.read
assert_match <<~EOS, (testpath/"output.txt").read.gsub(/\r\n?/, "\n")
├──a
├──b
└──c
EOS
end
end
end
broot: update 0.10.2 bottle.
Closes #17328.
Signed-off-by: Dawid Dziurla <c4a7db180859322ef5630a1dfc2805b5bc97fc25@gmail.com>
class Broot < Formula
desc "New way to see and navigate directory trees"
homepage "https://dystroy.org/broot"
url "https://github.com/Canop/broot/archive/v0.10.2.tar.gz"
sha256 "05b520b7511d06d152395b8ea9da3f78fe3bdc7fb2e262a338a7176c9511f395"
head "https://github.com/Canop/broot.git"
bottle do
cellar :any_skip_relocation
sha256 "8f199956e05eb8c777ee6f8f5ecd573d0f67e4502724b6a2a24eef632b377b80" => :catalina
sha256 "e7e084cdb1904deeb0f46710c962fe35496f470c0538ff4582404c1c028de95f" => :mojave
sha256 "ce7d18614a5cc44c3f85e1717b6cd4d1efbb005f3aedae96ac6d398cd22b4f06" => :high_sierra
sha256 "e61f1847d9d3e027da073938f5479fadbec86edee1fc8b5d91ccfc7778f59123" => :x86_64_linux
end
depends_on "rust" => :build
def install
system "cargo", "install", "--locked", "--root", prefix, "--path", "."
end
test do
# Errno::EIO: Input/output error @ io_fread - /dev/pts/0
return if ENV["CI"]
require "pty"
%w[a b c].each { |f| (testpath/"root"/f).write("") }
PTY.spawn("#{bin}/broot", "--cmd", ":pt", "--no-style", "--out", "#{testpath}/output.txt", testpath/"root") do |r, _w, _pid|
r.read
assert_match <<~EOS, (testpath/"output.txt").read.gsub(/\r\n?/, "\n")
├──a
├──b
└──c
EOS
end
end
end
|
class Byacc < Formula
desc "(Arguably) the best yacc variant"
homepage "https://invisible-island.net/byacc/"
url "https://invisible-mirror.net/archives/byacc/byacc-20220101.tgz"
sha256 "a796ce90e960bf18d256eba534b9bd1e394d394a141ee63f530cab1074615b67"
license :public_domain
livecheck do
url "https://invisible-mirror.net/archives/byacc/"
regex(/href=.*?byacc[._-]v?(\d{6,8})\.t/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "e2a7d54ef43d59f0f2352ded6608967b5aab2a33915c74e4858c2ab170229244"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "a9e9305e8f5f140acc5dd6b6a07545ef5bc2a9aac2330e8007d0d124a202dcbe"
sha256 cellar: :any_skip_relocation, monterey: "fa94999844237e75827856e9646819ace52c520e7f98ccf4f5617efdddcde308"
sha256 cellar: :any_skip_relocation, big_sur: "8de8f4f52e0d1ac475663f828a3356c067c983b31da38638e514f9da6596b45e"
sha256 cellar: :any_skip_relocation, catalina: "40b79ddef97e27cb0d75c46f4bebab0d97d6e35f2e1bbfe034770da8bea98430"
sha256 cellar: :any_skip_relocation, x86_64_linux: "9a949fa6a625842e96aa7f579ce8d2f3049da1ded256610fcd2b46d213ae74fd"
end
def install
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--program-prefix=b", "--prefix=#{prefix}", "--man=#{man}"
system "make", "install"
end
test do
system bin/"byacc", "-V"
end
end
byacc 20220109
Closes #92818.
Signed-off-by: Carlo Cabrera <3ffc397d0e4bded29cb84b56167de54c01e3a55b@users.noreply.github.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Byacc < Formula
desc "(Arguably) the best yacc variant"
homepage "https://invisible-island.net/byacc/"
url "https://invisible-mirror.net/archives/byacc/byacc-20220109.tgz"
sha256 "98966bc5e6558f5ee50c7b33ee3e0a75efc15dd99cc96739d1ac1af9c1a43535"
license :public_domain
livecheck do
url "https://invisible-mirror.net/archives/byacc/"
regex(/href=.*?byacc[._-]v?(\d{6,8})\.t/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "e2a7d54ef43d59f0f2352ded6608967b5aab2a33915c74e4858c2ab170229244"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "a9e9305e8f5f140acc5dd6b6a07545ef5bc2a9aac2330e8007d0d124a202dcbe"
sha256 cellar: :any_skip_relocation, monterey: "fa94999844237e75827856e9646819ace52c520e7f98ccf4f5617efdddcde308"
sha256 cellar: :any_skip_relocation, big_sur: "8de8f4f52e0d1ac475663f828a3356c067c983b31da38638e514f9da6596b45e"
sha256 cellar: :any_skip_relocation, catalina: "40b79ddef97e27cb0d75c46f4bebab0d97d6e35f2e1bbfe034770da8bea98430"
sha256 cellar: :any_skip_relocation, x86_64_linux: "9a949fa6a625842e96aa7f579ce8d2f3049da1ded256610fcd2b46d213ae74fd"
end
def install
system "./configure", "--disable-debug", "--disable-dependency-tracking",
"--program-prefix=b", "--prefix=#{prefix}", "--man=#{man}"
system "make", "install"
end
test do
system bin/"byacc", "-V"
end
end
|
class Bzip2 < Formula
desc "Freely available high-quality data compressor"
homepage "http://www.bzip.org/"
url "https://ftp.osuosl.org/pub/clfs/conglomeration/bzip2/bzip2-1.0.6.tar.gz"
mirror "https://fossies.org/linux/misc/bzip2-1.0.6.tar.gz"
sha256 "a2848f34fcd5d6cf47def00461fcb528a0484d8edef8208d6d2e2909dc61d9cd"
revision 1
bottle do
cellar :any_skip_relocation
sha256 "197655415959a8e856f5926ebbae88715b8aef68fa8612aaf0bfe7e1c96723bf" => :high_sierra
sha256 "8911d7904862dc4930d024d0459390c510566241015bc06ec97f9e3fbb869101" => :sierra
sha256 "a22f768ce625a56cc2f4b3c7f08f4b1ba30f79865b786dc4c57a97f672badff4" => :el_capitan
sha256 "1468f967e8a35954509a8beb40bd29b60b730db158054aeddadc7586890737e8" => :yosemite
end
keg_only :provided_by_macos
def install
inreplace "Makefile", "$(PREFIX)/man", "$(PREFIX)/share/man"
system "make", "install", "PREFIX=#{prefix}"
end
test do
testfilepath = testpath + "sample_in.txt"
zipfilepath = testpath + "sample_in.txt.bz2"
testfilepath.write "TEST CONTENT"
system "#{bin}/bzip2", testfilepath
system "#{bin}/bunzip2", zipfilepath
assert_equal "TEST CONTENT", testfilepath.read
end
end
bzip2: secure url(s)
The canonical domain was not renewed.
Ref: https://lwn.net/Articles/762264/
class Bzip2 < Formula
desc "Freely available high-quality data compressor"
homepage "https://en.wikipedia.org/wiki/Bzip2"
url "https://ftp.osuosl.org/pub/clfs/conglomeration/bzip2/bzip2-1.0.6.tar.gz"
mirror "https://fossies.org/linux/misc/bzip2-1.0.6.tar.gz"
sha256 "a2848f34fcd5d6cf47def00461fcb528a0484d8edef8208d6d2e2909dc61d9cd"
revision 1
bottle do
cellar :any_skip_relocation
sha256 "197655415959a8e856f5926ebbae88715b8aef68fa8612aaf0bfe7e1c96723bf" => :high_sierra
sha256 "8911d7904862dc4930d024d0459390c510566241015bc06ec97f9e3fbb869101" => :sierra
sha256 "a22f768ce625a56cc2f4b3c7f08f4b1ba30f79865b786dc4c57a97f672badff4" => :el_capitan
sha256 "1468f967e8a35954509a8beb40bd29b60b730db158054aeddadc7586890737e8" => :yosemite
end
keg_only :provided_by_macos
def install
inreplace "Makefile", "$(PREFIX)/man", "$(PREFIX)/share/man"
system "make", "install", "PREFIX=#{prefix}"
end
test do
testfilepath = testpath + "sample_in.txt"
zipfilepath = testpath + "sample_in.txt.bz2"
testfilepath.write "TEST CONTENT"
system "#{bin}/bzip2", testfilepath
system "#{bin}/bunzip2", zipfilepath
assert_equal "TEST CONTENT", testfilepath.read
end
end
|
class Cacli < Formula
desc "Train machine learning models from Cloud Annotations"
homepage "https://cloud.annotations.ai"
url "https://github.com/cloud-annotations/training/archive/v1.3.1.tar.gz"
sha256 "fae8c52e5d2824846641f5bd25697d48e9701d35127a2032d230fd3415b1006b"
bottle do
cellar :any_skip_relocation
sha256 "eb3ed4080f932a028dad2ee995d563b224aba8050ce996d081a941fe22277b23" => :catalina
sha256 "45221a4f754e577cb36ef5cf4da0f70c84d90020932e72478ffadcd75dc875eb" => :mojave
sha256 "931fed5c23af443c9dbc8cce44d31e46d6626201a2a8aaa323addfa5a5e461ae" => :high_sierra
end
depends_on "go" => :build
def install
cd "cacli" do
project = "github.com/cloud-annotations/training/cacli"
system "go", "build",
"-ldflags", "-s -w -X #{project}/version.Version=#{version}",
"-o", bin/"cacli"
end
end
test do
# Attempt to list training runs without credentials and confirm that it
# fails as expected.
output = shell_output("#{bin}/cacli list 2>&1", 1).strip
cleaned = output.gsub(/\e\[([;\d]+)?m/, "") # Remove colors from output.
assert_match "FAILED\nNot logged in. Use 'cacli login' to log in.", cleaned
end
end
cacli: update 1.3.1 bottle.
class Cacli < Formula
desc "Train machine learning models from Cloud Annotations"
homepage "https://cloud.annotations.ai"
url "https://github.com/cloud-annotations/training/archive/v1.3.1.tar.gz"
sha256 "fae8c52e5d2824846641f5bd25697d48e9701d35127a2032d230fd3415b1006b"
bottle do
cellar :any_skip_relocation
sha256 "eb3ed4080f932a028dad2ee995d563b224aba8050ce996d081a941fe22277b23" => :catalina
sha256 "45221a4f754e577cb36ef5cf4da0f70c84d90020932e72478ffadcd75dc875eb" => :mojave
sha256 "931fed5c23af443c9dbc8cce44d31e46d6626201a2a8aaa323addfa5a5e461ae" => :high_sierra
sha256 "6bb21c84c89d61ae692b76c6c1c54a0235c9a7802d5c33a1a8e17d5bfe1a327a" => :x86_64_linux
end
depends_on "go" => :build
def install
cd "cacli" do
project = "github.com/cloud-annotations/training/cacli"
system "go", "build",
"-ldflags", "-s -w -X #{project}/version.Version=#{version}",
"-o", bin/"cacli"
end
end
test do
# Attempt to list training runs without credentials and confirm that it
# fails as expected.
output = shell_output("#{bin}/cacli list 2>&1", 1).strip
cleaned = output.gsub(/\e\[([;\d]+)?m/, "") # Remove colors from output.
assert_match "FAILED\nNot logged in. Use 'cacli login' to log in.", cleaned
end
end
|
class Caddy < Formula
desc "Alternative general-purpose HTTP/2 web server"
homepage "https://caddyserver.com/"
url "https://github.com/mholt/caddy/archive/v0.11.0.tar.gz"
sha256 "81e593d258460a9f5c6b5a5f46890a08b6b1ce15f5c0fc7bcaf09826368c3a1a"
head "https://github.com/mholt/caddy.git"
bottle do
cellar :any_skip_relocation
sha256 "898e5498690d8951290a80bcb5988f965ef0de03f9371784345abb8fac051467" => :high_sierra
sha256 "c732041f4a4e55f9ade4e043eac13c3e7099af21072beba8131d6e82d71e6999" => :sierra
sha256 "8ded8ce37d31009d0e5a810ea76320fcb7847cb317ceea2c60eadfff91eea453" => :el_capitan
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
ENV["GOOS"] = "darwin"
ENV["GOARCH"] = MacOS.prefer_64_bit? ? "amd64" : "386"
(buildpath/"src/github.com/mholt").mkpath
ln_s buildpath, "src/github.com/mholt/caddy"
system "go", "build", "-ldflags",
"-X github.com/mholt/caddy/caddy/caddymain.gitTag=#{version}",
"-o", bin/"caddy", "github.com/mholt/caddy/caddy"
end
test do
begin
io = IO.popen("#{bin}/caddy")
sleep 2
ensure
Process.kill("SIGINT", io.pid)
Process.wait(io.pid)
end
io.read =~ /0\.0\.0\.0:2015/
end
end
caddy: update 0.11.0 bottle.
class Caddy < Formula
desc "Alternative general-purpose HTTP/2 web server"
homepage "https://caddyserver.com/"
url "https://github.com/mholt/caddy/archive/v0.11.0.tar.gz"
sha256 "81e593d258460a9f5c6b5a5f46890a08b6b1ce15f5c0fc7bcaf09826368c3a1a"
head "https://github.com/mholt/caddy.git"
bottle do
cellar :any_skip_relocation
sha256 "14906b4bf0d7cb2b8bf034d7464645af3b06b484631b001e1e7af5358af112b5" => :high_sierra
sha256 "5a73e124c3e217c89325f753542dc626f80bbe78a5dcfe2f4613bd59a609f883" => :sierra
sha256 "04c0e14fd79ee5cf0aba00b8d3ab233bdf50eb47ee33e204a7e750c6c6a23615" => :el_capitan
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
ENV["GOOS"] = "darwin"
ENV["GOARCH"] = MacOS.prefer_64_bit? ? "amd64" : "386"
(buildpath/"src/github.com/mholt").mkpath
ln_s buildpath, "src/github.com/mholt/caddy"
system "go", "build", "-ldflags",
"-X github.com/mholt/caddy/caddy/caddymain.gitTag=#{version}",
"-o", bin/"caddy", "github.com/mholt/caddy/caddy"
end
test do
begin
io = IO.popen("#{bin}/caddy")
sleep 2
ensure
Process.kill("SIGINT", io.pid)
Process.wait(io.pid)
end
io.read =~ /0\.0\.0\.0:2015/
end
end
|
require "language/go"
class Caddy < Formula
desc "Alternative general-purpose HTTP/2 web server"
homepage "https://caddyserver.com/"
url "https://github.com/mholt/caddy/archive/v0.8.1.tar.gz"
sha256 "360e49087c084ac61498f6cb6acf8f4c2480656f7635672265156136b6ae7474"
head "https://github.com/mholt/caddy.git"
bottle do
cellar :any_skip_relocation
sha256 "42f193d8198defa82104f5a14a351373bec0c380809b5dcab96ee66dbc1fd941" => :el_capitan
sha256 "50989f247c3ef052bb6292897904d11f48c2551f70b09805a8789d526dd77061" => :yosemite
sha256 "a6c652d74658ecb21dc801f6c504aa6a5287aebdc042ee302b71ff471710ccd1" => :mavericks
end
depends_on "go" => :build
go_resource "github.com/BurntSushi/toml" do
url "https://github.com/BurntSushi/toml.git",
:revision => "5c4df71dfe9ac89ef6287afc05e4c1b16ae65a1e"
end
go_resource "github.com/dustin/go-humanize" do
url "https://github.com/dustin/go-humanize.git",
:revision => "8929fe90cee4b2cb9deb468b51fb34eba64d1bf0"
end
go_resource "github.com/flynn/go-shlex" do
url "https://github.com/flynn/go-shlex.git",
:revision => "3f9db97f856818214da2e1057f8ad84803971cff"
end
go_resource "github.com/gorilla/websocket" do
url "https://github.com/gorilla/websocket.git",
:revision => "3986be78bf859e01f01af631ad76da5b269d270c"
end
go_resource "github.com/hashicorp/go-syslog" do
url "https://github.com/hashicorp/go-syslog.git",
:revision => "42a2b573b664dbf281bd48c3cc12c086b17a39ba"
end
go_resource "github.com/jimstudt/http-authentication" do
url "https://github.com/jimstudt/http-authentication.git",
:revision => "3eca13d6893afd7ecabe15f4445f5d2872a1b012"
end
go_resource "github.com/russross/blackfriday" do
url "https://github.com/russross/blackfriday.git",
:revision => "c8875c0ed47e07b063c3628e2e4d4c9826721795"
end
go_resource "github.com/shurcooL/sanitized_anchor_name" do
url "https://github.com/shurcooL/sanitized_anchor_name.git",
:revision => "10ef21a441db47d8b13ebcc5fd2310f636973c77"
end
go_resource "github.com/square/go-jose" do
url "https://github.com/square/go-jose.git",
:revision => "37934a899dd03635373fd1e143936d32cfe48d31"
end
go_resource "github.com/xenolf/lego" do
url "https://github.com/xenolf/lego.git",
:revision => "db3a956d52bf23cc5201fe98bc9c9787d3b32c2d"
end
go_resource "golang.org/x/crypto" do
url "https://go.googlesource.com/crypto.git",
:revision => "3760e016850398b85094c4c99e955b8c3dea5711"
end
go_resource "golang.org/x/net" do
url "https://go.googlesource.com/net.git",
:revision => "72aa00c6241a8013dc9b040abb45f57edbe73945"
end
go_resource "gopkg.in/natefinch/lumberjack.v2" do
url "https://gopkg.in/natefinch/lumberjack.v2.git",
:revision => "600ceb4523e5b7ff745f91083c8a023c2bf73af5"
end
go_resource "gopkg.in/yaml.v2" do
url "https://gopkg.in/yaml.v2.git",
:revision => "f7716cbe52baa25d2e9b0d0da546fcf909fc16b4"
end
def install
ENV["GOPATH"] = buildpath
ENV["GOOS"] = "darwin"
ENV["GOARCH"] = MacOS.prefer_64_bit? ? "amd64" : "386"
mkdir_p buildpath/"src/github.com/mholt/"
ln_s buildpath, buildpath/"src/github.com/mholt/caddy"
Language::Go.stage_deps resources, buildpath/"src"
system "go", "build", "-o", bin/"caddy"
doc.install %w[README.md LICENSE.txt]
end
test do
begin
io = IO.popen("#{bin}/caddy")
sleep 2
ensure
Process.kill("SIGINT", io.pid)
Process.wait(io.pid)
end
io.read =~ /0\.0\.0\.0:2015/
end
end
caddy: update 0.8.1 bottle.
require "language/go"
class Caddy < Formula
desc "Alternative general-purpose HTTP/2 web server"
homepage "https://caddyserver.com/"
url "https://github.com/mholt/caddy/archive/v0.8.1.tar.gz"
sha256 "360e49087c084ac61498f6cb6acf8f4c2480656f7635672265156136b6ae7474"
head "https://github.com/mholt/caddy.git"
bottle do
cellar :any_skip_relocation
sha256 "8e0566facfab8e80e493fbfc1a15e374e58ff40c588efafc3b939e180e1c3395" => :el_capitan
sha256 "a732b1135987289bd4ddd93f558960852b04ae289fe2890bc4864f1399d4e2e8" => :yosemite
sha256 "43e2c583ce80d05b36746550b7de29767fd56f53d3555ec7ff4d2da75b4d7f53" => :mavericks
end
depends_on "go" => :build
go_resource "github.com/BurntSushi/toml" do
url "https://github.com/BurntSushi/toml.git",
:revision => "5c4df71dfe9ac89ef6287afc05e4c1b16ae65a1e"
end
go_resource "github.com/dustin/go-humanize" do
url "https://github.com/dustin/go-humanize.git",
:revision => "8929fe90cee4b2cb9deb468b51fb34eba64d1bf0"
end
go_resource "github.com/flynn/go-shlex" do
url "https://github.com/flynn/go-shlex.git",
:revision => "3f9db97f856818214da2e1057f8ad84803971cff"
end
go_resource "github.com/gorilla/websocket" do
url "https://github.com/gorilla/websocket.git",
:revision => "3986be78bf859e01f01af631ad76da5b269d270c"
end
go_resource "github.com/hashicorp/go-syslog" do
url "https://github.com/hashicorp/go-syslog.git",
:revision => "42a2b573b664dbf281bd48c3cc12c086b17a39ba"
end
go_resource "github.com/jimstudt/http-authentication" do
url "https://github.com/jimstudt/http-authentication.git",
:revision => "3eca13d6893afd7ecabe15f4445f5d2872a1b012"
end
go_resource "github.com/russross/blackfriday" do
url "https://github.com/russross/blackfriday.git",
:revision => "c8875c0ed47e07b063c3628e2e4d4c9826721795"
end
go_resource "github.com/shurcooL/sanitized_anchor_name" do
url "https://github.com/shurcooL/sanitized_anchor_name.git",
:revision => "10ef21a441db47d8b13ebcc5fd2310f636973c77"
end
go_resource "github.com/square/go-jose" do
url "https://github.com/square/go-jose.git",
:revision => "37934a899dd03635373fd1e143936d32cfe48d31"
end
go_resource "github.com/xenolf/lego" do
url "https://github.com/xenolf/lego.git",
:revision => "db3a956d52bf23cc5201fe98bc9c9787d3b32c2d"
end
go_resource "golang.org/x/crypto" do
url "https://go.googlesource.com/crypto.git",
:revision => "3760e016850398b85094c4c99e955b8c3dea5711"
end
go_resource "golang.org/x/net" do
url "https://go.googlesource.com/net.git",
:revision => "72aa00c6241a8013dc9b040abb45f57edbe73945"
end
go_resource "gopkg.in/natefinch/lumberjack.v2" do
url "https://gopkg.in/natefinch/lumberjack.v2.git",
:revision => "600ceb4523e5b7ff745f91083c8a023c2bf73af5"
end
go_resource "gopkg.in/yaml.v2" do
url "https://gopkg.in/yaml.v2.git",
:revision => "f7716cbe52baa25d2e9b0d0da546fcf909fc16b4"
end
def install
ENV["GOPATH"] = buildpath
ENV["GOOS"] = "darwin"
ENV["GOARCH"] = MacOS.prefer_64_bit? ? "amd64" : "386"
mkdir_p buildpath/"src/github.com/mholt/"
ln_s buildpath, buildpath/"src/github.com/mholt/caddy"
Language::Go.stage_deps resources, buildpath/"src"
system "go", "build", "-o", bin/"caddy"
doc.install %w[README.md LICENSE.txt]
end
test do
begin
io = IO.popen("#{bin}/caddy")
sleep 2
ensure
Process.kill("SIGINT", io.pid)
Process.wait(io.pid)
end
io.read =~ /0\.0\.0\.0:2015/
end
end
|
class Caffe < Formula
desc "Fast open framework for deep learning"
homepage "https://caffe.berkeleyvision.org/"
url "https://github.com/BVLC/caffe/archive/1.0.tar.gz"
sha256 "71d3c9eb8a183150f965a465824d01fe82826c22505f7aa314f700ace03fa77f"
revision 7
bottle do
sha256 "30122317b26b4d7a80b3ed7f553d91107c251cc37345e27958661e74fea47ec7" => :mojave
sha256 "721b467dc10a5f8aee917320316d4ae28cb37b0364b26a39f7bf4fde2b3cd8b8" => :high_sierra
sha256 "1161eb4c1a61e167a2a3f0e43239223cdfe9fa7039b2430541fde663fee21c1e" => :sierra
end
depends_on "cmake" => :build
depends_on "boost"
depends_on "gflags"
depends_on "glog"
depends_on "hdf5"
depends_on "leveldb"
depends_on "lmdb"
depends_on "opencv"
depends_on "protobuf"
depends_on "snappy"
depends_on "szip"
resource "test_model_weights" do
url "http://dl.caffe.berkeleyvision.org/bvlc_reference_caffenet.caffemodel"
sha256 "472d4a06035497b180636d8a82667129960371375bd10fcb6df5c6c7631f25e0"
end
needs :cxx11
def install
ENV.cxx11
args = std_cmake_args + %w[
-DALLOW_LMDB_NOLOCK=OFF
-DBUILD_SHARED_LIBS=ON
-DBUILD_docs=OFF
-DBUILD_matlab=OFF
-DBUILD_python=OFF
-DBUILD_python_layer=OFF
-DCPU_ONLY=ON
-DUSE_LEVELDB=ON
-DUSE_LMDB=ON
-DUSE_NCCL=OFF
-DUSE_OPENCV=ON
-DUSE_OPENMP=OFF
]
system "cmake", ".", *args
system "make", "install"
pkgshare.install "models"
end
test do
model = "bvlc_reference_caffenet"
m_path = "#{pkgshare}/models/#{model}"
resource("test_model_weights").stage do
system "#{bin}/caffe", "test",
"-model", "#{m_path}/deploy.prototxt",
"-solver", "#{m_path}/solver.prototxt",
"-weights", "#{model}.caffemodel"
end
end
end
caffe: revision bump for openblas
class Caffe < Formula
desc "Fast open framework for deep learning"
homepage "https://caffe.berkeleyvision.org/"
url "https://github.com/BVLC/caffe/archive/1.0.tar.gz"
sha256 "71d3c9eb8a183150f965a465824d01fe82826c22505f7aa314f700ace03fa77f"
revision 8
bottle do
sha256 "30122317b26b4d7a80b3ed7f553d91107c251cc37345e27958661e74fea47ec7" => :mojave
sha256 "721b467dc10a5f8aee917320316d4ae28cb37b0364b26a39f7bf4fde2b3cd8b8" => :high_sierra
sha256 "1161eb4c1a61e167a2a3f0e43239223cdfe9fa7039b2430541fde663fee21c1e" => :sierra
end
depends_on "cmake" => :build
depends_on "boost"
depends_on "gflags"
depends_on "glog"
depends_on "hdf5"
depends_on "leveldb"
depends_on "lmdb"
depends_on "opencv"
depends_on "protobuf"
depends_on "snappy"
depends_on "szip"
resource "test_model_weights" do
url "http://dl.caffe.berkeleyvision.org/bvlc_reference_caffenet.caffemodel"
sha256 "472d4a06035497b180636d8a82667129960371375bd10fcb6df5c6c7631f25e0"
end
needs :cxx11
def install
ENV.cxx11
args = std_cmake_args + %w[
-DALLOW_LMDB_NOLOCK=OFF
-DBUILD_SHARED_LIBS=ON
-DBUILD_docs=OFF
-DBUILD_matlab=OFF
-DBUILD_python=OFF
-DBUILD_python_layer=OFF
-DCPU_ONLY=ON
-DUSE_LEVELDB=ON
-DUSE_LMDB=ON
-DUSE_NCCL=OFF
-DUSE_OPENCV=ON
-DUSE_OPENMP=OFF
]
system "cmake", ".", *args
system "make", "install"
pkgshare.install "models"
end
test do
model = "bvlc_reference_caffenet"
m_path = "#{pkgshare}/models/#{model}"
resource("test_model_weights").stage do
system "#{bin}/caffe", "test",
"-model", "#{m_path}/deploy.prototxt",
"-solver", "#{m_path}/solver.prototxt",
"-weights", "#{model}.caffemodel"
end
end
end
|
require 'numo/narray'
require 'chainer'
require "datasets"
class IrisChain < Chainer::Chain
L = Chainer::Links::Connection::Linear
F = Chainer::Functions
def initialize(n_units, n_out)
super()
init_scope do
@l1 = L.new(nil, out_size: n_units)
@l2 = L.new(nil, out_size: n_out)
end
end
def call(x, y)
return F::Loss::MeanSquaredError.mean_squared_error(fwd(x), y)
end
def fwd(x)
h1 = F::Activation::Sigmoid.sigmoid(@l1.(x))
h2 = @l2.(h1)
return h2
end
end
model = IrisChain.new(6,3)
optimizer = Chainer::Optimizers::Adam.new
optimizer.setup(model)
iris = Datasets::Iris.new
iris_table = iris.to_table
x = iris_table.fetch_values(:sepal_length, :sepal_width, :petal_length, :petal_width).transpose
# target
y_class = iris_table[:class]
# class index array
# ["Iris-setosa", "Iris-versicolor", "Iris-virginica"]
class_name = y_class.uniq
# y => [0, 0, 0, 0, ,,, 1, 1, ,,, ,2, 2]
y = y_class.map{|s|
class_name.index(s)
}
# y_onehot => One-hot [[1.0, 0.0, 0.0], [1.0, 0.0, 0.0],,, [0.0, 1.0, 0.0], ,, [0.0, 0.0, 1.0]]
y_onehot = Numo::SFloat.eye(class_name.size)[y,false]
puts "Iris Datasets"
puts "No. [sepal_length, sepal_width, petal_length, petal_width] one-hot #=> class"
x.each_with_index{|r, i|
puts "#{'%3d' % i} : [#{r.join(', ')}] #{y_onehot[i, false].to_a} #=> #{y_class[i]}(#{y[i]})"
}
# [5.1, 3.5, 1.4, 0.2, "Iris-setosa"] => 50 data
# [7.0, 3.2, 4.7, 1.4, "Iris-versicolor"] => 50 data
# [6.3, 3.3, 6.0, 2.5, "Iris-virginica"] => 50 data
x = Numo::SFloat.cast(x)
y = Numo::SFloat.cast(y)
y_onehot = Numo::SFloat.cast(y_onehot)
x_train = x[(1..-1).step(2), true] #=> 75 data (Iris-setosa : 25, Iris-versicolor : 25, Iris-virginica : 25)
y_train = y_onehot[(1..-1).step(2), true] #=> 75 data (Iris-setosa : 25, Iris-versicolor : 25, Iris-virginica : 25)
x_test = x[(0..-1).step(2), true] #=> 75 data (Iris-setosa : 25, Iris-versicolor : 25, Iris-virginica : 25)
y_test = y[(0..-1).step(2)] #=> 75 data (Iris-setosa : 25, Iris-versicolor : 25, Iris-virginica : 25)
puts
# Train
print("Training ")
10000.times{|i|
print(".") if i % 1000 == 0
x = Chainer::Variable.new(x_train)
y = Chainer::Variable.new(y_train)
model.cleargrads()
loss = model.(x, y)
loss.backward()
optimizer.update()
}
puts
# Test
xt = Chainer::Variable.new(x_test)
yt = model.fwd(xt)
n_row, n_col = yt.data.shape
puts "Result : Correct Answer : Answer <= One-Hot"
ok = 0
n_row.times{|i|
ans = yt.data[i, true].max_index()
if ans == y_test[i]
ok += 1
printf("OK")
else
printf("--")
end
printf(" : #{y_test[i].to_i} :")
puts " #{ans.to_i} <= #{yt.data[i, 0..-1].to_a}"
}
puts "Row: #{n_row}, Column: #{n_col}"
puts "Accuracy rate : #{ok}/#{n_row} = #{ok.to_f / n_row}"
Support cumo in iris example
require 'numo/narray'
require 'chainer'
require "datasets"
class IrisChain < Chainer::Chain
L = Chainer::Links::Connection::Linear
F = Chainer::Functions
def initialize(n_units, n_out)
super()
init_scope do
@l1 = L.new(nil, out_size: n_units)
@l2 = L.new(nil, out_size: n_out)
end
end
def call(x, y)
return F::Loss::MeanSquaredError.mean_squared_error(fwd(x), y)
end
def fwd(x)
h1 = F::Activation::Sigmoid.sigmoid(@l1.(x))
h2 = @l2.(h1)
return h2
end
end
device = Chainer.get_device(Integer(ENV['RED_CHAINER_GPU'] || -1))
Chainer.set_default_device(device)
xm = device.xm
model = IrisChain.new(6,3)
optimizer = Chainer::Optimizers::Adam.new
optimizer.setup(model)
iris = Datasets::Iris.new
iris_table = iris.to_table
x = iris_table.fetch_values(:sepal_length, :sepal_width, :petal_length, :petal_width).transpose
# target
y_class = iris_table[:class]
# class index array
# ["Iris-setosa", "Iris-versicolor", "Iris-virginica"]
class_name = y_class.uniq
# y => [0, 0, 0, 0, ,,, 1, 1, ,,, ,2, 2]
y = y_class.map{|s|
class_name.index(s)
}
# y_onehot => One-hot [[1.0, 0.0, 0.0], [1.0, 0.0, 0.0],,, [0.0, 1.0, 0.0], ,, [0.0, 0.0, 1.0]]
y_onehot = xm::SFloat.eye(class_name.size)[y, false]
puts "Iris Datasets"
puts "No. [sepal_length, sepal_width, petal_length, petal_width] one-hot #=> class"
x.each_with_index{|r, i|
puts "#{'%3d' % i} : [#{r.join(', ')}] #{y_onehot[i, false].to_a} #=> #{y_class[i]}(#{y[i]})"
}
# [5.1, 3.5, 1.4, 0.2, "Iris-setosa"] => 50 data
# [7.0, 3.2, 4.7, 1.4, "Iris-versicolor"] => 50 data
# [6.3, 3.3, 6.0, 2.5, "Iris-virginica"] => 50 data
x = xm::SFloat.cast(x)
y = xm::SFloat.cast(y)
y_onehot = xm::SFloat.cast(y_onehot)
x_train = x[(1..-1).step(2), true] #=> 75 data (Iris-setosa : 25, Iris-versicolor : 25, Iris-virginica : 25)
y_train = y_onehot[(1..-1).step(2), true] #=> 75 data (Iris-setosa : 25, Iris-versicolor : 25, Iris-virginica : 25)
x_test = x[(0..-1).step(2), true] #=> 75 data (Iris-setosa : 25, Iris-versicolor : 25, Iris-virginica : 25)
y_test = y[(0..-1).step(2)] #=> 75 data (Iris-setosa : 25, Iris-versicolor : 25, Iris-virginica : 25)
puts
# Train
print("Training ")
10000.times{|i|
print(".") if i % 1000 == 0
x = Chainer::Variable.new(x_train)
y = Chainer::Variable.new(y_train)
model.cleargrads()
loss = model.(x, y)
loss.backward()
optimizer.update()
}
puts
# Test
xt = Chainer::Variable.new(x_test)
yt = model.fwd(xt)
n_row, n_col = yt.data.shape
puts "Result : Correct Answer : Answer <= One-Hot"
ok = 0
n_row.times{|i|
ans = yt.data[i, true].max_index()
if ans == y_test[i]
ok += 1
printf("OK")
else
printf("--")
end
printf(" : #{y_test[i].to_i} :")
puts " #{ans.to_i} <= #{yt.data[i, 0..-1].to_a}"
}
puts "Row: #{n_row}, Column: #{n_col}"
puts "Accuracy rate : #{ok}/#{n_row} = #{ok.to_f / n_row}"
|
class Cairo < Formula
desc "Vector graphics library with cross-device output support"
homepage "https://cairographics.org/"
url "https://cairographics.org/releases/cairo-1.14.12.tar.xz"
mirror "https://www.mirrorservice.org/sites/ftp.netbsd.org/pub/pkgsrc/distfiles/cairo-1.14.12.tar.xz"
sha256 "8c90f00c500b2299c0a323dd9beead2a00353752b2092ead558139bd67f7bf16"
bottle do
sha256 "5a6cc135f8a373376dac7d8e2750d10c955fd83977f5549976ad590958971f93" => :mojave
sha256 "5bdc28de8e5a615ab664d43f7f322ed02d58071171415bb6e2750f486b9465e2" => :high_sierra
sha256 "102847d74a0a11bb6143d93b9f32e1736e88036fb4c685d554a8bcd376bbd929" => :sierra
sha256 "bec85433a35605164bdbf5f8913e29eb6d9ceb5acc5569dd9d864706ae6c8d49" => :el_capitan
end
devel do
url "https://cairographics.org/snapshots/cairo-1.15.12.tar.xz"
sha256 "7623081b94548a47ee6839a7312af34e9322997806948b6eec421a8c6d0594c9"
end
head do
url "https://anongit.freedesktop.org/git/cairo", :using => :git
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "fontconfig"
depends_on "freetype"
depends_on "glib"
depends_on "libpng"
depends_on "pixman"
def install
if build.head?
ENV["NOCONFIGURE"] = "1"
system "./autogen.sh"
end
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--enable-gobject=yes",
"--enable-svg=yes",
"--enable-tee=yes",
"--enable-quartz-image",
"--enable-xcb=no",
"--enable-xlib=no",
"--enable-xlib-xrender=no"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <cairo.h>
int main(int argc, char *argv[]) {
cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 600, 400);
cairo_t *context = cairo_create(surface);
return 0;
}
EOS
fontconfig = Formula["fontconfig"]
freetype = Formula["freetype"]
gettext = Formula["gettext"]
glib = Formula["glib"]
libpng = Formula["libpng"]
pixman = Formula["pixman"]
flags = %W[
-I#{fontconfig.opt_include}
-I#{freetype.opt_include}/freetype2
-I#{gettext.opt_include}
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{include}/cairo
-I#{libpng.opt_include}/libpng16
-I#{pixman.opt_include}/pixman-1
-L#{lib}
-lcairo
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
cairo 1.15.14 (devel)
class Cairo < Formula
desc "Vector graphics library with cross-device output support"
homepage "https://cairographics.org/"
url "https://cairographics.org/releases/cairo-1.14.12.tar.xz"
mirror "https://www.mirrorservice.org/sites/ftp.netbsd.org/pub/pkgsrc/distfiles/cairo-1.14.12.tar.xz"
sha256 "8c90f00c500b2299c0a323dd9beead2a00353752b2092ead558139bd67f7bf16"
bottle do
sha256 "5a6cc135f8a373376dac7d8e2750d10c955fd83977f5549976ad590958971f93" => :mojave
sha256 "5bdc28de8e5a615ab664d43f7f322ed02d58071171415bb6e2750f486b9465e2" => :high_sierra
sha256 "102847d74a0a11bb6143d93b9f32e1736e88036fb4c685d554a8bcd376bbd929" => :sierra
sha256 "bec85433a35605164bdbf5f8913e29eb6d9ceb5acc5569dd9d864706ae6c8d49" => :el_capitan
end
devel do
url "https://cairographics.org/snapshots/cairo-1.15.14.tar.xz"
sha256 "16566b6c015a761bb0b7595cf879b77f8de85f90b443119083c4c2769b93298d"
end
head do
url "https://anongit.freedesktop.org/git/cairo", :using => :git
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "fontconfig"
depends_on "freetype"
depends_on "glib"
depends_on "libpng"
depends_on "pixman"
def install
if build.head?
ENV["NOCONFIGURE"] = "1"
system "./autogen.sh"
end
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--enable-gobject=yes",
"--enable-svg=yes",
"--enable-tee=yes",
"--enable-quartz-image",
"--enable-xcb=no",
"--enable-xlib=no",
"--enable-xlib-xrender=no"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <cairo.h>
int main(int argc, char *argv[]) {
cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 600, 400);
cairo_t *context = cairo_create(surface);
return 0;
}
EOS
fontconfig = Formula["fontconfig"]
freetype = Formula["freetype"]
gettext = Formula["gettext"]
glib = Formula["glib"]
libpng = Formula["libpng"]
pixman = Formula["pixman"]
flags = %W[
-I#{fontconfig.opt_include}
-I#{freetype.opt_include}/freetype2
-I#{gettext.opt_include}
-I#{glib.opt_include}/glib-2.0
-I#{glib.opt_lib}/glib-2.0/include
-I#{include}/cairo
-I#{libpng.opt_include}/libpng16
-I#{pixman.opt_include}/pixman-1
-L#{lib}
-lcairo
]
system ENV.cc, "test.c", "-o", "test", *flags
system "./test"
end
end
|
class Carla < Formula
desc "Audio plugin host supporting LADSPA, LV2, VST2/3, SF2 and more"
homepage "https://kxstudio.linuxaudio.org/Applications:Carla"
url "https://github.com/falkTX/Carla/archive/v2.4.2.tar.gz"
sha256 "376884965e685242953cab757818dde262209c651bd563a04eade0678c6b9f39"
license "GPL-2.0-or-later"
head "https://github.com/falkTX/Carla.git", branch: "main"
livecheck do
url :stable
strategy :github_latest
end
bottle do
sha256 cellar: :any, arm64_big_sur: "47675f00c8b4a6651eb405321709115d71886fe0b9b13badf82cbd42bba34825"
sha256 cellar: :any, big_sur: "0303540b446d18d094cd6672687fbf80f434baa5fd92dc0d98c7fa30c672d184"
sha256 cellar: :any, catalina: "e81b8c253c51edf12ddef8b6ad8f2e4409102d98b9ce3cf5ea12a8f3f965eb21"
end
depends_on "pkg-config" => :build
depends_on "fluid-synth"
depends_on "liblo"
depends_on "libmagic"
depends_on "pyqt@5"
depends_on "python@3.9"
on_linux do
depends_on "gcc"
end
fails_with gcc: "5"
def install
system "make"
system "make", "install", "PREFIX=#{prefix}"
inreplace bin/"carla", "PYTHON=$(which python3 2>/dev/null)",
"PYTHON=#{Formula["python@3.9"].opt_bin}/python3"
end
test do
system bin/"carla", "--version"
system lib/"carla/carla-discovery-native", "internal", ":all"
end
end
carla: update 2.4.2 bottle.
class Carla < Formula
desc "Audio plugin host supporting LADSPA, LV2, VST2/3, SF2 and more"
homepage "https://kxstudio.linuxaudio.org/Applications:Carla"
url "https://github.com/falkTX/Carla/archive/v2.4.2.tar.gz"
sha256 "376884965e685242953cab757818dde262209c651bd563a04eade0678c6b9f39"
license "GPL-2.0-or-later"
head "https://github.com/falkTX/Carla.git", branch: "main"
livecheck do
url :stable
strategy :github_latest
end
bottle do
sha256 cellar: :any, arm64_big_sur: "47675f00c8b4a6651eb405321709115d71886fe0b9b13badf82cbd42bba34825"
sha256 cellar: :any, big_sur: "0303540b446d18d094cd6672687fbf80f434baa5fd92dc0d98c7fa30c672d184"
sha256 cellar: :any, catalina: "e81b8c253c51edf12ddef8b6ad8f2e4409102d98b9ce3cf5ea12a8f3f965eb21"
sha256 cellar: :any_skip_relocation, x86_64_linux: "f83cc88afa3b583ee452b733cd4de4664c0fd7578ee24ab89d7cea314bfb7eb0"
end
depends_on "pkg-config" => :build
depends_on "fluid-synth"
depends_on "liblo"
depends_on "libmagic"
depends_on "pyqt@5"
depends_on "python@3.9"
on_linux do
depends_on "gcc"
end
fails_with gcc: "5"
def install
system "make"
system "make", "install", "PREFIX=#{prefix}"
inreplace bin/"carla", "PYTHON=$(which python3 2>/dev/null)",
"PYTHON=#{Formula["python@3.9"].opt_bin}/python3"
end
test do
system bin/"carla", "--version"
system lib/"carla/carla-discovery-native", "internal", ":all"
end
end
|
require "language/haskell"
class Cgrep < Formula
include Language::Haskell::Cabal
desc "Context-aware grep for source code"
homepage "https://github.com/awgn/cgrep"
url "https://github.com/awgn/cgrep/archive/v6.6.32.tar.gz"
sha256 "c45d680a2a00ef9524fc921e4c10fc7e68f02e57f4d6f1e640b7638a2f49c198"
head "https://github.com/awgn/cgrep.git"
bottle do
cellar :any
sha256 "25a3c4ff800a06814949513f5ff70cffa610af9f49d08b72ee63070c39cc5f4d" => :catalina
sha256 "c402c0135483f72bfa98f3c53552d5cd9cbf2741e4934ee41451cc8a7cfbd781" => :mojave
sha256 "051c1842b448fb60b03c8afbdcd2827b94f8dfeab694a2f8a7bb8a438f64fc8d" => :high_sierra
end
depends_on "cabal-install" => :build
depends_on "ghc" => :build
depends_on "pkg-config" => :build
depends_on "pcre"
def install
install_cabal_package
end
test do
(testpath/"t.rb").write <<~EOS
# puts test comment.
puts "test literal."
EOS
assert_match ":1", shell_output("#{bin}/cgrep --count --comment test t.rb")
assert_match ":1", shell_output("#{bin}/cgrep --count --literal test t.rb")
assert_match ":1", shell_output("#{bin}/cgrep --count --code puts t.rb")
assert_match ":2", shell_output("#{bin}/cgrep --count puts t.rb")
end
end
cgrep: update 6.6.32 bottle.
require "language/haskell"
class Cgrep < Formula
include Language::Haskell::Cabal
desc "Context-aware grep for source code"
homepage "https://github.com/awgn/cgrep"
url "https://github.com/awgn/cgrep/archive/v6.6.32.tar.gz"
sha256 "c45d680a2a00ef9524fc921e4c10fc7e68f02e57f4d6f1e640b7638a2f49c198"
head "https://github.com/awgn/cgrep.git"
bottle do
cellar :any
sha256 "972f5d6688cd84ead3bc27a68a1a80936c0a62327ed6b39e7e7db0c84f88102c" => :catalina
sha256 "b6a491e69db289915f94813b51f401f672e12d9e075620a51e66c7c8883d5af2" => :mojave
sha256 "24170492fb0c2955676309ccdedd9c5bbfab037d90215c661ec3cb582a76ce34" => :high_sierra
end
depends_on "cabal-install" => :build
depends_on "ghc" => :build
depends_on "pkg-config" => :build
depends_on "pcre"
def install
install_cabal_package
end
test do
(testpath/"t.rb").write <<~EOS
# puts test comment.
puts "test literal."
EOS
assert_match ":1", shell_output("#{bin}/cgrep --count --comment test t.rb")
assert_match ":1", shell_output("#{bin}/cgrep --count --literal test t.rb")
assert_match ":1", shell_output("#{bin}/cgrep --count --code puts t.rb")
assert_match ":2", shell_output("#{bin}/cgrep --count puts t.rb")
end
end
|
class Cheat < Formula
include Language::Python::Virtualenv
desc "Create and view interactive cheat sheets for *nix commands"
homepage "https://github.com/chrisallenlane/cheat"
url "https://github.com/chrisallenlane/cheat/archive/2.1.26.tar.gz"
sha256 "427c4e5c9a76b78802c1b1959668af20812e8fae8474d9258fb726f166e8f498"
head "https://github.com/chrisallenlane/cheat.git"
bottle do
cellar :any_skip_relocation
sha256 "84bd2ebdbbf37b72e41eeedbdc558321d2508f202adc006ad94f82f5b1e32094" => :el_capitan
sha256 "6e60a0e4bd0211e5a9b6d5c1b2f58d2a21cb4dbd5bc0586c678162c4285477e9" => :yosemite
sha256 "8c5796ed54ee16c81fabec5d2d3e71724dc307b06261ac26ef2edec9182c99b4" => :mavericks
end
depends_on :python if MacOS.version <= :snow_leopard
resource "docopt" do
url "https://files.pythonhosted.org/packages/a2/55/8f8cab2afd404cf578136ef2cc5dfb50baa1761b68c9da1fb1e4eed343c9/docopt-0.6.2.tar.gz"
sha256 "49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491"
end
resource "Pygments" do
url "https://files.pythonhosted.org/packages/b8/67/ab177979be1c81bc99c8d0592ef22d547e70bb4c6815c383286ed5dec504/Pygments-2.1.3.tar.gz"
sha256 "88e4c8a91b2af5962bfa5ea2447ec6dd357018e86e94c7d14bd8cacbc5b55d81"
end
def install
virtualenv_install_with_resources
bash_completion.install "cheat/autocompletion/cheat.bash"
zsh_completion.install "cheat/autocompletion/cheat.zsh" => "_cheat"
end
test do
system bin/"cheat", "tar"
end
end
cheat: update 2.1.26 bottle.
class Cheat < Formula
include Language::Python::Virtualenv
desc "Create and view interactive cheat sheets for *nix commands"
homepage "https://github.com/chrisallenlane/cheat"
url "https://github.com/chrisallenlane/cheat/archive/2.1.26.tar.gz"
sha256 "427c4e5c9a76b78802c1b1959668af20812e8fae8474d9258fb726f166e8f498"
head "https://github.com/chrisallenlane/cheat.git"
bottle do
cellar :any_skip_relocation
sha256 "10add0338998299ab7c5f5f88b4ca4905c30365d33cee6cf5d26de50dc549f8f" => :sierra
sha256 "84bd2ebdbbf37b72e41eeedbdc558321d2508f202adc006ad94f82f5b1e32094" => :el_capitan
sha256 "6e60a0e4bd0211e5a9b6d5c1b2f58d2a21cb4dbd5bc0586c678162c4285477e9" => :yosemite
sha256 "8c5796ed54ee16c81fabec5d2d3e71724dc307b06261ac26ef2edec9182c99b4" => :mavericks
end
depends_on :python if MacOS.version <= :snow_leopard
resource "docopt" do
url "https://files.pythonhosted.org/packages/a2/55/8f8cab2afd404cf578136ef2cc5dfb50baa1761b68c9da1fb1e4eed343c9/docopt-0.6.2.tar.gz"
sha256 "49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491"
end
resource "Pygments" do
url "https://files.pythonhosted.org/packages/b8/67/ab177979be1c81bc99c8d0592ef22d547e70bb4c6815c383286ed5dec504/Pygments-2.1.3.tar.gz"
sha256 "88e4c8a91b2af5962bfa5ea2447ec6dd357018e86e94c7d14bd8cacbc5b55d81"
end
def install
virtualenv_install_with_resources
bash_completion.install "cheat/autocompletion/cheat.bash"
zsh_completion.install "cheat/autocompletion/cheat.zsh" => "_cheat"
end
test do
system bin/"cheat", "tar"
end
end
|
class Cheat < Formula
include Language::Python::Virtualenv
desc "Create and view interactive cheat sheets for *nix commands"
homepage "https://github.com/chrisallenlane/cheat"
url "https://github.com/chrisallenlane/cheat/archive/2.2.2.tar.gz"
sha256 "d898247e4d74e71afbf05943ca1430b3526cd8ec573fe3ee20e73bafcacc0e63"
head "https://github.com/chrisallenlane/cheat.git"
bottle do
cellar :any_skip_relocation
sha256 "5eb69f05c29b9be7a0b453d5dff25abf91af51c5a5c4c5a3956b78955bd0be6c" => :high_sierra
sha256 "65a2bf9dc7f1c50718f9811ad89958409ec14a24c140332a468d8b6520989328" => :sierra
sha256 "5da06a7464f2ef810c33d96f075dad2b5d5245e5d8e7700903d89daa029ca46a" => :el_capitan
end
depends_on :python if MacOS.version <= :snow_leopard
resource "docopt" do
url "https://files.pythonhosted.org/packages/a2/55/8f8cab2afd404cf578136ef2cc5dfb50baa1761b68c9da1fb1e4eed343c9/docopt-0.6.2.tar.gz"
sha256 "49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491"
end
resource "Pygments" do
url "https://files.pythonhosted.org/packages/71/2a/2e4e77803a8bd6408a2903340ac498cb0a2181811af7c9ec92cb70b0308a/Pygments-2.2.0.tar.gz"
sha256 "dbae1046def0efb574852fab9e90209b23f556367b5a320c0bcb871c77c3e8cc"
end
def install
virtualenv_install_with_resources
bash_completion.install "cheat/autocompletion/cheat.bash"
zsh_completion.install "cheat/autocompletion/cheat.zsh" => "_cheat"
end
test do
system bin/"cheat", "tar"
end
end
cheat 2.2.3
Closes #21898.
Signed-off-by: ilovezfs <fbd54dbbcf9e596abad4ccdc4dfc17f80ebeaee2@icloud.com>
class Cheat < Formula
include Language::Python::Virtualenv
desc "Create and view interactive cheat sheets for *nix commands"
homepage "https://github.com/chrisallenlane/cheat"
url "https://github.com/chrisallenlane/cheat/archive/2.2.3.tar.gz"
sha256 "adedab2d8047b129e07d67205f5470c120dbf05785f2786520226c412508d9ee"
head "https://github.com/chrisallenlane/cheat.git"
bottle do
cellar :any_skip_relocation
sha256 "5eb69f05c29b9be7a0b453d5dff25abf91af51c5a5c4c5a3956b78955bd0be6c" => :high_sierra
sha256 "65a2bf9dc7f1c50718f9811ad89958409ec14a24c140332a468d8b6520989328" => :sierra
sha256 "5da06a7464f2ef810c33d96f075dad2b5d5245e5d8e7700903d89daa029ca46a" => :el_capitan
end
depends_on :python if MacOS.version <= :snow_leopard
resource "docopt" do
url "https://files.pythonhosted.org/packages/a2/55/8f8cab2afd404cf578136ef2cc5dfb50baa1761b68c9da1fb1e4eed343c9/docopt-0.6.2.tar.gz"
sha256 "49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491"
end
resource "Pygments" do
url "https://files.pythonhosted.org/packages/71/2a/2e4e77803a8bd6408a2903340ac498cb0a2181811af7c9ec92cb70b0308a/Pygments-2.2.0.tar.gz"
sha256 "dbae1046def0efb574852fab9e90209b23f556367b5a320c0bcb871c77c3e8cc"
end
def install
virtualenv_install_with_resources
bash_completion.install "cheat/autocompletion/cheat.bash"
zsh_completion.install "cheat/autocompletion/cheat.zsh" => "_cheat"
end
test do
system bin/"cheat", "tar"
end
end
|
class Check < Formula
desc "C unit testing framework"
homepage "https://libcheck.github.io/check/"
url "https://github.com/libcheck/check/releases/download/0.13.0/check-0.13.0.tar.gz"
sha256 "c4336b31447acc7e3266854f73ec188cdb15554d0edd44739631da174a569909"
bottle do
cellar :any
sha256 "b33db26bf660192460c8ce4d53efcfa3a0ad60b5cb139f495157c444841ca1cb" => :catalina
sha256 "57498a48acaa07afcea73fc831986e4dbd8dd8742d35a600e6bbe3f328c32f08" => :mojave
sha256 "fd175fded31ecc36ad06beeb18e05fd4d5f5bc538e1a445e86b703bf34373fd8" => :high_sierra
sha256 "6ad1ff9e52d767968efb2b73b563b171561421818a86185c03639f65f0a22ab3" => :sierra
sha256 "5de09e615daf7e12f1b10485b7bc8cb5382e04f856dc516056bae0a30b5f6b49" => :el_capitan
end
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.tc").write <<~EOS
#test test1
ck_assert_msg(1, "This should always pass");
EOS
system "#{bin/"checkmk"} test.tc > test.c"
system ENV.cc, "test.c", "-I#{include}", "-L#{lib}", "-lcheck", "-o", "test"
system "./test"
end
end
check: update 0.13.0 bottle.
class Check < Formula
desc "C unit testing framework"
homepage "https://libcheck.github.io/check/"
url "https://github.com/libcheck/check/releases/download/0.13.0/check-0.13.0.tar.gz"
sha256 "c4336b31447acc7e3266854f73ec188cdb15554d0edd44739631da174a569909"
bottle do
cellar :any
sha256 "7e43575b92dbfe052ea8eee6f488799faa6c9e0a411040b10b0734cc3f50e375" => :catalina
sha256 "7ceb61ee5e716184068334f62a40c708270f88e7e0709e7d464eefd71366d272" => :mojave
sha256 "12147cd97f24af6c18fa393200f063e1d24ea95ffbd1b29cb2dd1f2a4f8ef24b" => :high_sierra
end
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.tc").write <<~EOS
#test test1
ck_assert_msg(1, "This should always pass");
EOS
system "#{bin/"checkmk"} test.tc > test.c"
system ENV.cc, "test.c", "-I#{include}", "-L#{lib}", "-lcheck", "-o", "test"
system "./test"
end
end
|
Pod::Spec.new do |s|
s.name = "ContentfulDialogs"
s.version = "0.2.0"
s.summary = 'Informational dialogs for iOS applications, like "About Us", licensing information and a quick overview of the product.'
s.homepage = "https://github.com/contentful/contentful-ios-dialogs"
s.license = 'MIT'
s.author = { "Boris Bügling" => "boris@contentful.com" }
s.source = { :git => "https://github.com/contentful/contentful-ios-dialogs.git",
:tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/contentful'
s.platform = :ios, '7.0'
s.requires_arc = true
s.resources = 'Pod/Assets/*.png'
s.source_files = 'Pod/Classes'
s.public_header_files = 'Pod/Classes/CDA{AboutUsView,Tutorial,Web}Controller.h',
'Pod/Classes/UIView+Geometry.h'
s.frameworks = 'UIKit'
s.dependency 'Bypass'
s.dependency 'CGLMail'
s.dependency 'ContentfulDeliveryAPI', '~> 1.4.7'
s.dependency 'DDPageControl'
s.dependency 'TSMiniWebBrowser@dblock'
end
Bump version.
Pod::Spec.new do |s|
s.name = "ContentfulDialogs"
s.version = "0.3.0"
s.summary = 'Informational dialogs for iOS applications, like "About Us", licensing information and a quick overview of the product.'
s.homepage = "https://github.com/contentful/contentful-ios-dialogs"
s.license = 'MIT'
s.author = { "Boris Bügling" => "boris@contentful.com" }
s.source = { :git => "https://github.com/contentful/contentful-ios-dialogs.git",
:tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/contentful'
s.platform = :ios, '7.0'
s.requires_arc = true
s.resources = 'Pod/Assets/*.png'
s.source_files = 'Pod/Classes'
s.public_header_files = 'Pod/Classes/CDA{AboutUsView,Tutorial,Web}Controller.h',
'Pod/Classes/UIView+Geometry.h'
s.frameworks = 'UIKit'
s.dependency 'Bypass'
s.dependency 'CGLMail'
s.dependency 'ContentfulDeliveryAPI', '~> 1.4.7'
s.dependency 'DDPageControl'
s.dependency 'TSMiniWebBrowser@dblock'
end
|
module Admin
class EditionFilter
EDITION_TYPE_LOOKUP = Whitehall.edition_classes.reduce({}) do |lookup, klass|
lookup[klass.to_s] = klass
lookup
end
attr_reader :options
def initialize(source, current_user, options={})
@source, @current_user, @options = source, current_user, options
end
def editions(locale = nil)
@editions ||= {}
return @editions[locale] if @editions[locale]
editions_without_translations = unpaginated_editions.includes(:last_author).order("editions.updated_at DESC")
editions_with_translations = if locale
editions_without_translations.with_translations(locale)
else
editions_without_translations.includes(:translations)
end
paginated_editions = editions_with_translations.page(options[:page]).per( options.fetch(:per_page) { default_page_size } )
permitted_only = paginated_editions.select do |edition|
Whitehall::Authority::Enforcer.new(@current_user, edition).can?(:see)
end
new_paginator = Kaminari.paginate_array(permitted_only, total_count: paginated_editions.total_count).page(options[:page])
@editions[locale] = new_paginator
end
def page_title
"#{ownership} #{edition_state} #{type_for_display}#{title_matches}#{location_matches} #{date_range_string}".squeeze(' ').strip
end
def default_page_size
50
end
def show_stats
['published'].include?(options[:state])
end
def published_count
unpaginated_editions.published.count
end
def force_published_count
unpaginated_editions.force_published.count
end
def force_published_percentage
if published_count > 0
(( force_published_count.to_f / published_count.to_f) * 100.0).round(2)
else
0
end
end
def valid?
author
organisation
true
rescue ActiveRecord::RecordNotFound
false
end
def from_date
@from_date ||= Chronic.parse(options[:from_date], endian_precedence: :little) if options[:from_date]
end
def to_date
@to_date ||= Chronic.parse(options[:to_date], endian_precedence: :little) if options[:to_date]
end
def date_range_string
if from_date && to_date
"from #{from_date.to_date.to_s(:uk_short)} to #{to_date.to_date.to_s(:uk_short)}"
elsif from_date
"after #{from_date.to_date.to_s(:uk_short)}"
elsif to_date
"before #{to_date.to_date.to_s(:uk_short)}"
end
end
private
def unpaginated_editions
return @unpaginated_editions if @unpaginated_editions
editions = @source
editions = editions.by_type(type) if type
editions = editions.by_subtype(type, subtype) if subtype
editions = editions.__send__(options[:state]) if options[:state]
editions = editions.authored_by(author) if options[:author]
editions = editions.in_organisation(organisation) if options[:organisation]
editions = editions.with_title_containing(options[:title]) if options[:title]
editions = editions.in_world_location(selected_world_locations) if selected_world_locations.any?
editions = editions.from_date(from_date) if from_date
editions = editions.to_date(to_date) if to_date
@unpaginated_editions = editions
end
def type
EDITION_TYPE_LOOKUP[options[:type].sub(/_\d+$/, '').classify] if options[:type]
end
def subtype
subtype_class.find_by_id(subtype_id) if type && subtype_id
end
def subtype_id
if options[:type] && options[:type][/\d+$/]
options[:type][/\d+$/].to_i
end
end
def subtype_class
"#{type}Type".constantize
end
def type_for_display
if subtype
subtype.plural_name.downcase
elsif type
type.model_name.human.pluralize.downcase
else
"documents"
end
end
def selected_world_locations
if options[:world_location].blank?
[]
elsif options[:world_location] == "user"
@current_user.world_locations
else
[options[:world_location]]
end
end
def ownership
if author && author == @current_user
"My"
elsif author
"#{author.name}'s"
elsif organisation && organisation == @current_user.organisation
"My department's"
elsif organisation
"#{organisation.name}'s"
else
"Everyone's"
end
end
def title_matches
" that match '#{options[:title]}'" if options[:title]
end
def edition_state
options[:state].humanize.downcase if options[:state] && options[:state] != 'active'
end
def organisation
Organisation.find(options[:organisation]) if options[:organisation]
end
def author
User.find(options[:author]) if options[:author]
end
def location_matches
if selected_world_locations.any?
" about #{selected_world_locations.map { |location| WorldLocation.find(location).name }.to_sentence}"
end
end
end
end
Tidy up edition filter
module Admin
class EditionFilter
EDITION_TYPE_LOOKUP = Whitehall.edition_classes.reduce({}) do |lookup, klass|
lookup[klass.to_s] = klass
lookup
end
attr_reader :options
def initialize(source, current_user, options={})
@source, @current_user, @options = source, current_user, options
end
def editions(locale = nil)
@editions ||= {}
return @editions[locale] if @editions[locale]
editions_without_translations = unpaginated_editions.includes(:last_author).order("editions.updated_at DESC")
editions_with_translations = if locale
editions_without_translations.with_translations(locale)
else
editions_without_translations.includes(:translations)
end
paginated_editions = editions_with_translations.page(options[:page]).per( options.fetch(:per_page) { default_page_size } )
permitted_only = paginated_editions.select do |edition|
Whitehall::Authority::Enforcer.new(@current_user, edition).can?(:see)
end
new_paginator = Kaminari.paginate_array(permitted_only, total_count: paginated_editions.total_count).page(options[:page])
@editions[locale] = new_paginator
end
def page_title
"#{ownership} #{edition_state} #{type_for_display}#{title_matches}#{location_matches} #{date_range_string}".squeeze(' ').strip
end
def default_page_size
50
end
def show_stats
['published'].include?(options[:state])
end
def published_count
unpaginated_editions.published.count
end
def force_published_count
unpaginated_editions.force_published.count
end
def force_published_percentage
if published_count > 0
(( force_published_count.to_f / published_count.to_f) * 100.0).round(2)
else
0
end
end
def valid?
author
organisation
true
rescue ActiveRecord::RecordNotFound
false
end
def from_date
@from_date ||= Chronic.parse(options[:from_date], endian_precedence: :little) if options[:from_date]
end
def to_date
@to_date ||= Chronic.parse(options[:to_date], endian_precedence: :little) if options[:to_date]
end
def date_range_string
if from_date && to_date
"from #{from_date.to_date.to_s(:uk_short)} to #{to_date.to_date.to_s(:uk_short)}"
elsif from_date
"after #{from_date.to_date.to_s(:uk_short)}"
elsif to_date
"before #{to_date.to_date.to_s(:uk_short)}"
end
end
private
def unpaginated_editions
return @unpaginated_editions if @unpaginated_editions
editions = @source
editions = editions.by_type(type) if type
editions = editions.by_subtype(type, subtype) if subtype
editions = editions.send(state) if state
editions = editions.authored_by(author) if author
editions = editions.in_organisation(organisation) if organisation
editions = editions.with_title_containing(title) if title
editions = editions.in_world_location(selected_world_locations) if selected_world_locations.any?
editions = editions.from_date(from_date) if from_date
editions = editions.to_date(to_date) if to_date
@unpaginated_editions = editions
end
def state
options[:state].presence
end
def title
options[:title].presence
end
def type
EDITION_TYPE_LOOKUP[options[:type].sub(/_\d+$/, '').classify] if options[:type]
end
def subtype
subtype_class.find_by_id(subtype_id) if type && subtype_id
end
def subtype_id
if options[:type] && options[:type][/\d+$/]
options[:type][/\d+$/].to_i
end
end
def subtype_class
"#{type}Type".constantize
end
def type_for_display
if subtype
subtype.plural_name.downcase
elsif type
type.model_name.human.pluralize.downcase
else
"documents"
end
end
def selected_world_locations
if options[:world_location].blank?
[]
elsif options[:world_location] == "user"
@current_user.world_locations
else
[options[:world_location]]
end
end
def ownership
if author && author == @current_user
"My"
elsif author
"#{author.name}'s"
elsif organisation && organisation == @current_user.organisation
"My department's"
elsif organisation
"#{organisation.name}'s"
else
"Everyone's"
end
end
def title_matches
" that match '#{options[:title]}'" if options[:title].present?
end
def edition_state
options[:state].humanize.downcase if options[:state].present? && options[:state] != 'active'
end
def organisation
Organisation.find(options[:organisation]) if options[:organisation].present?
end
def author
User.find(options[:author]) if options[:author].present?
end
def location_matches
if selected_world_locations.any?
sentence = selected_world_locations.map { |l| WorldLocation.find(l).name }.to_sentence
" about #{sentence}"
end
end
end
end
|
require File.expand_path("../../Homebrew/emacs_formula", __FILE__)
class Circe < EmacsFormula
desc "Emacs IRC client"
homepage "https://github.com/jorgenschaefer/circe"
url "https://github.com/jorgenschaefer/circe/archive/v2.3.tar.gz"
sha256 "7f751c3c988f33c49027eb0bf673512499b1266150d1353bf1e5124746f8147f"
head "https://github.com/jorgenschaefer/circe.git"
depends_on :emacs
depends_on "dunn/emacs/cl-lib" if Emacs.version < Version.create("24.3")
def install
byte_compile Dir["*.el"]
elisp.install Dir["*.el"], Dir["*.elc"]
end
test do
(testpath/"test.el").write <<-EOS.undent
(add-to-list 'load-path "#{elisp}")
(load "circe")
(print circe-version)
EOS
assert_equal "\"#{version}\"", shell_output("emacs -Q --batch -l #{testpath}/test.el").strip
end
end
circe 2.4
Closes #589.
Signed-off-by: Alex Dunn <46952c1342d5ce1a4f5689855eda3c9064bca8f6@gmail.com>
require File.expand_path("../../Homebrew/emacs_formula", __FILE__)
class Circe < EmacsFormula
desc "Emacs IRC client"
homepage "https://github.com/jorgenschaefer/circe"
url "https://github.com/jorgenschaefer/circe/archive/v2.4.tar.gz"
sha256 "36e5d4a22ba8fce24da222eb7ea4100999f35a0d7a47b3e609942b1e874b9fd1"
head "https://github.com/jorgenschaefer/circe.git"
depends_on :emacs
depends_on "dunn/emacs/cl-lib" if Emacs.version < Version.create("24.3")
depends_on "dunn/emacs/buttercup" => :build
def install
system Formula["dunn/emacs/buttercup"].bin/"buttercup", "-L", "."
byte_compile Dir["*.el"]
elisp.install Dir["*.el"], Dir["*.elc"]
end
test do
(testpath/"test.el").write <<-EOS.undent
(add-to-list 'load-path "#{elisp}")
(load "circe")
(print circe-version)
EOS
assert_equal "\"#{version}\"", shell_output("emacs -Q --batch -l #{testpath}/test.el").strip
end
end
|
class Adventure < ApplicationRecord
acts_as_paranoid
translates(:title, :content)
globalize_accessors(locales: [:en, :sv], attributes: [:title, :content])
belongs_to :introduction, required: true
has_many :adventure_missions, dependent: :destroy, inverse_of: :adventure
has_many :adventure_mission_groups, through: :adventure_missions
accepts_nested_attributes_for :adventure_missions, reject_if: :all_blank, allow_destroy: true
validates :title_sv, :start_date, :end_date, :introduction_id, presence: true
scope :published, -> { where('start_date <= ?', Time.zone.now).order(start_date: :desc) }
scope :published_asc, -> { where('start_date <= ?', Time.zone.now).order(start_date: :asc) }
scope :published_results, -> { where(publish_results: true) }
def published?
start_date < Time.zone.now
end
def week_number
# Just making sure the dates don't extend into another week
(end_date-3.days).strftime("%U").to_i
end
def self.can_show?(user)
User.joins(groups: :introduction)
.where('users.id': user.id, 'introductions.current': true, 'groups.group_type': 'regular')
.count > 0
end
def to_s
title
end
end
Unpublishing adventure after end date
class Adventure < ApplicationRecord
acts_as_paranoid
translates(:title, :content)
globalize_accessors(locales: [:en, :sv], attributes: [:title, :content])
belongs_to :introduction, required: true
has_many :adventure_missions, dependent: :destroy, inverse_of: :adventure
has_many :adventure_mission_groups, through: :adventure_missions
accepts_nested_attributes_for :adventure_missions, reject_if: :all_blank, allow_destroy: true
validates :title_sv, :start_date, :end_date, :introduction_id, presence: true
scope :published, -> { where('start_date <= ? AND end_date >= ?', Time.zone.now, Time.zone.now).order(start_date: :desc) }
scope :published_asc, -> { where('start_date <= ?', Time.zone.now).order(start_date: :asc) }
scope :published_results, -> { where(publish_results: true) }
def published?
start_date < Time.zone.now
end
def week_number
# Just making sure the dates don't extend into another week
(end_date-3.days).strftime("%U").to_i
end
def self.can_show?(user)
User.joins(groups: :introduction)
.where('users.id': user.id, 'introductions.current': true, 'groups.group_type': 'regular')
.count > 0
end
def to_s
title
end
end
|
class Citus < Formula
desc "PostgreSQL-based distributed RDBMS"
homepage "https://www.citusdata.com"
url "https://github.com/citusdata/citus/archive/v10.2.5.tar.gz"
sha256 "748beaf219163468f0b92bf5315798457f9859a6cd9069a7fd03208d8d231176"
license "AGPL-3.0-only"
head "https://github.com/citusdata/citus.git", branch: "master"
bottle do
sha256 cellar: :any, arm64_monterey: "5c1284be900f79340a7deb11cab8ec6ae499ae4d5fb3a353c38af68294f605ee"
sha256 cellar: :any, arm64_big_sur: "8d8da700da3660cd9bc01aa509a25c7500e571d6353f0b718504d0307462692b"
sha256 cellar: :any, monterey: "aed158c5fc1a817655cf33f8fdf52a4b35735ad81740fd40100e93247c3acad4"
sha256 cellar: :any, big_sur: "c081472f3ea377cba1898543bbc45f9fbc750c8a53dd538645b16ccda66ba555"
sha256 cellar: :any, catalina: "8d206df19b0d0c30e866571deb14ad101f170e8e5cd6574de218a41a266e7b36"
sha256 cellar: :any_skip_relocation, x86_64_linux: "ed813a71d6e8c6e3c78627707f6bfbf1dd135959f1518748318b956666f62400"
end
depends_on "lz4"
depends_on "postgresql"
depends_on "readline"
depends_on "zstd"
uses_from_macos "curl"
def install
ENV["PG_CONFIG"] = Formula["postgresql"].opt_bin/"pg_config"
system "./configure"
# workaround for https://github.com/Homebrew/legacy-homebrew/issues/49948
system "make", "libpq=-L#{Formula["postgresql"].opt_lib} -lpq"
# Use stage directory to prevent installing to pg_config-defined dirs,
# which would not be within this package's Cellar.
mkdir "stage"
system "make", "install", "DESTDIR=#{buildpath}/stage"
path = File.join("stage", HOMEBREW_PREFIX)
lib.install (buildpath/path/"lib").children
include.install (buildpath/path/"include").children
(share/"postgresql/extension").install (buildpath/path/"share/postgresql/extension").children
end
end
citus 11.0.2
Closes #103906.
Signed-off-by: Sean Molenaar <2b250e3fea88cfef248b497ad5fc17f7dc435154@users.noreply.github.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Citus < Formula
desc "PostgreSQL-based distributed RDBMS"
homepage "https://www.citusdata.com"
url "https://github.com/citusdata/citus/archive/v11.0.2.tar.gz"
sha256 "86ab78b6efc4739c7de3af935317b7ef6a7646250d80ccc0ab31ad28fc49070a"
license "AGPL-3.0-only"
head "https://github.com/citusdata/citus.git", branch: "master"
bottle do
sha256 cellar: :any, arm64_monterey: "5c1284be900f79340a7deb11cab8ec6ae499ae4d5fb3a353c38af68294f605ee"
sha256 cellar: :any, arm64_big_sur: "8d8da700da3660cd9bc01aa509a25c7500e571d6353f0b718504d0307462692b"
sha256 cellar: :any, monterey: "aed158c5fc1a817655cf33f8fdf52a4b35735ad81740fd40100e93247c3acad4"
sha256 cellar: :any, big_sur: "c081472f3ea377cba1898543bbc45f9fbc750c8a53dd538645b16ccda66ba555"
sha256 cellar: :any, catalina: "8d206df19b0d0c30e866571deb14ad101f170e8e5cd6574de218a41a266e7b36"
sha256 cellar: :any_skip_relocation, x86_64_linux: "ed813a71d6e8c6e3c78627707f6bfbf1dd135959f1518748318b956666f62400"
end
depends_on "lz4"
depends_on "postgresql"
depends_on "readline"
depends_on "zstd"
uses_from_macos "curl"
def install
ENV["PG_CONFIG"] = Formula["postgresql"].opt_bin/"pg_config"
system "./configure"
# workaround for https://github.com/Homebrew/legacy-homebrew/issues/49948
system "make", "libpq=-L#{Formula["postgresql"].opt_lib} -lpq"
# Use stage directory to prevent installing to pg_config-defined dirs,
# which would not be within this package's Cellar.
mkdir "stage"
system "make", "install", "DESTDIR=#{buildpath}/stage"
path = File.join("stage", HOMEBREW_PREFIX)
lib.install (buildpath/path/"lib").children
include.install (buildpath/path/"include").children
(share/"postgresql/extension").install (buildpath/path/"share/postgresql/extension").children
end
end
|
class ApplicationInstance < ActiveRecord::Base
belongs_to :application
has_and_belongs_to_many :machines
has_many :application_urls, :dependent => :destroy
accepts_nested_attributes_for :application_urls, :reject_if => lambda{|a| a[:url].blank? },
:allow_destroy => true
attr_accessible :name, :application_id, :machine_ids, :authentication_method, :application_urls_attributes
AVAILABLE_AUTHENTICATION_METHODS = %w(none cerbere cerbere-cas cerbere-bouchon ldap-minequip internal other)
validates_presence_of :name, :application_id, :authentication_method
validates_inclusion_of :authentication_method, :in => AVAILABLE_AUTHENTICATION_METHODS
def fullname
"#{application.name} (#{name})"
end
end
Fixed unability to update ApplicationInstance timestamps from nested forms
class ApplicationInstance < ActiveRecord::Base
belongs_to :application
has_and_belongs_to_many :machines
has_many :application_urls, :dependent => :destroy
accepts_nested_attributes_for :application_urls, :reject_if => lambda{|a| a[:url].blank? },
:allow_destroy => true
attr_accessible :name, :application_id, :machine_ids, :authentication_method, :application_urls_attributes,
:created_at, :updated_at
AVAILABLE_AUTHENTICATION_METHODS = %w(none cerbere cerbere-cas cerbere-bouchon ldap-minequip internal other)
validates_presence_of :name, :application_id, :authentication_method
validates_inclusion_of :authentication_method, :in => AVAILABLE_AUTHENTICATION_METHODS
def fullname
"#{application.name} (#{name})"
end
end
|
class Cjdns < Formula
desc "Advanced mesh routing system with cryptographic addressing"
homepage "https://github.com/cjdelisle/cjdns/"
url "https://github.com/cjdelisle/cjdns/archive/cjdns-v20.1.tar.gz"
sha256 "feea3e3884f66731b5efe3d289d5215ad4be27acb6a5879fabed14246f649cd7"
head "https://github.com/cjdelisle/cjdns.git"
bottle do
cellar :any_skip_relocation
sha256 "d712ae1cad6986d4616e87ff4ebc546d8b5624e50a26b53bfce65d4a9a20c8b7" => :high_sierra
sha256 "9126208cc88fdc96ebf63ac4eec3b872127a81fee599e5c258cd48dc8ebb5a85" => :sierra
sha256 "ad1a0398f7f4c9336ae2bd87d61ce4ab25bce3f670452c6c55a01c5b9cbdb250" => :el_capitan
sha256 "5a04a85d79d80a1238b5d2afeb5fb18a114555b0cd156c09bbd3f13c8af07a91" => :yosemite
end
depends_on "node" => :build
def install
system "./do"
bin.install "cjdroute"
(pkgshare/"test").install "build_darwin/test_testcjdroute_c" => "cjdroute_test"
end
test do
system "#{pkgshare}/test/cjdroute_test", "all"
end
end
cjdns: update 20.1 bottle.
class Cjdns < Formula
desc "Advanced mesh routing system with cryptographic addressing"
homepage "https://github.com/cjdelisle/cjdns/"
url "https://github.com/cjdelisle/cjdns/archive/cjdns-v20.1.tar.gz"
sha256 "feea3e3884f66731b5efe3d289d5215ad4be27acb6a5879fabed14246f649cd7"
head "https://github.com/cjdelisle/cjdns.git"
bottle do
cellar :any_skip_relocation
sha256 "c8de87eccf8e0c10f5e6b7b943c8f9e388aeccd7ac122cfa3c54edb94f1313ba" => :high_sierra
sha256 "9b9275abfa8abc4f0ca0013b6756a4dfe254282de869cc8fac716103aee05088" => :sierra
sha256 "25fdeeddcf62a47435f401d90975650af5a8b3a771270fe18f13aeac6d356536" => :el_capitan
end
depends_on "node" => :build
def install
system "./do"
bin.install "cjdroute"
(pkgshare/"test").install "build_darwin/test_testcjdroute_c" => "cjdroute_test"
end
test do
system "#{pkgshare}/test/cjdroute_test", "all"
end
end
|
# encoding: utf-8
require 'mail'
require 'iconv'
class Channel::EmailParser
def conv (charset, string)
if !charset || charset == 'US-ASCII' || charset == 'ASCII-8BIT'
charset = 'LATIN1'
end
return string if charset.downcase == 'utf8' || charset.downcase == 'utf-8'
# puts '-------' + charset
# puts string
# string.encode("UTF-8")
Iconv.conv( 'UTF8', charset, string )
end
=begin
mail = parse( msg_as_string )
mail = {
:from => 'Some Name <some@example.com>',
:from_email => 'some@example.com',
:from_local => 'some',
:from_domain => 'example.com',
:from_display_name => 'Some Name',
:message_id => 'some_message_id@example.com',
:to => 'Some System <system@example.com>',
:cc => 'Somebody <somebody@example.com>',
:subject => 'some message subject',
:body => 'some message body',
:attachments => [
{
:data => 'binary of attachment',
:filename => 'file_name_of_attachment.txt',
:preferences => {
:content-alternative => true,
:Mime-Type => 'text/plain',
:Charset => 'iso-8859-1',
},
},
],
# ignore email header
:x-zammad-ignore => 'false',
# customer headers
:x-zammad-customer-login => '',
:x-zammad-customer-email => '',
:x-zammad-customer-firstname => '',
:x-zammad-customer-lastname => '',
# ticket headers
:x-zammad-group => 'some_group',
:x-zammad-state => 'some_state',
:x-zammad-priority => 'some_priority',
:x-zammad-owner => 'some_owner_login',
# article headers
:x-zammad-article-visability => 'internal',
:x-zammad-article-type => 'agent',
:x-zammad-article-sender => 'customer',
# all other email headers
:some-header => 'some_value',
}
=end
def parse (msg)
data = {}
mail = Mail.new( msg )
# set all headers
mail.header.fields.each { |field|
data[field.name.downcase.to_sym] = field.to_s
}
# set extra headers
data[:from_email] = Mail::Address.new( mail[:from].value ).address
data[:from_local] = Mail::Address.new( mail[:from].value ).local
data[:from_domain] = Mail::Address.new( mail[:from].value ).domain
data[:from_display_name] = Mail::Address.new( mail[:from].value ).display_name ||
( Mail::Address.new( mail[:from].value ).comments && Mail::Address.new( mail[:from].value ).comments[0] )
# do extra decoding because we needed to use field.value
data[:from_display_name] = Mail::Field.new( 'X-From', data[:from_display_name] ).to_s
# compat headers
data[:message_id] = data['message-id'.to_sym]
# body
# plain_part = mail.multipart? ? (mail.text_part ? mail.text_part.body.decoded : nil) : mail.body.decoded
# html_part = message.html_part ? message.html_part.body.decoded : nil
data[:attachments] = []
# multi part email
if mail.multipart?
# text attachment/body exists
if mail.text_part
data[:body] = mail.text_part.body.decoded
data[:body] = conv( mail.text_part.charset, data[:body] )
# html attachment/body may exists and will be converted to text
else
filename = '-no name-'
if mail.html_part.body
filename = 'html-email'
data[:body] = mail.html_part.body.to_s
data[:body] = conv( mail.html_part.charset.to_s, data[:body] )
data[:body] = html2ascii( data[:body] )
# any other attachments
else
data[:body] = 'no visible content'
end
end
# add html attachment/body as real attachment
if mail.html_part
filename = 'message.html'
headers_store = {
'content-alternative' => true,
}
if mail.mime_type
headers_store['Mime-Type'] = mail.html_part.mime_type
end
if mail.charset
headers_store['Charset'] = mail.html_part.charset
end
attachment = {
:data => mail.html_part.body.to_s,
:filename => mail.html_part.filename || filename,
:preferences => headers_store
}
data[:attachments].push attachment
end
# get attachments
if mail.has_attachments?
mail.attachments.each { |file|
# get file preferences
headers_store = {}
file.header.fields.each { |field|
headers_store[field.name.to_s] = field.value.to_s
}
# get filename from content-disposition
filename = nil
if file.header[:content_disposition] && file.header[:content_disposition].filename
filename = file.header[:content_disposition].filename
end
# for some broken sm mail clients (X-MimeOLE: Produced By Microsoft Exchange V6.5)
if !filename
filename = file.header[:content_location].to_s
end
# get mime type
if file.header[:content_type] && file.header[:content_type].string
headers_store['Mime-Type'] = file.header[:content_type].string
end
# get charset
if file.header && file.header.charset
headers_store['Charset'] = file.header.charset
end
# remove not needed header
headers_store.delete('Content-Transfer-Encoding')
headers_store.delete('Content-Disposition')
attach = {
:data => file.body.to_s,
:filename => filename,
:preferences => headers_store,
}
data[:attachments].push attach
}
end
# not multipart email
else
# text part
if !mail.mime_type || mail.mime_type.to_s == '' || mail.mime_type.to_s.downcase == 'text/plain'
data[:body] = mail.body.decoded
data[:body] = conv( mail.charset, data[:body] )
# html part
else
filename = '-no name-'
if mail.mime_type.to_s.downcase == 'text/html'
filename = 'html-email'
data[:body] = mail.body.decoded
data[:body] = conv( mail.charset, data[:body] )
data[:body] = html2ascii( data[:body] )
# any other attachments
else
data[:body] = 'no visible content'
end
# add body as attachment
headers_store = {
'content-alternative' => true,
}
if mail.mime_type
headers_store['Mime-Type'] = mail.mime_type
end
if mail.charset
headers_store['Charset'] = mail.charset
end
attachment = {
:data => mail.body.decoded,
:filename => mail.filename || filename,
:preferences => headers_store
}
data[:attachments].push attachment
end
end
# strip not wanted chars
data[:body].gsub!( /\r\n/, "\n" )
data[:body].gsub!( /\r/, "\n" )
return data
end
def process(channel, msg)
mail = parse( msg )
# run postmaster pre filter
filters = {
'0010' => Channel::Filter::Trusted,
'1000' => Channel::Filter::Database,
}
# filter( channel, mail )
filters.each {|prio, backend|
begin
backend.run( channel, mail )
rescue Exception => e
puts "can't run postmaster pre filter #{backend}"
puts e.inspect
return false
end
}
# check ignore header
return true if mail[ 'x-zammad-ignore'.to_sym ] == 'true' || mail[ 'x-zammad-ignore'.to_sym ] == true
ticket = nil
article = nil
user = nil
# use transaction
ActiveRecord::Base.transaction do
if mail[ 'x-zammad-customer-login'.to_sym ]
user = User.where( :login => mail[ 'x-zammad-customer-login'.to_sym ] ).first
end
if !user
user = User.where( :email => mail[ 'x-zammad-customer-email'.to_sym ] || mail[:from_email] ).first
end
if !user
puts 'create user...'
roles = Role.where( :name => 'Customer' )
user = User.create(
:login => mail[ 'x-zammad-customer-login'.to_sym ] || mail[ 'x-zammad-customer-email'.to_sym ] || mail[:from_email],
:firstname => mail[ 'x-zammad-customer-firstname'.to_sym ] || mail[:from_display_name],
:lastname => mail[ 'x-zammad-customer-lastname'.to_sym ],
:email => mail[ 'x-zammad-customer-email'.to_sym ] || mail[:from_email],
:password => '',
:active => true,
:roles => roles,
:created_by_id => 1
)
end
# set current user
UserInfo.current_user_id = user.id
# get ticket# from subject
ticket = Ticket.number_check( mail[:subject] )
# set ticket state to open if not new
if ticket
ticket_state = Ticket::State.find( ticket.ticket_state_id )
ticket_state_type = Ticket::StateType.find( ticket_state.ticket_state_type_id )
# if tickte is merged, find linked ticket
if ticket_state_type.name == 'merged'
end
if ticket_state_type.name != 'new'
ticket.ticket_state = Ticket::State.where( :name => 'open' ).first
ticket.save
end
end
# create new ticket
if !ticket
# set attributes
ticket_attributes = {
:group_id => channel[:group_id] || 1,
:customer_id => user.id,
:title => mail[:subject] || '',
:ticket_state_id => Ticket::State.where( :name => 'new' ).first.id,
:ticket_priority_id => Ticket::Priority.where( :name => '2 normal' ).first.id,
:created_by_id => user.id,
}
# x-headers lookup
map = [
[ 'x-zammad-group', Group, 'group_id', 'name' ],
[ 'x-zammad-state', Ticket::State, 'ticket_state_id', 'name' ],
[ 'x-zammad-priority', Ticket::Priority, 'ticket_priority_id', 'name' ],
[ 'x-zammad-owner', User, 'owner_id', 'login' ],
]
object_lookup( ticket_attributes, map, mail )
# create ticket
ticket = Ticket.create( ticket_attributes )
end
# import mail
# set attributes
internal = false
if mail[ 'X-Zammad-Article-Visability'.to_sym ] && mail[ 'X-Zammad-Article-Visability'.to_sym ] == 'internal'
internal = true
end
article_attributes = {
:created_by_id => user.id,
:ticket_id => ticket.id,
:ticket_article_type_id => Ticket::Article::Type.where( :name => 'email' ).first.id,
:ticket_article_sender_id => Ticket::Article::Sender.where( :name => 'Customer' ).first.id,
:body => mail[:body],
:from => mail[:from],
:to => mail[:to],
:cc => mail[:cc],
:subject => mail[:subject],
:message_id => mail[:message_id],
:internal => internal,
}
# x-headers lookup
map = [
[ 'x-zammad-article-type', Ticket::Article::Type, 'ticket_article_type_id', 'name' ],
[ 'x-zammad-article-sender', Ticket::Article::Sender, 'ticket_article_sender_id', 'name' ],
]
object_lookup( article_attributes, map, mail )
# create article
article = Ticket::Article.create(article_attributes)
# store mail plain
Store.add(
:object => 'Ticket::Article::Mail',
:o_id => article.id,
:data => msg,
:filename => "ticket-#{ticket.number}-#{article.id}.eml",
:preferences => {}
)
# store attachments
if mail[:attachments]
mail[:attachments].each do |attachment|
Store.add(
:object => 'Ticket::Article',
:o_id => article.id,
:data => attachment[:data],
:filename => attachment[:filename],
:preferences => attachment[:preferences]
)
end
end
end
# execute ticket events
Ticket::Observer::Notification.transaction
# run postmaster post filter
filters = {
# '0010' => Channel::Filter::Trusted,
}
# filter( channel, mail )
filters.each {|prio, backend|
begin
backend.run( channel, mail, ticket, article, user )
rescue Exception => e
puts "can't run postmaster post filter #{backend}"
puts e.inspect
end
}
# return new objects
return ticket, article, user
end
def object_lookup( attributes, map, mail )
map.each { |item|
if mail[ item[0].to_sym ]
if item[1].where( item[3].to_sym => mail[ item[0].to_sym ] ).first
attributes[ item[2].to_sym ] = item[1].where( item[3].to_sym => mail[ item[0].to_sym ] ).first.id
end
end
}
end
def html2ascii(string)
# find <a href=....> and replace it with [x]
link_list = ''
counter = 0
string.gsub!( /<a\s.*?href=("|')(.+?)("|').*?>/ix ) { |item|
link = $2
counter = counter + 1
link_list += "[#{counter}] #{link}\n"
"[#{counter}]"
}
# remove empty lines
string.gsub!( /^\s*/m, '' )
# fix some bad stuff from opera and others
string.gsub!( /(\n\r|\r\r\n|\r\n)/, "\n" )
# strip all other tags
string.gsub!( /\<(br|br\/|br\s\/)\>/, "\n" )
# strip all other tags
string.gsub!( /\<.+?\>/, '' )
# encode html entities like "–"
string.gsub!( /(&\#(\d+);?)/x ) { |item|
$2.chr
}
# encode html entities like "d;"
string.gsub!( /(&\#[xX]([0-9a-fA-F]+);?)/x ) { |item|
chr_orig = $1
hex = $2.hex
if hex
chr = hex.chr
if chr
chr
else
chr_orig
end
else
chr_orig
end
}
# remove empty lines
string.gsub!( /^\s*\n\s*\n/m, "\n" )
# add extracted links
if link_list
string += "\n\n" + link_list
end
return string
end
end
# workaround to parse subjects with 2 different encodings correctly (e. g. quoted-printable see test/fixtures/mail9.box)
module Mail
module Encodings
def Encodings.value_decode(str)
# Optimization: If there's no encoded-words in the string, just return it
return str unless str.index("=?")
str = str.gsub(/\?=(\s*)=\?/, '?==?') # Remove whitespaces between 'encoded-word's
# Split on white-space boundaries with capture, so we capture the white-space as well
str.split(/([ \t])/).map do |text|
if text.index('=?') .nil?
text
else
# Join QP encoded-words that are adjacent to avoid decoding partial chars
# text.gsub!(/\?\=\=\?.+?\?[Qq]\?/m, '') if text =~ /\?==\?/
# Search for occurences of quoted strings or plain strings
text.scan(/( # Group around entire regex to include it in matches
\=\?[^?]+\?([QB])\?[^?]+?\?\= # Quoted String with subgroup for encoding method
| # or
.+?(?=\=\?|$) # Plain String
)/xmi).map do |matches|
string, method = *matches
if method == 'b' || method == 'B'
b_value_decode(string)
elsif method == 'q' || method == 'Q'
q_value_decode(string)
else
string
end
end
end
end.join("")
end
end
end
Fixed missing updated_by_id.
# encoding: utf-8
require 'mail'
require 'iconv'
class Channel::EmailParser
def conv (charset, string)
if !charset || charset == 'US-ASCII' || charset == 'ASCII-8BIT'
charset = 'LATIN1'
end
return string if charset.downcase == 'utf8' || charset.downcase == 'utf-8'
# puts '-------' + charset
# puts string
# string.encode("UTF-8")
Iconv.conv( 'UTF8', charset, string )
end
=begin
mail = parse( msg_as_string )
mail = {
:from => 'Some Name <some@example.com>',
:from_email => 'some@example.com',
:from_local => 'some',
:from_domain => 'example.com',
:from_display_name => 'Some Name',
:message_id => 'some_message_id@example.com',
:to => 'Some System <system@example.com>',
:cc => 'Somebody <somebody@example.com>',
:subject => 'some message subject',
:body => 'some message body',
:attachments => [
{
:data => 'binary of attachment',
:filename => 'file_name_of_attachment.txt',
:preferences => {
:content-alternative => true,
:Mime-Type => 'text/plain',
:Charset => 'iso-8859-1',
},
},
],
# ignore email header
:x-zammad-ignore => 'false',
# customer headers
:x-zammad-customer-login => '',
:x-zammad-customer-email => '',
:x-zammad-customer-firstname => '',
:x-zammad-customer-lastname => '',
# ticket headers
:x-zammad-group => 'some_group',
:x-zammad-state => 'some_state',
:x-zammad-priority => 'some_priority',
:x-zammad-owner => 'some_owner_login',
# article headers
:x-zammad-article-visability => 'internal',
:x-zammad-article-type => 'agent',
:x-zammad-article-sender => 'customer',
# all other email headers
:some-header => 'some_value',
}
=end
def parse (msg)
data = {}
mail = Mail.new( msg )
# set all headers
mail.header.fields.each { |field|
data[field.name.downcase.to_sym] = field.to_s
}
# set extra headers
data[:from_email] = Mail::Address.new( mail[:from].value ).address
data[:from_local] = Mail::Address.new( mail[:from].value ).local
data[:from_domain] = Mail::Address.new( mail[:from].value ).domain
data[:from_display_name] = Mail::Address.new( mail[:from].value ).display_name ||
( Mail::Address.new( mail[:from].value ).comments && Mail::Address.new( mail[:from].value ).comments[0] )
# do extra decoding because we needed to use field.value
data[:from_display_name] = Mail::Field.new( 'X-From', data[:from_display_name] ).to_s
# compat headers
data[:message_id] = data['message-id'.to_sym]
# body
# plain_part = mail.multipart? ? (mail.text_part ? mail.text_part.body.decoded : nil) : mail.body.decoded
# html_part = message.html_part ? message.html_part.body.decoded : nil
data[:attachments] = []
# multi part email
if mail.multipart?
# text attachment/body exists
if mail.text_part
data[:body] = mail.text_part.body.decoded
data[:body] = conv( mail.text_part.charset, data[:body] )
# html attachment/body may exists and will be converted to text
else
filename = '-no name-'
if mail.html_part.body
filename = 'html-email'
data[:body] = mail.html_part.body.to_s
data[:body] = conv( mail.html_part.charset.to_s, data[:body] )
data[:body] = html2ascii( data[:body] )
# any other attachments
else
data[:body] = 'no visible content'
end
end
# add html attachment/body as real attachment
if mail.html_part
filename = 'message.html'
headers_store = {
'content-alternative' => true,
}
if mail.mime_type
headers_store['Mime-Type'] = mail.html_part.mime_type
end
if mail.charset
headers_store['Charset'] = mail.html_part.charset
end
attachment = {
:data => mail.html_part.body.to_s,
:filename => mail.html_part.filename || filename,
:preferences => headers_store
}
data[:attachments].push attachment
end
# get attachments
if mail.has_attachments?
mail.attachments.each { |file|
# get file preferences
headers_store = {}
file.header.fields.each { |field|
headers_store[field.name.to_s] = field.value.to_s
}
# get filename from content-disposition
filename = nil
if file.header[:content_disposition] && file.header[:content_disposition].filename
filename = file.header[:content_disposition].filename
end
# for some broken sm mail clients (X-MimeOLE: Produced By Microsoft Exchange V6.5)
if !filename
filename = file.header[:content_location].to_s
end
# get mime type
if file.header[:content_type] && file.header[:content_type].string
headers_store['Mime-Type'] = file.header[:content_type].string
end
# get charset
if file.header && file.header.charset
headers_store['Charset'] = file.header.charset
end
# remove not needed header
headers_store.delete('Content-Transfer-Encoding')
headers_store.delete('Content-Disposition')
attach = {
:data => file.body.to_s,
:filename => filename,
:preferences => headers_store,
}
data[:attachments].push attach
}
end
# not multipart email
else
# text part
if !mail.mime_type || mail.mime_type.to_s == '' || mail.mime_type.to_s.downcase == 'text/plain'
data[:body] = mail.body.decoded
data[:body] = conv( mail.charset, data[:body] )
# html part
else
filename = '-no name-'
if mail.mime_type.to_s.downcase == 'text/html'
filename = 'html-email'
data[:body] = mail.body.decoded
data[:body] = conv( mail.charset, data[:body] )
data[:body] = html2ascii( data[:body] )
# any other attachments
else
data[:body] = 'no visible content'
end
# add body as attachment
headers_store = {
'content-alternative' => true,
}
if mail.mime_type
headers_store['Mime-Type'] = mail.mime_type
end
if mail.charset
headers_store['Charset'] = mail.charset
end
attachment = {
:data => mail.body.decoded,
:filename => mail.filename || filename,
:preferences => headers_store
}
data[:attachments].push attachment
end
end
# strip not wanted chars
data[:body].gsub!( /\r\n/, "\n" )
data[:body].gsub!( /\r/, "\n" )
return data
end
def process(channel, msg)
mail = parse( msg )
# run postmaster pre filter
filters = {
'0010' => Channel::Filter::Trusted,
'1000' => Channel::Filter::Database,
}
# filter( channel, mail )
filters.each {|prio, backend|
begin
backend.run( channel, mail )
rescue Exception => e
puts "can't run postmaster pre filter #{backend}"
puts e.inspect
return false
end
}
# check ignore header
return true if mail[ 'x-zammad-ignore'.to_sym ] == 'true' || mail[ 'x-zammad-ignore'.to_sym ] == true
ticket = nil
article = nil
user = nil
# use transaction
ActiveRecord::Base.transaction do
if mail[ 'x-zammad-customer-login'.to_sym ]
user = User.where( :login => mail[ 'x-zammad-customer-login'.to_sym ] ).first
end
if !user
user = User.where( :email => mail[ 'x-zammad-customer-email'.to_sym ] || mail[:from_email] ).first
end
if !user
puts 'create user...'
roles = Role.where( :name => 'Customer' )
user = User.create(
:login => mail[ 'x-zammad-customer-login'.to_sym ] || mail[ 'x-zammad-customer-email'.to_sym ] || mail[:from_email],
:firstname => mail[ 'x-zammad-customer-firstname'.to_sym ] || mail[:from_display_name],
:lastname => mail[ 'x-zammad-customer-lastname'.to_sym ],
:email => mail[ 'x-zammad-customer-email'.to_sym ] || mail[:from_email],
:password => '',
:active => true,
:roles => roles,
:updated_by_id => 1,
:created_by_id => 1,
)
end
# set current user
UserInfo.current_user_id = user.id
# get ticket# from subject
ticket = Ticket.number_check( mail[:subject] )
# set ticket state to open if not new
if ticket
ticket_state = Ticket::State.find( ticket.ticket_state_id )
ticket_state_type = Ticket::StateType.find( ticket_state.ticket_state_type_id )
# if tickte is merged, find linked ticket
if ticket_state_type.name == 'merged'
end
if ticket_state_type.name != 'new'
ticket.ticket_state = Ticket::State.where( :name => 'open' ).first
ticket.save
end
end
# create new ticket
if !ticket
# set attributes
ticket_attributes = {
:group_id => channel[:group_id] || 1,
:customer_id => user.id,
:title => mail[:subject] || '',
:ticket_state_id => Ticket::State.where( :name => 'new' ).first.id,
:ticket_priority_id => Ticket::Priority.where( :name => '2 normal' ).first.id,
:updated_by_id => user.id,
:created_by_id => user.id,
}
# x-headers lookup
map = [
[ 'x-zammad-group', Group, 'group_id', 'name' ],
[ 'x-zammad-state', Ticket::State, 'ticket_state_id', 'name' ],
[ 'x-zammad-priority', Ticket::Priority, 'ticket_priority_id', 'name' ],
[ 'x-zammad-owner', User, 'owner_id', 'login' ],
]
object_lookup( ticket_attributes, map, mail )
# create ticket
ticket = Ticket.create( ticket_attributes )
end
# import mail
# set attributes
internal = false
if mail[ 'X-Zammad-Article-Visability'.to_sym ] && mail[ 'X-Zammad-Article-Visability'.to_sym ] == 'internal'
internal = true
end
article_attributes = {
:created_by_id => user.id,
:updated_by_id => user.id,
:ticket_id => ticket.id,
:ticket_article_type_id => Ticket::Article::Type.where( :name => 'email' ).first.id,
:ticket_article_sender_id => Ticket::Article::Sender.where( :name => 'Customer' ).first.id,
:body => mail[:body],
:from => mail[:from],
:to => mail[:to],
:cc => mail[:cc],
:subject => mail[:subject],
:message_id => mail[:message_id],
:internal => internal,
}
# x-headers lookup
map = [
[ 'x-zammad-article-type', Ticket::Article::Type, 'ticket_article_type_id', 'name' ],
[ 'x-zammad-article-sender', Ticket::Article::Sender, 'ticket_article_sender_id', 'name' ],
]
object_lookup( article_attributes, map, mail )
# create article
article = Ticket::Article.create(article_attributes)
# store mail plain
Store.add(
:object => 'Ticket::Article::Mail',
:o_id => article.id,
:data => msg,
:filename => "ticket-#{ticket.number}-#{article.id}.eml",
:preferences => {}
)
# store attachments
if mail[:attachments]
mail[:attachments].each do |attachment|
Store.add(
:object => 'Ticket::Article',
:o_id => article.id,
:data => attachment[:data],
:filename => attachment[:filename],
:preferences => attachment[:preferences]
)
end
end
end
# execute ticket events
Ticket::Observer::Notification.transaction
# run postmaster post filter
filters = {
# '0010' => Channel::Filter::Trusted,
}
# filter( channel, mail )
filters.each {|prio, backend|
begin
backend.run( channel, mail, ticket, article, user )
rescue Exception => e
puts "can't run postmaster post filter #{backend}"
puts e.inspect
end
}
# return new objects
return ticket, article, user
end
def object_lookup( attributes, map, mail )
map.each { |item|
if mail[ item[0].to_sym ]
if item[1].where( item[3].to_sym => mail[ item[0].to_sym ] ).first
attributes[ item[2].to_sym ] = item[1].where( item[3].to_sym => mail[ item[0].to_sym ] ).first.id
end
end
}
end
def html2ascii(string)
# find <a href=....> and replace it with [x]
link_list = ''
counter = 0
string.gsub!( /<a\s.*?href=("|')(.+?)("|').*?>/ix ) { |item|
link = $2
counter = counter + 1
link_list += "[#{counter}] #{link}\n"
"[#{counter}]"
}
# remove empty lines
string.gsub!( /^\s*/m, '' )
# fix some bad stuff from opera and others
string.gsub!( /(\n\r|\r\r\n|\r\n)/, "\n" )
# strip all other tags
string.gsub!( /\<(br|br\/|br\s\/)\>/, "\n" )
# strip all other tags
string.gsub!( /\<.+?\>/, '' )
# encode html entities like "–"
string.gsub!( /(&\#(\d+);?)/x ) { |item|
$2.chr
}
# encode html entities like "d;"
string.gsub!( /(&\#[xX]([0-9a-fA-F]+);?)/x ) { |item|
chr_orig = $1
hex = $2.hex
if hex
chr = hex.chr
if chr
chr
else
chr_orig
end
else
chr_orig
end
}
# remove empty lines
string.gsub!( /^\s*\n\s*\n/m, "\n" )
# add extracted links
if link_list
string += "\n\n" + link_list
end
return string
end
end
# workaround to parse subjects with 2 different encodings correctly (e. g. quoted-printable see test/fixtures/mail9.box)
module Mail
module Encodings
def Encodings.value_decode(str)
# Optimization: If there's no encoded-words in the string, just return it
return str unless str.index("=?")
str = str.gsub(/\?=(\s*)=\?/, '?==?') # Remove whitespaces between 'encoded-word's
# Split on white-space boundaries with capture, so we capture the white-space as well
str.split(/([ \t])/).map do |text|
if text.index('=?') .nil?
text
else
# Join QP encoded-words that are adjacent to avoid decoding partial chars
# text.gsub!(/\?\=\=\?.+?\?[Qq]\?/m, '') if text =~ /\?==\?/
# Search for occurences of quoted strings or plain strings
text.scan(/( # Group around entire regex to include it in matches
\=\?[^?]+\?([QB])\?[^?]+?\?\= # Quoted String with subgroup for encoding method
| # or
.+?(?=\=\?|$) # Plain String
)/xmi).map do |matches|
string, method = *matches
if method == 'b' || method == 'B'
b_value_decode(string)
elsif method == 'q' || method == 'Q'
q_value_decode(string)
else
string
end
end
end
end.join("")
end
end
end |
class Cjson < Formula
desc "Ultralightweight JSON parser in ANSI C"
homepage "https://github.com/DaveGamble/cJSON"
url "https://github.com/DaveGamble/cJSON/archive/v1.7.14.tar.gz"
sha256 "fb50a663eefdc76bafa80c82bc045af13b1363e8f45cec8b442007aef6a41343"
license "MIT"
bottle do
cellar :any
sha256 "9d85bfec25eec9244a4e99807bcb976b72afd47e3c740f37f3d7033b910d6abc" => :big_sur
sha256 "19da0211d4aabe7a2bf7cf489682d8a9ec57f7d5749cdd39f81491354017a9b9" => :catalina
sha256 "32192c80f7a8dea4988342342dd80aabba292e8200e52f9cd2a2a35fc202b671" => :mojave
sha256 "0dfc85831529da5d33e07b46c08fbca4ed673f3879c4025a982b7612a0a05b7c" => :high_sierra
end
depends_on "cmake" => :build
def install
system "cmake", "-DENABLE_CJSON_UTILS=On", "-DENABLE_CJSON_TEST=Off",
"-DBUILD_SHARED_AND_STATIC_LIBS=On", ".",
*std_cmake_args
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <cjson/cJSON.h>
int main()
{
char *s = "{\\"key\\":\\"value\\"}";
cJSON *json = cJSON_Parse(s);
if (!json) {
return 1;
}
cJSON *item = cJSON_GetObjectItem(json, "key");
if (!item) {
return 1;
}
cJSON_Delete(json);
return 0;
}
EOS
system ENV.cc, "-L#{lib}", "-lcjson", "test.c", "-o", "test"
system "./test"
end
end
cjson: update 1.7.14 bottle.
class Cjson < Formula
desc "Ultralightweight JSON parser in ANSI C"
homepage "https://github.com/DaveGamble/cJSON"
url "https://github.com/DaveGamble/cJSON/archive/v1.7.14.tar.gz"
sha256 "fb50a663eefdc76bafa80c82bc045af13b1363e8f45cec8b442007aef6a41343"
license "MIT"
bottle do
cellar :any
sha256 "9d85bfec25eec9244a4e99807bcb976b72afd47e3c740f37f3d7033b910d6abc" => :big_sur
sha256 "1fa282ceccaeb65e3af86a5787cc5ff413ce6b97ecca802c9c562b85b1850804" => :arm64_big_sur
sha256 "19da0211d4aabe7a2bf7cf489682d8a9ec57f7d5749cdd39f81491354017a9b9" => :catalina
sha256 "32192c80f7a8dea4988342342dd80aabba292e8200e52f9cd2a2a35fc202b671" => :mojave
sha256 "0dfc85831529da5d33e07b46c08fbca4ed673f3879c4025a982b7612a0a05b7c" => :high_sierra
end
depends_on "cmake" => :build
def install
system "cmake", "-DENABLE_CJSON_UTILS=On", "-DENABLE_CJSON_TEST=Off",
"-DBUILD_SHARED_AND_STATIC_LIBS=On", ".",
*std_cmake_args
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <cjson/cJSON.h>
int main()
{
char *s = "{\\"key\\":\\"value\\"}";
cJSON *json = cJSON_Parse(s);
if (!json) {
return 1;
}
cJSON *item = cJSON_GetObjectItem(json, "key");
if (!item) {
return 1;
}
cJSON_Delete(json);
return 0;
}
EOS
system ENV.cc, "-L#{lib}", "-lcjson", "test.c", "-o", "test"
system "./test"
end
end
|
module RepoSearch
extend ActiveSupport::Concern
included do
include Elasticsearch::Model
index_name "repositories-#{Rails.env}"
FIELDS = ['full_name^2', 'exact_name^2', 'description', 'homepage', 'language', 'license']
settings index: { number_of_shards: 3, number_of_replicas: 1 } do
mapping do
indexes :full_name, type: 'string', :analyzer => 'snowball', :boost => 6
indexes :exact_name, type: 'string', :index => :not_analyzed, :boost => 2
indexes :description, type: 'string', :analyzer => 'snowball'
indexes :homepage, type: 'string'
indexes :language, type: 'string', :index => :not_analyzed
indexes :license, type: 'string', :index => :not_analyzed
indexes :keywords, type: 'string', :index => :not_analyzed
indexes :platforms, type: 'string', :index => :not_analyzed
indexes :host_type, type: 'string', :index => :not_analyzed
indexes :status, type: 'string', :index => :not_analyzed
indexes :default_branch, type: 'string', :index => :not_analyzed
indexes :source_name, type: 'string', :index => :not_analyzed
indexes :has_readme, type: 'boolean'
indexes :has_changelog, type: 'boolean'
indexes :has_contributing, type: 'boolean'
indexes :has_license, type: 'boolean'
indexes :has_coc, type: 'boolean'
indexes :has_threat_model, type: 'boolean'
indexes :has_audit, type: 'boolean'
indexes :created_at, type: 'date'
indexes :updated_at, type: 'date'
indexes :pushed_at, type: 'date'
indexes :last_synced_at, type: 'date'
indexes :owner_id, type: 'integer'
indexes :size, type: 'integer'
indexes :stargazers_count, type: 'integer'
indexes :forks_count, type: 'integer'
indexes :open_issues_count, type: 'integer'
indexes :subscribers_count, type: 'integer'
indexes :github_id, type: 'string'
indexes :uuid, type: 'string'
indexes :github_contributions_count, type: 'integer'
indexes :contributions_count, type: 'integer'
indexes :rank, type: 'integer'
indexes :fork, type: 'boolean'
indexes :has_issues, type: 'boolean'
indexes :has_wiki, type: 'boolean'
indexes :has_pages, type: 'boolean'
indexes :private, type: 'boolean'
end
end
after_save lambda { __elasticsearch__.index_document }
after_commit lambda { __elasticsearch__.delete_document rescue nil }, on: :destroy
def self.facets(options = {})
Rails.cache.fetch "repo_facet:#{options.to_s.gsub(/\W/, '')}", :expires_in => 1.hour, race_condition_ttl: 2.minutes do
search('', options).response.aggregations
end
end
def as_indexed_json(_options)
as_json methods: [:exact_name, :keywords, :platforms, :github_id, :github_contributions_count, :rank]
end
def rank
read_attribute(:rank) || 0
end
def exact_name
full_name
end
def keywords
(project_keywords + readme_keywords).uniq.first(10)
end
def project_keywords
projects.map(&:keywords_array).flatten.compact.uniq(&:downcase)
end
def readme_keywords
return [] unless readme.present?
readme.keywords
end
def platforms
projects.map(&:platform).compact.uniq(&:downcase)
end
def self.search(query, options = {})
facet_limit = options.fetch(:facet_limit, 35)
query = Project.sanitize_query(query)
options[:filters] ||= []
options[:must_not] ||= []
search_definition = {
query: {
function_score: {
query: {
filtered: {
query: {match_all: {}},
filter:{
bool: {
must: [],
must_not: [
{
term: {
"fork" => true
}
},
{
term: {
"private" => true
}
},
{
term: {
"status" => "Removed"
}
}
]
}
}
}
},
field_value_factor: {
field: "rank",
"modifier": "square"
}
}
},
aggs: {
language: Project.facet_filter(:language, facet_limit, options),
license: Project.facet_filter(:license, facet_limit, options),
keywords: Project.facet_filter(:keywords, facet_limit, options),
host_type: Project.facet_filter(:host_type, facet_limit, options)
},
filter: {
bool: {
must: [],
must_not: options[:must_not]
}
},
suggest: {
did_you_mean: {
text: query,
term: {
size: 1,
field: "full_name"
}
}
}
}
search_definition[:sort] = { (options[:sort] || '_score') => (options[:order] || 'desc') }
search_definition[:track_scores] = true
search_definition[:filter][:bool][:must] = Project.filter_format(options[:filters])
if query.present?
search_definition[:query][:function_score][:query][:filtered][:query] = Project.query_options(query, FIELDS)
elsif options[:sort].blank?
search_definition[:sort] = [{'rank' => 'desc'}, {'stargazers_count' => 'desc'}]
end
__elasticsearch__.search(search_definition)
end
end
end
Avoid indexing unused repo fields into elasticsearch
module RepoSearch
extend ActiveSupport::Concern
included do
include Elasticsearch::Model
index_name "repositories-#{Rails.env}"
FIELDS = ['full_name^2', 'exact_name^2', 'description', 'homepage', 'language', 'license']
settings index: { number_of_shards: 3, number_of_replicas: 1 } do
mapping do
indexes :full_name, type: 'string', :analyzer => 'snowball', :boost => 6
indexes :exact_name, type: 'string', :index => :not_analyzed, :boost => 2
indexes :description, type: 'string', :analyzer => 'snowball'
indexes :homepage, type: 'string'
indexes :language, type: 'string', :index => :not_analyzed
indexes :license, type: 'string', :index => :not_analyzed
indexes :keywords, type: 'string', :index => :not_analyzed
indexes :host_type, type: 'string', :index => :not_analyzed
indexes :status, type: 'string', :index => :not_analyzed
indexes :created_at, type: 'date'
indexes :updated_at, type: 'date'
indexes :pushed_at, type: 'date'
indexes :stargazers_count, type: 'integer'
indexes :forks_count, type: 'integer'
indexes :open_issues_count, type: 'integer'
indexes :subscribers_count, type: 'integer'
indexes :contributions_count, type: 'integer'
indexes :rank, type: 'integer'
indexes :fork, type: 'boolean'
indexes :private, type: 'boolean'
end
end
after_save lambda { __elasticsearch__.index_document }
after_commit lambda { __elasticsearch__.delete_document rescue nil }, on: :destroy
def self.facets(options = {})
Rails.cache.fetch "repo_facet:#{options.to_s.gsub(/\W/, '')}", :expires_in => 1.hour, race_condition_ttl: 2.minutes do
search('', options).response.aggregations
end
end
def as_indexed_json(_options)
as_json methods: [:exact_name, :keywords, :rank]
end
def rank
read_attribute(:rank) || 0
end
def exact_name
full_name
end
def keywords
(project_keywords + readme_keywords).uniq.first(10)
end
def project_keywords
projects.map(&:keywords_array).flatten.compact.uniq(&:downcase)
end
def readme_keywords
return [] unless readme.present?
readme.keywords
end
def platforms
projects.map(&:platform).compact.uniq(&:downcase)
end
def self.search(query, options = {})
facet_limit = options.fetch(:facet_limit, 35)
query = Project.sanitize_query(query)
options[:filters] ||= []
options[:must_not] ||= []
search_definition = {
query: {
function_score: {
query: {
filtered: {
query: {match_all: {}},
filter:{
bool: {
must: [],
must_not: [
{
term: {
"fork" => true
}
},
{
term: {
"private" => true
}
},
{
term: {
"status" => "Removed"
}
}
]
}
}
}
},
field_value_factor: {
field: "rank",
"modifier": "square"
}
}
},
aggs: {
language: Project.facet_filter(:language, facet_limit, options),
license: Project.facet_filter(:license, facet_limit, options),
keywords: Project.facet_filter(:keywords, facet_limit, options),
host_type: Project.facet_filter(:host_type, facet_limit, options)
},
filter: {
bool: {
must: [],
must_not: options[:must_not]
}
},
suggest: {
did_you_mean: {
text: query,
term: {
size: 1,
field: "full_name"
}
}
}
}
search_definition[:sort] = { (options[:sort] || '_score') => (options[:order] || 'desc') }
search_definition[:track_scores] = true
search_definition[:filter][:bool][:must] = Project.filter_format(options[:filters])
if query.present?
search_definition[:query][:function_score][:query][:filtered][:query] = Project.query_options(query, FIELDS)
elsif options[:sort].blank?
search_definition[:sort] = [{'rank' => 'desc'}, {'stargazers_count' => 'desc'}]
end
__elasticsearch__.search(search_definition)
end
end
end
|
class Clamz < Formula
desc "Download MP3 files from Amazon's music store"
homepage "https://code.google.com/archive/p/clamz/"
url "https://clamz.googlecode.com/files/clamz-0.5.tar.gz"
sha256 "5a63f23f15dfa6c2af00ff9531ae9bfcca0facfe5b1aa82790964f050a09832b"
revision 1
bottle do
cellar :any
sha256 "b960106e00e01e4dd8ff259feab6e0a1e399d373aa79d2b5d622f2ccf6f1e41b" => :el_capitan
sha256 "e0ba09e61f28b4d224f20b0922277b849bff48ce8c7738e8d22fe1a514d56fe2" => :yosemite
sha256 "70f9f355c7f53a6201b5e175dbc6db9b1f8b275327250a1e70e06d5c139c2a53" => :mavericks
end
depends_on "pkg-config" => :build
depends_on "libgcrypt"
def install
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
system "#{bin}/clamz"
end
end
clamz: migrate to archive URL
class Clamz < Formula
desc "Download MP3 files from Amazon's music store"
homepage "https://code.google.com/archive/p/clamz/"
url "https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/clamz/clamz-0.5.tar.gz"
sha256 "5a63f23f15dfa6c2af00ff9531ae9bfcca0facfe5b1aa82790964f050a09832b"
revision 1
bottle do
cellar :any
sha256 "b960106e00e01e4dd8ff259feab6e0a1e399d373aa79d2b5d622f2ccf6f1e41b" => :el_capitan
sha256 "e0ba09e61f28b4d224f20b0922277b849bff48ce8c7738e8d22fe1a514d56fe2" => :yosemite
sha256 "70f9f355c7f53a6201b5e175dbc6db9b1f8b275327250a1e70e06d5c139c2a53" => :mavericks
end
depends_on "pkg-config" => :build
depends_on "libgcrypt"
def install
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
assert_match version.to_s, shell_output("#{bin}/clamz --version 2>&1")
end
end
|
module SeedEntity
extend ActiveSupport::Concern
include Neo4j::ActiveNode
included do
property :created_at, type: Integer
property :updated_at, type: Integer
property :reference, type: String
property :name, type: String
property :description, type: String
property :thumbnail, type: String
property :url, type: String
property :latitude, type: BigDecimal
property :longitude, type: BigDecimal
property :start_date, type: Integer
property :end_date, type: Integer
property :urls
property :history
serialize :urls
serialize :history
has_many :both, :connected_seeds, type: false, model_class: false
before_create :set_creation_timestamp
before_save :set_update_timestamp
before_save :log_update
def visible_fields
attributes.
except('provider', 'tokens', 'current_sign_in_at', 'current_sign_in_ip', 'last_sign_in_at', 'last_sign_in_ip',
'sign_in_count', 'encrypted_password', 'history').
merge({'label' => label, 'id' => id, 'urls' => urls})
end
def label
self.class.to_s
end
def seeds
connected_seeds.collect {|s| s.id}
end
def seeds=(val)
if val && val.is_a?(Array)
new_seeds = Neo4j::Session.current.query.match(:n).where('n.uuid' => val.select {|v| !v.blank?}).return(:n).
collect {|res| res.n}
self.connected_seeds = new_seeds
end
end
def set_creation_timestamp
self.created_at = Time.current.to_i
end
def set_update_timestamp
self.updated_at = Time.current.to_i
end
def creation_date
Time.at(self.created_at)
end
def started_at
Time.at(start_date) unless start_date.nil?
end
def started_at=(val)
self.start_date = val.nil? ? nil : Time.parse(val).to_i
end
def ended_at
Time.at(end_date) unless end_date.nil?
end
def ended_at=(val)
self.end_date = val.nil? ? nil : Time.parse(val).to_i
end
def author=(val)
@author = val
end
def log_update
self.history ||= {}
self.history[:entries] ||= []
self.history[:entries] << {author: @author, timestamp: Time.current.to_i, changes: self.changes.except(:history)}
end
end
end
Rename tasks to actions
module SeedEntity
extend ActiveSupport::Concern
include Neo4j::ActiveNode
included do
property :created_at, type: Integer
property :updated_at, type: Integer
property :reference, type: String
property :name, type: String
property :description, type: String
property :thumbnail, type: String
property :url, type: String
property :latitude, type: BigDecimal
property :longitude, type: BigDecimal
property :start_date, type: Integer
property :end_date, type: Integer
property :urls
property :history
serialize :urls
serialize :history
has_many :both, :connected_seeds, type: false, model_class: false
before_create :set_creation_timestamp
before_save :set_update_timestamp
before_save :log_update
def visible_fields
attributes.
except('provider', 'tokens', 'current_sign_in_at', 'current_sign_in_ip', 'last_sign_in_at', 'last_sign_in_ip',
'sign_in_count', 'encrypted_password', 'history').
merge({'label' => label, 'id' => id, 'urls' => urls})
end
def label
self.is_a?(Task) ? 'Action' : self.class.to_s
end
def seeds
connected_seeds.collect {|s| s.id}
end
def seeds=(val)
if val && val.is_a?(Array)
new_seeds = Neo4j::Session.current.query.match(:n).where('n.uuid' => val.select {|v| !v.blank?}).return(:n).
collect {|res| res.n}
self.connected_seeds = new_seeds
end
end
def set_creation_timestamp
self.created_at = Time.current.to_i
end
def set_update_timestamp
self.updated_at = Time.current.to_i
end
def creation_date
Time.at(self.created_at)
end
def started_at
Time.at(start_date) unless start_date.nil?
end
def started_at=(val)
self.start_date = val.nil? ? nil : Time.parse(val).to_i
end
def ended_at
Time.at(end_date) unless end_date.nil?
end
def ended_at=(val)
self.end_date = val.nil? ? nil : Time.parse(val).to_i
end
def author=(val)
@author = val
end
def log_update
self.history ||= {}
self.history[:entries] ||= []
self.history[:entries] << {author: @author, timestamp: Time.current.to_i, changes: self.changes.except(:history)}
end
end
end
|
class Clasp < Formula
desc "Answer set solver for (extended) normal logic programs"
homepage "http://potassco.sourceforge.net/"
url "https://downloads.sourceforge.net/project/potassco/clasp/3.1.2/clasp-3.1.2-source.tar.gz"
sha256 "77d5b8fc9617436f7ba37f3c80ad2ce963dfefb7ddaf8ae14d5a4f40a30cc9d3"
bottle do
cellar :any
sha256 "d55865143a46df97accfa26272d8e0e126c7aa4b0c7dc47dd792e971563b6f77" => :yosemite
sha256 "8cfe71e8a7df4fb78c8a5adfc0cb196e570a92a33684eb8dec10e8306b816fd6" => :mavericks
sha256 "8a9687f4b906e97b44f6f865b1f4474a56f92398ff4b7a88f5890b2b95564056" => :mountain_lion
end
option "with-mt", "Enable multi-thread support"
depends_on "tbb" if build.with? "mt"
def install
if build.with? "mt"
ENV["TBB30_INSTALL_DIR"] = Formula["tbb"].opt_prefix
build_dir = "build/release_mt"
else
build_dir = "build/release"
end
args = %W[
--config=release
--prefix=#{prefix}
]
args << "--with-mt" if build.with? "mt"
bin.mkpath
system "./configure.sh", *args
system "make", "-C", build_dir, "install"
end
test do
assert_match /#{version}/, shell_output("#{bin}/clasp --version")
end
end
clasp 3.1.3
Closes Homebrew/homebrew#42727.
class Clasp < Formula
desc "Answer set solver for (extended) normal logic programs"
homepage "http://potassco.sourceforge.net/"
url "https://downloads.sourceforge.net/project/potassco/clasp/3.1.3/clasp-3.1.3-source.tar.gz"
sha256 "f08684eadfa5ae5efa5c06439edc361b775fc55b7c1a9ca862eda8f5bf7e5f1f"
bottle do
cellar :any
sha256 "d55865143a46df97accfa26272d8e0e126c7aa4b0c7dc47dd792e971563b6f77" => :yosemite
sha256 "8cfe71e8a7df4fb78c8a5adfc0cb196e570a92a33684eb8dec10e8306b816fd6" => :mavericks
sha256 "8a9687f4b906e97b44f6f865b1f4474a56f92398ff4b7a88f5890b2b95564056" => :mountain_lion
end
option "with-mt", "Enable multi-thread support"
depends_on "tbb" if build.with? "mt"
def install
if build.with? "mt"
ENV["TBB30_INSTALL_DIR"] = Formula["tbb"].opt_prefix
build_dir = "build/release_mt"
else
build_dir = "build/release"
end
args = %W[
--config=release
--prefix=#{prefix}
]
args << "--with-mt" if build.with? "mt"
bin.mkpath
system "./configure.sh", *args
system "make", "-C", build_dir, "install"
end
test do
assert_match /#{version}/, shell_output("#{bin}/clasp --version")
end
end
|
# frozen_string_literal: true
#
# Copyright (C) 2011 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
class DelayedNotification < ActiveRecord::Base
include Workflow
belongs_to :asset, polymorphic:
[:assessment_request, :attachment, :content_migration, :content_export, :collaborator, :submission,
:assignment, :communication_channel, :calendar_event, :conversation_message, :discussion_entry,
:submission_comment, { quiz_submission: 'Quizzes::QuizSubmission' }, :discussion_topic, :course, :enrollment,
:wiki_page, :group_membership, :web_conference], polymorphic_prefix: true, exhaustive: false
include NotificationPreloader
attr_accessor :data
validates_presence_of :notification_id, :asset_id, :asset_type, :workflow_state
serialize :recipient_keys
workflow do
state :to_be_processed do
event :do_process, :transitions_to => :processed
end
state :processed
state :errored
end
def self.process(asset, notification, recipient_keys, data = {}, **kwargs)
# RUBY 2.7 this can go away (**{} will work at the caller)
raise ArgumentError, "Only send one hash" if !data&.empty? && !kwargs.empty?
data = kwargs if data&.empty? && !kwargs.empty?
DelayedNotification.new(
asset: asset,
notification: notification,
recipient_keys: recipient_keys,
data: data
).process
end
def process
res = []
if asset
iterate_to_list do |to_list_slice|
slice_res = notification.create_message(self.asset, to_list_slice, data: self.data)
res.concat(slice_res) if Rails.env.test?
end
end
self.do_process unless self.new_record?
res
rescue => e
Canvas::Errors.capture(e, message: "Delayed Notification processing failed")
logger.error "delayed notification processing failed: #{e.message}\n#{e.backtrace.join "\n"}"
self.workflow_state = 'errored'
self.save
[]
end
def iterate_to_list
lookups = {}
(recipient_keys || []).each do |key|
pieces = key.split('_')
id = pieces.pop
klass = pieces.join('_').classify.constantize
lookups[klass] ||= []
lookups[klass] << id
end
lookups.each do |klass, ids|
includes = []
includes = [ :notification_policies, :notification_policy_overrides, { user: :pseudonyms } ] if klass == CommunicationChannel
includes = [ :pseudonyms, { communication_channels: [:notification_policies, :notification_policy_overrides] } ] if klass == User
ids.each_slice(100) do |slice|
yield klass.where(:id => slice).preload(includes).to_a
end
end
end
scope :to_be_processed, lambda { |limit|
where(:workflow_state => 'to_be_processed').limit(limit).order("delayed_notifications.created_at")
}
end
preload notification_policies for both objects
this is the same queries, but now both objects recognize that the
policies are already loaded
test plan
- specs should pass
refs VICE-1280
flag = none
Change-Id: Ide3ada84bfd1f7ff97077d54065af6cc3519eee0
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/263270
Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com>
Reviewed-by: Omar Soto-Fortuño <2ca100155bc0669318a7e6f3850629c7667465e1@instructure.com>
QA-Review: Omar Soto-Fortuño <2ca100155bc0669318a7e6f3850629c7667465e1@instructure.com>
Product-Review: Omar Soto-Fortuño <2ca100155bc0669318a7e6f3850629c7667465e1@instructure.com>
# frozen_string_literal: true
#
# Copyright (C) 2011 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
class DelayedNotification < ActiveRecord::Base
include Workflow
belongs_to :asset, polymorphic:
[:assessment_request, :attachment, :content_migration, :content_export, :collaborator, :submission,
:assignment, :communication_channel, :calendar_event, :conversation_message, :discussion_entry,
:submission_comment, { quiz_submission: 'Quizzes::QuizSubmission' }, :discussion_topic, :course, :enrollment,
:wiki_page, :group_membership, :web_conference], polymorphic_prefix: true, exhaustive: false
include NotificationPreloader
attr_accessor :data
validates_presence_of :notification_id, :asset_id, :asset_type, :workflow_state
serialize :recipient_keys
workflow do
state :to_be_processed do
event :do_process, :transitions_to => :processed
end
state :processed
state :errored
end
def self.process(asset, notification, recipient_keys, data = {}, **kwargs)
# RUBY 2.7 this can go away (**{} will work at the caller)
raise ArgumentError, "Only send one hash" if !data&.empty? && !kwargs.empty?
data = kwargs if data&.empty? && !kwargs.empty?
DelayedNotification.new(
asset: asset,
notification: notification,
recipient_keys: recipient_keys,
data: data
).process
end
def process
res = []
if asset
iterate_to_list do |to_list_slice|
slice_res = notification.create_message(self.asset, to_list_slice, data: self.data)
res.concat(slice_res) if Rails.env.test?
end
end
self.do_process unless self.new_record?
res
rescue => e
Canvas::Errors.capture(e, message: "Delayed Notification processing failed")
logger.error "delayed notification processing failed: #{e.message}\n#{e.backtrace.join "\n"}"
self.workflow_state = 'errored'
self.save
[]
end
def iterate_to_list
lookups = {}
(recipient_keys || []).each do |key|
pieces = key.split('_')
id = pieces.pop
klass = pieces.join('_').classify.constantize
lookups[klass] ||= []
lookups[klass] << id
end
lookups.each do |klass, ids|
# notification_policies, and notification_policy_overrides are included in
# each of the preloads twice intentionally.
# rails de-dups them and only does one query, but if not included twice,
# they will not show as loaded against both objects.
includes = if klass == CommunicationChannel
[:notification_policies, :notification_policy_overrides, { user: [:pseudonyms, :notification_policies, :notification_policy_overrides] }]
elsif klass == User
[:pseudonyms, { communication_channels: [:notification_policies, :notification_policy_overrides] }, :notification_policies, :notification_policy_overrides]
else
[]
end
ids.each_slice(100) do |slice|
yield klass.where(:id => slice).preload(includes).to_a
end
end
end
scope :to_be_processed, lambda { |limit|
where(:workflow_state => 'to_be_processed').limit(limit).order("delayed_notifications.created_at")
}
end
|
class Cli53 < Formula
desc "command-line tool for Amazon Route 53"
homepage "https://github.com/barnybug/cli53"
url "https://github.com/barnybug/cli53/archive/0.8.3.tar.gz"
sha256 "e87225714a42801dcbe96a1ebe12a841315c7db2eee992d7eddef18827469e7b"
bottle do
cellar :any_skip_relocation
sha256 "99cc44d91bbed5282c6ccbbe7c0613e343495838c2fc6fd7cd4dc209b6f2f093" => :el_capitan
sha256 "77febccd0665b60dec469e323d5556c67c011b5e685b01327869c1d5f355bb0d" => :yosemite
sha256 "0f0b0b26685886897ee7910ab24d298a95c5631ea76473674a9799ca960f46d9" => :mavericks
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
mkdir_p buildpath/"src/github.com/barnybug"
ln_s buildpath, buildpath/"src/github.com/barnybug/cli53"
system "make", "build"
bin.install "cli53"
end
test do
assert_match "list domains", shell_output("#{bin}/cli53 help list")
end
end
cli53: update 0.8.3 bottle.
class Cli53 < Formula
desc "command-line tool for Amazon Route 53"
homepage "https://github.com/barnybug/cli53"
url "https://github.com/barnybug/cli53/archive/0.8.3.tar.gz"
sha256 "e87225714a42801dcbe96a1ebe12a841315c7db2eee992d7eddef18827469e7b"
bottle do
cellar :any_skip_relocation
sha256 "8527b915200bf4ecf957c0695f18c909eabf99b8699453268dc465efeed4494a" => :el_capitan
sha256 "f979d84645fe43b51de6db1d268ab2f687523413d5d7f458bf965911ecc37d1e" => :yosemite
sha256 "c7443e2999db2eb176473693db22874034d2f743834c818c89848d801afca5a5" => :mavericks
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
mkdir_p buildpath/"src/github.com/barnybug"
ln_s buildpath, buildpath/"src/github.com/barnybug/cli53"
system "make", "build"
bin.install "cli53"
end
test do
assert_match "list domains", shell_output("#{bin}/cli53 help list")
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.