code
stringlengths
1
1.73M
language
stringclasses
1 value
# # << Haru Free PDF Library 2.0.2 >> -- ttfont_demo.rb # # http://libharu.org/ # # Copyright (c) 1999-2006 Takeshi Kanno # # Permission to use, copy, modify, distribute and sell this software # and its documentation for any purpose is hereby granted without fee, # provided that the above copyright notice appe...
Ruby
# # << Haru Free PDF Library 2.0.0 >> -- font_example.rb # # Copyright (c) 1999-2006 Takeshi Kanno <takeshi_kanno@est.hi-ho.ne.jp> # # Permission to use, copy, modify, distribute and sell this software # and its documentation for any purpose is hereby granted without fee, # provided that the above copyright noti...
Ruby
# # << Haru Free PDF Library 2.0.0 >> -- encryption.rb # # Copyright (c) 1999-2006 Takeshi Kanno <takeshi_kanno@est.hi-ho.ne.jp> # # Permission to use, copy, modify, distribute and sell this software # and its documentation for any purpose is hereby granted without fee, # provided that the above copyright notice...
Ruby
# # << Haru Free PDF Library 2.0.0 >> -- demo.rb # # Copyright (c) 1999-2006 Takeshi Kanno <takeshi_kanno@est.hi-ho.ne.jp> # # Permission to use, copy, modify, distribute and sell this software # and its documentation for any purpose is hereby granted without fee, # provided that the above copyright notice appea...
Ruby
# # << Haru Free PDF Library 2.0.6 >> -- slideshow_demo.rb # # http://libharu.org/ # # Copyright (c) 1999-2006 Takeshi Kanno # # Permission to use, copy, modify, distribute and sell this software # and its documentation for any purpose is hereby granted without fee, # provided that the above copyright notice a...
Ruby
# # << Haru Free PDF Library 2.0.2 >> -- arc_demo.rb # # http://libharu.org/ # # Copyright (c) 1999-2006 Takeshi Kanno # # Permission to use, copy, modify, distribute and sell this software # and its documentation for any purpose is hereby granted without fee, # provided that the above copyright notice appear ...
Ruby
require 'mkmf' $CPPFLAGS = $CPPFLAGS + " -I../../include" $LDFLAGS = $LDFLAGS + " -L../../" $LIBS = $LIBS + " -lhpdf -lpng -lz" create_makefile 'hpdf'
Ruby
# Require any additional compass plugins here. # Set this to the root of your project when deployed: http_path = "/" css_dir = "theme/css" sass_dir = "theme/scss" images_dir = "images" javascripts_dir = "js" # You can select your preferred output style here (can be overridden via the command line): output_style = :co...
Ruby
# $ext_path: This should be the path of where the ExtJS SDK is installed # Generally this will be in a lib/extjs folder in your applications root # <root>/lib/extjs $ext_path = "../../" # sass_path: the directory your Sass files are in. THIS file should also be in the Sass folder # Generally this will be in a resource...
Ruby
# include the utils rb file which has extra functionality for the ext theme dir = File.dirname(__FILE__) require File.join(dir, 'lib', 'utils.rb') # register ext4 as a compass framework Compass::Frameworks.register 'ext4', dir
Ruby
# $ext_path: This should be the path of the Ext JS SDK relative to this file $ext_path = "../../extjs" # sass_path: the directory your Sass files are in. THIS file should also be in the Sass folder # Generally this will be in a resources/sass folder # <root>/resources/sass sass_path = File.dirname(__FILE__) # css_pat...
Ruby
module ExtJS4 module SassExtensions module Functions module Utils def parsebox(list, n) assert_type n, :Number if !n.int? raise ArgumentError.new("List index #{n} must be an integer") elsif n.to_i < 1 raise ArgumentError.new("List index #{n} must...
Ruby
# Require any additional compass plugins here. # Set this to the root of your project when deployed: http_path = "/" css_dir = "theme/css" sass_dir = "theme/scss" images_dir = "images" javascripts_dir = "js" # You can select your preferred output style here (can be overridden via the command line): output_style = :co...
Ruby
# Require any additional compass plugins here. # Set this to the root of your project when deployed: http_path = "/" css_dir = "theme/css" sass_dir = "theme/scss" images_dir = "images" javascripts_dir = "js" # You can select your preferred output style here (can be overridden via the command line): output_style = :co...
Ruby
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format # (all these examples are active by default): # ActiveSupport::Inflector.inflections do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', ...
Ruby
class Time def basic_format self.strftime("%Y-%m-%d %T") end end
Ruby
# uncomment these lines and set appropriately # path to rake #configatron.rake_path = "/usr/local/bin/rake" # # twitter oauth credentials (only necessary if you're using twitter) #configatron.twitter_consumer_key = 'xxx' #configatron.twitter_consumer_secret = 'xxx' #configatron.twitter_oauth_token = 'xxx' #configatron....
Ruby
class Array # Matches elements of a to elements of b and passes each pair to a block. # If an element of a has no match in b or vice versa, nil is passed. # Assumes no duplicates in either array. def match(arr, &block) # create hashes from a and b ah = Hash[*self.collect{|x| [x,x]}.flatten] bh = Has...
Ruby
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone
Ruby
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attac...
Ruby
# Be sure to restart your server when you modify this file. Aggie::Application.config.session_store :cookie_store, :key => '_aggie_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails ge...
Ruby
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a probl...
Ruby
CONF = configatron Setting.copy_to_config CONF.site_email = "Aggie <tomsmyth@gmail.com>" CONF.chunk_start_time = Time.zone.parse("2011-04-02 00:00:00") CONF.chunk_size = 5.minutes CONF.saved_search_chunks_per_page = 72 CONF.saved_search_htick_interval = 12 # unit is chunks; should divide per_page value evenly CONF.sav...
Ruby
Aggie::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on ...
Ruby
Aggie::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserv...
Ruby
Aggie::Application.configure do # Settings specified here will take precedence over those in config/application.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test su...
Ruby
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Aggie::Application.initialize!
Ruby
require 'rubygems' # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
Ruby
require File.expand_path('../boot', __FILE__) require 'rails/all' # If you have a Gemfile, require the gems listed there, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) if defined?(Bundler) module Aggie class Application < Rails::Application # S...
Ruby
Aggie::Application.routes.draw do resources(:settings) resources(:categories) resources(:users){collection {get 'welcome'; get 'logout'}} resources(:incidents){collection {get 'picker'; get 'lookup'}; member {get 'choose'; get 'delete'}} resource(:crawler){member {get 'log'}} resources(:rules){member {ge...
Ruby
module ReportsHelper def reports_index_fields(options) %w[authored sourcename author content pertinent incidents] end def reports_format_field(obj, field, options) case field when "sourcename" link_to(obj.send(field), edit_source_path(obj.source_id)) when "incidents" (obj.incidents....
Ruby
module ApplicationHelper def flash_and_form_errors(object = nil) render("layouts/flash", :flash => flash, :object => object) end # draws a basic form for the given object def basic_form(obj, &block) form_for(obj) do |f| f.mode = controller.action_name.to_sym # get the fields spec spec ...
Ruby
module RulesHelper def rules_index_fields(options) %w[id search_query actions] end def rules_format_field(obj, field, options) case field when "id" "#" + obj.id.to_s.rjust(3, "0") when "actions" link_to("Delete", rule_path(obj), :method => :delete, :confirm => "Are you sure you want to...
Ruby
module SourcesHelper def sources_index_fields(options) %w[name kind url enabled? keywords languages actions] end def sources_format_field(obj, field, options) case field when "type" then obj.type.gsub(/Source$/, "") when "actions" link_to("Edit", edit_source_path(obj)) + " | " + link_t...
Ruby
module CategoriesHelper def categories_index_fields(options) %w[name parent actions] end def categories_format_field(obj, field, options) case field when "name" obj.full_name when "parent" obj.parent.name rescue "[none]" when "actions" action_links(obj, :exclude => :show) ...
Ruby
module IncidentsHelper def incidents_index_fields(options) %w[id category_name title num_rpts status place_name last_updated actions] end def incidents_format_field(obj, field, options) case field when "id" "#" + obj.id.to_s.rjust(3, "0") when "last_updated" distance_of_time_in_word...
Ruby
module BatchesHelper def batches_index_fields(options) %w[authored sourcename author content] end def batches_format_field(obj, field, options) reports_format_field(obj, field, options) end def batches_index_links(objs, options) [ batch_op_link(:name => "Finish", :action => "batches#fi...
Ruby
# a category for incidents. supports hierarchies. should probably change this to a tagging setup. class Category < ActiveRecord::Base belongs_to(:parent, :class_name => "Category") has_many(:children, :foreign_key => "parent_id", :class_name => "Category") # before destroy check for stuff before_destroy(:che...
Ruby
# association between an incident and a report class IncidentReport < ActiveRecord::Base belongs_to(:incident) belongs_to(:report) end
Ruby
class Timespan < ActiveRecord::Base has_many(:search_runs) has_many(:searches, :through => :search_runs) def self.common find(:all, :conditions => "is_common=1", :order => "before_offset desc, before_date desc") end def self.find_chunks_between(start, stop) find(:all, :conditions => ["is_search_...
Ruby
class TwitterSource < Source def fetch super # if we have a thread obj already, make sure it's alive. otherwise create a thread reason = nil if !@thread reason = "Stream thread doesn't exist. Restarting stream." elsif !@thread.alive? puts @thread.inspect reason = "Stream thr...
Ruby
# a post or update from one of the sources. this is the central object in the system. class Report < ActiveRecord::Base belongs_to(:source) has_many(:incident_reports) has_many(:incidents, :through => :incident_reports) before_create(:strip_html) #before_save(:check_for_duplicates) scope(:unmarked, wh...
Ruby
module Crawler def self.table_name_prefix '' end end
Ruby
# a facebook group source # TODO: prevent duplicates when new comments are added # TODO: fix auth class FacebookGroupSource < Source MAX_PER_FETCH = 25 def fetch super fetched = 0 done = false # this is the proper way, but not working #token = FGraph.oauth_access_token('283815398303966',...
Ruby
# one run of a search, including most importantly the result class SearchRun < ActiveRecord::Base belongs_to(:search) belongs_to(:timespan) def self.last_run find(:first, :order => "created_at desc").updated_at rescue nil end # updates or creates the search run with the given search id and timespan ...
Ruby
class User < ActiveRecord::Base end
Ruby
# a particular search of the reports # searches can be saved and run on a regular basis class Search < ActiveRecord::Base has_many(:search_runs, :include => :timespan, :order => "timespans.after_date") has_many(:rules) # converts the given query to canonical format such that any two queries with the same # s...
Ruby
# a grouping of reports into a single event or occurrence, allowing tracking and annotation class Incident < ActiveRecord::Base has_many(:incident_reports, :dependent => :destroy) has_many(:reports, :through => :incident_reports) belongs_to(:category) before_save(:ensure_status) scope(:for_index, inclu...
Ruby
# one token or term in a search class SearchToken FIELDS = %w(sourcename sourcetype title content author before after pertinent report-id duplicate-of) REGEXP_FIELDS = %w(sourcename sourcetype title content author) DEFAULT_FIELDS = %w(title content author) def initialize(str) @str = str end # returns...
Ruby
class Crawler::SourceMonitorJob < Crawler::Job def initialize(crawler) super(crawler) # at first, set deadline to immediate b/c sources are needed @deadline = Time.now end def run # updates sources from database, detecting any changes made by other processes. if @crawler.sources.nil...
Ruby
class Crawler::BatchJob < Crawler::Job end
Ruby
# a background processor that retrieves reports, runs searches, and does other housekeeping. class Crawler::Crawler < ActiveRecord::Base before_create(:remove_others) after_create(:write_pid) attr_accessor(:sources) VERBOSITY = 1 # can be 1 (low), 2, 3 (high) # returns the current crawler if it is runni...
Ruby
class Crawler::Job attr_accessor :deadline def self.create_all(crawler) [ Crawler::SourceMonitorJob.new(crawler), Crawler::FetchJob.new(crawler), Crawler::TrendJob.new(crawler), Crawler::RuleJob.new(crawler) ] end def initialize(crawler) @crawler = crawler update_de...
Ruby
class Crawler::FetchJob < Crawler::Job def run # sort jobs by deadline and get first next_src = @crawler.sources.reject{|s| !s.enabled}.sort_by{|s| s.deadline}.first # if no sources, do nothing if next_src.nil? log_info("No enabled sources to fetch.") # if deadline is in past, run...
Ruby
class Crawler::TrendJob < Crawler::Job def run log_info("Running searches") start_time = Time.now Search.run_saved finish_time = Time.now elapsed = (finish_time - start_time).to_f.round(1) log_info("Searches complete (#{elapsed} s).") @deadline = Time.now + 5.minutes end end
Ruby
class Crawler::RuleJob < Crawler::Job def run log_info("Applying rules") start_time = Time.now Rule.apply_all finish_time = Time.now elapsed = (finish_time - start_time).to_f.round(1) log_info("Rule application complete (#{elapsed} s).") @deadline = Time.now + 30.seconds end e...
Ruby
# an automatically applied search. reports matching this search are automatically marked important. class Rule < ActiveRecord::Base belongs_to(:search) # applies all rules in a transaction def self.apply_all transaction do cutoff = (Time.now.utc - 1.hour).basic_format # apply all.each{|a...
Ruby
# models all the user-configurable settings in the app # there should only therefore need to be one row in this table class Setting < ActiveRecord::Base validates(:webmaster_email, :presence => true) validates(:timezone, :presence => true) after_save(:copy_to_config) # loads the one and only row def self.g...
Ruby
require 'feedzirra' class RssSource < Source def fetch super # load the items feed = Feedzirra::Feed.fetch_and_parse(url) # save the max latest_time (this is in case the feed entries are not sorted by date) old_latest = latest_authored_at.dup rescue nil fetched = 0 # for e...
Ruby
# a batch of records to be scanned. currently nothing needed in model. class Batch < ActiveRecord::Base end
Ruby
require 'open-uri' require 'fileutils' # one source of reports (e.g. Joe's blog, Fatima's Facebook group) class Source < ActiveRecord::Base has_many(:reports) validates(:name, :presence => true, :uniqueness => true, :format => {:with => /^[a-z0-9 ]+$/i}) validates(:kind, :presence => true) validate(:only_on...
Ruby
class SettingsController < ApplicationController def index @setting = Setting.get render(:action => :edit) end def update @setting = Setting.find(params[:id]) if @setting.update_attributes(params[:setting]) flash[:success] = "Settings updated successfully." redirect_to(:action => :i...
Ruby
class BatchesController < ApplicationController def new @title = "Batch Scan" # mark a batch with the session id and then load them sid = session[:session_id] Report.checkout_batch(sid) @reports = Report.batch(sid) end def finish finish_batch redirect_to(reports_path) end def...
Ruby
class ReportsController < ApplicationController def index @search = session[:search] || Search.new @impt_search = Search.find_or_create_by_query("pertinent:yes") begin @reports = Report.all_by_page(params[:page], @search.conditions) render(:partial => "table_only", :locals => {:reports => @rep...
Ruby
class SourcesController < ApplicationController def index @sources = Source.sorted(:paginate => true, :page => params[:page]) end def new @source = Source.new end def create @source = Source.new(params[:source]) if @source.save flash[:success] = "Source created successfully." ...
Ruby
class CategoriesController < ApplicationController def index @categories = Category.all end def new @category = Category.new end def edit @category = Category.find(params[:id]) end def create @category = Category.new(params[:category]) if @category.save redirect_to(categories_...
Ruby
class ApplicationController < ActionController::Base protect_from_forgery rescue_from(Exception, :with => :notify_error) before_filter(:set_default_title) before_filter(:get_crawler) before_filter(:login_required) before_filter(:set_timezone) protected def login_required redirect_to(welcome_u...
Ruby
class IncidentsController < ApplicationController def index @lookup = session[:incident_lookup] || "" @incidents = Incident.for_index.by_id @incidents = @incidents.where(Incident.search_condition(@lookup)) unless @lookup.blank? @incidents = @incidents.paginate(:page => params[:page]) end d...
Ruby
class SearchesController < ApplicationController def index @title = "Trends" @searches = Search.find_all_by_is_saved(true) @timespans = Timespan.paginate_default_to_last(params[:page]) @new_search = Search.new(:is_saved => true) end def create update end def update ref = params[:ref] ...
Ruby
class CrawlersController < ApplicationController def log @log = Crawler::Crawler.log(50) @title = "Crawler Log" render(:partial => "log") if ajax_request? end end
Ruby
class RulesController < ApplicationController def index @new_rule = Rule.new @search = Search.new @rules = Rule.all end def create # create the search search = Search.find_or_create_by_query(params[:search][:query]) # create the rule Rule.find_or_create_by_search_id(search.id) ...
Ruby
class UsersController < ApplicationController def welcome @title = "Login" end def create # if this is really a login, redirect login if params[:login] end def login pass = params[:user][:password] the_user = User.find(:first) if pass == the_user.password session[:user] = t...
Ruby
class AdminMailer < ActionMailer::Base default :from => CONF.site_email def error(exception, session = nil, params = nil, env = nil) @exception = exception @session = session @params = params @env = env path = env && (": " + env['REQUEST_URI']) || "" mail(:to => CONF.webmaster_emails, :su...
Ruby
# Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) require 'rake' Aggie::Application.load_tasks
Ruby
#!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) require File.expand_path('../../config/boot', __FILE__) require 'rails/commands'
Ruby
source 'http://rubygems.org' gem 'rails', '3.0.19' gem 'json' gem 'mysql' gem 'libxml-ruby' gem 'will_paginate', '3.0.pre2' gem 'configatron' gem 'tweetstream' gem 'feedzirra' gem 'rake', "0.8.7" gem 'fgraph'
Ruby
class AddIndicesToPlaces < ActiveRecord::Migration def self.up add_index(:places, [:code]) end def self.down remove_index(:places, [:code]) end end
Ruby
class AddAuthorIdToReport < ActiveRecord::Migration def self.up add_column :reports, :author_id, :integer end def self.down remove_column :reports, :author_id end end
Ruby
class CreateUrlRefs < ActiveRecord::Migration def self.up create_table :url_refs do |t| t.integer :report_id t.integer :url_id t.timestamps end end def self.down drop_table :url_refs end end
Ruby
class AddKindToSource < ActiveRecord::Migration def self.up add_column :sources, :kind, :string end def self.down remove_column :sources, :kind end end
Ruby
class ChangeUshahidiToRss < ActiveRecord::Migration def self.up execute("UPDATE sources SET type = 'RssSource' WHERE type = 'UshahidiSource'") end def self.down end end
Ruby
class DropScrapes < ActiveRecord::Migration def self.up drop_table :scrapes end def self.down end end
Ruby
class AddSweeperSource < ActiveRecord::Migration def self.up Source.create(:name => "Sweeper", :kind => "Db", :url => "http://184.106.192.231/scrape.php") end def self.down end end
Ruby
class RemoveEntityAssocs < ActiveRecord::Migration def self.up drop_table :entity_assocs end def self.down create_table :entity_assocs do |t| t.integer :report_id t.integer :entity_id t.timestamps end add_index(:entity_assocs, [:report_id, :entity_id], :unique => true) e...
Ruby
class AddIndicesToTimespan < ActiveRecord::Migration def self.up add_index :timespans, :after_date add_index :timespans, :before_date end def self.down remove_index :timespans, :after_date remove_index :timespans, :before_date end end
Ruby
class AddDataToReports < ActiveRecord::Migration def self.up add_column :reports, :data, :text end def self.down remove_column :reports, :data end end
Ruby
class CreateSources < ActiveRecord::Migration def self.up create_table :sources do |t| t.string :name t.string :type t.string :url t.timestamps end end def self.down drop_table :sources end end
Ruby
class ChangeSourceEnabledDefault < ActiveRecord::Migration def self.up execute("alter table sources change is_enabled enabled tinyint(1) default 1") end def self.down end end
Ruby
class AddNewIndices < ActiveRecord::Migration def self.up add_index(:authors, [:name]) add_index(:reports, [:source_id]) add_index(:reports, [:author_id]) add_index(:reports, [:created_at]) execute("create unique index index_reports_on_author_id_and_title_and_content on reports (author_id, title, ...
Ruby
class AddSourceIdToScrape < ActiveRecord::Migration def self.up add_column :scrapes, :source_id, :integer end def self.down remove_column :scrapes, :source_id end end
Ruby
class CreateEntities < ActiveRecord::Migration def self.up create_table :entities do |t| t.string :type t.string :content t.timestamps end add_index(:entities, [:type]) add_index(:entities, [:content]) end def self.down drop_table :entities end end
Ruby
class CreateIncidentReports < ActiveRecord::Migration def self.up create_table :incident_reports do |t| t.integer :incident_id t.integer :report_id t.timestamps end add_index(:incident_reports, [:incident_id, :report_id], :unique => true) end def self.down remove_index(:inciden...
Ruby
class AddIsSearchChunkToTimespans < ActiveRecord::Migration def self.up add_column :timespans, :is_search_chunk, :boolean # Add some initial search chunk timespans d = CONF.chunk_start_time while d < Time.now do Timespan.create(:after_date => d, :before_date => d + CONF.chunk_size, :is_sear...
Ruby
class CreateReports < ActiveRecord::Migration def self.up create_table :reports do |t| t.integer :source_id # twitter, news feed, etc. t.string :author t.string :url t.decimal :lat, :precision => 20, :scale => 15 t.decimal :lng, :precision => 20, :scale => 15 t.text :title ...
Ruby
class CreateUrls < ActiveRecord::Migration def self.up create_table :urls do |t| t.string :address t.timestamps end end def self.down drop_table :urls end end
Ruby
class CreateSearchRuns < ActiveRecord::Migration def self.up create_table :search_runs do |t| t.integer :search_id t.integer :timespan_id t.integer :num t.timestamps end end def self.down drop_table :search_runs end end
Ruby
class AddScrapedAtToSources < ActiveRecord::Migration def self.up add_column :sources, :scraped_at, :datetime end def self.down remove_column :sources, :scraped_at end end
Ruby
class AddAuthoredAtIndexToReports < ActiveRecord::Migration def self.up add_index(:reports, [:authored_at]) end def self.down remove_index(:reports, [:authored_at]) end end
Ruby
class RenameAutoscansToRules < ActiveRecord::Migration def self.up rename_table(:autoscans, :rules) Job.find_all_by_name("apply_autoscans").each{|j| j.name = "apply_rules"; j.save} end def self.down rename_table(:rules, :autoscans) end end
Ruby
class AddMarkReasonToReports < ActiveRecord::Migration def self.up add_column :reports, :mark_reason, :string end def self.down remove_column :reports, :mark_reason end end
Ruby