repo
string
commit
string
message
string
diff
string
nateleavitt/infusionsoft
c57d2cb0b47ebd97c5c8db6779e57fcc347e80fb
Make variable names match response type
diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb index 509816a..fa4ab38 100644 --- a/lib/infusionsoft/client/contact.rb +++ b/lib/infusionsoft/client/contact.rb @@ -1,189 +1,189 @@ module Infusionsoft class Client # Contact service is used to manage contacts. You can add, update and find contacts in # addition to managing follow up sequences, tags and action sets. module Contact # Creates a new contact record from the data passed in the associative array. # # @param [Hash] data contains the mappable contact fields and it's data # @return [Integer] the id of the newly added contact # @example # { :Email => 'test@test.com', :FirstName => 'first_name', :LastName => 'last_name' } def contact_add(data) contact_id = get('ContactService.add', data) if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end return contact_id end # Adds or updates a contact record based on matching data # # @param [Array<Hash>] data the contact data you want added # @param [String] check_type available options are 'Email', 'EmailAndName', # 'EmailAndNameAndCompany' # @return [Integer] id of the contact added or updated def contact_add_with_dup_check(data, check_type) - response = get('ContactService.addWithDupCheck', data, check_type) + contact_id = get('ContactService.addWithDupCheck', data, check_type) if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end - return response + return contact_id end # Updates a contact in the database. # # @param [Integer] contact_id # @param [Hash] data contains the mappable contact fields and it's data # @return [Integer] the id of the contact updated # @example # { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' } def contact_update(contact_id, data) - bool = get('ContactService.update', contact_id, data) + contact_id = get('ContactService.update', contact_id, data) if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end - return bool + return contact_id end # Loads a contact from the database # # @param [Integer] id # @param [Array] selected_fields the list of fields you want back # @return [Array] the fields returned back with it's data # @example this is what you would get back # { "FirstName" => "John", "LastName" => "Doe" } def contact_load(id, selected_fields) response = get('ContactService.load', id, selected_fields) end # Finds all contacts with the supplied email address in any of the three contact record email # addresses. # # @param [String] email # @param [Array] selected_fields the list of fields you want with it's data # @return [Array<Hash>] the list of contacts with it's fields and data def contact_find_by_email(email, selected_fields) response = get('ContactService.findByEmail', email, selected_fields) end # Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences). # # @param [Integer] contact_id # @param [Integer] campaign_id # @return [Boolean] returns true/false if the contact was added to the follow-up sequence # successfully def contact_add_to_campaign(contact_id, campaign_id) response = get('ContactService.addToCampaign', contact_id, campaign_id) end # Returns the Id number of the next follow-up sequence step for the given contact. # # @param [Integer] contact_id # @param [Integer] campaign_id # @return [Integer] id number of the next unfishished step in the given follow up sequence # for the given contact def contact_get_next_campaign_step(contact_id, campaign_id) response = get('ContactService.getNextCampaignStep', contact_id, campaign_id) end # Pauses a follow-up sequence for the given contact record # # @param [Integer] contact_id # @param [Integer] campaign_id # @return [Boolean] returns true/false if the sequence was paused def contact_pause_campaign(contact_id, campaign_id) response = get('ContactService.pauseCampaign', contact_id, campaign_id) end # Removes a follow-up sequence from a contact record # # @param [Integer] contact_id # @param [Integer] campaign_id # @return [Boolean] returns true/false if removed def contact_remove_from_campaign(contact_id, campaign_id) response = get('ContactService.removeFromCampaign', contact_id, campaign_id) end # Resumes a follow-up sequence that has been stopped/paused for a given contact. # # @param [Integer] contact_id # @param [Ingeger] campaign_id # @return [Boolean] returns true/false if sequence was resumed def contact_resume_campaign(contact_id, campaign_id) response = get('ConactService.resumeCampaignForContact', contact_id, campaign_id) end # Immediately performs the given follow-up sequence step_id for the given contacts. # # @param [Array<Integer>] list_of_contacts # @param [Integer] ) step_id # @return [Boolean] returns true/false if the step was rescheduled def contact_reschedule_campaign_step(list_of_contacts, step_id) response = get('ContactService.reschedulteCampaignStep', list_of_contacts, step_id) end # Removes a tag from a contact (groups were the original name of tags). # # @param [Integer] contact_id # @param [Integer] group_id # @return [Boolean] returns true/false if tag was removed successfully def contact_remove_from_group(contact_id, group_id) response = get('ContactService.removeFromGroup', contact_id, group_id) end # Adds a tag to a contact # # @param [Integer] contact_id # @param [Integer] group_id # @return [Boolean] returns true/false if the tag was added successfully def contact_add_to_group(contact_id, group_id) response = get('ContactService.addToGroup', contact_id, group_id) end # Runs an action set on a given contact record # # @param [Integer] contact_id # @param [Integer] action_set_id # @return [Array<Hash>] A list of details on each action run # @example here is a list of what you get back # [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' => # nil }] def contact_run_action_set(contact_id, action_set_id) response = get('ContactService.runActionSequence', contact_id, action_set_id) end def contact_link_contact(remoteApp, remoteId, localId) response = get('ContactService.linkContact', remoteApp, remoteId, localId) end def contact_locate_contact_link(locate_map_id) response = get('ContactService.locateContactLink', locate_map_id) end def contact_mark_link_updated(locate_map_id) response = get('ContactService.markLinkUpdated', locate_map_id) end # Creates a new recurring order for a contact. # # @param [Integer] contact_id # @param [Boolean] allow_duplicate # @param [Integer] cprogram_id # @param [Integer] merchant_account_id # @param [Integer] credit_card_id # @param [Integer] affiliate_id def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id, credit_card_id, affiliate_id, days_till_charge) response = get('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id, merchant_account_id, credit_card_id, affiliate_id, days_till_charge) end # Executes an action sequence for a given contact, passing in runtime params # for running affiliate signup actions, etc # # @param [Integer] contact_id # @param [Integer] action_set_id # @param [Hash] data def contact_run_action_set_with_params(contact_id, action_set_id, data) response = get('ContactService.runActionSequence', contact_id, action_set_id, data) end end end end
nateleavitt/infusionsoft
ba81581fb49daff070e28cfba1b9e86e7390e564
Add email optin to the add_dup method, since it's in both add and update seperately
diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb index aaa05f0..509816a 100644 --- a/lib/infusionsoft/client/contact.rb +++ b/lib/infusionsoft/client/contact.rb @@ -1,187 +1,189 @@ module Infusionsoft class Client # Contact service is used to manage contacts. You can add, update and find contacts in # addition to managing follow up sequences, tags and action sets. module Contact # Creates a new contact record from the data passed in the associative array. # # @param [Hash] data contains the mappable contact fields and it's data # @return [Integer] the id of the newly added contact # @example # { :Email => 'test@test.com', :FirstName => 'first_name', :LastName => 'last_name' } def contact_add(data) contact_id = get('ContactService.add', data) if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end return contact_id end # Adds or updates a contact record based on matching data # # @param [Array<Hash>] data the contact data you want added # @param [String] check_type available options are 'Email', 'EmailAndName', # 'EmailAndNameAndCompany' # @return [Integer] id of the contact added or updated def contact_add_with_dup_check(data, check_type) response = get('ContactService.addWithDupCheck', data, check_type) + if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end + return response end # Updates a contact in the database. # # @param [Integer] contact_id # @param [Hash] data contains the mappable contact fields and it's data # @return [Integer] the id of the contact updated # @example # { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' } def contact_update(contact_id, data) bool = get('ContactService.update', contact_id, data) if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end return bool end # Loads a contact from the database # # @param [Integer] id # @param [Array] selected_fields the list of fields you want back # @return [Array] the fields returned back with it's data # @example this is what you would get back # { "FirstName" => "John", "LastName" => "Doe" } def contact_load(id, selected_fields) response = get('ContactService.load', id, selected_fields) end # Finds all contacts with the supplied email address in any of the three contact record email # addresses. # # @param [String] email # @param [Array] selected_fields the list of fields you want with it's data # @return [Array<Hash>] the list of contacts with it's fields and data def contact_find_by_email(email, selected_fields) response = get('ContactService.findByEmail', email, selected_fields) end # Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences). # # @param [Integer] contact_id # @param [Integer] campaign_id # @return [Boolean] returns true/false if the contact was added to the follow-up sequence # successfully def contact_add_to_campaign(contact_id, campaign_id) response = get('ContactService.addToCampaign', contact_id, campaign_id) end # Returns the Id number of the next follow-up sequence step for the given contact. # # @param [Integer] contact_id # @param [Integer] campaign_id # @return [Integer] id number of the next unfishished step in the given follow up sequence # for the given contact def contact_get_next_campaign_step(contact_id, campaign_id) response = get('ContactService.getNextCampaignStep', contact_id, campaign_id) end # Pauses a follow-up sequence for the given contact record # # @param [Integer] contact_id # @param [Integer] campaign_id # @return [Boolean] returns true/false if the sequence was paused def contact_pause_campaign(contact_id, campaign_id) response = get('ContactService.pauseCampaign', contact_id, campaign_id) end # Removes a follow-up sequence from a contact record # # @param [Integer] contact_id # @param [Integer] campaign_id # @return [Boolean] returns true/false if removed def contact_remove_from_campaign(contact_id, campaign_id) response = get('ContactService.removeFromCampaign', contact_id, campaign_id) end # Resumes a follow-up sequence that has been stopped/paused for a given contact. # # @param [Integer] contact_id # @param [Ingeger] campaign_id # @return [Boolean] returns true/false if sequence was resumed def contact_resume_campaign(contact_id, campaign_id) response = get('ConactService.resumeCampaignForContact', contact_id, campaign_id) end # Immediately performs the given follow-up sequence step_id for the given contacts. # # @param [Array<Integer>] list_of_contacts # @param [Integer] ) step_id # @return [Boolean] returns true/false if the step was rescheduled def contact_reschedule_campaign_step(list_of_contacts, step_id) response = get('ContactService.reschedulteCampaignStep', list_of_contacts, step_id) end # Removes a tag from a contact (groups were the original name of tags). # # @param [Integer] contact_id # @param [Integer] group_id # @return [Boolean] returns true/false if tag was removed successfully def contact_remove_from_group(contact_id, group_id) response = get('ContactService.removeFromGroup', contact_id, group_id) end # Adds a tag to a contact # # @param [Integer] contact_id # @param [Integer] group_id # @return [Boolean] returns true/false if the tag was added successfully def contact_add_to_group(contact_id, group_id) response = get('ContactService.addToGroup', contact_id, group_id) end # Runs an action set on a given contact record # # @param [Integer] contact_id # @param [Integer] action_set_id # @return [Array<Hash>] A list of details on each action run # @example here is a list of what you get back # [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' => # nil }] def contact_run_action_set(contact_id, action_set_id) response = get('ContactService.runActionSequence', contact_id, action_set_id) end def contact_link_contact(remoteApp, remoteId, localId) response = get('ContactService.linkContact', remoteApp, remoteId, localId) end def contact_locate_contact_link(locate_map_id) response = get('ContactService.locateContactLink', locate_map_id) end def contact_mark_link_updated(locate_map_id) response = get('ContactService.markLinkUpdated', locate_map_id) end # Creates a new recurring order for a contact. # # @param [Integer] contact_id # @param [Boolean] allow_duplicate # @param [Integer] cprogram_id # @param [Integer] merchant_account_id # @param [Integer] credit_card_id # @param [Integer] affiliate_id def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id, credit_card_id, affiliate_id, days_till_charge) response = get('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id, merchant_account_id, credit_card_id, affiliate_id, days_till_charge) end # Executes an action sequence for a given contact, passing in runtime params # for running affiliate signup actions, etc # # @param [Integer] contact_id # @param [Integer] action_set_id # @param [Hash] data def contact_run_action_set_with_params(contact_id, action_set_id, data) response = get('ContactService.runActionSequence', contact_id, action_set_id, data) end end end end
nateleavitt/infusionsoft
70f432522ce907ffd3e1ad915db645e82bc45bf1
v1.1.7b
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb index 057e397..98153aa 100644 --- a/lib/infusionsoft/version.rb +++ b/lib/infusionsoft/version.rb @@ -1,4 +1,4 @@ module Infusionsoft # The version of the gem - VERSION = '1.1.7a'.freeze unless defined?(::Infusionsoft::VERSION) + VERSION = '1.1.7b'.freeze unless defined?(::Infusionsoft::VERSION) end
nateleavitt/infusionsoft
f87c5e4a1d7428b1439585c88a12affd005b1863
removing comma on last error type
diff --git a/lib/infusionsoft/exception_handler.rb b/lib/infusionsoft/exception_handler.rb index 617f6dd..0f1dc05 100644 --- a/lib/infusionsoft/exception_handler.rb +++ b/lib/infusionsoft/exception_handler.rb @@ -1,32 +1,32 @@ require 'infusionsoft/exceptions' class Infusionsoft::ExceptionHandler ERRORS = { 1 => Infusionsoft::InvalidConfigError, 2 => Infusionsoft::InvalidKeyError, 3 => Infusionsoft::UnexpectedError, 4 => Infusionsoft::DatabaseError, 5 => Infusionsoft::RecordNotFoundError, 6 => Infusionsoft::LoadingError, 7 => Infusionsoft::NoTableAccessError, 8 => Infusionsoft::NoFieldAccessError, 9 => Infusionsoft::NoTableFoundError, 10 => Infusionsoft::NoFieldFoundError, 11 => Infusionsoft::NoFieldsError, 12 => Infusionsoft::InvalidParameterError, 13 => Infusionsoft::FailedLoginAttemptError, 14 => Infusionsoft::NoAccessError, - 15 => Infusionsoft::FailedLoginAttemptPasswordExpiredError, + 15 => Infusionsoft::FailedLoginAttemptPasswordExpiredError } def initialize(xmlrpc_exception) error_class = ERRORS[xmlrpc_exception.faultCode] if error_class raise error_class, xmlrpc_exception.faultString else raise InfusionAPIError, xmlrpc_exception.faultString end end end
nateleavitt/infusionsoft
5dca91aa1924819b2c571c5d30ce4896bb8f58aa
adding space for result to match all logger outputs
diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb index 5625d7b..b75bf8b 100644 --- a/lib/infusionsoft/connection.rb +++ b/lib/infusionsoft/connection.rb @@ -1,42 +1,42 @@ require "xmlrpc/client" require 'infusionsoft/exception_handler' module Infusionsoft module Connection private def connection(service_call, *args) server = XMLRPC::Client.new3({ 'host' => api_url, 'path' => "/api/xmlrpc", 'port' => 443, 'use_ssl' => true }) begin api_logger.info "CALL: #{service_call} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}" result = server.call("#{service_call}", api_key, *args) if result.nil?; ok_to_retry('nil response') end rescue Timeout::Error => timeout # Retry up to 5 times on a Timeout before raising it ok_to_retry(timeout) ? retry : raise rescue XMLRPC::FaultException => xmlrpc_error # Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code Infusionsoft::ExceptionHandler.new(xmlrpc_error) end # Purposefully not catching other exceptions so that they can be handled up the stack - api_logger.info "RESULT:#{result.inspect}" + api_logger.info "RESULT: #{result.inspect}" return result end def ok_to_retry(e) @retry_count += 1 if @retry_count <= 5 api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}" true else false end end end end
nateleavitt/infusionsoft
7b2c141ee9efad311f9343f50275e74799ecd568
v1.1.7a
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2ac39bf --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.gem +log/*.log +tmp/**/* +.DS_Store +rdoc/ diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..c7febe1 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013 Nathan Leavitt + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..704129c --- /dev/null +++ b/README.md @@ -0,0 +1,113 @@ +# The Infusionsoft Ruby Gem +A Ruby wrapper for the Infusionsoft API + +**update notes** + +* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration). + +## <a name="installation">Installation</a> + gem install infusionsoft + +## <a name="documentation">Documentation</a> +[http://rubydoc.info/gems/infusionsoft/frames](http://rubydoc.info/gems/infusionsoft/frames) + +## <a name="setup">Setup & Configuration</a> +1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails 3** - add `'infusionsoft'` to your `Gemfile` +2. Then create an initializer in `config\initializers` called infusionsoft.rb and the following + +<b></b> + + # Added to your config\initializers file + Infusionsoft.configure do |config| + config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com + config.api_key = 'YOUR_INFUSIONSOFT_API_KEY' + config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file + end + +## <a name="examples">Usage Examples</a> + + # Get a users first and last name using the DataService + Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName]) + + # Update a contact with specific field values + Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => 'test@test.com' }) + + # Add a new Contact + Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => 'test@test.com'}) + + # Create a blank Invoice + invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id) + + # Then add item to invoice + Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes) + + # Then charge the invoice + Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions) + + +## <a name="contributing">Contributing</a> +In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project. + +Here are some ways *you* can contribute: + +* by using alpha, beta, and prerelease versions +* by reporting bugs +* by suggesting new features +* by writing or editing documentation +* by writing specifications +* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace) +* by refactoring code +* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues) +* by reviewing patches + +## <a name="issues">Submitting an Issue</a> +We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and +features. Before submitting a bug report or feature request, check to make sure it hasn't already +been submitted. You can indicate support for an existing issuse by voting it up. When submitting a +bug report, please include a [Gist](https://gist.github.com/) that includes a stack trace and any +details that may be necessary to reproduce the bug, including your gem version, Ruby version, and +operating system. Ideally, a bug report should include a pull request with failing specs. + +## <a name="pulls">Submitting a Pull Request</a> +1. Fork the project. +2. Create a topic branch. +3. Implement your feature or bug fix. +4. Add documentation for your feature or bug fix. +5. Run <tt>bundle exec rake doc:yard</tt>. If your changes are not 100% documented, go back to step 4. +6. Add specs for your feature or bug fix. +7. Run <tt>bundle exec rake spec</tt>. If your changes are not 100% covered, go back to step 6. +8. Commit and push your changes. +9. Submit a pull request. Please do not include changes to the gemspec, version, or history file. (If you want to create your own version for some reason, please do so in a separate commit.) + +## <a name="rubies">Supported Rubies</a> +This library aims to support the following Ruby implementations: + +* Ruby = 1.8.7 +* Ruby >= 1.9 +* [JRuby](http://www.jruby.org/) +* [Rubinius](http://rubini.us/) +* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/) + +If something doesn't work on one of these interpreters, it should be considered +a bug. + +This library may inadvertently work (or seem to work) on other Ruby +implementations, however support will only be provided for the versions listed +above. + +If you would like this library to support another Ruby version, you may +volunteer to be a maintainer. Being a maintainer entails making sure all tests +run and pass on that implementation. When something breaks on your +implementation, you will be personally responsible for providing patches in a +timely fashion. If critical issues for a particular implementation exist at the +time of a major release, support for that Ruby version may be dropped. + +## <a name="todos">Todos</a> +* Need to fully implement testing +* Need to add a history log for additional contributers + +## <a name="copyright">Copyright</a> +Copyright (c) 2013 Nathan Leavitt + +See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details. + diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..639ef53 --- /dev/null +++ b/Rakefile @@ -0,0 +1,3 @@ +require 'rake/testtask' + +Rake::TestTask.new diff --git a/infusionsoft.gemspec b/infusionsoft.gemspec new file mode 100644 index 0000000..a67e298 --- /dev/null +++ b/infusionsoft.gemspec @@ -0,0 +1,19 @@ +# encoding: utf-8 +require File.expand_path('../lib/infusionsoft/version', __FILE__) + +Gem::Specification.new do |gem| + gem.name = 'infusionsoft' + gem.summary = %q{Ruby wrapper for the Infusionsoft API} + gem.description = 'A Ruby wrapper written for the Infusionsoft API' + gem.authors = ["Nathan Leavitt"] + gem.email = ['nate@infusedsystems.com'] + gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)} + gem.files = `git ls-files`.split("\n") + gem.homepage = 'https://github.com/nateleavitt/infusionsoft' + gem.require_paths = ['lib'] + gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') + gem.add_development_dependency 'rake' + + gem.version = Infusionsoft::VERSION.dup +end + diff --git a/lib/infusionsoft.rb b/lib/infusionsoft.rb new file mode 100644 index 0000000..b507b13 --- /dev/null +++ b/lib/infusionsoft.rb @@ -0,0 +1,27 @@ +require 'infusionsoft/api' +require 'infusionsoft/client' +require 'infusionsoft/configuration' +require 'infusionsoft/api_logger' + +module Infusionsoft + extend Configuration + class << self + # Alias for Infusionsoft::Client.new + # + # @return [Infusionsoft::Client] + def new(options={}) + Infusionsoft::Client.new(options) + end + + # Delegate to ApiInfusionsoft::Client + def method_missing(method, *args, &block) + return super unless new.respond_to?(method) + new.send(method, *args, &block) + end + + def respond_to?(method, include_private = false) + new.respond_to?(method, include_private) || super(method, include_private) + end + end +end + diff --git a/lib/infusionsoft/api.rb b/lib/infusionsoft/api.rb new file mode 100644 index 0000000..3abe1fe --- /dev/null +++ b/lib/infusionsoft/api.rb @@ -0,0 +1,24 @@ +require 'infusionsoft/configuration' +require 'infusionsoft/connection' +require 'infusionsoft/request' + +module Infusionsoft + + class Api + include Connection + include Request + + attr_accessor :retry_count + attr_accessor *Configuration::VALID_OPTION_KEYS + + def initialize(options={}) + @retry_count = 0 + options = Infusionsoft.options.merge(options) + Configuration::VALID_OPTION_KEYS.each do |key| + send("#{key}=", options[key]) + end + end + + end + +end diff --git a/lib/infusionsoft/api_logger.rb b/lib/infusionsoft/api_logger.rb new file mode 100644 index 0000000..775bcb9 --- /dev/null +++ b/lib/infusionsoft/api_logger.rb @@ -0,0 +1,14 @@ +module Infusionsoft + class APILogger + + def info(msg); $stdout.puts msg end + + def warn(msg); $stdout.puts msg end + + def error(msg); $stdout.puts msg end + + def debug(msg); $stdout.puts msg end + + def fatal(msg); $stdout.puts msg end + end +end diff --git a/lib/infusionsoft/client.rb b/lib/infusionsoft/client.rb new file mode 100644 index 0000000..153e9aa --- /dev/null +++ b/lib/infusionsoft/client.rb @@ -0,0 +1,29 @@ +module Infusionsoft + # Wrapper for the Infusionsoft API + # + # @note all services have been separated into different modules + class Client < Api + # Require client method modules after initializing the Client class in + # order to avoid a superclass mismatch error, allowing those modules to be + # Client-namespaced. + require 'infusionsoft/client/contact' + require 'infusionsoft/client/email' + require 'infusionsoft/client/invoice' + require 'infusionsoft/client/data' + require 'infusionsoft/client/affiliate' + require 'infusionsoft/client/file' + require 'infusionsoft/client/ticket' # Deprecated by Infusionsoft + require 'infusionsoft/client/search' + require 'infusionsoft/client/credit_card' + + include Infusionsoft::Client::Contact + include Infusionsoft::Client::Email + include Infusionsoft::Client::Invoice + include Infusionsoft::Client::Data + include Infusionsoft::Client::Affiliate + include Infusionsoft::Client::File + include Infusionsoft::Client::Ticket # Deprecated by Infusionsoft + include Infusionsoft::Client::Search + include Infusionsoft::Client::CreditCard + end +end diff --git a/lib/infusionsoft/client/affiliate.rb b/lib/infusionsoft/client/affiliate.rb new file mode 100644 index 0000000..a3b8f47 --- /dev/null +++ b/lib/infusionsoft/client/affiliate.rb @@ -0,0 +1,62 @@ +module Infusionsoft + class Client + # The Affiliate service is used to pull commission data and activities for affiliates. + # With this service, you have access to Clawbacks, Commissions, Payouts, Running Totals, + # and the Activity Summary. The methods in the Affiliate service mirror the reports + # produced inside Infusionsoft. + # + # @note To manage affiliate information (ie Name, Phone, etc.) you will need to use the Data service. + module Affiliate + # Used when you need to retrieve all clawed back commissions for a particular affiliate. + # + # @param [Integer] affiliate_id + # @params [Date] start_date + # @end_date [Date] end_date + # @return [Array] all claw backs for the given affiliate that have occurred within the date + # range specified + def affiliate_clawbacks(affiliate_id, start_date, end_date) + response = get('APIAffiliateService.affClawbacks', affiliate_id, start_date, end_date) + end + + # Used to retrieve all commissions for a specific affiliate within a date range. + # + # @param [Integer] affiliate_id + # @param [Date] start_date + # @param [Date] end_date + # @return [Array] all sales commissions for the given affiliate earned within the date range + # specified + def affiliate_commissions(affiliate_id, start_date, end_date) + response = get('APIAffiliateService.affCommissions', affiliate_id, start_date, end_date) + end + + # Used to retrieve all payments for a specific affiliate within a date range. + # + # @param [Integer] affiliate_id + # @param [Date] start_date + # @param [Date] end_date + # @return [Array] a list of rows, each row is a single payout + def affiliate_payouts(affiliate_id, start_date, end_date) + response = get('APIAffiliateService.affPayouts', affiliate_id, start_date, end_date) + end + + # This method is used to retrieve all commissions for a specific affiliate within a date range. + # + # @param [Array] affiliate_list + # @return [Array] all sales commissions for the given affiliate earned within the date range + # specified + def affiliate_running_totals(affiliate_list) + response = get('APIAffiliateService.affRunningTotals', affiliate_list) + end + + # Used to retrieve a summary of statistics for a list of affiliates. + # + # @param [Array] affiliate_list + # @param [Date] start_date + # @param [Date] end_date + # @return [Array<Hash>] a summary of the affiliates information for a specified date range + def affiliate_summary(affiliate_list, start_date, end_date) + response = get('APIAffiliateService.affSummary', affiliate_list, start_date, end_date) + end + end + end +end diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb new file mode 100644 index 0000000..aaa05f0 --- /dev/null +++ b/lib/infusionsoft/client/contact.rb @@ -0,0 +1,187 @@ +module Infusionsoft + class Client + # Contact service is used to manage contacts. You can add, update and find contacts in + # addition to managing follow up sequences, tags and action sets. + module Contact + # Creates a new contact record from the data passed in the associative array. + # + # @param [Hash] data contains the mappable contact fields and it's data + # @return [Integer] the id of the newly added contact + # @example + # { :Email => 'test@test.com', :FirstName => 'first_name', :LastName => 'last_name' } + def contact_add(data) + contact_id = get('ContactService.add', data) + if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end + return contact_id + end + + # Adds or updates a contact record based on matching data + # + # @param [Array<Hash>] data the contact data you want added + # @param [String] check_type available options are 'Email', 'EmailAndName', + # 'EmailAndNameAndCompany' + # @return [Integer] id of the contact added or updated + def contact_add_with_dup_check(data, check_type) + response = get('ContactService.addWithDupCheck', data, check_type) + end + + # Updates a contact in the database. + # + # @param [Integer] contact_id + # @param [Hash] data contains the mappable contact fields and it's data + # @return [Integer] the id of the contact updated + # @example + # { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' } + def contact_update(contact_id, data) + bool = get('ContactService.update', contact_id, data) + if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end + return bool + end + + # Loads a contact from the database + # + # @param [Integer] id + # @param [Array] selected_fields the list of fields you want back + # @return [Array] the fields returned back with it's data + # @example this is what you would get back + # { "FirstName" => "John", "LastName" => "Doe" } + def contact_load(id, selected_fields) + response = get('ContactService.load', id, selected_fields) + end + + # Finds all contacts with the supplied email address in any of the three contact record email + # addresses. + # + # @param [String] email + # @param [Array] selected_fields the list of fields you want with it's data + # @return [Array<Hash>] the list of contacts with it's fields and data + def contact_find_by_email(email, selected_fields) + response = get('ContactService.findByEmail', email, selected_fields) + end + + # Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences). + # + # @param [Integer] contact_id + # @param [Integer] campaign_id + # @return [Boolean] returns true/false if the contact was added to the follow-up sequence + # successfully + def contact_add_to_campaign(contact_id, campaign_id) + response = get('ContactService.addToCampaign', contact_id, campaign_id) + end + + # Returns the Id number of the next follow-up sequence step for the given contact. + # + # @param [Integer] contact_id + # @param [Integer] campaign_id + # @return [Integer] id number of the next unfishished step in the given follow up sequence + # for the given contact + def contact_get_next_campaign_step(contact_id, campaign_id) + response = get('ContactService.getNextCampaignStep', contact_id, campaign_id) + end + + # Pauses a follow-up sequence for the given contact record + # + # @param [Integer] contact_id + # @param [Integer] campaign_id + # @return [Boolean] returns true/false if the sequence was paused + def contact_pause_campaign(contact_id, campaign_id) + response = get('ContactService.pauseCampaign', contact_id, campaign_id) + end + + # Removes a follow-up sequence from a contact record + # + # @param [Integer] contact_id + # @param [Integer] campaign_id + # @return [Boolean] returns true/false if removed + def contact_remove_from_campaign(contact_id, campaign_id) + response = get('ContactService.removeFromCampaign', contact_id, campaign_id) + end + + # Resumes a follow-up sequence that has been stopped/paused for a given contact. + # + # @param [Integer] contact_id + # @param [Ingeger] campaign_id + # @return [Boolean] returns true/false if sequence was resumed + def contact_resume_campaign(contact_id, campaign_id) + response = get('ConactService.resumeCampaignForContact', contact_id, campaign_id) + end + + # Immediately performs the given follow-up sequence step_id for the given contacts. + # + # @param [Array<Integer>] list_of_contacts + # @param [Integer] ) step_id + # @return [Boolean] returns true/false if the step was rescheduled + def contact_reschedule_campaign_step(list_of_contacts, step_id) + response = get('ContactService.reschedulteCampaignStep', list_of_contacts, step_id) + end + + # Removes a tag from a contact (groups were the original name of tags). + # + # @param [Integer] contact_id + # @param [Integer] group_id + # @return [Boolean] returns true/false if tag was removed successfully + def contact_remove_from_group(contact_id, group_id) + response = get('ContactService.removeFromGroup', contact_id, group_id) + end + + # Adds a tag to a contact + # + # @param [Integer] contact_id + # @param [Integer] group_id + # @return [Boolean] returns true/false if the tag was added successfully + def contact_add_to_group(contact_id, group_id) + response = get('ContactService.addToGroup', contact_id, group_id) + end + + # Runs an action set on a given contact record + # + # @param [Integer] contact_id + # @param [Integer] action_set_id + # @return [Array<Hash>] A list of details on each action run + # @example here is a list of what you get back + # [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' => + # nil }] + def contact_run_action_set(contact_id, action_set_id) + response = get('ContactService.runActionSequence', contact_id, action_set_id) + end + + def contact_link_contact(remoteApp, remoteId, localId) + response = get('ContactService.linkContact', remoteApp, remoteId, localId) + end + + + def contact_locate_contact_link(locate_map_id) + response = get('ContactService.locateContactLink', locate_map_id) + end + + def contact_mark_link_updated(locate_map_id) + response = get('ContactService.markLinkUpdated', locate_map_id) + end + + # Creates a new recurring order for a contact. + # + # @param [Integer] contact_id + # @param [Boolean] allow_duplicate + # @param [Integer] cprogram_id + # @param [Integer] merchant_account_id + # @param [Integer] credit_card_id + # @param [Integer] affiliate_id + def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id, + credit_card_id, affiliate_id, days_till_charge) + response = get('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id, + merchant_account_id, credit_card_id, affiliate_id, days_till_charge) + end + + # Executes an action sequence for a given contact, passing in runtime params + # for running affiliate signup actions, etc + # + # @param [Integer] contact_id + # @param [Integer] action_set_id + # @param [Hash] data + def contact_run_action_set_with_params(contact_id, action_set_id, data) + response = get('ContactService.runActionSequence', contact_id, action_set_id, data) + end + + end + end +end diff --git a/lib/infusionsoft/client/credit_card.rb b/lib/infusionsoft/client/credit_card.rb new file mode 100644 index 0000000..502c43d --- /dev/null +++ b/lib/infusionsoft/client/credit_card.rb @@ -0,0 +1,24 @@ +module Infusionsoft + class Client + # CreditCardSubmission service is used to obtain a token that is to be submitted + # through a form when adding a credit card. In accordance with PCI compliance, + # adding credit cards through the API will no longer be supported. + module CreditCard + + # This service will request a token that will be used when submitting + # a new credit card through a form + # + # @param [Integer] contact_id of the Infusionsoft contact + # @param [String] url that will be redirected to upon successfully adding card + # @param [String] url that will be redirected to when there is a failure upon adding card + def credit_card_request_token(contact_id, success_url, failure_url) + response = get('CreditCardSubmissionService.requestSubmissionToken', contact_id, success_url, failure_url) + end + + def credit_card_lookup_by_token(token) + response = get('CreditCardSubmissionService.requestCreditCardId', token) + end + + end + end +end diff --git a/lib/infusionsoft/client/data.rb b/lib/infusionsoft/client/data.rb new file mode 100644 index 0000000..e277302 --- /dev/null +++ b/lib/infusionsoft/client/data.rb @@ -0,0 +1,146 @@ +module Infusionsoft + class Client + # The Data service is used to manipulate most data in Infusionsoft. It permits you to + # work on any available tables and has a wide range of uses. + module Data + # Adds a record with the data provided. + # + # @param [String] table the name of the Infusiosoft database table + # @param [Hash] data the fields and it's data + # @return [Integer] returns the id of the record added + def data_add(table, data) + response = get('DataService.add', table, data) + end + + # This method will load a record from the database given the primary key. + # + # @param [String] table + # @param [Integer] id + # @param [Array] selected_fields + # @return [Hash] the field names and their data + # @example + # { "FirstName" => "John", "LastName" => "Doe" } + def data_load(table, id, selected_fields) + response = get('DataService.load', table, id, selected_fields) + end + + # Updates the specified record (indicated by ID) with the data provided. + # + # @param [String] table + # @param [Integer] id + # @param [Hash] data this is the fields and values you would like to update + # @return [Integer] id of the record updated + # @example + # { :FirstName => 'John', :Email => 'test@test.com' } + def data_update(table, id, data) + response = get('DataService.update', table, id, data) + end + + # Deletes the record (specified by id) in the given table from the database. + # + # @param [String] table + # @param [Integer] id + # @return [Boolean] returns true/false if the record was successfully deleted + def data_delete(table, id) + response = get('DataService.delete', table, id) + end + + # This will locate all records in a given table that match the criteria for a given field. + # + # @param [String] table + # @param [Integer] limit how many records you would like to return (max is 1000) + # @param [Integer] page the page of results (each page is max 1000 records) + # @param [String] field_name + # @param [String, Integer, Date] field_value + # @param [Array] selected_fields + # @return [Array<Hash>] returns the array of records with a hash of the fields and values + def data_find_by_field(table, limit, page, field_name, field_value, selected_fields) + response = get('DataService.findByField', table, limit, page, field_name, + field_value, selected_fields) + end + + # Queries records in a given table to find matches on certain fields. + # + # @param [String] table + # @param [Integer] limit + # @param [Integer] page + # @param [Hash] data the data you would like to query on. { :FirstName => 'first_name' } + # @param [Array] selected_fields the fields and values you want back + # @return [Array<Hash>] the fields and associated values + def data_query(table, limit, page, data, selected_fields) + response = get('DataService.query', table, limit, page, data, selected_fields) + end + + # Queries records in a given table to find matches on certain fields. + # + # @param [String] table + # @param [Integer] limit + # @param [Integer] page + # @param [Hash] data the data you would like to query on. { :FirstName => 'first_name' } + # @param [Array] selected_fields the fields and values you want back + # @param [String] field by which to order the output results + # @param [Boolean] true ascending, false descending + # @return [Array<Hash>] the fields and associated values + def data_query_order_by(table, limit, page, data, selected_fields, by, ascending) + response = get('DataService.query', table, limit, page, data, selected_fields, by, ascending) + end + + # Adds a custom field to Infusionsoft + # + # @param [String] field_type options include Person, Company, Affiliate, Task/Appt/Note, + # Order, Subscription, or Opportunity + # @param [String] name + # @param [String] data_type the type of field Text, Dropdown, TextArea + # @param [Integer] header_id see notes here + # http://help.infusionsoft.com/developers/services-methods/data/addCustomField + def data_add_custom_field(field_type, name, data_type, header_id) + response = get('DataService.addCustomField', field_type, name, data_type, header_id) + end + + # Authenticate an Infusionsoft username and password(md5 hash). If the credentials match + # it will return back a User ID, if the credentials do not match it will send back an + # error message + # + # @param [String] username + # @param [String] password + # @return [Integer] id of the authenticated user + def data_authenticate_user(username, password) + response = get('DataService.authenticateUser', username, password) + end + + # This method will return back the data currently configured in a user configured + # application setting. + # + # @param [String] module + # @param [String] setting + # @return [String] current values in given application setting + # @note to find the module and option names, view the HTML field name within the Infusionsoft + # settings. You will see something such as name="Contact_WebModule0optiontypes" . The portion + # before the underscore is the module name. "Contact" in this example. The portion after the + # 0 is the setting name, "optiontypes" in this example. + def data_get_app_setting(module_name, setting) + response = get('DataService.getAppSetting', module_name, setting) + end + + # Returns a temporary API key if given a valid Vendor key and user credentials. + # + # @param [String] vendor_key + # @param [String] username + # @param [String] password_hash an md5 hash of users password + # @return [String] temporary API key + def data_get_temporary_key(vendor_key, username, password_hash) + response = get('DataService.getTemporaryKey', username, password_hash) + end + + # Updates a custom field. Every field can have it’s display name and group id changed, + # but only certain data types will allow you to change values(dropdown, listbox, radio, etc). + # + # @param [Integer] field_id + # @param [Hash] field_values + # @return [Boolean] returns true/false if it was updated + def data_update_custom_field(field_id, field_values) + response = get('DataService.updateCustomField', field_id, field_values) + end + end + end +end diff --git a/lib/infusionsoft/client/email.rb b/lib/infusionsoft/client/email.rb new file mode 100644 index 0000000..15f9102 --- /dev/null +++ b/lib/infusionsoft/client/email.rb @@ -0,0 +1,152 @@ +module Infusionsoft + class Client + # The Email service allows you to email your contacts as well as attaching emails sent + # elsewhere (this lets you send email from multiple services and still see all communications + # inside of Infusionsoft). + module Email + + # Create a new email template that can be used for future emails + # + # @param [String] title + # @param [String] categories a comma separated list of the categories + # you want this template in Infusionsoft + # @param [String] from the from address format use is 'FirstName LastName <email@domain.com>' + # @param [String] to the email address this template is sent to + # @param [String] cc a comma separated list of cc email addresses + # @param [String] bcc a comma separated list of bcc email addresses + # @param [String] subject + # @param [String] text_body + # @param [String] html_body + # @param [String] content_type can be Text, HTML, Multipart + # @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard + def email_add(title, categories, from, to, cc, bcc, subject, text_body, html_body, + content_type, merge_context) + response = get('APIEmailService.addEmailTemplate', title, categories, from, to, + cc, bcc, subject, text_body, html_body, content_type, merge_context) + end + + # This will create an item in the email history for a contact. This does not actually + # send the email, it only places an item into the email history. Using the API to + # instruct Infusionsoft to send an email will handle this automatically. + # + # @param [Integer] contact_id + # @param [String] from_name the name portion of the from address, not the email + # @param [String] from_address + # @param [String] to_address + # @param [String] cc_addresses + # @param [String] bcc_addresses + # @param [String] content_type can be Text, HTML, Multipart + # @param [String] subject + # @param [String] html_body + # @param [String] text_body + # @param [String] header the header info for this email (will be listed in history) + # @param [Date] receive_date + # @param [Date] sent_date + def email_attach(contact_id, from_name, from_address, to_address, cc_addresses, + bcc_addresses, content_type, subject, html_body, txt_body, + header, receive_date, send_date) + response = get('APIEmailService.attachEmail', contact_id, from_name, from_address, + to_address, cc_addresses, bcc_addresses, content_type, subject, + html_body, txt_body, header, receive_date, send_date) + end + + # This retrieves all possible merge fields for the context provided. + # + # @param [String] merge_context could include Contact, ServiceCall, Opportunity, or CreditCard + # @return [Array] returns the merge fields for the given context + def email_get_available_merge_fields(merge_context) + response = get('APIEmailService.getAvailableMergeFields', merge_context) + end + + # Retrieves the details for a particular email template. + # + # @param [Integer] id + # @return [Hash] all data for the email template + def email_get_template(id) + response = get('APIEmailService.getEmailTemplate', id) + end + + # Retrieves the status of the given email address. + # + # @param [String] email_address + # @return [Integer] 0 = opted out, 1 = single opt-in, 2 = double opt-in + def email_get_opt_status(email_address) + response = get('APIEmailService.getOptStatus', email_address) + end + + # This method opts-in an email address. This method only works the first time + # an email address opts-in. + # + # @param [String] email_address + # @param [String] reason + # This is how you can note why/how this email was opted-in. If a blank + # reason is passed the system will default a reason of "API Opt In" + # @return [Boolean] + def email_optin(email_address, reason) + response = get('APIEmailService.optIn', email_address, reason) + end + + # Opts-out an email address. Note that once an address is opt-out, + # the API cannot opt it back in. + # + # @param [String] email_address + # @param [String] reason + # @return [Boolean] + def email_optout(email_address, reason) + response = get('APIEmailService.optOut', email_address, reason) + end + + # This will send an email to a list of contacts, as well as record the email + # in the contacts' email history. + # + # @param [Array<Integer>] contact_list list of contact ids you want to send this email to + # @param [String] from_address + # @param [String] to_address + # @param [String] cc_address + # @param [String] bcc_address + # @param [String] content_type this must be one of the following Text, HTML, or Multipart + # @param [String] subject + # @param [String] html_body + # @param [String] text_body + # @return [Boolean] returns true/false if the email has been sent + def email_send(contact_list, from_address, to_address, cc_addresses, + bcc_addresses, content_type, subject, html_body, text_body) + response = get('APIEmailService.sendEmail', contact_list, from_address, + to_address, cc_addresses, bcc_addresses, content_type, subject, + html_body, text_body) + end + + # This will send an email to a list of contacts, as well as record the email in the + # contacts' email history. + # + # @param [Array<Integer>] contact_list is an array of Contact id numbers you would like to send this email to + # @param [String] The Id of the template to send + # @return returns true if the email has been sent, an error will be sent back otherwise. + def email_send_template(contact_list, template_id) + response = get('APIEmailService.sendTemplate', contact_list, template_id) + end + + + # This method is used to update an already existing email template. + # + # @param [Integer] id + # @param [String] title + # @param [String] category + # @param [String] from + # @param [String] to + # @param [String] cc + # @param [String] bcc + # @param [String subject + # @param [String] text_body + # @param [String] html_body + # @param [String] content_type can be Text, HTML, Multipart + # @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard + # @return [Boolean] returns true/false if teamplate was updated successfully + def email_update_template(id, title, category, from, to, cc, bcc, subject, + text_body, html_body, content_type, merge_context) + response = get('APIEmailService.updateEmailTemplate', id, title, category, from, + to, cc, bcc, subject, text_body, html_body, content_type, merge_context) + end + end + end +end diff --git a/lib/infusionsoft/client/file.rb b/lib/infusionsoft/client/file.rb new file mode 100644 index 0000000..9d83632 --- /dev/null +++ b/lib/infusionsoft/client/file.rb @@ -0,0 +1,26 @@ +module Infusionsoft + class Client + module File + def file_upload(contact_id, file_name, encoded_file_base64) + response = get('FileService.uploadFile', contact_id, file_name, encoded_file_base64) + end + + # returns the Base64 encoded file contents + def file_get(id) + response = get('FileService.getFile', id) + end + + def file_url(id) + response = get('FileService.getDownloadUrl', id) + end + + def file_rename(id, new_name) + response = get('FileService.renameFile', id, new_name) + end + + def file_replace(id, encoded_file_base64) + response = get('FileService.replaceFile', id, encoded_file_base64) + end + end + end +end diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb new file mode 100644 index 0000000..1b5aebf --- /dev/null +++ b/lib/infusionsoft/client/invoice.rb @@ -0,0 +1,254 @@ +module Infusionsoft + class Client + # The Invoice service allows you to manage eCommerce transactions. + module Invoice + # Creates a blank order with no items. + # + # @param [Integer] contact_id + # @param [String] description the name this order will display + # @param [Date] order_date + # @param [Integer] lead_affiliate_id 0 should be used if none + # @param [Integer] sale_affiliate_id 0 should be used if none + # @return [Integer] returns the invoice id + def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id, + sale_affiliate_id) + response = get('InvoiceService.createBlankOrder', contact_id, description, order_date, + lead_affiliate_id, sale_affiliate_id) + end + + # Adds a line item to an order. This used to add a Product to an order as well as + # any other sort of charge/discount. + # + # @param [Integer] invoice_id + # @param [Integer] product_id + # @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4, + # UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7 + # @param [Float] price + # @param [Integer] quantity + # @param [String] description a full description of the line item + # @param [String] notes + # @return [Boolean] returns true/false if it was added successfully or not + def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes) + response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price, + quantity, description, notes) + end + + # This will cause a credit card to be charged for the amount currently due on an invoice. + # + # @param [Integer] invoice_id + # @param [String] notes a note about the payment + # @param [Integer] credit_card_id + # @param [Integer] merchant_account_id + # @param [Boolean] bypass_commission + # @return [Hash] containing the following keys {'Successful => [Boolean], + # 'Code' => [String], 'RefNum' => [String], 'Message' => [String]} + def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id, + bypass_commissions) + response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id, + merchant_account_id, bypass_commissions) + end + + # Deletes the specified subscription from the database, as well as all invoices + # tied to the subscription. + # + # @param [Integer] cprogram_id the id of the subscription being deleted + # @return [Boolean] + def invoice_delete_subscription(cprogram_id) + response = get('InvoiceService.deleteSubscription', cprogram_id) + end + + # Creates a subscription for a contact. Subscriptions are billing automatically + # by infusionsoft within the next six hours. If you want to bill immediately you + # will need to utilize the create_invoice_for_recurring and then + # charge_invoice method to accomplish this. + # + # @param [Integer] contact_id + # @param [Boolean] allow_duplicate + # @param [Integer] cprogram_id the subscription id + # @param [Integer] merchant_account_id + # @param [Integer] credit_card_id + # @param [Integer] affiliate_id + # @param [Integer] days_till_charge number of days you want to wait till it's charged + def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id, + merchant_account_id, credit_card_id, affiliate_id, + days_till_charge) + response = get('InvoiceService.addRecurringOrder', contact_id, + allow_duplicate, cprogram_id, merchant_account_id, credit_card_id, + affiliate_id, days_till_charge) + end + + # This modifies the commissions being earned on a particular subscription. + # This does not affect previously generated invoices for this subscription. + # + # @param [Integer] recurring_order_id + # @param [Integer] affiliate_id + # @param [Float] amount + # @param [Integer] paryout_type how commissions will be earned (possible options are + # 4 - up front earning, 5 - upon customer payment) typically this is 5 + # @return [Boolean] + def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id, + amount, payout_type, description) + response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id, + affiliate_id, amount, payout_type, description) + end + + # Adds a payment to an invoice without actually processing a charge through a merchant. + # + # @param [Integer] invoice_id + # @param [Float] amount + # @param [Date] date + # @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc. + # @param [String] description an area useful for noting payment details such as check number + # @param [Boolean] bypass_commissions + # @return [Boolean] + def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions) + response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type, + description, bypass_commissions) + end + + # This will create an invoice for all charges due on a Subscription. If the + # subscription has three billing cycles that are due, it will create one + # invoice with all three items attached. + # + # @param [Integer] recurring_order_id + # @return [Integer] returns the id of the invoice that was created + def invoice_create_invoice_for_recurring(recurring_order_id) + response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id) + end + + # Adds a payment plan to an existing invoice. + # + # @param [Integer] invoice_id + # @param [Boolean] + # @param [Integer] credit_card_id + # @param [Integer] merchant_account_id + # @param [Integer] days_between_retry the number of days Infusionsoft should wait + # before re-attempting to charge a failed payment + # @param [Integer] max_retry the maximum number of charge attempts + # @param [Float] initial_payment_ammount the amount of the very first charge + # @param [Date] initial_payment_date + # @param [Date] plan_start_date + # @param [Integer] number_of_payments the number of payments in this payplan (does not include + # initial payment) + # @param [Integer] days_between_payments the number of days between each payment + # @return [Boolean] + def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id, + merchant_account_id, days_between_retry, max_retry, + initial_payment_amount, initial_payment_date, plan_start_date, + number_of_payments, days_between_payments) + response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge, + credit_card_id, merchant_account_id, days_between_retry, max_retry, + initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments, + days_between_payments) + end + + # Calculates the amount owed for a given invoice. + # + # @param [Integer] invoice_id + # @return [Float] + def invoice_calculate_amount_owed(invoice_id) + response = get('InvoiceService.calculateAmountOwed', invoice_id) + end + + # Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft. + # + # @return [Array] + def invoice_get_all_payment_otpions + response = get('InvoiceService.getAllPaymentOptions') + end + + # Retrieves all payments for a given invoice. + # + # @param [Integer] invoice_id + # @return [Array<Hash>] returns an array of payments + def invoice_get_payments(invoice_id) + response = get('Invoice.getPayments', invoice_id) + end + + # Locates an existing card in the system for a contact, using the last 4 digits. + # + # @param [Integer] contact_id + # @param [Integer] last_four + # @return [Integer] returns the id of the credit card + def invoice_locate_existing_card(contact_id, last_four) + response = get('InvoiceService.locateExistingCard', contact_id, last_four) + end + + # Calculates tax, and places it onto the given invoice. + # + # @param [Integer] invoice_id + # @return [Boolean] + def invoice_recalculate_tax(invoice_id) + response = get('InvoiceService.recalculateTax', invoice_id) + end + + # This will validate a credit card in the system. + # + # @param [Integer] credit_card_id if the card is already in the system + # @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' } + def invoice_validate_card(credit_card_id) + response = get('InvoiceService.validateCreditCard', credit_card_id) + end + + # This will validate a credit card by passing in values of the + # card directly (this card doesn't have to be added to the system). + # + # @param [Hash] data + # @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' } + def invoice_validate_card(data) + response = get('InvoiceService.validateCreditCard', data) + end + + # Retrieves the shipping options currently setup for the Infusionsoft shopping cart. + # + # @return [Array] + def invoice_get_all_shipping_options + response = get('Invoice.getAllShippingOptions') + end + + # Changes the next bill date on a subscription. + # + # @param [Integer] job_recurring_id this is the subscription id on the contact + # @param [Date] next_bill_date + # @return [Boolean] + def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date) + response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date) + end + + + # Adds a commission override to a one time order, using a combination of percentage + # and hard-coded amounts. + # + # @param [Integer] invoice_id + # @param [Integer] affiliate_id + # @param [Integer] product_id + # @param [Integer] percentage + # @param [Float] amount + # @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon + # customer payment + # @param [String] description a note about this commission + # @param [Date] date the commission was generated, not necessarily earned + # @return [Boolean] + def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage, + amount, payout_type, description, date) + response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id, + product_id, percentage, amount, payout_type, description, date) + end + + + # Deprecated - Adds a recurring order to the database. + def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty, + price, allow_tax, merchant_account_id, + credit_card_id, affiliate_id, days_till_charge) + response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate, + cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id, + affiliate_id, days_till_charge) + end + + # Deprecated - returns the invoice id from a one time order. + def invoice_get_invoice_id(order_id) + response = get('InvoiceService.getinvoice_id', order_id) + end + end + end +end diff --git a/lib/infusionsoft/client/search.rb b/lib/infusionsoft/client/search.rb new file mode 100644 index 0000000..7136de0 --- /dev/null +++ b/lib/infusionsoft/client/search.rb @@ -0,0 +1,66 @@ +module Infusionsoft + class Client + # The SearchService allows you to retrieve the results of saved searches and reports that + # have been saved within Infusionsoft. Saved searches/reports are tied to the User that + # created them. This service also allows you to utilize the quick search function found in + # the upper right hand corner of your Infusionsoft application. + + # @note In order to retrieve the id number for saved searches you will need to utilize + # the data_query method and query the table called SavedFilter based on the user_id + # you are looking for the saved search Id for. Also note that UserId field on the + # SavedFilter table can contain multiple userId’s separated by a comma, so if you are + # querying for a report created by userId 6, I recommend appending the wildcard to the + # end of the userId. Something like $query = array( ‘UserId’ => ’6%’ ); + module Search + # Gets all possible fields/columns available for return on a saved search/report. + # + # @param [Integer] saved_search_id + # @param [Integer] user_id the user id who the saved search is assigned to + # @return [Hash] + def search_get_all_report_columns(saved_search_id, user_id) + response = get('SearchService.getAllReportColumns', saved_search_id, user_id) + end + + # Runs a saved search/report and returns all possible fields. + # + # @param [Integer] saved_search_id + # @param [Integer] user_id the user id who the saved search is assigned to + # @param [Integer] page_number + # @return [Hash] + def search_get_saved_search_results(saved_search_id, user_id, page_number) + response = get('SearchService.getSavedSearchResultsAllFields', saved_search_id, + user_id, page_number) + end + + # This is used to find what possible quick searches the given user has access to. + # + # @param [Integer] user_id + # @return [Array] + def search_get_available_quick_searches(user_id) + response = get('SearchService.getAvailableQuickSearches', user_id) + end + + # This allows you to run a quick search via the API. The quick search is the + # search bar in the upper right hand corner of the Infusionsoft application + # + # @param [String] search_type the type of search (Person, Order, Opportunity, Company, Task, + # Subscription, or Affiliate) + # @param [Integer] user_id + # @param [String] search_data + # @param [Integer] page + # @param [Integer] limit max is 1000 + # @return [Array<Hash>] + def search_quick_search(search_type, user_id, search_data, page, limit) + response = get('SearchService.quickSearch', search_type, user_id, search_data, page, limit) + end + + # Retrieves the quick search type that the given users has set as their default. + # + # @param [Integer] user_id + # @return [String] the quick search type that the given user selected as their default + def search_get_default_search_type(user_id) + response = get('SearchService.getDefaultQuickSearch', user_id) + end + end + end +end diff --git a/lib/infusionsoft/client/ticket.rb b/lib/infusionsoft/client/ticket.rb new file mode 100644 index 0000000..89f3bf0 --- /dev/null +++ b/lib/infusionsoft/client/ticket.rb @@ -0,0 +1,18 @@ +module Infusionsoft + class Client + module Ticket + # add move notes to existing tickets + def ticket_add_move_notes(ticket_list, move_notes, + move_to_stage_id, notify_ids) + response = get('ServiceCallService.addMoveNotes', ticket_list, + move_notes, move_to_stage_id, notify_ids) + end + + # add move notes to existing tickets + def ticket_move_stage(ticket_id, ticket_stage, move_notes, notify_ids) + response = get('ServiceCallService.moveTicketStage', + ticket_id, ticket_stage, move_notes, notify_ids) + end + end + end +end diff --git a/lib/infusionsoft/client/version.rb b/lib/infusionsoft/client/version.rb new file mode 100644 index 0000000..23f485b --- /dev/null +++ b/lib/infusionsoft/client/version.rb @@ -0,0 +1,5 @@ +module Infusionsoft + # The version of the gem + VERSION = '1.0.0'.freeze unless defined?(::Infusionsoft::VERSION) +end + diff --git a/lib/infusionsoft/configuration.rb b/lib/infusionsoft/configuration.rb new file mode 100644 index 0000000..a53f96a --- /dev/null +++ b/lib/infusionsoft/configuration.rb @@ -0,0 +1,41 @@ +module Infusionsoft + + module Configuration + # The list of available options + VALID_OPTION_KEYS = [ + :api_url, + :api_key, + :api_logger + ].freeze + + # @private + attr_accessor *VALID_OPTION_KEYS + + # When this module is extended, set all configuration options to their default values + #def self.extended(base) + #base.reset + #end + + # Convenience method to allow configuration options to be set in a block + def configure + yield self + end + + # Create a hash of options and their values + def options + options = {} + VALID_OPTION_KEYS.each{|k| options[k] = send(k)} + options + end + + #def reset + #self.url = '' + #self.api_key = 'na' + #end + + def api_logger + @api_logger || Infusionsoft::APILogger.new + end + end + +end diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb new file mode 100644 index 0000000..5625d7b --- /dev/null +++ b/lib/infusionsoft/connection.rb @@ -0,0 +1,42 @@ +require "xmlrpc/client" +require 'infusionsoft/exception_handler' + +module Infusionsoft + module Connection + private + + def connection(service_call, *args) + server = XMLRPC::Client.new3({ + 'host' => api_url, + 'path' => "/api/xmlrpc", + 'port' => 443, + 'use_ssl' => true + }) + begin + api_logger.info "CALL: #{service_call} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}" + result = server.call("#{service_call}", api_key, *args) + if result.nil?; ok_to_retry('nil response') end + rescue Timeout::Error => timeout + # Retry up to 5 times on a Timeout before raising it + ok_to_retry(timeout) ? retry : raise + rescue XMLRPC::FaultException => xmlrpc_error + # Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code + Infusionsoft::ExceptionHandler.new(xmlrpc_error) + end # Purposefully not catching other exceptions so that they can be handled up the stack + + api_logger.info "RESULT:#{result.inspect}" + return result + end + + def ok_to_retry(e) + @retry_count += 1 + if @retry_count <= 5 + api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}" + true + else + false + end + end + + end +end diff --git a/lib/infusionsoft/exception_handler.rb b/lib/infusionsoft/exception_handler.rb new file mode 100644 index 0000000..617f6dd --- /dev/null +++ b/lib/infusionsoft/exception_handler.rb @@ -0,0 +1,32 @@ +require 'infusionsoft/exceptions' + +class Infusionsoft::ExceptionHandler + + ERRORS = { + 1 => Infusionsoft::InvalidConfigError, + 2 => Infusionsoft::InvalidKeyError, + 3 => Infusionsoft::UnexpectedError, + 4 => Infusionsoft::DatabaseError, + 5 => Infusionsoft::RecordNotFoundError, + 6 => Infusionsoft::LoadingError, + 7 => Infusionsoft::NoTableAccessError, + 8 => Infusionsoft::NoFieldAccessError, + 9 => Infusionsoft::NoTableFoundError, + 10 => Infusionsoft::NoFieldFoundError, + 11 => Infusionsoft::NoFieldsError, + 12 => Infusionsoft::InvalidParameterError, + 13 => Infusionsoft::FailedLoginAttemptError, + 14 => Infusionsoft::NoAccessError, + 15 => Infusionsoft::FailedLoginAttemptPasswordExpiredError, + } + + def initialize(xmlrpc_exception) + error_class = ERRORS[xmlrpc_exception.faultCode] + if error_class + raise error_class, xmlrpc_exception.faultString + else + raise InfusionAPIError, xmlrpc_exception.faultString + end + end + +end diff --git a/lib/infusionsoft/exceptions.rb b/lib/infusionsoft/exceptions.rb new file mode 100644 index 0000000..ba06f8d --- /dev/null +++ b/lib/infusionsoft/exceptions.rb @@ -0,0 +1,58 @@ +# Extend StandardError to keep track of Error being wrapped +# Pattern from Exceptional Ruby by Avdi Grimm (http://avdi.org/talks/exceptional-ruby-2011-02-04/) +class InfusionAPIError < StandardError + attr_reader :original + def initialize(msg, original=nil); + Infusionsoft.api_logger.error "ERROR: #{msg}" + super(msg); + @original = original; + end +end + +module Infusionsoft + # For now I'm inheriting from InfusionAPIError so that the code will remain backwards compatible...may be deprecated in the future + class InvalidConfigError < InfusionAPIError + end + + class InvalidKeyError < InfusionAPIError + end + + class UnexpectedError < InfusionAPIError + end + + class DatabaseError < InfusionAPIError + end + + class RecordNotFoundError < InfusionAPIError + end + + class LoadingError < InfusionAPIError + end + + class NoTableAccessError < InfusionAPIError + end + + class NoFieldAccessError < InfusionAPIError + end + + class NoTableFoundError < InfusionAPIError + end + + class NoFieldFoundError < InfusionAPIError + end + + class NoFieldsError < InfusionAPIError + end + + class InvalidParameterError < InfusionAPIError + end + + class FailedLoginAttemptError < InfusionAPIError + end + + class NoAccessError < InfusionAPIError + end + + class FailedLoginAttemptPasswordExpiredError < InfusionAPIError + end +end diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb new file mode 100644 index 0000000..661154d --- /dev/null +++ b/lib/infusionsoft/request.rb @@ -0,0 +1,33 @@ +module Infusionsoft + module Request + # Perform an GET request + def get(service_call, *args) + request(:get, service_call, *args) + end + + def post(path, params={}, options={}) + request(:post, path, params, options) + end + + # Perform an HTTP PUT request + def put(path, params={}, options={}) + request(:put, path, params, options) + end + + # Perform an HTTP DELETE request + def delete(path, params={}, options={}) + request(:delete, path, params, options) + end + + + private + + # Perform request + def request(method, service_call, *args) + case method.to_sym + when :get + response = connection(service_call, *args) + end + end + end +end diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb new file mode 100644 index 0000000..057e397 --- /dev/null +++ b/lib/infusionsoft/version.rb @@ -0,0 +1,4 @@ +module Infusionsoft + # The version of the gem + VERSION = '1.1.7a'.freeze unless defined?(::Infusionsoft::VERSION) +end diff --git a/test/api_infusion_test.rb b/test/api_infusion_test.rb new file mode 100644 index 0000000..30a7288 --- /dev/null +++ b/test/api_infusion_test.rb @@ -0,0 +1,8 @@ +require 'test/unit' + +class ApiInfusionTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_this_plugin + flunk # will implement later :( + end +end diff --git a/test/test_exceptions.rb b/test/test_exceptions.rb new file mode 100644 index 0000000..530e275 --- /dev/null +++ b/test/test_exceptions.rb @@ -0,0 +1,113 @@ +require 'test/unit' +require 'infusionsoft' + + +# override XMLRPC call method +class XMLRPC::Client + + def call(method, *args) + raise XMLRPC::FaultException.new(@@code, @@message) + end + + def self.set_fault_response(code, message) + @@code = code + @@message = message + end +end + +class TestLogger + def info(msg); end + def warn(msg); end + def error(msg); end + def debug(msg); end + def fatal(msg); end +end + + +class TestExceptions < Test::Unit::TestCase + + def setup + Infusionsoft.configure do |c| + c.api_logger = TestLogger.new() + end + end + + def test_should_raise_invalid_config + exception_test(Infusionsoft::InvalidConfigError, 1, 'The configuration for the application is invalid. Usually this is because there has not been a passphrase entered to generate an encrypted key.') + end + + def test_should_raise_invalid_key + exception_test(Infusionsoft::InvalidKeyError, 2, "The key passed up for authentication was not valid. It was either empty or didn't match.") + end + + def test_should_raise_unexpected_error + exception_test(Infusionsoft::UnexpectedError, 3, "An unexpected error has occurred. There was either an error in the data you passed up or there was an unknown error on") + end + + def test_should_raise_database_error + exception_test(Infusionsoft::DatabaseError, 4, "There was an error in the database access") + end + + def test_should_raise_record_not_found + exception_test(Infusionsoft::RecordNotFoundError, 5, "A requested record was not found in the database.") + end + + def test_should_raise_loading_error + exception_test(Infusionsoft::LoadingError, 6, "There was a problem loading a record from the database.") + end + + def test_should_raise_no_table_access + exception_test(Infusionsoft::NoTableAccessError, 7, "A table was accessed without the proper permission") + end + + def test_should_raise_no_field_access + exception_test(Infusionsoft::NoFieldAccessError, 8, "A field was accessed without the proper permission.") + end + + def test_should_raise_no_table_found + exception_test(Infusionsoft::NoTableFoundError, 9, "A table was accessed that doesn't exist in the Data Spec.") + end + + def test_should_raise_no_field_found + exception_test(Infusionsoft::NoFieldFoundError, 10, "A field was accessed that doesn't exist in the Data Spec.") + end + + def test_should_raise_no_fields_error + exception_test(Infusionsoft::NoFieldsError, 11, "An update or add operation was attempted with no valid fields to update or add.") + end + + def test_should_raise_invalid_parameter_error + exception_test(Infusionsoft::InvalidParameterError, 12, "Data sent into the call was invalid.") + end + + def test_should_raise_failed_login_attempt + exception_test(Infusionsoft::FailedLoginAttemptError, 13, "Someone attempted to authenticate a user and failed.") + end + + def test_should_raise_no_access_error + exception_test(Infusionsoft::NoAccessError, 14, "Someone attempted to access a plugin they are not paying for.") + end + + def test_should_raise_failed_login_attempt_password_expired + exception_test(Infusionsoft::FailedLoginAttemptPasswordExpiredError, 15, "Someone attempted to authenticate a user and the password is expired.") + end + + def test_should_raise_infusionapierror_when_fault_code_unknown + exception_test(InfusionAPIError, 42, "Some random error occurred") + end + + + private + def exception_test(exception, code, message) + XMLRPC::Client.set_fault_response(code, message) + caught = false + begin + Infusionsoft.data_query(:Contact, 1, 0, {}, [:BlahdyDah]) + rescue exception => e + caught = true + assert_equal message, e.message + end + assert_equal true, caught + end + +end
nateleavitt/infusionsoft
8c9340a7cde6d2309b8417e538cb36e82c3bbf43
Fixed default logger implementation to add new lines
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2ac39bf --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.gem +log/*.log +tmp/**/* +.DS_Store +rdoc/ diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..c7febe1 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013 Nathan Leavitt + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..704129c --- /dev/null +++ b/README.md @@ -0,0 +1,113 @@ +# The Infusionsoft Ruby Gem +A Ruby wrapper for the Infusionsoft API + +**update notes** + +* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration). + +## <a name="installation">Installation</a> + gem install infusionsoft + +## <a name="documentation">Documentation</a> +[http://rubydoc.info/gems/infusionsoft/frames](http://rubydoc.info/gems/infusionsoft/frames) + +## <a name="setup">Setup & Configuration</a> +1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails 3** - add `'infusionsoft'` to your `Gemfile` +2. Then create an initializer in `config\initializers` called infusionsoft.rb and the following + +<b></b> + + # Added to your config\initializers file + Infusionsoft.configure do |config| + config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com + config.api_key = 'YOUR_INFUSIONSOFT_API_KEY' + config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file + end + +## <a name="examples">Usage Examples</a> + + # Get a users first and last name using the DataService + Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName]) + + # Update a contact with specific field values + Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => 'test@test.com' }) + + # Add a new Contact + Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => 'test@test.com'}) + + # Create a blank Invoice + invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id) + + # Then add item to invoice + Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes) + + # Then charge the invoice + Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions) + + +## <a name="contributing">Contributing</a> +In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project. + +Here are some ways *you* can contribute: + +* by using alpha, beta, and prerelease versions +* by reporting bugs +* by suggesting new features +* by writing or editing documentation +* by writing specifications +* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace) +* by refactoring code +* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues) +* by reviewing patches + +## <a name="issues">Submitting an Issue</a> +We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and +features. Before submitting a bug report or feature request, check to make sure it hasn't already +been submitted. You can indicate support for an existing issuse by voting it up. When submitting a +bug report, please include a [Gist](https://gist.github.com/) that includes a stack trace and any +details that may be necessary to reproduce the bug, including your gem version, Ruby version, and +operating system. Ideally, a bug report should include a pull request with failing specs. + +## <a name="pulls">Submitting a Pull Request</a> +1. Fork the project. +2. Create a topic branch. +3. Implement your feature or bug fix. +4. Add documentation for your feature or bug fix. +5. Run <tt>bundle exec rake doc:yard</tt>. If your changes are not 100% documented, go back to step 4. +6. Add specs for your feature or bug fix. +7. Run <tt>bundle exec rake spec</tt>. If your changes are not 100% covered, go back to step 6. +8. Commit and push your changes. +9. Submit a pull request. Please do not include changes to the gemspec, version, or history file. (If you want to create your own version for some reason, please do so in a separate commit.) + +## <a name="rubies">Supported Rubies</a> +This library aims to support the following Ruby implementations: + +* Ruby = 1.8.7 +* Ruby >= 1.9 +* [JRuby](http://www.jruby.org/) +* [Rubinius](http://rubini.us/) +* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/) + +If something doesn't work on one of these interpreters, it should be considered +a bug. + +This library may inadvertently work (or seem to work) on other Ruby +implementations, however support will only be provided for the versions listed +above. + +If you would like this library to support another Ruby version, you may +volunteer to be a maintainer. Being a maintainer entails making sure all tests +run and pass on that implementation. When something breaks on your +implementation, you will be personally responsible for providing patches in a +timely fashion. If critical issues for a particular implementation exist at the +time of a major release, support for that Ruby version may be dropped. + +## <a name="todos">Todos</a> +* Need to fully implement testing +* Need to add a history log for additional contributers + +## <a name="copyright">Copyright</a> +Copyright (c) 2013 Nathan Leavitt + +See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details. + diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..639ef53 --- /dev/null +++ b/Rakefile @@ -0,0 +1,3 @@ +require 'rake/testtask' + +Rake::TestTask.new diff --git a/infusionsoft.gemspec b/infusionsoft.gemspec new file mode 100644 index 0000000..a67e298 --- /dev/null +++ b/infusionsoft.gemspec @@ -0,0 +1,19 @@ +# encoding: utf-8 +require File.expand_path('../lib/infusionsoft/version', __FILE__) + +Gem::Specification.new do |gem| + gem.name = 'infusionsoft' + gem.summary = %q{Ruby wrapper for the Infusionsoft API} + gem.description = 'A Ruby wrapper written for the Infusionsoft API' + gem.authors = ["Nathan Leavitt"] + gem.email = ['nate@infusedsystems.com'] + gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)} + gem.files = `git ls-files`.split("\n") + gem.homepage = 'https://github.com/nateleavitt/infusionsoft' + gem.require_paths = ['lib'] + gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') + gem.add_development_dependency 'rake' + + gem.version = Infusionsoft::VERSION.dup +end + diff --git a/lib/infusionsoft.rb b/lib/infusionsoft.rb new file mode 100644 index 0000000..b507b13 --- /dev/null +++ b/lib/infusionsoft.rb @@ -0,0 +1,27 @@ +require 'infusionsoft/api' +require 'infusionsoft/client' +require 'infusionsoft/configuration' +require 'infusionsoft/api_logger' + +module Infusionsoft + extend Configuration + class << self + # Alias for Infusionsoft::Client.new + # + # @return [Infusionsoft::Client] + def new(options={}) + Infusionsoft::Client.new(options) + end + + # Delegate to ApiInfusionsoft::Client + def method_missing(method, *args, &block) + return super unless new.respond_to?(method) + new.send(method, *args, &block) + end + + def respond_to?(method, include_private = false) + new.respond_to?(method, include_private) || super(method, include_private) + end + end +end + diff --git a/lib/infusionsoft/api.rb b/lib/infusionsoft/api.rb new file mode 100644 index 0000000..3abe1fe --- /dev/null +++ b/lib/infusionsoft/api.rb @@ -0,0 +1,24 @@ +require 'infusionsoft/configuration' +require 'infusionsoft/connection' +require 'infusionsoft/request' + +module Infusionsoft + + class Api + include Connection + include Request + + attr_accessor :retry_count + attr_accessor *Configuration::VALID_OPTION_KEYS + + def initialize(options={}) + @retry_count = 0 + options = Infusionsoft.options.merge(options) + Configuration::VALID_OPTION_KEYS.each do |key| + send("#{key}=", options[key]) + end + end + + end + +end diff --git a/lib/infusionsoft/api_logger.rb b/lib/infusionsoft/api_logger.rb new file mode 100644 index 0000000..775bcb9 --- /dev/null +++ b/lib/infusionsoft/api_logger.rb @@ -0,0 +1,14 @@ +module Infusionsoft + class APILogger + + def info(msg); $stdout.puts msg end + + def warn(msg); $stdout.puts msg end + + def error(msg); $stdout.puts msg end + + def debug(msg); $stdout.puts msg end + + def fatal(msg); $stdout.puts msg end + end +end diff --git a/lib/infusionsoft/client.rb b/lib/infusionsoft/client.rb new file mode 100644 index 0000000..153e9aa --- /dev/null +++ b/lib/infusionsoft/client.rb @@ -0,0 +1,29 @@ +module Infusionsoft + # Wrapper for the Infusionsoft API + # + # @note all services have been separated into different modules + class Client < Api + # Require client method modules after initializing the Client class in + # order to avoid a superclass mismatch error, allowing those modules to be + # Client-namespaced. + require 'infusionsoft/client/contact' + require 'infusionsoft/client/email' + require 'infusionsoft/client/invoice' + require 'infusionsoft/client/data' + require 'infusionsoft/client/affiliate' + require 'infusionsoft/client/file' + require 'infusionsoft/client/ticket' # Deprecated by Infusionsoft + require 'infusionsoft/client/search' + require 'infusionsoft/client/credit_card' + + include Infusionsoft::Client::Contact + include Infusionsoft::Client::Email + include Infusionsoft::Client::Invoice + include Infusionsoft::Client::Data + include Infusionsoft::Client::Affiliate + include Infusionsoft::Client::File + include Infusionsoft::Client::Ticket # Deprecated by Infusionsoft + include Infusionsoft::Client::Search + include Infusionsoft::Client::CreditCard + end +end diff --git a/lib/infusionsoft/client/affiliate.rb b/lib/infusionsoft/client/affiliate.rb new file mode 100644 index 0000000..a3b8f47 --- /dev/null +++ b/lib/infusionsoft/client/affiliate.rb @@ -0,0 +1,62 @@ +module Infusionsoft + class Client + # The Affiliate service is used to pull commission data and activities for affiliates. + # With this service, you have access to Clawbacks, Commissions, Payouts, Running Totals, + # and the Activity Summary. The methods in the Affiliate service mirror the reports + # produced inside Infusionsoft. + # + # @note To manage affiliate information (ie Name, Phone, etc.) you will need to use the Data service. + module Affiliate + # Used when you need to retrieve all clawed back commissions for a particular affiliate. + # + # @param [Integer] affiliate_id + # @params [Date] start_date + # @end_date [Date] end_date + # @return [Array] all claw backs for the given affiliate that have occurred within the date + # range specified + def affiliate_clawbacks(affiliate_id, start_date, end_date) + response = get('APIAffiliateService.affClawbacks', affiliate_id, start_date, end_date) + end + + # Used to retrieve all commissions for a specific affiliate within a date range. + # + # @param [Integer] affiliate_id + # @param [Date] start_date + # @param [Date] end_date + # @return [Array] all sales commissions for the given affiliate earned within the date range + # specified + def affiliate_commissions(affiliate_id, start_date, end_date) + response = get('APIAffiliateService.affCommissions', affiliate_id, start_date, end_date) + end + + # Used to retrieve all payments for a specific affiliate within a date range. + # + # @param [Integer] affiliate_id + # @param [Date] start_date + # @param [Date] end_date + # @return [Array] a list of rows, each row is a single payout + def affiliate_payouts(affiliate_id, start_date, end_date) + response = get('APIAffiliateService.affPayouts', affiliate_id, start_date, end_date) + end + + # This method is used to retrieve all commissions for a specific affiliate within a date range. + # + # @param [Array] affiliate_list + # @return [Array] all sales commissions for the given affiliate earned within the date range + # specified + def affiliate_running_totals(affiliate_list) + response = get('APIAffiliateService.affRunningTotals', affiliate_list) + end + + # Used to retrieve a summary of statistics for a list of affiliates. + # + # @param [Array] affiliate_list + # @param [Date] start_date + # @param [Date] end_date + # @return [Array<Hash>] a summary of the affiliates information for a specified date range + def affiliate_summary(affiliate_list, start_date, end_date) + response = get('APIAffiliateService.affSummary', affiliate_list, start_date, end_date) + end + end + end +end diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb new file mode 100644 index 0000000..aaa05f0 --- /dev/null +++ b/lib/infusionsoft/client/contact.rb @@ -0,0 +1,187 @@ +module Infusionsoft + class Client + # Contact service is used to manage contacts. You can add, update and find contacts in + # addition to managing follow up sequences, tags and action sets. + module Contact + # Creates a new contact record from the data passed in the associative array. + # + # @param [Hash] data contains the mappable contact fields and it's data + # @return [Integer] the id of the newly added contact + # @example + # { :Email => 'test@test.com', :FirstName => 'first_name', :LastName => 'last_name' } + def contact_add(data) + contact_id = get('ContactService.add', data) + if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end + return contact_id + end + + # Adds or updates a contact record based on matching data + # + # @param [Array<Hash>] data the contact data you want added + # @param [String] check_type available options are 'Email', 'EmailAndName', + # 'EmailAndNameAndCompany' + # @return [Integer] id of the contact added or updated + def contact_add_with_dup_check(data, check_type) + response = get('ContactService.addWithDupCheck', data, check_type) + end + + # Updates a contact in the database. + # + # @param [Integer] contact_id + # @param [Hash] data contains the mappable contact fields and it's data + # @return [Integer] the id of the contact updated + # @example + # { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' } + def contact_update(contact_id, data) + bool = get('ContactService.update', contact_id, data) + if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end + return bool + end + + # Loads a contact from the database + # + # @param [Integer] id + # @param [Array] selected_fields the list of fields you want back + # @return [Array] the fields returned back with it's data + # @example this is what you would get back + # { "FirstName" => "John", "LastName" => "Doe" } + def contact_load(id, selected_fields) + response = get('ContactService.load', id, selected_fields) + end + + # Finds all contacts with the supplied email address in any of the three contact record email + # addresses. + # + # @param [String] email + # @param [Array] selected_fields the list of fields you want with it's data + # @return [Array<Hash>] the list of contacts with it's fields and data + def contact_find_by_email(email, selected_fields) + response = get('ContactService.findByEmail', email, selected_fields) + end + + # Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences). + # + # @param [Integer] contact_id + # @param [Integer] campaign_id + # @return [Boolean] returns true/false if the contact was added to the follow-up sequence + # successfully + def contact_add_to_campaign(contact_id, campaign_id) + response = get('ContactService.addToCampaign', contact_id, campaign_id) + end + + # Returns the Id number of the next follow-up sequence step for the given contact. + # + # @param [Integer] contact_id + # @param [Integer] campaign_id + # @return [Integer] id number of the next unfishished step in the given follow up sequence + # for the given contact + def contact_get_next_campaign_step(contact_id, campaign_id) + response = get('ContactService.getNextCampaignStep', contact_id, campaign_id) + end + + # Pauses a follow-up sequence for the given contact record + # + # @param [Integer] contact_id + # @param [Integer] campaign_id + # @return [Boolean] returns true/false if the sequence was paused + def contact_pause_campaign(contact_id, campaign_id) + response = get('ContactService.pauseCampaign', contact_id, campaign_id) + end + + # Removes a follow-up sequence from a contact record + # + # @param [Integer] contact_id + # @param [Integer] campaign_id + # @return [Boolean] returns true/false if removed + def contact_remove_from_campaign(contact_id, campaign_id) + response = get('ContactService.removeFromCampaign', contact_id, campaign_id) + end + + # Resumes a follow-up sequence that has been stopped/paused for a given contact. + # + # @param [Integer] contact_id + # @param [Ingeger] campaign_id + # @return [Boolean] returns true/false if sequence was resumed + def contact_resume_campaign(contact_id, campaign_id) + response = get('ConactService.resumeCampaignForContact', contact_id, campaign_id) + end + + # Immediately performs the given follow-up sequence step_id for the given contacts. + # + # @param [Array<Integer>] list_of_contacts + # @param [Integer] ) step_id + # @return [Boolean] returns true/false if the step was rescheduled + def contact_reschedule_campaign_step(list_of_contacts, step_id) + response = get('ContactService.reschedulteCampaignStep', list_of_contacts, step_id) + end + + # Removes a tag from a contact (groups were the original name of tags). + # + # @param [Integer] contact_id + # @param [Integer] group_id + # @return [Boolean] returns true/false if tag was removed successfully + def contact_remove_from_group(contact_id, group_id) + response = get('ContactService.removeFromGroup', contact_id, group_id) + end + + # Adds a tag to a contact + # + # @param [Integer] contact_id + # @param [Integer] group_id + # @return [Boolean] returns true/false if the tag was added successfully + def contact_add_to_group(contact_id, group_id) + response = get('ContactService.addToGroup', contact_id, group_id) + end + + # Runs an action set on a given contact record + # + # @param [Integer] contact_id + # @param [Integer] action_set_id + # @return [Array<Hash>] A list of details on each action run + # @example here is a list of what you get back + # [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' => + # nil }] + def contact_run_action_set(contact_id, action_set_id) + response = get('ContactService.runActionSequence', contact_id, action_set_id) + end + + def contact_link_contact(remoteApp, remoteId, localId) + response = get('ContactService.linkContact', remoteApp, remoteId, localId) + end + + + def contact_locate_contact_link(locate_map_id) + response = get('ContactService.locateContactLink', locate_map_id) + end + + def contact_mark_link_updated(locate_map_id) + response = get('ContactService.markLinkUpdated', locate_map_id) + end + + # Creates a new recurring order for a contact. + # + # @param [Integer] contact_id + # @param [Boolean] allow_duplicate + # @param [Integer] cprogram_id + # @param [Integer] merchant_account_id + # @param [Integer] credit_card_id + # @param [Integer] affiliate_id + def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id, + credit_card_id, affiliate_id, days_till_charge) + response = get('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id, + merchant_account_id, credit_card_id, affiliate_id, days_till_charge) + end + + # Executes an action sequence for a given contact, passing in runtime params + # for running affiliate signup actions, etc + # + # @param [Integer] contact_id + # @param [Integer] action_set_id + # @param [Hash] data + def contact_run_action_set_with_params(contact_id, action_set_id, data) + response = get('ContactService.runActionSequence', contact_id, action_set_id, data) + end + + end + end +end diff --git a/lib/infusionsoft/client/credit_card.rb b/lib/infusionsoft/client/credit_card.rb new file mode 100644 index 0000000..502c43d --- /dev/null +++ b/lib/infusionsoft/client/credit_card.rb @@ -0,0 +1,24 @@ +module Infusionsoft + class Client + # CreditCardSubmission service is used to obtain a token that is to be submitted + # through a form when adding a credit card. In accordance with PCI compliance, + # adding credit cards through the API will no longer be supported. + module CreditCard + + # This service will request a token that will be used when submitting + # a new credit card through a form + # + # @param [Integer] contact_id of the Infusionsoft contact + # @param [String] url that will be redirected to upon successfully adding card + # @param [String] url that will be redirected to when there is a failure upon adding card + def credit_card_request_token(contact_id, success_url, failure_url) + response = get('CreditCardSubmissionService.requestSubmissionToken', contact_id, success_url, failure_url) + end + + def credit_card_lookup_by_token(token) + response = get('CreditCardSubmissionService.requestCreditCardId', token) + end + + end + end +end diff --git a/lib/infusionsoft/client/data.rb b/lib/infusionsoft/client/data.rb new file mode 100644 index 0000000..e277302 --- /dev/null +++ b/lib/infusionsoft/client/data.rb @@ -0,0 +1,146 @@ +module Infusionsoft + class Client + # The Data service is used to manipulate most data in Infusionsoft. It permits you to + # work on any available tables and has a wide range of uses. + module Data + # Adds a record with the data provided. + # + # @param [String] table the name of the Infusiosoft database table + # @param [Hash] data the fields and it's data + # @return [Integer] returns the id of the record added + def data_add(table, data) + response = get('DataService.add', table, data) + end + + # This method will load a record from the database given the primary key. + # + # @param [String] table + # @param [Integer] id + # @param [Array] selected_fields + # @return [Hash] the field names and their data + # @example + # { "FirstName" => "John", "LastName" => "Doe" } + def data_load(table, id, selected_fields) + response = get('DataService.load', table, id, selected_fields) + end + + # Updates the specified record (indicated by ID) with the data provided. + # + # @param [String] table + # @param [Integer] id + # @param [Hash] data this is the fields and values you would like to update + # @return [Integer] id of the record updated + # @example + # { :FirstName => 'John', :Email => 'test@test.com' } + def data_update(table, id, data) + response = get('DataService.update', table, id, data) + end + + # Deletes the record (specified by id) in the given table from the database. + # + # @param [String] table + # @param [Integer] id + # @return [Boolean] returns true/false if the record was successfully deleted + def data_delete(table, id) + response = get('DataService.delete', table, id) + end + + # This will locate all records in a given table that match the criteria for a given field. + # + # @param [String] table + # @param [Integer] limit how many records you would like to return (max is 1000) + # @param [Integer] page the page of results (each page is max 1000 records) + # @param [String] field_name + # @param [String, Integer, Date] field_value + # @param [Array] selected_fields + # @return [Array<Hash>] returns the array of records with a hash of the fields and values + def data_find_by_field(table, limit, page, field_name, field_value, selected_fields) + response = get('DataService.findByField', table, limit, page, field_name, + field_value, selected_fields) + end + + # Queries records in a given table to find matches on certain fields. + # + # @param [String] table + # @param [Integer] limit + # @param [Integer] page + # @param [Hash] data the data you would like to query on. { :FirstName => 'first_name' } + # @param [Array] selected_fields the fields and values you want back + # @return [Array<Hash>] the fields and associated values + def data_query(table, limit, page, data, selected_fields) + response = get('DataService.query', table, limit, page, data, selected_fields) + end + + # Queries records in a given table to find matches on certain fields. + # + # @param [String] table + # @param [Integer] limit + # @param [Integer] page + # @param [Hash] data the data you would like to query on. { :FirstName => 'first_name' } + # @param [Array] selected_fields the fields and values you want back + # @param [String] field by which to order the output results + # @param [Boolean] true ascending, false descending + # @return [Array<Hash>] the fields and associated values + def data_query_order_by(table, limit, page, data, selected_fields, by, ascending) + response = get('DataService.query', table, limit, page, data, selected_fields, by, ascending) + end + + # Adds a custom field to Infusionsoft + # + # @param [String] field_type options include Person, Company, Affiliate, Task/Appt/Note, + # Order, Subscription, or Opportunity + # @param [String] name + # @param [String] data_type the type of field Text, Dropdown, TextArea + # @param [Integer] header_id see notes here + # http://help.infusionsoft.com/developers/services-methods/data/addCustomField + def data_add_custom_field(field_type, name, data_type, header_id) + response = get('DataService.addCustomField', field_type, name, data_type, header_id) + end + + # Authenticate an Infusionsoft username and password(md5 hash). If the credentials match + # it will return back a User ID, if the credentials do not match it will send back an + # error message + # + # @param [String] username + # @param [String] password + # @return [Integer] id of the authenticated user + def data_authenticate_user(username, password) + response = get('DataService.authenticateUser', username, password) + end + + # This method will return back the data currently configured in a user configured + # application setting. + # + # @param [String] module + # @param [String] setting + # @return [String] current values in given application setting + # @note to find the module and option names, view the HTML field name within the Infusionsoft + # settings. You will see something such as name="Contact_WebModule0optiontypes" . The portion + # before the underscore is the module name. "Contact" in this example. The portion after the + # 0 is the setting name, "optiontypes" in this example. + def data_get_app_setting(module_name, setting) + response = get('DataService.getAppSetting', module_name, setting) + end + + # Returns a temporary API key if given a valid Vendor key and user credentials. + # + # @param [String] vendor_key + # @param [String] username + # @param [String] password_hash an md5 hash of users password + # @return [String] temporary API key + def data_get_temporary_key(vendor_key, username, password_hash) + response = get('DataService.getTemporaryKey', username, password_hash) + end + + # Updates a custom field. Every field can have it’s display name and group id changed, + # but only certain data types will allow you to change values(dropdown, listbox, radio, etc). + # + # @param [Integer] field_id + # @param [Hash] field_values + # @return [Boolean] returns true/false if it was updated + def data_update_custom_field(field_id, field_values) + response = get('DataService.updateCustomField', field_id, field_values) + end + end + end +end diff --git a/lib/infusionsoft/client/email.rb b/lib/infusionsoft/client/email.rb new file mode 100644 index 0000000..3d58ce1 --- /dev/null +++ b/lib/infusionsoft/client/email.rb @@ -0,0 +1,152 @@ +module Infusionsoft + class Client + # The Email service allows you to email your contacts as well as attaching emails sent + # elsewhere (this lets you send email from multiple services and still see all communications + # inside of Infusionsoft). + module Email + + # Create a new email template that can be used for future emails + # + # @param [String] title + # @param [String] categories a comma separated list of the categories + # you want this template in Infusionsoft + # @param [String] from the from address format use is 'FirstName LastName <email@domain.com>' + # @param [String] to the email address this template is sent to + # @param [String] cc a comma separated list of cc email addresses + # @param [String] bcc a comma separated list of bcc email addresses + # @param [String] subject + # @param [String] text_body + # @param [String] html_body + # @param [String] content_type can be Text, HTML, Multipart + # @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard + def email_add(title, categories, from, to, cc, bcc, subject, text_body, html_body, + content_type, merge_context) + response = get('APIEmailService.addEmailTemplate', title, categories, from, to, + cc, bcc, subject, text_body, html_body, content_type, merge_context) + end + + # This will create an item in the email history for a contact. This does not actually + # send the email, it only places an item into the email history. Using the API to + # instruct Infusionsoft to send an email will handle this automatically. + # + # @param [Integer] contact_id + # @param [String] from_name the name portion of the from address, not the email + # @param [String] from_address + # @param [String] to_address + # @param [String] cc_addresses + # @param [String] bcc_addresses + # @param [String] content_type can be Text, HTML, Multipart + # @param [String] subject + # @param [String] html_body + # @param [String] text_body + # @param [String] header the header info for this email (will be listed in history) + # @param [Date] receive_date + # @param [Date] sent_date + def email_attach(contact_id, from_name, from_address, to_address, cc_addresses, + bcc_addresses, content_type, subject, html_body, txt_body, + header, receive_date, send_date) + response = get('APIEmailService.attachEmail', contact_id, from_name, from_address, + to_address, cc_addresses, bcc_addresses, content_type, subject, + html_body, txt_body, header, receive_date, send_date) + end + + # This retrieves all possible merge fields for the context provided. + # + # @param [String] merge_context could include Contact, ServiceCall, Opportunity, or CreditCard + # @return [Array] returns the merge fields for the given context + def email_get_available_merge_fields(merge_context) + response = get('APIEmailService.getAvailableMergeFields', merge_context) + end + + # Retrieves the details for a particular email template. + # + # @param [Integer] id + # @return [Hash] all data for the email template + def email_get_template(id) + response = get('APIEmailService.getEmailTemplate', id) + end + + # Retrieves the status of the given email address. + # + # @param [String] email_address + # @return [Integer] 0 = opted out, 1 = single opt-in, 2 = double opt-in + def email_get_opt_status(email_address) + response = get('APIEmailService.getOptStatus', email_address) + end + + # This method opts-in an email address. This method only works the first time + # an email address opts-in. + # + # @param [String] email_address + # @param [String] reason + # This is how you can note why/how this email was opted-in. If a blank + # reason is passed the system will default a reason of "API Opt In" + # @return [Boolean] + def email_optin(email_address, reason) + response = get('APIEmailService.optIn', email_address, reason) + end + + # Opts-out an email address. Note that once an address is opt-out, + # the API cannot opt it back in. + # + # @param [String] email_address + # @param [String] reason + # @return [Boolean] + def email_optout(email_address, reason) + response = get('APIEmailService.optOut', email_address, reason) + end + + # This will send an email to a list of contacts, as well as record the email + # in the contacts' email history. + # + # @param [Array<Integer>] contact_list list of contact ids you want to send this email to + # @param [String] from_address + # @param [String] to_address + # @param [String] cc_address + # @param [String] bcc_address + # @param [String] content_type this must be one of the following Text, HTML, or Multipart + # @param [String] subject + # @param [String] html_body + # @param [String] text_body + # @return [Boolean] returns true/false if the email has been sent + def email_send(contact_list, from_address, to_address, cc_addresses, + bcc_addresses, content_type, subject, html_body, text_body) + response = get('APIEmailService.sendEmail', contact_list, from_address, + to_address, cc_addresses, bcc_addresses, content_type, subject, + html_body, text_body) + end + + # This will send an email to a list of contacts, as well as record the email in the + # contacts' email history. + # + # @param [Array<Integer>] contact_list is an array of Contact id numbers you would like to send this email to + # @param [String] The Id of the template to send + # @return returns true if the email has been sent, an error will be sent back otherwise. + def email_send_template(contact_list, template_id) + response = get('APIEmailService.sendTemplate', contact_list, template_id) + end + + + # This method is used to update an already existing email template. + # + # @param [Integer] id + # @param [String] title + # @param [String] category + # @param [String] from + # @param [String] to + # @param [String] cc + # @param [String] bcc + # @param [String subject + # @param [String] text_body + # @param [String] html_body + # @param [String] content_type can be Text, HTML, Multipart + # @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard + # @return [Boolean] returns true/false if teamplate was updated successfully + def email_update_template(id, title, category, from, to, cc, bcc, subject, + text_body, html_body, content_type, merge_context) + response = get('APIEmailService.updateEmailTemplate', title, category, from, + to, cc, bcc, subject, text_body, html_body, content_type, merge_context) + end + end + end +end diff --git a/lib/infusionsoft/client/file.rb b/lib/infusionsoft/client/file.rb new file mode 100644 index 0000000..9d83632 --- /dev/null +++ b/lib/infusionsoft/client/file.rb @@ -0,0 +1,26 @@ +module Infusionsoft + class Client + module File + def file_upload(contact_id, file_name, encoded_file_base64) + response = get('FileService.uploadFile', contact_id, file_name, encoded_file_base64) + end + + # returns the Base64 encoded file contents + def file_get(id) + response = get('FileService.getFile', id) + end + + def file_url(id) + response = get('FileService.getDownloadUrl', id) + end + + def file_rename(id, new_name) + response = get('FileService.renameFile', id, new_name) + end + + def file_replace(id, encoded_file_base64) + response = get('FileService.replaceFile', id, encoded_file_base64) + end + end + end +end diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb new file mode 100644 index 0000000..1b5aebf --- /dev/null +++ b/lib/infusionsoft/client/invoice.rb @@ -0,0 +1,254 @@ +module Infusionsoft + class Client + # The Invoice service allows you to manage eCommerce transactions. + module Invoice + # Creates a blank order with no items. + # + # @param [Integer] contact_id + # @param [String] description the name this order will display + # @param [Date] order_date + # @param [Integer] lead_affiliate_id 0 should be used if none + # @param [Integer] sale_affiliate_id 0 should be used if none + # @return [Integer] returns the invoice id + def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id, + sale_affiliate_id) + response = get('InvoiceService.createBlankOrder', contact_id, description, order_date, + lead_affiliate_id, sale_affiliate_id) + end + + # Adds a line item to an order. This used to add a Product to an order as well as + # any other sort of charge/discount. + # + # @param [Integer] invoice_id + # @param [Integer] product_id + # @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4, + # UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7 + # @param [Float] price + # @param [Integer] quantity + # @param [String] description a full description of the line item + # @param [String] notes + # @return [Boolean] returns true/false if it was added successfully or not + def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes) + response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price, + quantity, description, notes) + end + + # This will cause a credit card to be charged for the amount currently due on an invoice. + # + # @param [Integer] invoice_id + # @param [String] notes a note about the payment + # @param [Integer] credit_card_id + # @param [Integer] merchant_account_id + # @param [Boolean] bypass_commission + # @return [Hash] containing the following keys {'Successful => [Boolean], + # 'Code' => [String], 'RefNum' => [String], 'Message' => [String]} + def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id, + bypass_commissions) + response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id, + merchant_account_id, bypass_commissions) + end + + # Deletes the specified subscription from the database, as well as all invoices + # tied to the subscription. + # + # @param [Integer] cprogram_id the id of the subscription being deleted + # @return [Boolean] + def invoice_delete_subscription(cprogram_id) + response = get('InvoiceService.deleteSubscription', cprogram_id) + end + + # Creates a subscription for a contact. Subscriptions are billing automatically + # by infusionsoft within the next six hours. If you want to bill immediately you + # will need to utilize the create_invoice_for_recurring and then + # charge_invoice method to accomplish this. + # + # @param [Integer] contact_id + # @param [Boolean] allow_duplicate + # @param [Integer] cprogram_id the subscription id + # @param [Integer] merchant_account_id + # @param [Integer] credit_card_id + # @param [Integer] affiliate_id + # @param [Integer] days_till_charge number of days you want to wait till it's charged + def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id, + merchant_account_id, credit_card_id, affiliate_id, + days_till_charge) + response = get('InvoiceService.addRecurringOrder', contact_id, + allow_duplicate, cprogram_id, merchant_account_id, credit_card_id, + affiliate_id, days_till_charge) + end + + # This modifies the commissions being earned on a particular subscription. + # This does not affect previously generated invoices for this subscription. + # + # @param [Integer] recurring_order_id + # @param [Integer] affiliate_id + # @param [Float] amount + # @param [Integer] paryout_type how commissions will be earned (possible options are + # 4 - up front earning, 5 - upon customer payment) typically this is 5 + # @return [Boolean] + def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id, + amount, payout_type, description) + response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id, + affiliate_id, amount, payout_type, description) + end + + # Adds a payment to an invoice without actually processing a charge through a merchant. + # + # @param [Integer] invoice_id + # @param [Float] amount + # @param [Date] date + # @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc. + # @param [String] description an area useful for noting payment details such as check number + # @param [Boolean] bypass_commissions + # @return [Boolean] + def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions) + response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type, + description, bypass_commissions) + end + + # This will create an invoice for all charges due on a Subscription. If the + # subscription has three billing cycles that are due, it will create one + # invoice with all three items attached. + # + # @param [Integer] recurring_order_id + # @return [Integer] returns the id of the invoice that was created + def invoice_create_invoice_for_recurring(recurring_order_id) + response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id) + end + + # Adds a payment plan to an existing invoice. + # + # @param [Integer] invoice_id + # @param [Boolean] + # @param [Integer] credit_card_id + # @param [Integer] merchant_account_id + # @param [Integer] days_between_retry the number of days Infusionsoft should wait + # before re-attempting to charge a failed payment + # @param [Integer] max_retry the maximum number of charge attempts + # @param [Float] initial_payment_ammount the amount of the very first charge + # @param [Date] initial_payment_date + # @param [Date] plan_start_date + # @param [Integer] number_of_payments the number of payments in this payplan (does not include + # initial payment) + # @param [Integer] days_between_payments the number of days between each payment + # @return [Boolean] + def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id, + merchant_account_id, days_between_retry, max_retry, + initial_payment_amount, initial_payment_date, plan_start_date, + number_of_payments, days_between_payments) + response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge, + credit_card_id, merchant_account_id, days_between_retry, max_retry, + initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments, + days_between_payments) + end + + # Calculates the amount owed for a given invoice. + # + # @param [Integer] invoice_id + # @return [Float] + def invoice_calculate_amount_owed(invoice_id) + response = get('InvoiceService.calculateAmountOwed', invoice_id) + end + + # Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft. + # + # @return [Array] + def invoice_get_all_payment_otpions + response = get('InvoiceService.getAllPaymentOptions') + end + + # Retrieves all payments for a given invoice. + # + # @param [Integer] invoice_id + # @return [Array<Hash>] returns an array of payments + def invoice_get_payments(invoice_id) + response = get('Invoice.getPayments', invoice_id) + end + + # Locates an existing card in the system for a contact, using the last 4 digits. + # + # @param [Integer] contact_id + # @param [Integer] last_four + # @return [Integer] returns the id of the credit card + def invoice_locate_existing_card(contact_id, last_four) + response = get('InvoiceService.locateExistingCard', contact_id, last_four) + end + + # Calculates tax, and places it onto the given invoice. + # + # @param [Integer] invoice_id + # @return [Boolean] + def invoice_recalculate_tax(invoice_id) + response = get('InvoiceService.recalculateTax', invoice_id) + end + + # This will validate a credit card in the system. + # + # @param [Integer] credit_card_id if the card is already in the system + # @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' } + def invoice_validate_card(credit_card_id) + response = get('InvoiceService.validateCreditCard', credit_card_id) + end + + # This will validate a credit card by passing in values of the + # card directly (this card doesn't have to be added to the system). + # + # @param [Hash] data + # @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' } + def invoice_validate_card(data) + response = get('InvoiceService.validateCreditCard', data) + end + + # Retrieves the shipping options currently setup for the Infusionsoft shopping cart. + # + # @return [Array] + def invoice_get_all_shipping_options + response = get('Invoice.getAllShippingOptions') + end + + # Changes the next bill date on a subscription. + # + # @param [Integer] job_recurring_id this is the subscription id on the contact + # @param [Date] next_bill_date + # @return [Boolean] + def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date) + response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date) + end + + + # Adds a commission override to a one time order, using a combination of percentage + # and hard-coded amounts. + # + # @param [Integer] invoice_id + # @param [Integer] affiliate_id + # @param [Integer] product_id + # @param [Integer] percentage + # @param [Float] amount + # @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon + # customer payment + # @param [String] description a note about this commission + # @param [Date] date the commission was generated, not necessarily earned + # @return [Boolean] + def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage, + amount, payout_type, description, date) + response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id, + product_id, percentage, amount, payout_type, description, date) + end + + + # Deprecated - Adds a recurring order to the database. + def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty, + price, allow_tax, merchant_account_id, + credit_card_id, affiliate_id, days_till_charge) + response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate, + cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id, + affiliate_id, days_till_charge) + end + + # Deprecated - returns the invoice id from a one time order. + def invoice_get_invoice_id(order_id) + response = get('InvoiceService.getinvoice_id', order_id) + end + end + end +end diff --git a/lib/infusionsoft/client/search.rb b/lib/infusionsoft/client/search.rb new file mode 100644 index 0000000..7136de0 --- /dev/null +++ b/lib/infusionsoft/client/search.rb @@ -0,0 +1,66 @@ +module Infusionsoft + class Client + # The SearchService allows you to retrieve the results of saved searches and reports that + # have been saved within Infusionsoft. Saved searches/reports are tied to the User that + # created them. This service also allows you to utilize the quick search function found in + # the upper right hand corner of your Infusionsoft application. + + # @note In order to retrieve the id number for saved searches you will need to utilize + # the data_query method and query the table called SavedFilter based on the user_id + # you are looking for the saved search Id for. Also note that UserId field on the + # SavedFilter table can contain multiple userId’s separated by a comma, so if you are + # querying for a report created by userId 6, I recommend appending the wildcard to the + # end of the userId. Something like $query = array( ‘UserId’ => ’6%’ ); + module Search + # Gets all possible fields/columns available for return on a saved search/report. + # + # @param [Integer] saved_search_id + # @param [Integer] user_id the user id who the saved search is assigned to + # @return [Hash] + def search_get_all_report_columns(saved_search_id, user_id) + response = get('SearchService.getAllReportColumns', saved_search_id, user_id) + end + + # Runs a saved search/report and returns all possible fields. + # + # @param [Integer] saved_search_id + # @param [Integer] user_id the user id who the saved search is assigned to + # @param [Integer] page_number + # @return [Hash] + def search_get_saved_search_results(saved_search_id, user_id, page_number) + response = get('SearchService.getSavedSearchResultsAllFields', saved_search_id, + user_id, page_number) + end + + # This is used to find what possible quick searches the given user has access to. + # + # @param [Integer] user_id + # @return [Array] + def search_get_available_quick_searches(user_id) + response = get('SearchService.getAvailableQuickSearches', user_id) + end + + # This allows you to run a quick search via the API. The quick search is the + # search bar in the upper right hand corner of the Infusionsoft application + # + # @param [String] search_type the type of search (Person, Order, Opportunity, Company, Task, + # Subscription, or Affiliate) + # @param [Integer] user_id + # @param [String] search_data + # @param [Integer] page + # @param [Integer] limit max is 1000 + # @return [Array<Hash>] + def search_quick_search(search_type, user_id, search_data, page, limit) + response = get('SearchService.quickSearch', search_type, user_id, search_data, page, limit) + end + + # Retrieves the quick search type that the given users has set as their default. + # + # @param [Integer] user_id + # @return [String] the quick search type that the given user selected as their default + def search_get_default_search_type(user_id) + response = get('SearchService.getDefaultQuickSearch', user_id) + end + end + end +end diff --git a/lib/infusionsoft/client/ticket.rb b/lib/infusionsoft/client/ticket.rb new file mode 100644 index 0000000..89f3bf0 --- /dev/null +++ b/lib/infusionsoft/client/ticket.rb @@ -0,0 +1,18 @@ +module Infusionsoft + class Client + module Ticket + # add move notes to existing tickets + def ticket_add_move_notes(ticket_list, move_notes, + move_to_stage_id, notify_ids) + response = get('ServiceCallService.addMoveNotes', ticket_list, + move_notes, move_to_stage_id, notify_ids) + end + + # add move notes to existing tickets + def ticket_move_stage(ticket_id, ticket_stage, move_notes, notify_ids) + response = get('ServiceCallService.moveTicketStage', + ticket_id, ticket_stage, move_notes, notify_ids) + end + end + end +end diff --git a/lib/infusionsoft/client/version.rb b/lib/infusionsoft/client/version.rb new file mode 100644 index 0000000..23f485b --- /dev/null +++ b/lib/infusionsoft/client/version.rb @@ -0,0 +1,5 @@ +module Infusionsoft + # The version of the gem + VERSION = '1.0.0'.freeze unless defined?(::Infusionsoft::VERSION) +end + diff --git a/lib/infusionsoft/configuration.rb b/lib/infusionsoft/configuration.rb new file mode 100644 index 0000000..a53f96a --- /dev/null +++ b/lib/infusionsoft/configuration.rb @@ -0,0 +1,41 @@ +module Infusionsoft + + module Configuration + # The list of available options + VALID_OPTION_KEYS = [ + :api_url, + :api_key, + :api_logger + ].freeze + + # @private + attr_accessor *VALID_OPTION_KEYS + + # When this module is extended, set all configuration options to their default values + #def self.extended(base) + #base.reset + #end + + # Convenience method to allow configuration options to be set in a block + def configure + yield self + end + + # Create a hash of options and their values + def options + options = {} + VALID_OPTION_KEYS.each{|k| options[k] = send(k)} + options + end + + #def reset + #self.url = '' + #self.api_key = 'na' + #end + + def api_logger + @api_logger || Infusionsoft::APILogger.new + end + end + +end diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb new file mode 100644 index 0000000..5625d7b --- /dev/null +++ b/lib/infusionsoft/connection.rb @@ -0,0 +1,42 @@ +require "xmlrpc/client" +require 'infusionsoft/exception_handler' + +module Infusionsoft + module Connection + private + + def connection(service_call, *args) + server = XMLRPC::Client.new3({ + 'host' => api_url, + 'path' => "/api/xmlrpc", + 'port' => 443, + 'use_ssl' => true + }) + begin + api_logger.info "CALL: #{service_call} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}" + result = server.call("#{service_call}", api_key, *args) + if result.nil?; ok_to_retry('nil response') end + rescue Timeout::Error => timeout + # Retry up to 5 times on a Timeout before raising it + ok_to_retry(timeout) ? retry : raise + rescue XMLRPC::FaultException => xmlrpc_error + # Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code + Infusionsoft::ExceptionHandler.new(xmlrpc_error) + end # Purposefully not catching other exceptions so that they can be handled up the stack + + api_logger.info "RESULT:#{result.inspect}" + return result + end + + def ok_to_retry(e) + @retry_count += 1 + if @retry_count <= 5 + api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}" + true + else + false + end + end + + end +end diff --git a/lib/infusionsoft/exception_handler.rb b/lib/infusionsoft/exception_handler.rb new file mode 100644 index 0000000..617f6dd --- /dev/null +++ b/lib/infusionsoft/exception_handler.rb @@ -0,0 +1,32 @@ +require 'infusionsoft/exceptions' + +class Infusionsoft::ExceptionHandler + + ERRORS = { + 1 => Infusionsoft::InvalidConfigError, + 2 => Infusionsoft::InvalidKeyError, + 3 => Infusionsoft::UnexpectedError, + 4 => Infusionsoft::DatabaseError, + 5 => Infusionsoft::RecordNotFoundError, + 6 => Infusionsoft::LoadingError, + 7 => Infusionsoft::NoTableAccessError, + 8 => Infusionsoft::NoFieldAccessError, + 9 => Infusionsoft::NoTableFoundError, + 10 => Infusionsoft::NoFieldFoundError, + 11 => Infusionsoft::NoFieldsError, + 12 => Infusionsoft::InvalidParameterError, + 13 => Infusionsoft::FailedLoginAttemptError, + 14 => Infusionsoft::NoAccessError, + 15 => Infusionsoft::FailedLoginAttemptPasswordExpiredError, + } + + def initialize(xmlrpc_exception) + error_class = ERRORS[xmlrpc_exception.faultCode] + if error_class + raise error_class, xmlrpc_exception.faultString + else + raise InfusionAPIError, xmlrpc_exception.faultString + end + end + +end diff --git a/lib/infusionsoft/exceptions.rb b/lib/infusionsoft/exceptions.rb new file mode 100644 index 0000000..ba06f8d --- /dev/null +++ b/lib/infusionsoft/exceptions.rb @@ -0,0 +1,58 @@ +# Extend StandardError to keep track of Error being wrapped +# Pattern from Exceptional Ruby by Avdi Grimm (http://avdi.org/talks/exceptional-ruby-2011-02-04/) +class InfusionAPIError < StandardError + attr_reader :original + def initialize(msg, original=nil); + Infusionsoft.api_logger.error "ERROR: #{msg}" + super(msg); + @original = original; + end +end + +module Infusionsoft + # For now I'm inheriting from InfusionAPIError so that the code will remain backwards compatible...may be deprecated in the future + class InvalidConfigError < InfusionAPIError + end + + class InvalidKeyError < InfusionAPIError + end + + class UnexpectedError < InfusionAPIError + end + + class DatabaseError < InfusionAPIError + end + + class RecordNotFoundError < InfusionAPIError + end + + class LoadingError < InfusionAPIError + end + + class NoTableAccessError < InfusionAPIError + end + + class NoFieldAccessError < InfusionAPIError + end + + class NoTableFoundError < InfusionAPIError + end + + class NoFieldFoundError < InfusionAPIError + end + + class NoFieldsError < InfusionAPIError + end + + class InvalidParameterError < InfusionAPIError + end + + class FailedLoginAttemptError < InfusionAPIError + end + + class NoAccessError < InfusionAPIError + end + + class FailedLoginAttemptPasswordExpiredError < InfusionAPIError + end +end diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb new file mode 100644 index 0000000..661154d --- /dev/null +++ b/lib/infusionsoft/request.rb @@ -0,0 +1,33 @@ +module Infusionsoft + module Request + # Perform an GET request + def get(service_call, *args) + request(:get, service_call, *args) + end + + def post(path, params={}, options={}) + request(:post, path, params, options) + end + + # Perform an HTTP PUT request + def put(path, params={}, options={}) + request(:put, path, params, options) + end + + # Perform an HTTP DELETE request + def delete(path, params={}, options={}) + request(:delete, path, params, options) + end + + + private + + # Perform request + def request(method, service_call, *args) + case method.to_sym + when :get + response = connection(service_call, *args) + end + end + end +end diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb new file mode 100644 index 0000000..82353b7 --- /dev/null +++ b/lib/infusionsoft/version.rb @@ -0,0 +1,4 @@ +module Infusionsoft + # The version of the gem + VERSION = '1.1.6'.freeze unless defined?(::Infusionsoft::VERSION) +end diff --git a/test/api_infusion_test.rb b/test/api_infusion_test.rb new file mode 100644 index 0000000..30a7288 --- /dev/null +++ b/test/api_infusion_test.rb @@ -0,0 +1,8 @@ +require 'test/unit' + +class ApiInfusionTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_this_plugin + flunk # will implement later :( + end +end diff --git a/test/test_exceptions.rb b/test/test_exceptions.rb new file mode 100644 index 0000000..530e275 --- /dev/null +++ b/test/test_exceptions.rb @@ -0,0 +1,113 @@ +require 'test/unit' +require 'infusionsoft' + + +# override XMLRPC call method +class XMLRPC::Client + + def call(method, *args) + raise XMLRPC::FaultException.new(@@code, @@message) + end + + def self.set_fault_response(code, message) + @@code = code + @@message = message + end +end + +class TestLogger + def info(msg); end + def warn(msg); end + def error(msg); end + def debug(msg); end + def fatal(msg); end +end + + +class TestExceptions < Test::Unit::TestCase + + def setup + Infusionsoft.configure do |c| + c.api_logger = TestLogger.new() + end + end + + def test_should_raise_invalid_config + exception_test(Infusionsoft::InvalidConfigError, 1, 'The configuration for the application is invalid. Usually this is because there has not been a passphrase entered to generate an encrypted key.') + end + + def test_should_raise_invalid_key + exception_test(Infusionsoft::InvalidKeyError, 2, "The key passed up for authentication was not valid. It was either empty or didn't match.") + end + + def test_should_raise_unexpected_error + exception_test(Infusionsoft::UnexpectedError, 3, "An unexpected error has occurred. There was either an error in the data you passed up or there was an unknown error on") + end + + def test_should_raise_database_error + exception_test(Infusionsoft::DatabaseError, 4, "There was an error in the database access") + end + + def test_should_raise_record_not_found + exception_test(Infusionsoft::RecordNotFoundError, 5, "A requested record was not found in the database.") + end + + def test_should_raise_loading_error + exception_test(Infusionsoft::LoadingError, 6, "There was a problem loading a record from the database.") + end + + def test_should_raise_no_table_access + exception_test(Infusionsoft::NoTableAccessError, 7, "A table was accessed without the proper permission") + end + + def test_should_raise_no_field_access + exception_test(Infusionsoft::NoFieldAccessError, 8, "A field was accessed without the proper permission.") + end + + def test_should_raise_no_table_found + exception_test(Infusionsoft::NoTableFoundError, 9, "A table was accessed that doesn't exist in the Data Spec.") + end + + def test_should_raise_no_field_found + exception_test(Infusionsoft::NoFieldFoundError, 10, "A field was accessed that doesn't exist in the Data Spec.") + end + + def test_should_raise_no_fields_error + exception_test(Infusionsoft::NoFieldsError, 11, "An update or add operation was attempted with no valid fields to update or add.") + end + + def test_should_raise_invalid_parameter_error + exception_test(Infusionsoft::InvalidParameterError, 12, "Data sent into the call was invalid.") + end + + def test_should_raise_failed_login_attempt + exception_test(Infusionsoft::FailedLoginAttemptError, 13, "Someone attempted to authenticate a user and failed.") + end + + def test_should_raise_no_access_error + exception_test(Infusionsoft::NoAccessError, 14, "Someone attempted to access a plugin they are not paying for.") + end + + def test_should_raise_failed_login_attempt_password_expired + exception_test(Infusionsoft::FailedLoginAttemptPasswordExpiredError, 15, "Someone attempted to authenticate a user and the password is expired.") + end + + def test_should_raise_infusionapierror_when_fault_code_unknown + exception_test(InfusionAPIError, 42, "Some random error occurred") + end + + + private + def exception_test(exception, code, message) + XMLRPC::Client.set_fault_response(code, message) + caught = false + begin + Infusionsoft.data_query(:Contact, 1, 0, {}, [:BlahdyDah]) + rescue exception => e + caught = true + assert_equal message, e.message + end + assert_equal true, caught + end + +end
nmccrina/game_of_life
a0a3b8864b6574460f9109414eb35dbcc802f215
Added build instructions in README
diff --git a/README b/README index 11ddb59..cfa7731 100644 --- a/README +++ b/README @@ -1,10 +1,14 @@ ABOUT ------------------------------------------------------------------------------- This is a Java implementation of the Game of Life, a cellular automaton devised by the mathematician John Conway. For more information on the game of life, visit http://en.wikipedia.org/wiki/Conway's_Game_of_Life. BUILDING ------------------------------------------------------------------------------- +The program of course requires the presence of a JDK to be compiled. Also, it +uses Ant to manage the build. To compile and run the program, ensure those two +dependencies are installed, then cd into the top-level directory (the one with +build.xml) and run 'ant'. That's it!
nmccrina/game_of_life
78f4596cb150b80497160760c2c0ddf101851909
Added build.xml
diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..c127776 --- /dev/null +++ b/build.xml @@ -0,0 +1,34 @@ +<project name="GameOfLife" basedir="." default="main"> + + <property name="src.dir" value="src" /> + <property name="build.dir" value="build" /> + <property name="classes.dir" value="${build.dir}/classes" /> + <property name="jar.dir" value="${build.dir}/jar" /> + <property name="main-class" value="org.mccrina.GameOfLife.GameDriver" /> + + <target name="clean"> + <delete dir="${build.dir}" /> + </target> + + <target name="compile"> + <mkdir dir="${classes.dir}" /> + <javac srcdir="${src.dir}" destdir="${classes.dir}" /> + </target> + + <target name="jar" depends="compile"> + <mkdir dir="${jar.dir}" /> + <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}"> + <manifest> + <attribute name="Main-Class" value="${main-class}" /> + </manifest> + </jar> + </target> + + <target name="run" depends="jar"> + <java jar="${jar.dir}/${ant.project.name}.jar" fork="true" /> + </target> + + <target name="clean-build" depends="clean,jar"/> + + <target name="main" depends="clean,run"/> +</project>
nmccrina/game_of_life
6d1c5cefea5f97c78e843f5d50559b404a7e5c25
Added README
diff --git a/README b/README new file mode 100644 index 0000000..11ddb59 --- /dev/null +++ b/README @@ -0,0 +1,10 @@ +ABOUT +------------------------------------------------------------------------------- + +This is a Java implementation of the Game of Life, a cellular automaton devised +by the mathematician John Conway. For more information on the game of life, +visit http://en.wikipedia.org/wiki/Conway's_Game_of_Life. + +BUILDING +------------------------------------------------------------------------------- +
isiri/wordpress_import
7d609398a5a4b6876098df9b641946463b038559
modified: url_mapping.rb
diff --git a/url_mapping.rb b/url_mapping.rb index 841dd4f..2e903af 100755 --- a/url_mapping.rb +++ b/url_mapping.rb @@ -8,1694 +8,1694 @@ def url_mapping_arr [ ' are-the-big-four-econ-errors-biases ' , ' the_big_four_ec ' ], [ ' surprisingly-friendly-suburbs ' , ' surprisingly_fr ' ], [ ' beware-amateur-science-history ' , ' beware_amateur_ ' ], [ ' whats-a-bias-again ' , ' whats_a_bias_ag ' ], [ ' why-truth-and ' , ' why_truth_and ' ], [ ' asymmetric-paternalism ' , ' asymmetric_pate ' ], [ ' to-the-barricades-against-what-exactly ' , ' to_the_barricad ' ], [ ' foxes-vs-hedgehogs-predictive-success ' , ' foxes_vs_hedgho ' ], [ ' follow-the-crowd ' , ' follow_the_crow ' ], [ ' what-exactly-is-bias ' , ' what_exactly_is ' ], [ ' moral-overconfidence ' , ' moral_hypocricy ' ], [ ' why-are-academics-liberal ' , ' the_cause_of_is ' ], [ ' a-1990-corporate-prediction-market ' , ' first_known_bus ' ], [ ' the-martial-art-of-rationality ' , ' the_martial_art ' ], [ ' beware-heritable-beliefs ' , ' beware_heritabl ' ], [ ' the-wisdom-of-bromides ' , ' the_wisdom_of_b ' ], [ ' the-movie-click ' , ' click_christmas ' ], [ ' quiz-fox-or-hedgehog ' , ' quiz_fox_or_hed ' ], [ ' hide-sociobiology-like-sex ' , ' does_sociobiolo ' ], [ ' how-to-join ' , ' introduction ' ], [ ' normative-bayesianism-and-disagreement ' , ' normative_bayes ' ], [ ' vulcan-logic ' , ' vulcan_logic ' ], [ ' benefit-of-doubt-bias ' , ' benefit_of_doub ' ], [ ' see-but-dont-believe ' , ' see_but_dont_be ' ], [ ' the-future-of-oil-prices-2-option-probabilities ' , ' the_future_of_o_1 ' ], [ ' resolving-your-hypocrisy ' , ' resolving_your_ ' ], [ ' academic-overconfidence ' , ' academic_overco ' ], [ ' gnosis ' , ' gnosis ' ], [ ' ads-that-hurt ' , ' ads_that_hurt ' ], [ ' gifts-hurt ' , ' gifts_hurt ' ], [ ' advertisers-vs-teachers-ii ' , ' advertisers_vs_ ' ], [ ' why-common-priors ' , ' why_common_prio ' ], [ ' the-future-of-oil-prices ' , ' the_future_of_o ' ], [ ' a-fable-of-science-and-politics ' , ' a_fable_of_scie ' ], [ ' a-christmas-gift-for-rationalists ' , ' a_christmas_gif ' ], [ ' when-truth-is-a-trap ' , ' when_truth_is_a ' ], [ ' you-will-age-and-die ' , ' you_will_age_an ' ], [ ' contributors-be-half-accessible ' , ' contributors_be ' ], [ ' i-dont-know ' , ' i_dont_know ' ], [ ' you-are-never-entitled-to-your-opinion ' , ' you_are_never_e ' ], [ ' a-decent-respect ' , ' a_decent_respec ' ], [ ' why-not-impossible-worlds ' , ' why_not_impossi ' ], [ ' modesty-in-a-disagreeable-world ' , ' modesty_in_a_di ' ], [ ' to-win-press-feign-surprise ' , ' to_win_press_fe ' ], [ ' advertisers-vs-teachers ' , ' suppose_that_co ' ], [ ' when-error-is-high-simplify ' , ' when_error_is_h ' ], [ ' finding-the-truth-in-controversies ' , ' finding_the_tru ' ], [ ' bias-in-christmas-shopping ' , ' bias_in_christm ' ], [ ' does-the-modesty-argument-apply-to-moral-claims ' , ' does_the_modest ' ], [ ' philosophers-on-moral-bias ' , ' philosophers_on ' ], [ ' meme-lineages-and-expert-consensus ' , ' meme_lineages_a ' ], [ ' the-conspiracy-against-cuckolds ' , ' the_conspiracy_ ' ], [ ' malatesta-estimator ' , ' malatesta_estim ' ], [ ' fillers-neglect-framers ' , ' fillers_neglect ' ], [ ' the-80-forecasting-solution ' , ' the_80_forecast ' ], [ ' ignorance-of-frankenfoods ' , ' ignorance_of_fr ' ], [ ' do-helping-professions-help-more ' , ' do_helping_prof ' ], [ ' should-prediction-markets-be-charities ' , ' should_predicti ' ], [ ' we-are-smarter-than-me ' , ' we_are_smarter_ ' ], [ ' law-as-no-bias-theatre ' , ' law_as_nobias_t ' ], [ ' the-modesty-argument ' , ' the_modesty_arg ' ], [ ' agreeing-to-agree ' , ' agreeing_to_agr ' ], [ ' time-on-risk ' , ' time_on_risk ' ], [ ' leamers-1986-idea-futures-proposal ' , ' leamers_1986_id ' ], [ ' alas-amateur-futurism ' , ' alas_amateur_fu ' ], [ ' the-wisdom-of-crowds ' , ' the_wisdom_of_c ' ], [ ' reasonable-disagreement ' , ' reasonable_disa ' ], [ ' math-zero-vs-political-zero ' , ' math_zero_vs_po ' ], [ ' bosses-prefer-overconfident-managers ' , ' bosses_prefer_o ' ], [ ' seen-vs-unseen-biases ' , ' seen_vs_unseen_ ' ], [ ' future-selves ' , ' future_selves ' ], [ ' does-profit-rate-insight-best ' , ' does_profit_rat ' ], [ ' bias-well-being-and-the-placebo-effect ' , ' bias_wellbeing_ ' ], [ ' biases-of-science-fiction ' , ' biases_of_scien ' ], [ ' the-proper-use-of-humility ' , ' the_proper_use_ ' ], [ ' the-onion-on-bias-duh ' , ' the_onion_on_bi ' ], [ ' prizes-versus-grants ' , ' prizes_versus_g ' ], [ ' wanted-a-meta-poll ' , ' wanted_a_metapo ' ], [ ' excess-signaling-example ' , ' excess_signalin ' ], [ ' rationalization ' , ' rationalization ' ], [ ' against-admirable-activities ' , ' against_admirab ' ], [ ' effects-of-ideological-media-persuasion ' , ' effects_of_ideo ' ], [ ' whats-the-right-rule-for-a-juror ' , ' whats_the_right ' ], [ ' galt-on-abortion-and-bias ' , ' galt_on_abortio ' ], [ ' -the-procrastinators-clock ' , ' the_procrastina ' ], [ ' keeping-score ' , ' keeping_score ' ], [ ' agree-with-young-duplicate ' , ' agree_with_your ' ], [ ' sick-of-textbook-errors ' , ' sick_of_textboo ' ], [ ' manipulating-jury-biases ' , ' manipulating_ju ' ], [ ' what-insight-in-innocence ' , ' what_insight_in ' ], [ ' on-policy-fact-experts-ignore-facts ' , ' on_policy_fact_ ' ], [ ' the-butler-did-it-of-course ' , ' the_butler_did_ ' ], [ ' no-death-of-a-buyerman ' , ' no_death_of_a_b ' ], [ ' is-there-such-a-thing-as-bigotry ' , ' is_there_such_a ' ], [ ' moby-dick-seeks-thee-not ' , ' moby_dick_seeks ' ], [ ' morale-markets-vs-decision-markets ' , ' morale_markets_ ' ], [ ' follow-your-passion-from-a-distance ' , ' follow_your_pas ' ], [ ' a-model-of-extraordinary-claims ' , ' a_model_of_extr ' ], [ ' socially-influenced-beliefs ' , ' socially_influe ' ], [ ' agree-with-yesterdays-duplicate ' , ' agree_with_yest ' ], [ ' outside-the-laboratory ' , ' outside_the_lab ' ], [ ' symmetry-is-not-pretty ' , ' symmetry_is_not ' ], [ ' some-claims-are-just-too-extraordinary ' , ' some_claims_are ' ], [ ' womens-mathematical-abilities ' , ' womens_mathemat ' ], [ ' benefits-of-cost-benefit-analyis ' , ' benefits_of_cos ' ], [ ' godless-professors ' , ' godless_profess ' ], [ ' how-to-not-spend-money ' , ' suppose_youre_a ' ], [ ' sometimes-the-facts-are-irrelevant ' , ' sometimes_the_f ' ], [ ' extraordinary-claims-are-extraordinary-evidence ' , ' extraordinary_c ' ], [ ' ' , ' in_a_recent_pos ' ], [ ' 70-for-me-30-for-you ' , ' 70_for_me_30_fo ' ], [ ' some-people-just-wont-quit ' , ' some_people_jus ' ], [ ' statistical-discrimination-is-probably-bad ' , ' statistical_dis ' ], [ ' costbenefit-analysis ' , ' costbenefit_ana ' ], [ ' smoking-warning-labels ' , ' smoking_warning ' ], [ ' conclusion-blind-review ' , ' conclusionblind ' ], [ ' is-more-information-always-better ' , ' is_more_informa ' ], [ ' should-we-defer-to-secret-evidence ' , ' should_we_defer ' ], [ ' peaceful-speculation ' , ' peaceful_specul ' ], [ ' supping-with-the-devil ' , ' supping_with_th ' ], [ ' disagree-with-suicide-rock ' , ' disagree_with_s ' ], [ ' biased-courtship ' , ' biased_courtshi ' ], [ ' reject-your-personalitys-politics ' , ' reject_your_pol ' ], [ ' laws-of-bias-in-science ' , ' laws_of_bias_in ' ], [ ' epidemics-are-98-below-average ' , ' epidemics_are_9 ' ], [ ' bias-not-a-bug-but-a-feature ' , ' bias_not_a_bug_ ' ], [ ' a-game-for-self-calibration ' , ' a_game_for_self ' ], [ ' why-allow-referee-bias ' , ' why_is_referee_ ' ], [ ' disagreement-at-thoughts-arguments-and-rants ' , ' disagreement_at ' ], [ ' hobgoblins-of-voter-minds ' , ' hobgoblins_of_v ' ], [ ' how-are-we-doing ' , ' how_are_we_doin ' ], [ ' avoiding-truth ' , ' avoiding_truth ' ], [ ' conspicuous-consumption-of-info ' , ' conspicuous_con ' ], [ ' we-cant-foresee-to-disagree ' , ' we_cant_foresee ' ], [ ' do-biases-favor-hawks ' , ' do_biases_favor ' ], [ ' convenient-bias-theories ' , ' convenient_bias ' ], [ ' fair-betting-odds-and-prediction-market-prices ' , ' fair_betting_od ' ], [ ' the-cognitive-architecture-of-bias ' , ' the_cognitive_a ' ], [ ' poll-on-nanofactories ' , ' poll_on_nanofac ' ], [ ' all-bias-is-signed ' , ' all_bias_is_sig ' ], [ ' two-cheers-for-ignoring-plain-facts ' , ' two_cheers_for_ ' ], [ ' what-if-everybody-overcame-bias ' , ' what_if_everybo ' ], [ ' discussions-of-bias-in-answers-to-the-edge-2007-question ' , ' media_biases_us ' ], [ ' why-dont-the-young-learn-from-the-old ' , ' why_dont_the_yo ' ], [ ' the-coin-guessing-game ' , ' the_coin_guessi ' ], [ ' a-honest-doctor-sort-of ' , ' a_honest_doctor ' ], [ ' medical-study-biases ' , ' medical_study_b ' ], [ ' this-is-my-dataset-there-are-many-datasets-like-it-but-this-one-is-mine ' , ' this_is_my_data ' ], [ ' professors-progress-like-ads-advise ' , ' ads_advise_prof ' ], [ ' disagreement-case-study-1 ' , ' disagreement_ca ' ], [ ' marginally-revolved-biases ' , ' marginally_revo ' ], [ ' calibrate-your-ad-response ' , ' calibrate_your_ ' ], [ ' disagreement-case-studies ' , ' seeking_disagre ' ], [ ' just-lose-hope-already ' , ' a_time_to_lose_ ' ], [ ' less-biased-memories ' , ' unbiased_memori ' ], [ ' think-frequencies-not-probabilities ' , ' think_frequenci ' ], [ ' fig-leaf-models ' , ' fig_leaf_models ' ], [ ' do-we-get-used-to-stuff-but-not-friends ' , ' do_we_get_used_ ' ], [ ' buss-on-true-love ' , ' buss_on_true_lo ' ], [ ' is-overcoming-bias-male ' , ' is_overcoming_b ' ], [ ' bias-in-the-classroom ' , ' bias_in_the_cla ' ], [ ' our-house-my-rules ' , ' our_house_my_ru ' ], [ ' how-paranoid-should-i-be-the-limits-of-overcoming-bias ' , ' how_paranoid_sh ' ], [ ' evidence-based-medicine-backlash ' , ' evidencebased_m ' ], [ ' politics-is-the-mind-killer ' , ' politics_is_the ' ], [ ' disagreement-on-inflation ' , ' disagreement_on ' ], [ ' moderate-moderation ' , ' moderate_modera ' ], [ ' bias-toward-certainty ' , ' bias_toward_cer ' ], [ ' multi-peaked-distributions ' , ' multipeaked_dis ' ], [ ' selection-bias-in-economic-theory ' , ' selection_bias_ ' ], [ ' induce-presidential-candidates-to-take-iq-tests ' , ' induce_presiden ' ], [ ' crackpot-people-and-crackpot-ideas ' , ' crackpot_people ' ], [ ' press-confirms-your-health-fears ' , ' press_confirms_ ' ], [ ' too-many-loner-theorists ' , ' too_many_loner_ ' ], [ ' words-for-love-and-sex ' , ' words_for_love_ ' ], [ ' its-sad-when-bad-ideas-drive-out-good-ones ' , ' its_sad_when_ba ' ], [ ' truth-is-stranger-than-fiction ' , ' truth_is_strang ' ], [ ' posterity-review-comes-cheap ' , ' posterity_revie ' ], [ ' reputation-commitment-mechanism ' , ' reputation_comm ' ], [ ' more-lying ' , ' more_lying ' ], [ ' is-truth-in-the-hump-or-the-tails ' , ' is_truth_in_the ' ], [ ' what-opinion-game-do-we-play ' , ' what_opinion_ga ' ], [ ' philip-tetlocks-long-now-talk ' , ' philip_tetlocks ' ], [ ' the-more-amazing-penn ' , ' the_more_amazin ' ], [ ' when-are-weak-clues-uncomfortable ' , ' when_are_weak_c ' ], [ ' detecting-lies ' , ' detecting_lies ' ], [ ' how-and-when-to-listen-to-the-crowd ' , ' how_and_when_to ' ], [ ' institutions-as-levers ' , ' institutions_as ' ], [ ' one-reason-why-power-corrupts ' , ' one_reason_why_ ' ], [ ' will-blog-posts-get-credit ' , ' will_blog_posts ' ], [ ' needed-cognitive-forensics ' , ' wanted_cognitiv ' ], [ ' control-variables-avoid-bias ' , ' control_variabl ' ], [ ' dare-to-deprogram-me ' , ' dare_to_deprogr ' ], [ ' bias-and-health-care ' , ' bias_and_health ' ], [ ' just-world-bias-and-inequality ' , ' just_world_bias_1 ' ], [ ' subduction-phrases ' , ' subduction_phra ' ], [ ' what-evidence-in-silence-or-confusion ' , ' what_evidence_i ' ], [ ' gender-profiling ' , ' gender_profilin ' ], [ ' unequal-inequality ' , ' unequal_inequal ' ], [ ' academic-tool-overconfidence ' , ' academic_tool_o ' ], [ ' why-are-there-no-comforting-words-that-arent-also-factual-statements ' , ' why_are_there_n ' ], [ ' big-issues-vs-small-issues ' , ' big_issues_vs_s ' ], [ ' tolstoy-on-patriotism ' , ' tolstoy_on_patr ' ], [ ' statistical-bias ' , ' statistical_bia ' ], [ ' explain-your-wins ' , ' explain_your_wi ' ], [ ' beware-of-information-porn ' , ' beware_of_infor ' ], [ ' info-has-no-trend ' , ' info_has_no_tre ' ], [ ' tsuyoku-vs-the-egalitarian-instinct ' , ' tsuyoku_vs_the_ ' ], [ ' libertarian-purity-duels ' , ' libertarian_pur ' ], [ ' tsuyoku-naritai-i-want-to-become-stronger ' , ' tsuyoku_naritai ' ], [ ' reporting-chains-swallow-extraordinary-evidence ' , ' reporting_chain ' ], [ ' self-deception-hypocrisy-or-akrasia ' , ' selfdeception_h ' ], [ ' the-very-worst-kind-of-bias ' , ' the_very_worst_ ' ], [ ' home-sweet-home-bias ' , ' home_sweet_home ' ], [ ' norms-of-reason-and-the-prospects-for-technologies-and-policies-of-debiasing ' , ' ways_of_debiasi ' ], [ ' useful-bias ' , ' useful_bias ' ], [ ' chronophone-motivations ' , ' chronophone_mot ' ], [ ' archimedess-chronophone ' , ' archimedess_chr ' ], [ ' masking-expert-disagreement ' , ' masking_expert_ ' ], [ ' archimedess-binding-dilemma ' , ' archimedess_bin ' ], [ ' morality-of-the-future ' , ' morality_of_the ' ], [ ' moral-progress-and-scope-of-moral-concern ' , ' moral_progress_ ' ], [ ' awareness-of-intimate-bias ' , ' awareness_of_in ' ], [ ' all-ethics-roads-lead-to-ours ' , ' all_ethics_road ' ], [ ' challenges-of-majoritarianism ' , ' challenges_of_m ' ], [ ' classic-bias-doubts ' , ' classic_bias_do ' ], [ ' philosophical-majoritarianism ' , ' on_majoritarian ' ], [ ' useless-medical-disclaimers ' , ' useless_medical ' ], [ ' arguments-and-duels ' , ' arguments_and_d ' ], [ ' believing-in-todd ' , ' believing_in_to ' ], [ ' ideologues-or-fools ' , ' ideologues_or_f ' ], [ ' bias-caused-by-fear-of-islamic-extremists ' , ' bias_caused_by_ ' ], [ ' bias-on-self-control-bias ' , ' selfcontrol_bia ' ], [ ' multipolar-disagreements-hals-religious-quandry ' , ' multipolar_disa ' ], [ ' superstimuli-and-the-collapse-of-western-civilization ' , ' superstimuli_an ' ], [ ' good-news-only-please ' , ' good_news_only_ ' ], [ ' blue-or-green-on-regulation ' , ' blue_or_green_o ' ], [ ' 100000-visits ' , ' 100000_visits ' ], [ ' disagreement-case-study-robin-hanson-and-david-balan ' , ' disagreement_ca_2 ' ], [ ' the-trouble-with-track-records ' , ' the_trouble_wit ' ], [ ' genetics-and-cognitive-bias ' , ' genetics_and_co ' ], [ ' marketing-as-asymmetrical-warfare ' , ' marketing_as_as ' ], [ ' disagreement-case-study---balan-and-i ' , ' disagreement_ca_1 ' ], [ ' moral-dilemmas-criticism-plumping ' , ' moral_dilemmas_ ' ], [ ' the-scales-of-justice-the-notebook-of-rationality ' , ' the_scales_of_j ' ], [ ' none-evil-or-all-evil ' , ' none_evil_or_al ' ], [ ' biases-by-and-large ' , ' biases_by_and_l ' ], [ ' disagreement-case-study---hawk-bias ' , ' disagreement_ca ' ], [ ' overcome-cognitive-bias-with-multiple-selves ' , ' overcome_cognit ' ], [ ' extreme-paternalism ' , ' extreme_paterna ' ], [ ' learn-from-politicians-personal-failings ' , ' learn_from_poli ' ], [ ' whose-framing ' , ' whose_framing ' ], [ ' who-are-the-god-experts ' , ' who_are_the_god ' ], [ ' bias-against-introverts ' , ' bias_against_in ' ], [ ' paternal-policies-fight-cognitive-bias-slash-information-costs-and-privelege-responsible-subselves ' , ' paternal_polici ' ], [ ' the-fog-of-disagreement ' , ' the_fog_of_disa ' ], [ ' burchs-law ' , ' burchs_law ' ], [ ' lets-get-ready-to-rumble ' , ' heres_my_openin ' ], [ ' rational-agent-paternalism ' , ' rational_agent_ ' ], [ ' the-give-us-more-money-bias ' , ' the_give_us_mor ' ], [ ' white-collar-crime-and-moral-freeloading ' , ' whitecollar_cri ' ], [ ' happy-capital-day ' , ' happy_capital_d ' ], [ ' outlandish-pundits ' , ' outlandish_pund ' ], [ ' policy-debates-should-not-appear-one-sided ' , ' policy_debates_ ' ], [ ' romantic-predators ' , ' romantic_predat ' ], [ ' swinging-for-the-fences-when-you-should-bunt ' , ' swinging_for_th ' ], [ ' paternalism-is-about-bias ' , ' paternalism_is_ ' ], [ ' you-are-not-hiring-the-top-1 ' , ' you_are_not_hir ' ], [ ' morality-or-manipulation ' , ' morality_or_man ' ], [ ' accountable-financial-regulation ' , ' accountable_fin ' ], [ ' today-is-honesty-day ' , ' today_is_honest ' ], [ ' more-on-future-self-paternalism ' , ' more_on_future_ ' ], [ ' universal-law ' , ' universal_law ' ], [ ' universal-fire ' , ' universal_fire ' ], [ ' the-fallacy-fallacy ' , ' the_fallacy_fal ' ], [ ' to-learn-or-credential ' , ' to_learn_or_cre ' ], [ ' feeling-rational ' , ' feeling_rationa ' ], [ ' overconfidence-erases-doc-advantage ' , ' overconfidence_ ' ], [ ' the-bleeding-edge-of-innovation ' , ' the_bleeding_ed ' ], [ ' expert-at-versus-expert-on ' , ' expert_at_versu ' ], [ ' meta-majoritarianism ' , ' meta_majoritari ' ], [ ' future-self-paternalism ' , ' future_self_pat ' ], [ ' popularity-is-random ' , ' popularity_is_r ' ], [ ' holocaust-denial ' , ' holocaust_denia ' ], [ ' exercise-sizzle-works-sans-steak ' , ' exercise_sizzle ' ], [ ' the-shame-of-tax-loopholing ' , ' the_shame_of_ta ' ], [ ' vonnegut-on-overcoming-fiction ' , ' vonnegut_on_ove ' ], [ ' consolidated-nature-of-morality-thread ' , ' consolidated_na ' ], [ ' irrationality-or-igustibusi ' , ' irrationality_o ' ], [ ' your-rationality-is-my-business ' , ' your_rationalit ' ], [ ' statistical-inefficiency-bias-or-increasing-efficiency-will-reduce-bias-on-average-or-there-is-no-bias-variance-tradeoff ' , ' statistical_ine ' ], [ ' new-improved-lottery ' , ' new_improved_lo ' ], [ ' non-experts-need-documentation ' , ' nonexperts_need ' ], [ ' overconfident-evaluation ' , ' overconfident_e ' ], [ ' lotteries-a-waste-of-hope ' , ' lotteries_a_was ' ], [ ' just-a-smile ' , ' just_a_smile ' ], [ ' priors-as-mathematical-objects ' , ' priors_as_mathe ' ], [ ' predicting-the-future-with-futures ' , ' predicting_the_ ' ], [ ' the-future-is-glamorous ' , ' the_future_is_g ' ], [ ' marginally-zero-sum-efforts ' , ' marginally_zero ' ], [ ' overcoming-credulity ' , ' overcoming_cred ' ], [ ' urgent-and-important-not ' , ' very_important_ ' ], [ ' futuristic-predictions-as-consumable-goods ' , ' futuristic_pred ' ], [ ' suggested-posts ' , ' suggested_posts ' ], [ ' modular-argument ' , ' modular_argumen ' ], [ ' inductive-bias ' , ' inductive_bias ' ], [ ' debiasing-as-non-self-destruction ' , ' debiasing_as_no ' ], [ ' overcoming-bias---what-is-it-good-for ' , ' overcoming_bias ' ], [ ' as-good-as-it-gets ' , ' as_good_as_it_g ' ], [ ' driving-while-red ' , ' driving_while_r ' ], [ ' media-bias ' , ' media_bias ' ], [ ' could-gambling-save-science ' , ' could_gambling_ ' ], [ ' casanova-on-innocence ' , ' casanova_on_inn ' ], [ ' black-swans-from-the-future ' , ' black_swans_fro ' ], [ ' having-to-do-something-wrong ' , ' having_to_do_so ' ], [ ' knowing-about-biases-can-hurt-people ' , ' knowing_about_b ' ], [ ' a-tough-balancing-act ' , ' a_tough_balanci ' ], [ ' mapping-academia ' , ' mapping_academi ' ], [ ' the-majority-is-always-wrong ' , ' the_majority_is ' ], [ ' overcoming-fiction ' , ' overcoming_fict ' ], [ ' the-error-of-crowds ' , ' the_error_of_cr ' ], [ ' do-moral-systems-have-to-make-sense ' , ' do_moral_system ' ], [ ' useful-statistical-biases ' , ' useful_statisti ' ], [ ' is-there-manipulation-in-the-hillary-clinton-prediction-market ' , ' is_there_manipu ' ], [ ' shock-response-futures ' , ' shock_response_ ' ], [ ' free-money-going-fast ' , ' free_money_goin ' ], [ ' arrogance-as-virtue ' , ' arrogance_as_vi ' ], [ ' are-any-human-cognitive-biases-genetically-universal ' , ' are_any_human_c_1 ' ], [ ' hofstadters-law ' , ' hofstadters_law ' ], [ ' the-agency-problem ' , ' the_agency_prob ' ], [ ' cryonics ' , ' cryonics ' ], [ ' my-podcast-with-russ-roberts ' , ' my_podcast_with ' ], [ ' truly-worth-honoring ' , ' truly_worth_hon ' ], [ ' scientists-as-parrots ' , ' scientists_as_p ' ], [ ' in-obscurity-errors-remain ' , ' in_obscurity_er ' ], [ ' requesting-honesty ' , ' requesting_hone ' ], [ ' winning-at-rock-paper-scissors ' , ' winning_at_rock ' ], [ ' policy-tug-o-war ' , ' policy_tugowar ' ], [ ' why-pretty-hs-play-leads ' , ' why_pretty_hs_p ' ], [ ' the-perils-of-being-clearer-than-truth ' , ' the_perils_of_b ' ], [ ' when-differences-make-a-difference ' , ' when_difference ' ], [ ' you-felt-sorry-for-her ' , ' you_felt_sorry_ ' ], [ ' do-androids-dream-of-electric-rabbit-feet ' , ' do_androids_dre ' ], [ ' one-life-against-the-world ' , ' one_life_agains ' ], [ ' cheating-as-status-symbol ' , ' cheating_as_sta ' ], [ ' underconfident-experts ' , ' underconfident_ ' ], [ ' are-almost-all-investors-biased ' , ' are_almost_all_ ' ], [ ' data-management ' , ' data_management ' ], [ ' are-any-human-cognitive-biases-genetic ' , ' are_any_human_c ' ], [ ' is-your-rationality-on-standby ' , ' is_your_rationa ' ], [ ' joke ' , ' joke ' ], [ ' opinions-of-the-politically-informed ' , ' opinions_of_the ' ], [ ' the-case-for-dangerous-testing ' , ' the_case_for_da ' ], [ ' i-had-the-same-idea-as-david-brin-sort-of ' , ' i_had_the_same_ ' ], [ ' disagreement-case-study----genetics-of-free-trade-and-a-new-cognitive-bias ' , ' disagreement_ca ' ], [ ' rand-experiment-ii-petition ' , ' rand_experiment ' ], [ ' skepticism-about-skepticism ' , ' skepticism_abou ' ], [ ' scope-insensitivity ' , ' scope_insensiti ' ], [ ' medicine-as-scandal ' , ' medicine_as_sca ' ], [ ' the-us-should-bet-against-iran-testing-a-nuclear-weapon ' , ' the_us_should_b ' ], [ ' medicare-train-wreck ' , ' medicare_train_ ' ], [ ' eclipsing-nobel ' , ' eclipsing_nobel ' ], [ ' what-speaks-silence ' , ' what_speaks_sil ' ], [ ' the-worst-youve-seen-isnt-the-worst-there-is ' , ' the_worst_youve ' ], [ ' rand-health-insurance-experiment-ii ' , ' rand_health_ins_1 ' ], [ ' the-conspiracy-glitch ' , ' the_conspiracy_ ' ], [ ' doubting-thomas-and-pious-pete ' , ' doubting_thomas ' ], [ ' rand-health-insurance-experiment ' , ' rand_health_ins ' ], [ ' third-alternatives-for-afterlife-ism ' , ' third_alternati ' ], [ ' scope-neglect-hits-a-new-low ' , ' scope_neglect_h ' ], [ ' motivated-stopping-in-philanthropy ' , ' early_stopping_ ' ], [ ' cold-fusion-continues ' , ' cold_fusion_con ' ], [ ' feel-lucky-punk ' , ' feel_luck_punk ' ], [ ' the-third-alternative ' , ' the_third_alter ' ], [ ' academics-against-evangelicals ' , ' academics_again ' ], [ ' race-bias-of-nba-refs ' , ' race_bias_of_nb ' ], [ ' brave-us-tv-news-not ' , ' brave_us_tv_new ' ], [ ' beware-the-unsurprised ' , ' beware_the_unsu ' ], [ ' academic-self-interest-bias ' , ' selfinterest_bi ' ], [ ' the-bias-in-please-and-thank-you ' , ' the_bias_in_ple ' ], [ ' social-norms-need-neutrality-simplicity ' , ' social_norms_ne ' ], [ ' think-like-reality ' , ' think_like_real ' ], [ ' overcoming-bias-on-the-simpsons ' , ' overcoming_bias ' ], [ ' eh-hunt-helped-lbj-kill-jfk ' , ' eh_hunt_helped_ ' ], [ ' myth-of-the-rational-academic ' , ' myth_of_the_rat ' ], [ ' biases-are-fattening ' , ' biases-are-fatt ' ], [ ' true-love-and-unicorns ' , ' true_love_and_u ' ], [ ' bayes-radical-liberal-or-conservative ' , ' bayes-radical-l ' ], [ ' global-warming-blowhards ' , ' global-warming ' ], [ ' extraordinary-physics ' , ' extraordinary_c ' ], [ ' are-your-enemies-innately-evil ' , ' are-your-enemie ' ], [ ' how-to-be-radical ' , ' how_to_be_radic ' ], [ ' auctioning-book-royalties ' , ' auctioning-book ' ], [ ' fair-landowner-coffee ' , ' fair-landownert ' ], [ ' death-risk-biases ' , ' death_risk_bias ' ], [ ' correspondence-bias ' , ' correspondence ' ], [ ' applaud-info-not-agreement ' , ' applaud-info-no ' ], [ ' risk-free-bonds-arent ' , ' risk-free-bonds ' ], [ ' adam-smith-on-overconfidence ' , ' adam_smith_on_o ' ], [ ' ethics-applied-vs-meta ' , ' ethics_applied_ ' ], [ ' wandering-philosophers ' , ' wandering_philo ' ], [ ' randomly-review-criminal-cases ' , ' randomly_review ' ], [ ' functional-is-not-optimal ' , ' functional_is_n ' ], [ ' were-people-better-off-in-the-middle-ages-than-they-are-now ' , ' politics_and_ec ' ], [ ' selling-overcoming-bias ' , ' selling_overcom ' ], [ ' tell-me-your-politics-and-i-can-tell-you-what-you-think-about-nanotechnology ' , ' tell_me_your_po ' ], [ ' beware-neuroscience-stories ' , ' beware_neurosci ' ], [ ' against-free-thinkers ' , ' against_free_th ' ], [ ' 1-2-3-infinity ' , ' 1_2_3_infinity ' ], [ ' total-vs-marginal-effects-or-are-the-overall-benefits-of-health-care-probably-minor ' , ' total_vs_margin ' ], [ ' one-reason-why-plans-are-good ' , ' one_reason_why_ ' ], [ ' 200000-visits ' , ' 200000_visits ' ], [ ' choose-credit-or-influence ' , ' choose_credit_o ' ], [ ' disagreement-case-study-hanson-and-hughes ' , ' disagreement_ca_1 ' ], [ ' odd-kid-names ' , ' odd_kid_names ' ], [ ' uncovering-rational-irrationalities ' , ' uncovering_rati ' ], [ ' blind-elites ' , ' blind_elites ' ], [ ' blind-winners ' , ' blind_winners ' ], [ ' disagreement-case-study-hanson-and-cutler ' , ' disagreement_ca ' ], [ ' why-not-pre-debate-talk ' , ' why_not_predeba ' ], [ ' nutritional-prediction-markets ' , ' nutritional_pre ' ], [ ' progress-is-not-enough ' , ' progress_is_not ' ], [ ' two-meanings-of-overcoming-bias-for-one-focus-is-fundamental-for-second ' , ' two-meanings-of ' ], [ ' only-losers-overcome-bias ' , ' only-losers-ove ' ], [ ' bayesian-judo ' , ' bayesian-judo ' ], [ ' self-interest-intent-deceit ' , ' self-interest-i ' ], [ ' colorful-characters ' , ' color-character ' ], [ ' belief-in-belief ' , ' belief-in-belie ' ], [ ' phone-shy-ufos ' , ' phone-shy-ufos ' ], [ ' making-beliefs-pay-rent-in-anticipated-experiences ' , ' making-beliefs ' ], [ ' ts-eliot-quote ' , ' ts-eliot-quote ' ], [ ' not-every-negative-judgment-is-a-bias ' , ' not-every-negat ' ], [ ' schools-that-dont-want-to-be-graded ' , ' schools-that-do ' ], [ ' the-judo-principle ' , ' the-judo-princi ' ], [ ' beware-the-inside-view ' , ' beware-the-insi ' ], [ ' goofy-best-friend ' , ' goofy-best-frie ' ], [ ' meta-textbooks ' , ' meta-textbooks ' ], [ ' fantasys-essence ' , ' fantasys-essens ' ], [ ' clever-controls ' , ' clever-controls ' ], [ ' investing-in-index-funds-a-tangible-reward-of-overcoming-bias ' , ' investing-in-in ' ], [ ' bad-balance-bias ' , ' bad-balance-bia ' ], [ ' raging-memories ' , ' raging-memories ' ], [ ' calibration-in-chess ' , ' calibration-in ' ], [ ' theyre-telling-you-theyre-lying ' , ' theyre-telling ' ], [ ' on-lying ' , ' on-lying ' ], [ ' gullible-then-skeptical ' , ' gullible-then-s ' ], [ ' how-biases-save-us-from-giving-in-to-terrorism ' , ' how-biases-save ' ], [ ' privacy-rights-and-cognitive-bias ' , ' privacy-rights ' ], [ ' conspiracy-believers ' , ' conspiracy-beli ' ], [ ' overcoming-bias-sometimes-makes-us-change-our-minds-but-sometimes-not ' , ' overcoming-bias ' ], [ ' blogging-doubts ' , ' blogging-doubts ' ], [ ' should-charges-of-cognitive-bias-ever-make-us-change-our-minds-a-global-warming-case-study ' , ' should-charges- ' ], [ ' radical-research-evaluation ' , ' radical-researc ' ], [ ' a-real-life-quandry ' , ' a-real-life-qua ' ], [ ' looking-for-a-hard-headed-blogger ' , ' looking-for-a-h ' ], [ ' goals-and-plans-in-decision-making ' , ' goals-and-plans ' ], [ ' 7707-weddings ' , ' 7707-weddings ' ], [ ' just-take-the-average ' , ' just-take-the-a ' ], [ ' two-more-things-to-unlearn-from-school ' , ' two-more-things ' ], [ ' introducing-ramone ' , ' introducing-ram ' ], [ ' tell-your-anti-story ' , ' tell-your-anti ' ], [ ' reviewing-caplans-reviewers ' , ' reviewing-capla ' ], [ ' how-should-unproven-findings-be-publicized ' , ' how-should-unpr ' ], [ ' global-warming-skeptics-charge-believers-with-more-cognitive-biases-than-believers-do-skeptics-why-the-asymmetry ' , ' global-warming ' ], [ ' what-is-public-info ' , ' what-is-public ' ], [ ' take-our-survey ' , ' take-our-survey ' ], [ ' lets-bet-on-talk ' , ' lets-bet-on-tal ' ], [ ' more-possible-political-biases-relative-vs-absolute-well-being ' , ' more-possible-p ' ], [ ' what-signals-what ' , ' what-signals-wh ' ], [ ' reply-to-libertarian-optimism-bias ' , ' in-this-entry-o ' ], [ ' biased-birth-rates ' , ' biased-birth-ra ' ], [ ' libertarian-optimism-bias-vs-statist-pessimism-bias ' , ' libertarian-opt ' ], [ ' painfully-honest ' , ' painfully-hones ' ], [ ' biased-revenge ' , ' biased-revenge ' ], [ ' the-road-not-taken ' , ' the_road_not_ta ' ], [ ' open-thread ' , ' open-thread ' ], [ ' making-history-available ' , ' making-history ' ], [ ' we-are-not-unbaised ' , ' we-are-not-unba ' ], [ ' failing-to-learn-from-history ' , ' failing-to-lear ' ], [ ' seeking-unbiased-game-host ' , ' seeking-unbiase ' ], [ ' my-wild-and-reckless-youth ' , ' my-wild-and-rec ' ], [ ' kind-right-handers ' , ' kind-right-hand ' ], [ ' say-not-complexity ' , ' say-not-complex ' ], [ ' the-function-of-prizes ' , ' the-function-of ' ], [ ' positive-bias-look-into-the-dark ' , ' positive-bias-l ' ], [ ' the-way-is-subtle ' , ' the-way-is-subt ' ], [ ' is-overcoming-bias-important ' , ' how-important-i ' ], [ ' the-futility-of-emergence ' , ' the-futility-of ' ], [ ' bias-as-objectification ' , ' bias-as-objecti ' ], [ ' mysterious-answers-to-mysterious-questions ' , ' mysterious-answ ' ], [ ' bias-against-torture ' , ' bias-against-to ' ], [ ' semantic-stopsigns ' , ' semantic-stopsi ' ], [ ' exccess-trust-in-experts ' , ' exccess-trust-i ' ], [ ' fake-causality ' , ' fake-causality ' ], [ ' is-hybrid-vigor-iq-warm-and-fuzzy ' , ' is-hybrid-vigor ' ], [ ' science-as-attire ' , ' science-as-lite ' ], [ ' moral-bias-as-group-glue ' , ' moral-bias-as-g ' ], [ ' guessing-the-teachers-password ' , ' guessing-the-te ' ], [ ' nerds-as-bad-connivers ' , ' post ' ], [ ' why-do-corporations-buy-insurance ' , ' why-do-corporat ' ], [ ' fake-explanations ' , ' fake-explanatio ' ], [ ' media-risk-bias-feedback ' , ' media-risk-bias ' ], [ ' irrational-investment-disagreement ' , ' irrational-inve ' ], [ ' is-molecular-nanotechnology-scientific ' , ' is-molecular-na ' ], [ ' what-evidence-is-brevity ' , ' what-evidence-i ' ], [ ' are-more-complicated-revelations-less-probable ' , ' are-more-compli ' ], [ ' scientific-evidence-legal-evidence-rational-evidence ' , ' scientific-evid ' ], [ ' pseudo-criticism ' , ' pseudo-criticis ' ], [ ' are-brilliant-scientists-less-likely-to-cheat ' , ' are-brilliant-s ' ], [ ' hindsight-devalues-science ' , ' hindsight-deval ' ], [ ' sometimes-learning-is-very-slow ' , ' sometimes-learn ' ], [ ' hindsight-bias ' , ' hindsight-bias ' ], -[ ' truth---the-neglected-virtue ' , ' truth---the-neg ' ], -[ ' one-argument-against-an-army ' , ' one-argument--1 ' ], +[ ' truth---the-neglected-virtue ' , ' truth-the-neg ' ], +[ ' one-argument-against-an-army ' , ' one-argument-1 ' ], [ ' strangeness-heuristic ' , ' strangeness-heu ' ], [ ' never-ever-forget-there-are-maniacs-out-there ' , ' never-ever-forg ' ], [ ' update-yourself-incrementally ' , ' update-yourself ' ], [ ' harry-potter-the-truth-seeker ' , ' harry-potter-th ' ], [ ' dangers-of-political-betting-markets ' , ' dangers-of-poli ' ], [ ' conservation-of-expected-evidence ' , ' conservation-of ' ], [ ' biases-of-biography ' , ' biases-of-biogr ' ], [ ' absence-of-evidence-iisi-evidence-of-absence ' , ' absence-of-evid ' ], [ ' confident-proposer-bias ' , ' confident-propo ' ], [ ' i-defy-the-data ' , ' i-defy-the-data ' ], [ ' what-is-a-taboo-question ' , ' what-is-a-taboo ' ], [ ' your-strength-as-a-rationalist ' , ' your-strength-a ' ], [ ' accountable-public-opinion ' , ' accountable-pub ' ], [ ' truth-bias ' , ' truth-bias ' ], [ ' the-apocalypse-bet ' , ' the-apocalypse ' ], [ ' spencer-vs-wilde-on-truth-vs-lie ' , ' spencer-vs-wild ' ], [ ' you-icani-face-reality ' , ' you-can-face-re ' ], [ ' food-vs-sex-charity ' , ' food-vs-sex-cha ' ], [ ' the-virtue-of-narrowness ' , ' the-virtue-of-n ' ], [ ' wishful-investing ' , ' wishful-investi ' ], [ ' the-proper-use-of-doubt ' , ' the-proper-use ' ], [ ' academic-political-bias ' , ' academic-politi ' ], [ ' focus-your-uncertainty ' , ' focus-your-unce ' ], [ ' disagreeing-about-cognitive-style-or-personality ' , ' disagreeing-abo ' ], [ ' the-importance-of-saying-oops ' , ' the-importance ' ], [ ' the-real-inter-disciplinary-barrier ' , ' the-real-inter ' ], [ ' religions-claim-to-be-non-disprovable ' , ' religions-claim ' ], [ ' is-advertising-the-playground-of-cognitive-bias ' , ' is-advertising ' ], [ ' anonymous-review-matters ' , ' anonymous-revie ' ], [ ' if-you-wouldnt-want-profits-to-influence-this-blog-you-shouldnt-want-for-profit-schools ' , ' if-you-wouldnt ' ], [ ' belief-as-attire ' , ' belief-as-attir ' ], [ ' overcoming-bias-hobby-virtue-or-moral-obligation ' , ' overcoming-bias ' ], [ ' the-dogmatic-defense ' , ' dogmatism ' ], [ ' professing-and-cheering ' , ' professing-and ' ], [ ' how-to-torture-a-reluctant-disagreer ' , ' how-to-torture ' ], [ ' open-thread ' , ' open-thread ' ], [ ' rationalization ' , ' rationalization ' ], [ ' lies-about-sex ' , ' lies-about-sex ' ], [ ' what-evidence-filtered-evidence ' , ' what-evidence-f ' ], [ ' a-moral-conundrum ' , ' a-moral-conundr ' ], [ ' jewish-people-and-israel ' , ' jewish-people-a ' ], [ ' the-bottom-line ' , ' the-bottom-line ' ], [ ' false-findings-unretracted ' , ' false-findings ' ], [ ' how-to-convince-me-that-2-2-3 ' , ' how-to-convince ' ], [ ' elusive-conflict-experts ' , ' elusive-conflic ' ], [ ' 926-is-petrov-day ' , ' 926-is-petrov-d ' ], [ ' drinking-our-own-kool-aid ' , ' drinking-our-ow ' ], [ ' occams-razor ' , ' occams-razor ' ], [ ' even-when-contrarians-win-they-lose ' , ' even-when-contr ' ], [ ' einsteins-arrogance ' , ' einsteins-arrog ' ], [ ' history-is-written-by-the-dissenters ' , ' history-is-writ ' ], [ ' the-bright-side-of-life ' , ' always-look-on ' ], [ ' how-much-evidence-does-it-take ' , ' how-much-eviden ' ], [ ' treat-me-like-a-statistic-but-please-be-nice-to-me ' , ' treat-me-like-a ' ], [ ' small-business-overconfidence ' , ' small-business ' ], [ ' the-lens-that-sees-its-flaws ' , ' the-lens-that-s ' ], [ ' why-so-little-model-checking-done-in-statistics ' , ' one-thing-that ' ], [ ' bounded-rationality-and-the-conjunction-fallacy ' , ' bounded-rationa ' ], [ ' what-is-evidence ' , ' what-is-evidenc ' ], [ ' radically-honest-meetings ' , ' radically-hones ' ], [ ' burdensome-details ' , ' burdensome-deta ' ], [ ' wielding-occams-razor ' , ' wielding-occams ' ], [ ' your-future-has-detail ' , ' in-the-sept-7-s ' ], [ ' medicine-has-been-overcoming-bias-too ' , ' medicine-has-be ' ], [ ' conjunction-controversy-or-how-they-nail-it-down ' , ' conjunction-con ' ], [ ' why-not-cut-medicine-all-the-way-to-zero ' , ' why-not-cut-med ' ], [ ' why-teen-paternalism ' , ' why-teen-patern ' ], [ ' conjunction-fallacy ' , ' conjunction-fal ' ], [ ' beware-monkey-traps ' , ' beware-monkey-t ' ], [ ' outputs-require-inputs ' , ' to-judge-output ' ], [ ' kahnemans-planning-anecdote ' , ' kahnemans-plann ' ], [ ' epidemiology-doubts ' , ' health-epidemio ' ], [ ' planning-fallacy ' , ' planning-fallac ' ], [ ' seven-sources-of-disagreement-cant-be-eliminated-by-overcoming-cognitive-bias ' , ' seven-sources-o ' ], [ ' dont-trust-your-lying-eyes ' , ' dont-trust-your ' ], [ ' scott-adams-on-bias ' , ' scott-adams-on ' ], [ ' naive-small-investors ' , ' naive-small-inv ' ], [ ' not-open-to-compromise ' , ' not-open-to-com ' ], [ ' why-im-blooking ' , ' why-im-blooking ' ], [ ' noise-in-the-courtroom ' , ' noise-in-the-co ' ], [ ' bias-awareness-bias-or-was-91101-a-black-swan ' , ' bias-awareness ' ], [ ' doublethink-choosing-to-be-biased ' , ' doublethink-cho ' ], [ ' acquisitions-signal-ceo-dominance ' , ' acquisitions-si ' ], [ ' human-evil-and-muddled-thinking ' , ' human-evil-and ' ], [ ' gotchas-are-not-biases ' , ' gotchas-are-not ' ], [ ' rationality-and-the-english-language ' , ' rationality-and ' ], [ ' never-confuse-could-and-would ' , ' never-confuse-c ' ], [ ' what-evidence-reluctant-authors ' , ' what-evidence-r ' ], [ ' applause-lights ' , ' applause-lights ' ], [ ' what-evidence-dry-one-sided-arguments ' , ' what-evidence-d ' ], [ ' bad-college-quality-incentives ' , ' bad-college-qua ' ], [ ' case-study-of-cognitive-bias-induced-disagreements-on-petraeus-crocker ' , ' case-study-of-c ' ], [ ' we-dont-really-want-your-participation ' , ' we-dont-really ' ], [ ' tyler-finds-overcoming-bias-iisi-important-for-others ' , ' tyler-cowen-fin ' ], [ ' cut-medicine-in-half ' , ' cut-medicine-in ' ], [ ' radical-honesty ' , ' radical-honesty ' ], [ ' no-press-release-no-retraction ' , ' no-press-releas ' ], [ ' the-crackpot-offer ' , ' the-crackpot-of ' ], [ ' anchoring-and-adjustment ' , ' anchoring-and-a ' ], [ ' what-evidence-bad-arguments ' , ' what-evidence-b ' ], [ ' why-is-the-future-so-absurd ' , ' why-is-the-futu ' ], [ ' strength-to-doubt-or-believe ' , ' strength-to-dou ' ], [ ' availability ' , ' availability ' ], [ ' the-deniers-dilemna ' , ' the-deniers-con ' ], [ ' absurdity-heuristic-absurdity-bias ' , ' absurdity-heuri ' ], [ ' medical-quality-bias ' , ' medical-quality ' ], [ ' science-as-curiosity-stopper ' , ' science-as-curi ' ], [ ' basic-research-as-signal ' , ' basic-research ' ], [ ' ueuxplainuwuorshipuiugnore ' , ' explainworshipi ' ], [ ' the-pinch-hitter-syndrome-a-general-principle ' , ' the-pinch-hitte ' ], [ ' what-evidence-ease-of-imagination ' , ' what-evidence-e ' ], [ ' stranger-than-history ' , ' stranger-than-h ' ], [ ' bias-as-objectification-ii ' , ' bias-as-objecti ' ], [ ' open-thread ' , ' open-thread ' ], [ ' what-wisdom-tradition ' , ' what-wisdom-tra ' ], [ ' random-vs-certain-death ' , ' random-vs-certa ' ], [ ' who-told-you-moral-questions-would-be-easy ' , ' who-told-you-mo ' ], [ ' a-case-study-of-motivated-continuation ' , ' a-case-study-of ' ], [ ' double-or-nothing-lawsuits-ten-years-on ' , ' double-or-nothi ' ], [ ' torture-vs-dust-specks ' , ' torture-vs-dust ' ], [ ' college-choice-futures ' , ' college-choice ' ], [ ' motivated-stopping-and-motivated-continuation ' , ' motivated-stopp ' ], [ ' bay-area-bayesians-unite ' , ' meetup ' ], [ ' dan-kahneman-puzzles-with-us ' , ' dan-kahneman-pu ' ], [ ' why-are-individual-iq-differences-ok ' , ' why-is-individu ' ], [ ' if-not-data-what ' , ' if-not-data-wha ' ], [ ' no-one-knows-what-science-doesnt-know ' , ' no-one-knows-wh ' ], [ ' dennetts-special-pleading ' , ' special-pleadin ' ], [ ' double-illusion-of-transparency ' , ' double-illusion ' ], [ ' why-im-betting-on-the-red-sox ' , ' why-im-betting ' ], [ ' intrade-nominee-advice ' , ' intrade-nominee ' ], [ ' explainers-shoot-high-aim-low ' , ' explainers-shoo ' ], [ ' distrust-effect-names ' , ' distrust-effect ' ], [ ' the-fallacy-of-the-one-sided-bet-for-example-risk-god-torture-and-lottery-tickets ' , ' the-fallacy-of ' ], [ ' expecting-short-inferential-distances ' , ' inferential-dis ' ], [ ' marriage-futures ' , ' marriage-future ' ], [ ' self-anchoring ' , ' self-anchoring ' ], [ ' how-close-lifes-birth ' , ' how-close-lifes ' ], [ ' illusion-of-transparency-why-no-one-understands-you ' , ' illusion-of-tra ' ], [ ' a-valid-concern ' , ' a-valid-concern ' ], [ ' pascals-mugging-tiny-probabilities-of-vast-utilities ' , ' pascals-mugging ' ], [ ' should-we-simplify-ourselves ' , ' should-we-simpl ' ], [ ' hanson-joins-cult ' , ' hanson-joins-cu ' ], [ ' congratulations-to-paris-hilton ' , ' congratulations ' ], [ ' cut-us-military-in-half ' , ' cut-us-military ' ], [ ' cant-say-no-spending ' , ' cant-say-no-spe ' ], [ ' share-your-original-wisdom ' , ' original-wisdom ' ], [ ' buy-health-not-medicine ' , ' buy-health-not ' ], [ ' hold-off-on-proposing-solutions ' , ' hold-off-solvin ' ], [ ' doctors-kill ' , ' doctors-kill ' ], [ ' the-logical-fallacy-of-generalization-from-fictional-evidence ' , ' fictional-evide ' ], [ ' my-local-hospital ' , ' my-local-hospit ' ], [ ' how-to-seem-and-be-deep ' , ' how-to-seem-and ' ], [ ' megan-has-a-point ' , ' megan-has-a-poi ' ], [ ' original-seeing ' , ' original-seeing ' ], [ ' fatty-food-is-healthy ' , ' fatty-food-is-h ' ], [ ' the-outside-the-box-box ' , ' outside-the-box ' ], [ ' meta-honesty ' , ' meta-honesty ' ], [ ' cached-thoughts ' , ' cached-thoughts ' ], [ ' health-hopes-spring-eternal ' , ' health-hope-spr ' ], [ ' do-we-believe-ieverythingi-were-told ' , ' do-we-believe-e ' ], [ ' chinks-in-the-bayesian-armor ' , ' chinks-in-the-b ' ], [ ' priming-and-contamination ' , ' priming-and-con ' ], [ ' what-evidence-intuition ' , ' what-evidence-i ' ], [ ' a-priori ' , ' a-priori ' ], [ ' regulation-ratchet ' , ' what-evidence-b ' ], [ ' no-one-can-exempt-you-from-rationalitys-laws ' , ' its-the-law ' ], [ ' flexible-legal-similarity ' , ' flexible-legal ' ], [ ' singlethink ' , ' singlethink ' ], [ ' what-evidence-divergent-explanations ' , ' what-evidence-d ' ], [ ' the-meditation-on-curiosity ' , ' curiosity ' ], [ ' pleasant-beliefs ' , ' pleasant-belief ' ], [ ' isshoukenmei-make-a-desperate-effort ' , ' isshoukenmei-ma ' ], [ ' author-misreads-expert-re-crowds ' , ' author-misreads ' ], [ ' avoiding-your-beliefs-real-weak-points ' , ' avoiding-your-b ' ], [ ' got-crisis ' , ' got-crisis ' ], [ ' why-more-history-than-futurism ' , ' why-more-histor ' ], [ ' we-change-our-minds-less-often-than-we-think ' , ' we-change-our-m ' ], [ ' why-not-dating-coaches ' , ' why-not-dating ' ], [ ' a-rational-argument ' , ' a-rational-argu ' ], [ ' can-school-debias ' , ' can-education-d ' ], [ ' recommended-rationalist-reading ' , ' recommended-rat ' ], [ ' confession-errors ' , ' confession-erro ' ], [ ' open-thread ' , ' open-thread ' ], [ ' precious-silence-lost ' , ' precious-silenc ' ], [ ' leader-gender-bias ' , ' leader-gender-b ' ], [ ' the-halo-effect ' , ' halo-effect ' ], [ ' unbounded-scales-huge-jury-awards-futurism ' , ' unbounded-scale ' ], [ ' what-insight-literature ' , ' what-insight-li ' ], [ ' evaluability-and-cheap-holiday-shopping ' , ' evaluability ' ], [ ' the-affect-heuristic ' , ' affect-heuristi ' ], [ ' academia-clumps ' , ' academia-clumps ' ], [ ' purpose-and-pragmatism ' , ' purpose-and-pra ' ], [ ' lost-purposes ' , ' lost-purposes ' ], [ ' intrade-fee-structure-discourages-selling-the-tails ' , ' intrade-fee-str ' ], [ ' growing-into-atheism ' , ' growing-into-at ' ], [ ' the-hidden-complexity-of-wishes ' , ' complex-wishes ' ], [ ' aliens-among-us ' , ' aliens-among-us ' ], [ ' leaky-generalizations ' , ' leaky-generaliz ' ], [ ' good-intrade-bets ' , ' good-intrade-be ' ], [ ' not-for-the-sake-of-happiness-alone ' , ' not-for-the-sak ' ], [ ' interpreting-the-fed ' , ' interpreting-th ' ], [ ' merry-hallowthankmas-eve ' , ' merry-hallowmas ' ], [ ' truly-part-of-you ' , ' truly-part-of-y ' ], [ ' overcoming-bias-after-one-year ' , ' overcoming-bi-1 ' ], [ ' artificial-addition ' , ' artificial-addi ' ], [ ' publication-bias-and-the-death-penalty ' , ' publication-bia ' ], [ ' development-futures ' , ' development-fut ' ], [ ' conjuring-an-evolution-to-serve-you ' , ' conjuring-an-ev ' ], [ ' us-south-had-42-chance ' , ' us-south-had-42 ' ], [ ' towards-a-typology-of-bias ' , ' towards-a-typol ' ], [ ' the-simple-math-of-everything ' , ' the-simple-math ' ], [ ' my-guatemala-interviews ' , ' my-guatemala-in ' ], [ ' no-evolutions-for-corporations-or-nanodevices ' , ' no-evolution-fo ' ], [ ' inaturei-endorses-human-extinction ' , ' terrible-optimi ' ], [ ' evolving-to-extinction ' , ' evolving-to-ext ' ], [ ' dont-do-something ' , ' dont-do-somethi ' ], [ ' terminal-values-and-instrumental-values ' , ' terminal-values ' ], [ ' treatment-futures ' , ' treatment-futur ' ], [ ' thou-art-godshatter ' , ' thou-art-godsha ' ], [ ' implicit-conditionals ' , ' implicit-condit ' ], [ ' protein-reinforcement-and-dna-consequentialism ' , ' protein-reinfor ' ], [ ' polarized-usa ' , ' polarized-usa ' ], [ ' evolutionary-psychology ' , ' evolutionary-ps ' ], [ ' adaptation-executers-not-fitness-maximizers ' , ' adaptation-exec ' ], [ ' overcoming-bias-at-work-for-engineers ' , ' overcoming-bias ' ], [ ' fake-optimization-criteria ' , ' fake-optimizati ' ], [ ' dawes-on-therapy ' , ' dawes-on-psycho ' ], [ ' friendly-ai-guide ' , ' fake-utility-fu ' ], [ ' fake-morality ' , ' fake-morality ' ], [ ' seat-belts-work ' , ' seat-belts-work ' ], [ ' fake-selfishness ' , ' fake-selfishnes ' ], [ ' inconsistent-paternalism ' , ' inconsistent-pa ' ], [ ' the-tragedy-of-group-selectionism ' , ' group-selection ' ], [ ' are-the-self-righteous-righteous ' , ' are-the-self-ri ' ], [ ' beware-of-stephen-j-gould ' , ' beware-of-gould ' ], [ ' college-admission-futures ' , ' college-admissi ' ], [ ' natural-selections-speed-limit-and-complexity-bound ' , ' natural-selecti ' ], [ ' -a-test-for-political-prediction-markets ' , ' a-test-for-poli ' ], [ ' passionately-wrong ' , ' passionately-wr ' ], [ ' evolutions-are-stupid-but-work-anyway ' , ' evolutions-are ' ], [ ' serious-unconventional-de-grey ' , ' serious-unconve ' ], [ ' the-wonder-of-evolution ' , ' the-wonder-of-e ' ], [ ' hospice-beats-hospital ' , ' hospice-beats-h ' ], [ ' an-alien-god ' , ' an-alien-god ' ], [ ' open-thread ' , ' open-thread ' ], [ ' how-much-defer-to-experts ' , ' how-much-defer ' ], [ ' the-right-belief-for-the-wrong-reasons ' , ' the-right-belie ' ], [ ' fake-justification ' , ' fake-justificat ' ], [ ' a-terrifying-halloween-costume ' , ' a-terrifying-ha ' ], [ ' honest-teen-paternalism ' , ' teen-paternalis ' ], [ ' my-strange-beliefs ' , ' my-strange-beli ' ], [ ' cultish-countercultishness ' , ' cultish-counter ' ], [ ' to-lead-you-must-stand-up ' , ' stand-to-lead ' ], [ ' econ-of-longer-lives ' , ' neglected-pro-l ' ], [ ' lonely-dissent ' , ' lonely-dissent ' ], [ ' on-expressing-your-concerns ' , ' express-concern ' ], [ ' too-much-hope ' , ' too-much-hope ' ], [ ' aschs-conformity-experiment ' , ' aschs-conformit ' ], [ ' the-amazing-virgin-pregnancy ' , ' amazing-virgin ' ], [ ' procrastination ' , ' procrastination ' ], [ ' testing-hillary-clintons-oil-claim ' , ' testing-hillary ' ], [ ' zen-and-the-art-of-rationality ' , ' zen-and-the-art ' ], [ ' effortless-technique ' , ' effortless-tech ' ], [ ' false-laughter ' , ' false-laughter ' ], [ ' obligatory-self-mockery ' , ' obligatory-self ' ], [ ' the-greatest-gift-the-best-exercise ' , ' the-best-exerci ' ], [ ' two-cult-koans ' , ' cult-koans ' ], [ ' interior-economics ' , ' interior-econom ' ], [ ' politics-and-awful-art ' , ' politics-and-aw ' ], [ ' judgment-can-add-accuracy ' , ' judgment-can-ad ' ], [ ' the-litany-against-gurus ' , ' the-litany-agai ' ], [ ' the-root-of-all-political-stupidity ' , ' the-root-of-all ' ], [ ' guardians-of-ayn-rand ' , ' ayn-rand ' ], [ ' power-corrupts ' , ' power-corrupts ' ], [ ' teen-revolution-and-evolutionary-psychology ' , ' teen-revolution ' ], [ ' gender-tax ' , ' gender-tax ' ], -[ ' guardians-of-the-gene-pool ' , ' guardians-of--1 ' ], +[ ' guardians-of-the-gene-pool ' , ' guardians-of-1 ' ], [ ' battle-of-the-election-forecasters ' , ' battle-of-the-e ' ], [ ' guardians-of-the-truth ' , ' guardians-of-th ' ], [ ' hug-the-query ' , ' hug-the-query ' ], [ ' economist-judgment ' , ' economist-judgm ' ], [ ' justly-acquired-endowment-taxing-as-punishment-or-as-a-way-to-raise-money ' , ' justly-acquired ' ], [ ' argument-screens-off-authority ' , ' argument-screen ' ], [ ' give-juries-video-recordings-of-testimony ' , ' give-juries-vid ' ], [ ' reversed-stupidity-is-not-intelligence ' , ' reversed-stupid ' ], [ ' tax-the-tall ' , ' tax-the-tall ' ], [ ' every-cause-wants-to-be-a-cult ' , ' every-cause-wan ' ], [ ' does-healthcare-do-any-good-at-all ' , ' does-healthcare ' ], [ ' art-and-moral-responsibility ' , ' art-and-moral-r ' ], [ ' misc-meta ' , ' misc-meta ' ], [ ' it-is-good-to-exist ' , ' it-is-good-to-e ' ], [ ' the-robbers-cave-experiment ' , ' the-robbers-cav ' ], [ ' medicine-has-been-overcoming-bias-too ' , ' medicine-has-be ' ], [ ' when-none-dare-urge-restraint ' , ' when-none-dare ' ], [ ' modules-signals-and-guilt ' , ' modules-signals ' ], [ ' evaporative-cooling-of-group-beliefs ' , ' evaporative-coo ' ], [ ' doctor-hypocrisy ' , ' doctors-lie ' ], [ ' fake-utility-functions ' , ' fake-utility-fu ' ], [ ' open-thread ' , ' open-thread ' ], [ ' fake-fake-utility-functions ' , ' fake-fake-utili ' ], [ ' ethical-shortsightedness ' , ' ethical-shortsi ' ], [ ' heroic-job-bias ' , ' heroic-job-bias ' ], [ ' uncritical-supercriticality ' , ' supercritical-u ' ], [ ' resist-the-happy-death-spiral ' , ' resist-the-happ ' ], [ ' baby-selling ' , ' baby-selling ' ], [ ' affective-death-spirals ' , ' affective-death ' ], [ ' mere-messiahs ' , ' mere-messiahs ' ], [ ' superhero-bias ' , ' superhero-bias ' ], [ ' ob-meetup-millbrae-thu-21-feb-7pm ' , ' ob-meetup-millb ' ], [ ' newcombs-problem-and-regret-of-rationality ' , ' newcombs-proble ' ], [ ' dark-police ' , ' privacy-lost ' ], [ ' contingent-truth-value ' , ' contingent-trut ' ], [ ' deliberative-prediction-markets----a-reply ' , ' deliberative-pr ' ], [ ' something-to-protect ' , ' something-to-pr ' ], [ ' deliberation-in-prediction-markets ' , ' deliberation-in ' ], [ ' trust-in-bayes ' , ' trust-in-bayes ' ], [ ' predictocracy----a-preliminary-response ' , ' predictocracy ' ], [ ' the-intuitions-behind-utilitarianism ' , ' the-intuitions ' ], [ ' voters-want-simplicity ' , ' voters-want-sim ' ], [ ' predictocracy ' , ' predictocracy ' ], [ ' rationality-quotes-9 ' , ' quotes-9 ' ], [ ' knowing-your-argumentative-limitations-or-one-rationalists-modus-ponens-is-anothers-modus-tollens ' , ' knowing-your-ar ' ], [ ' problems-with-prizes ' , ' problems-with-p ' ], [ ' rationality-quotes-8 ' , ' quotes-8 ' ], [ ' acceptable-casualties ' , ' acceptable-casu ' ], [ ' rationality-quotes-7 ' , ' quotes-7 ' ], [ ' cfo-overconfidence ' , ' ceo-overconfide ' ], [ ' rationality-quotes-6 ' , ' quotes-6 ' ], [ ' rationality-quotes-5 ' , ' quotes-5 ' ], [ ' connections-versus-insight ' , ' connections-ver ' ], [ ' circular-altruism ' , ' circular-altrui ' ], [ ' for-discount-rates ' , ' protecting-acro ' ], [ ' against-discount-rates ' , ' against-discoun ' ], [ ' allais-malaise ' , ' allais-malaise ' ], [ ' mandatory-sensitivity-training-fails ' , ' mandatory-sensi ' ], [ ' rationality-quotes-4 ' , ' quotes-4 ' ], [ ' zut-allais ' , ' zut-allais ' ], [ ' the-allais-paradox ' , ' allais-paradox ' ], [ ' nesse-on-academia ' , ' nesse-on-academ ' ], [ ' antidepressant-publication-bias ' , ' antidepressant ' ], [ ' rationality-quotes-3 ' , ' rationality-quo ' ], [ ' rationality-quotes-2 ' , ' quotes-2 ' ], [ ' just-enough-expertise ' , ' trolls-on-exper ' ], [ ' rationality-quotes-1 ' , ' quotes-1 ' ], [ ' trust-in-math ' , ' trust-in-math ' ], [ ' economist-as-scrooge ' , ' economist-as-sc ' ], [ ' beautiful-probability ' , ' beautiful-proba ' ], [ ' leading-bias-researcher-turns-out-to-be-biased-renounces-result ' , ' leading-bias-re ' ], [ ' is-reality-ugly ' , ' is-reality-ugly ' ], [ ' dont-choose-a-president-the-way-youd-choose-an-assistant-regional-manager ' , ' dont-choose-a-p ' ], [ ' expecting-beauty ' , ' expecting-beaut ' ], [ ' how-to-fix-wage-bias ' , ' profit-by-corre ' ], [ ' beautiful-math ' , ' beautiful-math ' ], [ ' 0-and-1-are-not-probabilities ' , ' 0-and-1-are-not ' ], [ ' once-more-with-feeling ' , ' once-more-with ' ], [ ' political-inequality ' , ' political-inequ ' ], [ ' infinite-certainty ' , ' infinite-certai ' ], [ ' more-presidential-decision-markets ' , ' more-presidenti ' ], [ ' experiencing-the-endowment-effect ' , ' experiencing-th ' ], [ ' absolute-authority ' , ' absolute-author ' ], [ ' social-scientists-know-lots ' , ' social-scientis ' ], [ ' the-fallacy-of-gray ' , ' gray-fallacy ' ], [ ' are-we-just-pumping-against-entropy-or-can-we-win ' , ' are-we-just-pum ' ], [ ' art-trust-and-betrayal ' , ' art-trust-and-b ' ], [ ' nuked-us-futures ' , ' nuked-us-future ' ], [ ' but-theres-still-a-chance-right ' , ' still-a-chance ' ], [ ' a-failed-just-so-story ' , ' a-failed-just-s ' ], [ ' presidential-decision-markets ' , ' presidential-de ' ], [ ' open-thread ' , ' open-thread ' ], [ ' rational-vs-scientific-ev-psych ' , ' rational-vs-sci ' ], [ ' weekly-exercises ' , ' weekly-exercise ' ], [ ' yes-it-can-be-rational-to-vote-in-presidential-elections ' , ' yes-it-can-be-r ' ], [ ' debugging-comments ' , ' debugging-comme ' ], [ ' stop-voting-for-nincompoops ' , ' stop-voting-for ' ], [ ' i-dare-you-bunzl ' , ' in-yesterdays-p ' ], [ ' the-american-system-and-misleading-labels ' , ' the-american-sy ' ], [ ' some-structural-biases-of-the-political-system ' , ' some-structural ' ], [ ' a-politicians-job ' , ' a-politicians-j ' ], [ ' the-ordering-of-authors-names-in-academic-publications ' , ' the-ordering-of ' ], [ ' the-two-party-swindle ' , ' the-two-party-s ' ], [ ' posting-on-politics ' , ' posting-on-poli ' ], [ ' searching-for-bayes-structure ' , ' bayes-structure ' ], [ ' perpetual-motion-beliefs ' , ' perpetual-motio ' ], [ ' ignoring-advice ' , ' ignoring-advice ' ], [ ' the-second-law-of-thermodynamics-and-engines-of-cognition ' , ' second-law ' ], [ ' leave-a-line-of-retreat ' , ' leave-retreat ' ], [ ' more-referee-bias ' , ' more-referee-bi ' ], [ ' superexponential-conceptspace-and-simple-words ' , ' superexp-concep ' ], [ ' my-favorite-liar ' , ' my-favorite-lia ' ], [ ' mutual-information-and-density-in-thingspace ' , ' mutual-informat ' ], [ ' if-self-fulfilling-optimism-is-wrong-i-dont-wanna-be-right ' , ' if-self-fulfill ' ], [ ' entropy-and-short-codes ' , ' entropy-codes ' ], [ ' more-moral-wiggle-room ' , ' more-moral-wigg ' ], [ ' where-to-draw-the-boundary ' , ' where-boundary ' ], [ ' the-hawthorne-effect ' , ' the-hawthorne-e ' ], [ ' categories-and-information-theory ' , ' a-bayesian-view ' ], [ ' arguing-by-definition ' , ' arguing-by-defi ' ], [ ' against-polish ' , ' against-polish ' ], [ ' colorful-character-again ' , ' colorful-charac ' ], [ ' sneaking-in-connotations ' , ' sneak-connotati ' ], [ ' nephew-versus-nepal-charity ' , ' nephews-versus ' ], [ ' categorizing-has-consequences ' , ' category-conseq ' ], [ ' the-public-intellectual-plunge ' , ' the-public-inte ' ], [ ' fallacies-of-compression ' , ' compress-fallac ' ], [ ' with-blame-comes-hope ' , ' with-blame-come ' ], [ ' relative-vs-absolute-rationality ' , ' relative-vs-abs ' ], [ ' replace-the-symbol-with-the-substance ' , ' replace-symbol ' ], [ ' talking-versus-trading ' , ' comparing-delib ' ], [ ' taboo-your-words ' , ' taboo-words ' ], [ ' why-just-believe ' , ' why-just-believ ' ], [ ' classic-sichuan-in-millbrae-thu-feb-21-7pm ' , ' millbrae-thu-fe ' ], [ ' empty-labels ' , ' empty-labels ' ], [ ' is-love-something-more ' , ' is-love-somethi ' ], [ ' the-argument-from-common-usage ' , ' common-usage ' ], [ ' pod-people-paternalism ' , ' pod-people-pate ' ], [ ' feel-the-meaning ' , ' feel-meaning ' ], [ ' dinos-on-the-moon ' , ' dinos-on-the-mo ' ], [ ' disputing-definitions ' , ' disputing-defin ' ], [ ' what-is-worth-study ' , ' what-is-worth-s ' ], [ ' how-an-algorithm-feels-from-inside ' , ' algorithm-feels ' ], [ ' nanotech-views-value-driven ' , ' nanotech-views ' ], [ ' neural-categories ' , ' neural-categori ' ], [ ' believing-too-little ' , ' believing-too-l ' ], [ ' disguised-queries ' , ' disguised-queri ' ], [ ' eternal-medicine ' , ' eternal-medicin ' ], [ ' the-cluster-structure-of-thingspace ' , ' thingspace-clus ' ], [ ' typicality-and-asymmetrical-similarity ' , ' typicality-and ' ], [ ' what-wisdom-silence ' , ' what-wisdom-sil ' ], [ ' similarity-clusters ' , ' similarity-clus ' ], [ ' buy-now-or-forever-hold-your-peace ' , ' buy-now-or-fore ' ], [ ' extensions-and-intensions ' , ' extensions-inte ' ], [ ' lets-do-like-them ' , ' lets-do-like-th ' ], [ ' words-as-hidden-inferences ' , ' words-as-hidden ' ], [ ' predictocracy-vs-futarchy ' , ' predictocracy-v ' ], [ ' the-parable-of-hemlock ' , ' hemlock-parable ' ], [ ' merger-decision-markets ' , ' merger-decision ' ], [ ' open-thread ' , ' open-thread ' ], [ ' the-parable-of-the-dagger ' , ' dagger-parable ' ], [ ' futarchy-vs-predictocracy ' , ' futarchy-vs-pre ' ], [ ' against-news ' , ' against-news ' ], [ ' angry-atoms ' , ' angry-atoms ' ], [ ' hand-vs-fingers ' , ' hand-vs-fingers ' ], [ ' impotence-of-belief-in-bias ' , ' impotence-of-be ' ], [ ' initiation-ceremony ' , ' initiation-cere ' ], [ ' cash-increases-accuracy ' , ' cash-clears-the ' ], [ ' to-spread-science-keep-it-secret ' , ' spread-science ' ], [ ' ancient-political-self-deception ' , ' ancient-politic ' ], [ ' scarcity ' , ' scarcity ' ], [ ' fantasy-and-reality-substitutes-or-complements ' , ' fantasy-and-rea ' ], [ ' is-humanism-a-religion-substitute ' , ' is-humanism-rel ' ], [ ' showing-that-you-care ' , ' showing-that-yo ' ], [ ' amazing-breakthrough-day-april-1st ' , ' amazing-breakth ' ], [ ' correction-ny-ob-meetup-13-astor-place-25 ' , ' correction-ny-o ' ], [ ' religious-cohesion ' , ' religious-cohes ' ], [ ' the-beauty-of-settled-science ' , ' beauty-settled ' ], [ ' where-want-fewer-women ' , ' where-want-less ' ], [ ' new-york-ob-meetup-ad-hoc-on-monday-mar-24-6pm ' , ' new-york-ob-mee ' ], [ ' if-you-demand-magic-magic-wont-help ' , ' against-magic ' ], [ ' biases-in-processing-political-information ' , ' biases-in-proce ' ], [ ' bind-yourself-to-reality ' , ' bind-yourself-t ' ], [ ' boards-of-advisors-dont-advise-do-board ' , ' boards-of-advis ' ], [ ' joy-in-discovery ' , ' joy-in-discover ' ], [ ' joy-in-the-merely-real ' , ' joy-in-the-real ' ], [ ' sincerity-is-overrated ' , ' sincerity-is-wa ' ], [ ' rationalists-lets-make-a-movie ' , ' rationalists-le ' ], [ ' savanna-poets ' , ' savanna-poets ' ], [ ' biases-and-investing ' , ' biases-and-inve ' ], [ ' morality-is-overrated ' , ' unwanted-morali ' ], [ ' fake-reductionism ' , ' fake-reductioni ' ], [ ' theyre-only-tokens ' , ' theyre-only-tok ' ], [ ' explaining-vs-explaining-away ' , ' explaining-away ' ], [ ' reductionism ' , ' reductionism ' ], [ ' a-few-quick-links ' , ' a-few-quick-lin ' ], [ ' qualitatively-confused ' , ' qualitatively-c ' ], [ ' the-kind-of-project-to-watch ' , ' the-project-to ' ], [ ' penguicon-blook ' , ' penguicon-blook ' ], [ ' one-million-visits ' , ' one-million-vis ' ], [ ' distinguish-info-analysis-belief-action ' , ' distinguish-inf ' ], [ ' the-quotation-is-not-the-referent ' , ' quote-not-refer ' ], [ ' neglecting-conceptual-research ' , ' scott-aaronson ' ], [ ' probability-is-in-the-mind ' , ' mind-probabilit ' ], [ ' limits-to-physics-insight ' , ' limits-to-physi ' ], [ ' mind-projection-fallacy ' , ' mind-projection ' ], [ ' mind-projection-by-default ' , ' mpf-by-default ' ], [ ' uninformative-experience ' , ' uninformative-e ' ], [ ' righting-a-wrong-question ' , ' righting-a-wron ' ], [ ' wrong-questions ' , ' wrong-questions ' ], [ ' dissolving-the-question ' , ' dissolving-the ' ], [ ' bias-and-power ' , ' biased-for-and ' ], [ ' gary-gygax-annihilated-at-69 ' , ' gary-gygax-anni ' ], [ ' wilkinson-on-paternalism ' , ' wilkinson-on-pa ' ], [ ' 37-ways-that-words-can-be-wrong ' , ' wrong-words ' ], [ ' overvaluing-ideas ' , ' overvaluing-ide ' ], [ ' reject-random-beliefs ' , ' reject-random-b ' ], [ ' variable-question-fallacies ' , ' variable-questi ' ], [ ' rationality-quotes-11 ' , ' rationality-q-1 ' ], [ ' human-capital-puzzle-explained ' , ' human-capital-p ' ], [ ' rationality-quotes-10 ' , ' rationality-quo ' ], [ ' words-as-mental-paintbrush-handles ' , ' mental-paintbru ' ], [ ' open-thread ' , ' open-thread ' ], [ ' framing-problems-as-separate-from-people ' , ' framing-problem ' ], [ ' conditional-independence-and-naive-bayes ' , ' conditional-ind ' ], [ ' be-biased-to-be-happy ' , ' be-biased-to-be ' ], [ ' optimism-bias-desired ' , ' optimism-bias-d ' ], [ ' decoherent-essences ' , ' decoherent-esse ' ], [ ' self-copying-factories ' , ' replication-bre ' ], [ ' decoherence-is-pointless ' , ' pointless-decoh ' ], [ ' charm-beats-accuracy ' , ' charm-beats-acc ' ], [ ' the-conscious-sorites-paradox ' , ' conscious-sorit ' ], [ ' decoherent-details ' , ' decoherent-deta ' ], [ ' on-being-decoherent ' , ' on-being-decohe ' ], [ ' quantum-orthodoxy ' , ' quantum-quotes ' ], [ ' if-i-had-a-million ' , ' if-i-had-a-mill ' ], [ ' where-experience-confuses-physicists ' , ' where-experienc ' ], [ ' thou-art-decoherent ' , ' the-born-probab ' ], [ ' blaming-the-unlucky ' , ' blaming-the-unl ' ], [ ' where-physics-meets-experience ' , ' physics-meets-e ' ], [ ' early-scientists-chose-influence-over-credit ' , ' early-scientist ' ], [ ' which-basis-is-more-fundamental ' , ' which-basis-is ' ], [ ' a-model-disagreement ' , ' a-model-disagre ' ], [ ' the-so-called-heisenberg-uncertainty-principle ' , ' heisenberg ' ], [ ' caplan-pulls-along-ropes ' , ' caplan-pulls-al ' ], [ ' decoherence ' , ' decoherence ' ], [ ' paternalism-parable ' , ' paternalism-par ' ], [ ' three-dialogues-on-identity ' , ' identity-dialog ' ], [ ' on-philosophers ' , ' on-philosophers ' ], [ ' zombies-the-movie ' , ' zombie-movie ' ], [ ' schwitzgebel-thoughts ' , ' schwitzgebel-th ' ], [ ' identity-isnt-in-specific-atoms ' , ' identity-isnt-i ' ], [ ' elevator-myths ' , ' elevator-myths ' ], [ ' no-individual-particles ' , ' no-individual-p ' ], [ ' is-she-just-friendly ' , ' is-she-just-bei ' ], [ ' feynman-paths ' , ' feynman-paths ' ], [ ' kids-parents-disagree-on-spouses ' , ' kids-parents-di ' ], [ ' the-quantum-arena ' , ' quantum-arena ' ], [ ' classical-configuration-spaces ' , ' conf-space ' ], [ ' how-to-vs-what-to ' , ' how-to-vs-what ' ], [ ' can-you-prove-two-particles-are-identical ' , ' identical-parti ' ], [ ' naming-beliefs ' , ' naming-beliefs ' ], [ ' where-philosophy-meets-science ' , ' philosophy-meet ' ], [ ' distinct-configurations ' , ' distinct-config ' ], [ ' conformity-questions ' , ' conformity-ques ' ], [ ' conformity-myths ' , ' conformity-myth ' ], [ ' joint-configurations ' , ' joint-configura ' ], [ ' configurations-and-amplitude ' , ' configurations ' ], [ ' prevention-costs ' , ' prevention-cost ' ], [ ' quantum-explanations ' , ' quantum-explana ' ], [ ' inhuman-rationality ' , ' inhuman-rationa ' ], [ ' belief-in-the-implied-invisible ' , ' implied-invisib ' ], [ ' endearing-sincerity ' , ' sincerity-i-lik ' ], [ ' gazp-vs-glut ' , ' gazp-vs-glut ' ], [ ' the-generalized-anti-zombie-principle ' , ' anti-zombie-pri ' ], [ ' anxiety-about-what-is-true ' , ' anxiety-about-w ' ], [ ' ramone-on-knowing-god ' , ' ramone-on-knowi ' ], [ ' zombie-responses ' , ' zombies-ii ' ], [ ' brownlee-on-selling-anxiety ' , ' brownlee-on-sel ' ], [ ' zombies-zombies ' , ' zombies ' ], [ ' reductive-reference ' , ' reductive-refer ' ], [ ' arbitrary-silliness ' , ' arbitrary-silli ' ], [ ' brain-breakthrough-its-made-of-neurons ' , ' brain-breakthro ' ], [ ' open-thread ' , ' open-thread ' ], [ ' why-i-dont-like-bayesian-statistics ' , ' why-i-dont-like ' ], [ ' beware-of-brain-images ' , ' beware-of-brain ' ], [ ' heat-vs-motion ' , ' heat-vs-motion ' ], [ ' physics-your-brain-and-you ' , ' physics-your-br ' ], [ ' a-premature-word-on-ai ' , ' an-ai-new-timer ' ], [ ' ai-old-timers ' , ' roger-shank-ai ' ], [ ' empty-space ' , ' empty-space ' ], [ ' class-project ' , ' class-project ' ], [ ' einsteins-superpowers ' , ' einsteins-super ' ], [ ' intro-to-innovation ' , ' intro-to-innova ' ], [ ' timeless-causality ' , ' timeless-causal ' ], [ ' overconfidence-paternalism ' , ' paul-graham-off ' ], [ ' timeless-beauty ' , ' timeless-beauty ' ], [ ' lazy-lineup-study ' , ' why-is-this-so ' ], [ ' timeless-physics ' , ' timeless-physic ' ], [ ' the-end-of-time ' , ' the-end-of-time ' ], [ ' 2nd-annual-roberts-podcast ' , ' 2nd-annual-robe ' ], [ ' who-shall-we-honor ' , ' who-should-we-h ' ], [ ' relative-configuration-space ' , ' relative-config ' ], [ ' beware-identity ' , ' beware-identity ' ], [ ' prediction-markets-and-insider-trading ' , ' prediction-mark ' ], [ ' a-broken-koan ' , ' a-broken-koan ' ], [ ' machs-principle-anti-epiphenomenal-physics ' , ' machs-principle ' ], [ ' lying-to-kids ' , ' lying-to-kids ' ], [ ' my-childhood-role-model ' , ' my-childhood-ro ' ], [ ' that-alien-message ' , ' faster-than-ein ' ], [ ' anthropic-breakthrough ' , ' anthropic-break ' ], [ ' einsteins-speed ' , ' einsteins-speed ' ], [ ' transcend-or-die ' , ' transcend-or-di ' ], [ ' far-future-disagreement ' , ' far-future-disa ' ], [ ' faster-than-science ' , ' faster-than-sci ' ], [ ' conference-on-global-catastrophic-risks ' , ' conference-on-g ' ], [ ' biting-evolution-bullets ' , ' biting-evolutio ' ], [ ' changing-the-definition-of-science ' , ' changing-the-de ' ], [ ' no-safe-defense-not-even-science ' , ' no-defenses ' ], [ ' bounty-slander ' , ' bounty-slander ' ], [ ' idea-futures-in-lumpaland ' , ' idea-futures-in ' ], [ ' do-scientists-already-know-this-stuff ' , ' do-scientists-a ' ], [ ' lobbying-for-prediction-markets ' , ' lobbying-for-pr ' ], [ ' science-isnt-strict-ienoughi ' , ' science-isnt-st ' ], [ ' lumpaland-parable ' , ' lumpaland-parab ' ], [ ' when-science-cant-help ' , ' when-science-ca ' ], [ ' honest-politics ' , ' honest-politics ' ], [ ' science-doesnt-trust-your-rationality ' , ' science-doesnt ' ], [ ' sleepy-fools ' , ' sleepy-fools ' ], [ ' the-dilemma-science-or-bayes ' , ' science-or-baye ' ], [ ' the-failures-of-eld-science ' , ' eld-science ' ], [ ' condemned-to-repeat-finance-past ' , ' condemned-to-re ' ], [ ' many-worlds-one-best-guess ' , ' many-worlds-one ' ], [ ' why-quantum ' , ' why-quantum ' ], [ ' happy-conservatives ' , ' happy-conservat ' ], [ ' if-many-worlds-had-come-first ' , ' if-many-worlds ' ], [ ' elusive-placebos ' , ' elusive-placebo ' ], [ ' collapse-postulates ' , ' collapse-postul ' ], [ ' faith-in-docs ' , ' faith-in-docs ' ], [ ' quantum-non-realism ' , ' eppur-si-moon ' ], [ ' iexpelledi-beats-isickoi ' , ' expelled-beats ' ], [ ' decoherence-is-falsifiable-and-testable ' , ' mwi-is-falsifia ' ], [ ' guilt-by-association ' , ' guilt-and-all-b ' ], [ ' decoherence-is-simple ' , ' mwi-is-simple ' ], [ ' keeping-math-real ' , ' keeping-math-re ' ], [ ' spooky-action-at-a-distance-the-no-communication-theorem ' , ' spooky-action-a ' ], [ ' walking-on-grass-others ' , ' walking-on-gras ' ], [ ' bells-theorem-no-epr-reality ' , ' bells-theorem-n ' ], [ ' beware-transfusions ' , ' beware-blood-tr ' ], [ ' entangled-photons ' , ' entangled-photo ' ], [ ' beware-supplements ' , ' beware-suppleme ' ], [ ' decoherence-as-projection ' , ' projection ' ], [ ' open-thread ' , ' open-thread ' ], [ ' im-in-boston ' , ' im-in-boston ' ], [ ' the-born-probabilities ' , ' the-born-prob-1 ' ], [ ' experience-increases-overconfidence ' , ' the-latest-jour ' ], [ ' the-moral-void ' , ' moral-void ' ], [ ' what-would-you-do-without-morality ' , ' without-moralit ' ], [ ' average-your-guesses ' , ' average-your-gu ' ], [ ' the-opposite-sex ' , ' opposite-sex ' ], [ ' the-conversation-so-far ' , ' the-conversatio ' ], [ ' glory-vs-relations ' , ' glory-vs-relati ' ], [ ' 2-place-and-1-place-words ' , ' 2-place-and-1-p ' ], [ ' caution-kills-when-fighting-malaria ' , ' caution-kills-w ' ], [ ' to-what-expose-kids ' , ' to-what-expose ' ], [ ' no-universally-compelling-arguments ' , ' no-universally ' ], [ ' the-design-space-of-minds-in-general ' , ' minds-in-genera ' ], [ ' should-bad-boys-win ' , ' why-do-psychopa ' ], [ ' the-psychological-unity-of-humankind ' , ' psychological-u ' ], [ ' eliezers-meta-level-determinism ' , ' eliezers-meta-l ' ], [ ' optimization-and-the-singularity ' , ' optimization-an ' ], [ ' tyler-vid-on-disagreement ' , ' tyler-vid-on-di ' ], [ ' are-meta-views-outside-views ' , ' are-meta-views ' ], [ ' surface-analogies-and-deep-causes ' , ' surface-analogi ' ], [ ' parsing-the-parable ' , ' parsing-the-par ' ], [ ' the-outside-views-domain ' , ' when-outside-vi ' ], [ ' outside-view-of-singularity ' , ' singularity-out ' ], [ ' heading-toward-morality ' , ' toward-morality ' ], [ ' la-602-vs-rhic-review ' , ' la-602-vs-rhic ' ], [ ' history-of-transition-inequality ' , ' singularity-ine ' ], [ ' britain-was-too-small ' , ' britain-was-too ' ], [ ' natural-genocide ' , ' natural-genocid ' ], [ ' what-is-the-probability-of-the-large-hadron-collider-destroying-the-universe ' , ' what-is-the-pro ' ], [ ' ghosts-in-the-machine ' , ' ghosts-in-the-m ' ], [ ' gratitude-decay ' , ' gratitude-decay ' ], [ ' loud-bumpers ' , ' loud-bumpers ' ], [ ' grasping-slippery-things ' , ' grasping-slippe ' ], -[ ' in-bias-meta-is-max ' , ' meta-is-max---b ' ], +[ ' in-bias-meta-is-max ' , ' meta-is-max-b ' ], [ ' passing-the-recursive-buck ' , ' pass-recursive ' ], -[ ' in-innovation-meta-is-max ' , ' meta-is-max---i ' ], +[ ' in-innovation-meta-is-max ' , ' meta-is-max-i ' ], [ ' the-ultimate-source ' , ' the-ultimate-so ' ], [ ' possibility-and-could-ness ' , ' possibility-and ' ], [ ' joe-epstein-on-youth ' , ' joe-epstein-on ' ], [ ' causality-and-moral-responsibility ' , ' causality-and-r ' ], [ ' anti-depressants-fail ' , ' anti-depressant ' ], [ ' quantum-mechanics-and-personal-identity ' , ' qm-and-identity ' ], [ ' and-the-winner-is-many-worlds ' , ' mwi-wins ' ], [ ' quantum-physics-revealed-as-non-mysterious ' , ' quantum-physics ' ], [ ' an-intuitive-explanation-of-quantum-mechanics ' , ' an-intuitive-ex ' ], [ ' prediction-market-based-electoral-map-forecast ' , ' prediction-mark ' ], [ ' tv-is-porn ' , ' tv-is-porn ' ], [ ' the-quantum-physics-sequence ' , ' the-quantum-phy ' ], [ ' never-is-a-long-time ' , ' never-is-a-long ' ], [ ' eliezers-post-dependencies-book-notification-graphic-designer-wanted ' , ' eliezers-post-d ' ], [ ' anti-foreign-bias ' , ' tyler-in-the-ny ' ], [ ' against-devils-advocacy ' , ' against-devils ' ], [ ' the-future-of-oil-prices-3-nonrenewable-resource-pricing ' , ' the-future-of-o ' ], [ ' meetup-in-nyc-wed ' , ' meetup-in-nyc-w ' ], [ ' how-honest-with-kids ' , ' how-honest-with ' ], [ ' bloggingheads-yudkowsky-and-horgan ' , ' bloggingheads-y ' ], [ ' oil-scapegoats ' , ' manipulation-go ' ], [ ' timeless-control ' , ' timeless-contro ' ], [ ' how-to-add-2-to-gdp ' , ' how-to-increase ' ], [ ' thou-art-physics ' , ' thou-art-physic ' ], [ ' overcoming-disagreement ' , ' overcoming-disa ' ], [ ' living-in-many-worlds ' , ' living-in-many ' ], [ ' wait-for-it ' , ' wait-for-it ' ], [ ' why-quantum ' , ' why-quantum ' ], [ ' against-disclaimers ' , ' against-disclai ' ], [ ' timeless-identity ' , ' timeless-identi ' ], [ ' exploration-as-status ' , ' exploration-as ' ], [ ' principles-of-disagreement ' , ' principles-of-d ' ], [ ' the-rhythm-of-disagreement ' , ' the-rhythm-of-d ' ], [ ' open-thread ' , ' open-thread ' ], [ ' singularity-economics ' , ' economics-of-si ' ], [ ' detached-lever-fallacy ' , ' detached-lever ' ], [ ' ok-now-im-worried ' , ' ok-im-worried ' ], [ ' humans-in-funny-suits ' , ' humans-in-funny ' ], [ ' touching-vs-understanding ' , ' touching-vs-und ' ], [ ' intrades-conditional-prediction-markets ' , ' intrades-condit ' ], [ ' when-to-think-critically ' , ' when-to-think-c ' ], [ ' interpersonal-morality ' , ' interpersonal-m ' ], [ ' the-meaning-of-right ' , ' the-meaning-of ' ], [ ' funding-bias ' , ' funding-bias ' ], [ ' setting-up-metaethics ' , ' setting-up-meta ' ], [ ' bias-against-the-unseen ' , ' biased-against ' ], [ ' changing-your-metaethics ' , ' retreat-from-me ' ], [ ' is-ideology-about-status ' , ' is-ideology-abo ' ], [ ' gary-taubes-good-calories-bad-calories ' , ' gary-taubes-goo ' ], [ ' does-your-morality-care-what-you-think ' , ' does-morality-c ' ], [ ' refuge-markets ' , ' refuge-markets ' ], [ ' math-is-subjunctively-objective ' , ' math-is-subjunc ' ], [ ' can-counterfactuals-be-true ' , ' counterfactual ' ], [ ' when-not-to-use-probabilities ' , ' when-not-to-use ' ], [ ' banning-bad-news ' , ' banning-bad-new ' ], [ ' your-morality-doesnt-care-what-you-think ' , ' moral-counterfa ' ], [ ' fake-norms-or-truth-vs-truth ' , ' fake-norms-or-t ' ], [ ' loving-loyalty ' , ' loving-loyalty ' ], [ ' should-we-ban-physics ' , ' should-we-ban-p ' ], [ ' touching-the-old ' , ' touching-the-ol ' ], [ ' existential-angst-factory ' , ' existential-ang ' ], [ ' corporate-assassins ' , ' corporate-assas ' ], [ ' could-anything-be-right ' , ' anything-right ' ], [ ' doxastic-voluntarism-and-some-puzzles-about-rationality ' , ' doxastic-volunt ' ], [ ' disaster-bias ' , ' disaster-bias ' ], [ ' the-gift-we-give-to-tomorrow ' , ' moral-miracle-o ' ], [ ' world-welfare-state ' , ' world-welfare-s ' ], [ ' whither-moral-progress ' , ' whither-moral-p ' ], [ ' posting-may-slow ' , ' posting-may-slo ' ], [ ' bias-in-political-conversation ' , ' bias-in-politic ' ], [ ' lawrence-watt-evanss-fiction ' , ' lawrence-watt-e ' ], [ ' fear-god-and-state ' , ' fear-god-and-st ' ], [ ' probability-is-subjectively-objective ' , ' probability-is ' ], [ ' rebelling-within-nature ' , ' rebelling-withi ' ], [ ' ask-for-help ' , ' ask-for-help ' ], [ ' fundamental-doubts ' , ' fundamental-dou ' ], [ ' biases-of-elite-education ' , ' biases-of-elite ' ], [ ' the-genetic-fallacy ' , ' genetic-fallacy ' ], [ ' my-kind-of-reflection ' , ' my-kind-of-refl ' ], [ ' helsinki-meetup ' , ' helsinki-meetup ' ], [ ' poker-vs-chess ' , ' poker-vs-chess ' ], [ ' cloud-seeding-markets ' , ' cloud-seeding-m ' ], [ ' the-fear-of-common-knowledge ' , ' fear-of-ck ' ], [ ' where-recursive-justification-hits-bottom ' , ' recursive-justi ' ], [ ' artificial-volcanoes ' , ' artificial-volc ' ], [ ' cftc-event-market-comment ' , ' my-cftc-event-c ' ], [ ' will-as-thou-wilt ' , ' will-as-thou-wi ' ], [ ' rationalist-origin-stories ' , ' rationalist-ori ' ], [ ' all-hail-info-theory ' , ' all-hail-info-t ' ], [ ' morality-is-subjectively-objective ' , ' subjectively-ob ' ], [ ' bloggingheads-hanson-wilkinson ' , ' bloggingheads-m ' ], [ ' is-morality-given ' , ' is-morality-giv ' ], [ ' the-most-amazing-productivity-tip-ever ' , ' the-most-amazin ' ], [ ' is-morality-preference ' , ' is-morality-pre ' ], [ ' rah-my-country ' , ' yeah-my-country ' ], [ ' moral-complexities ' , ' moral-complexit ' ], [ ' 2-of-10-not-3-total ' , ' 2-of-10-not-3-t ' ], [ ' overconfident-investing ' , ' overconfident-i ' ], [ ' the-bedrock-of-fairness ' , ' bedrock-fairnes ' ], [ ' sex-nerds-and-entitlement ' , ' sex-nerds-and-e ' ], [ ' break-it-down ' , ' break-it-down ' ], [ ' why-argue-values ' , ' why-argue-value ' ], [ ' id-take-it ' , ' id-take-it ' ], [ ' distraction-overcomes-moral-hypocrisy ' , ' distraction-ove ' ], [ ' open-thread ' , ' open-thread ' ], [ ' overcoming-our-vs-others-biases ' , ' overcoming-our ' ], [ ' created-already-in-motion ' , ' moral-ponens ' ], [ ' morality-made-easy ' , ' morality-made-e ' ], [ ' brief-break ' , ' brief-break ' ], [ ' dreams-of-friendliness ' , ' dreams-of-frien ' ], [ ' fake-fish ' , ' fake-fish ' ], [ ' qualitative-strategies-of-friendliness ' , ' qualitative-str ' ], [ ' cowen-hanson-bloggingheads-topics ' , ' cowen-hanson-bl ' ], [ ' moral-false-consensus ' , ' moral-false-con ' ], [ ' harder-choices-matter-less ' , ' harder-choices ' ], [ ' the-complexity-critique ' , ' the-complexity ' ], [ ' against-modal-logics ' , ' against-modal-l ' ], [ ' top-teachers-ineffective ' , ' certified-teach ' ], [ ' dreams-of-ai-design ' , ' dreams-of-ai-de ' ], [ ' top-docs-no-healthier ' , ' top-school-docs ' ], [ ' three-fallacies-of-teleology ' , ' teleology ' ], [ ' use-the-native-architecture ' , ' use-the-native ' ], [ ' cowen-disses-futarchy ' , ' cowen-dises-fut ' ], [ ' magical-categories ' , ' magical-categor ' ], [ ' randomised-controlled-trials-of-parachutes ' , ' randomised-cont ' ], [ ' unnatural-categories ' , ' unnatural-categ ' ], [ ' good-medicine-in-merry-old-england ' , ' good-medicine-i ' ], [ ' mirrors-and-paintings ' , ' mirrors-and-pai ' ], [ ' beauty-bias ' , ' ignore-beauty ' ], [ ' invisible-frameworks ' , ' invisible-frame ' ], [ ' dark-dreams ' , ' dark-dreams ' ], [ ' no-license-to-be-human ' , ' no-human-licens ' ], [ ' are-ufos-aliens ' , ' are-ufos-aliens ' ], [ ' you-provably-cant-trust-yourself ' , ' no-self-trust ' ], [ ' caplan-gums-bullet ' , ' caplan-gums-bul ' ], [ ' dumb-deplaning ' , ' dumb-deplaning ' ], [ ' mundane-dishonesty ' , ' mundane-dishone ' ], [ ' the-cartoon-guide-to-lbs-theorem ' , ' lobs-theorem ' ], [ ' bias-in-real-life-a-personal-story ' , ' bias-in-real-li ' ], [ ' when-anthropomorphism-became-stupid ' , ' when-anthropomo ' ], [ ' hot-air-doesnt-disagree ' , ' hot-air-doesnt ' ], [ ' the-baby-eating-aliens-13 ' , ' baby-eaters ' ], [ ' manipulators-as-mirrors ' , ' manipulators-as ' ], [ ' the-bedrock-of-morality-arbitrary ' , ' arbitrary-bedro ' ], [ ' is-fairness-arbitrary ' , ' arbitrarily-fai ' ], [ ' self-indication-solves-time-asymmetry ' , ' self-indication ' ], [ ' schelling-and-the-nuclear-taboo ' , ' schelling-and-t ' ], [ ' arbitrary ' , ' unjustified ' ], [ ' new-best-game-theory ' , ' new-best-game-t ' ], [ ' abstracted-idealized-dynamics ' , ' computations ' ], [ ' future-altruism-not ' , ' future-altruism ' ], [ ' moral-error-and-moral-disagreement ' , ' moral-disagreem ' ], [ ' doctor-there-are-two-kinds-of-no-evidence ' , ' doctor-there-ar ' ], [ ' suspiciously-vague-lhc-forecasts ' , ' suspiciously-va ' ], [ ' sorting-pebbles-into-correct-heaps ' , ' pebblesorting-p ' ], [ ' the-problem-at-the-heart-of-pascals-wager ' , ' the-problem-at ' ], [ ' inseparably-right-or-joy-in-the-merely-good ' , ' rightness-redux ' ], [ ' baxters-ifloodi ' , ' baxters-flood ' ], [ ' morality-as-fixed-computation ' , ' morality-as-fix ' ], [ ' our-comet-ancestors ' , ' our-comet-ances ' ], [ ' hiroshima-day ' , ' hiroshima-day ' ], [ ' the-robots-rebellion ' , ' the-robots-rebe ' ], [ ' ignore-prostate-cancer ' , ' ignore-cancer ' ], [ ' contaminated-by-optimism ' , ' contaminated-by ' ], [ ' anthropology-patrons ' , ' anthropology-pa ' ], [ ' anthropomorphic-optimism ' , ' anthropomorph-1 ' ], [ ' now-im-scared ' , ' now-im-scared ' ], [ ' incomplete-analysis ' , ' incomplete-anal ' ], [ ' no-logical-positivist-i ' , ' no-logical-posi ' ], [ ' bias-against-some-types-of-foreign-wives ' , ' bias-against-so ' ], [ ' where-does-pascals-wager-fail ' , ' where-does-pasc ' ], [ ' the-comedy-of-behaviorism ' , ' behaviorism ' ], [ ' anthropomorphism-as-formal-fallacy ' , ' anthropomorphic ' ], [ ' variance-induced-test-bias ' , ' variance-induce ' ], [ ' a-genius-for-destruction ' , ' destructive-gen ' ], [ ' open-thread ' , ' open-thread ' ], [ ' the-magnitude-of-his-own-folly ' , ' it-was-pretty-b ' ], [ ' the-hope-premium ' , ' the-hope-premiu ' ], [ ' dangerous-species-warnings ' , ' species-protect ' ], [ ' friedmans-prediction-vs-explanation ' , ' friedmans-predi ' ], [ ' above-average-ai-scientists ' , ' above-average-s ' ], [ ' competent-elites ' , ' stratified-by-c ' ], [ ' bank-politics-is-not-about-bank-policy ' , ' bank-politics-i ' ], [ ' the-level-above-mine ' , ' level-above ' ], [ ' doable-green ' , ' saveable-nature ' ], [ ' give-it-to-me-straight-i-swear-i-wont-be-mad ' , ' give-it-to-me-s ' ], [ ' my-naturalistic-awakening ' , ' naturalistic-aw ' ], [ ' pundits-as-moles ' , ' pundits-as-mole ' ], [ ' fighting-a-rearguard-action-against-the-truth ' , ' fighting-a-rear ' ], [ ' white-swans-painted-black ' , ' white-swans-p-1 ' ], [ ' correcting-biases-once-youve-identified-them ' , ' correcting-bias ' ], [ ' that-tiny-note-of-discord ' , ' tiny-note-of-di ' ], [ ' noble-lies ' , ' noble-lies ' ], [ ' horrible-lhc-inconsistency ' , ' horrible-lhc-in ' ], [ ' certainty-effects-and-credit-default-swaps ' , ' certainty-effec ' ], [ ' politics-isnt-about-policy ' , ' politics-isnt-a ' ], [ ' how-many-lhc-failures-is-too-many ' , ' how-many-lhc-fa ' ], [ ' ban-the-bear ' , ' ban-the-bear ' ], [ ' say-it-loud ' , ' say-it-loud ' ], [ ' bad-news-ban-is-very-bad-news ' , ' bad-news-ban-is ' ], [ ' overconfidence-is-stylish ' , ' overconfidence ' ], [ ' the-sheer-folly-of-callow-youth ' , ' youth-folly ' ], [ ' isshoukenmei ' , ' isshoukenmei ' ], [ ' who-to-blame ' , ' who-to-blame ' ], [ ' a-prodigy-of-refutation ' , ' refutation-prod ' ], [ ' money-is-serious ' , ' money-frames ' ], [ ' raised-in-technophilia ' , ' raised-in-sf ' ], [ ' pharmaceutical-freedom-for-those-who-have-overcome-many-of-their-biases ' , ' pharmaceutical ' ], [ ' deafening-silence ' , ' deafening-silen ' ], [ ' my-best-and-worst-mistake ' , ' my-best-and-wor ' ], [ ' noble-abstention ' , ' noble-abstentio ' ], [ ' my-childhood-death-spiral ' , ' childhood-spira ' ], [ ' maturity-bias ' , ' maturity-bias ' ], [ ' serious-music ' , ' serious-music ' ], [ ' optimization ' , ' optimization ' ], [ ' beware-high-standards ' , ' beware-high-sta ' ], [ ' lemon-glazing-fallacy ' , ' lemon-glazing-f ' ], [ ' psychic-powers ' , ' psychic-powers ' ], [ ' immodest-caplan ' , ' immodest-caplan ' ], [ ' excluding-the-supernatural ' , ' excluding-the-s ' ], [ ' intelligent-design-honesty ' , ' intelligent-des ' ], [ ' rationality-quotes-17 ' , ' quotes-17 ' ], [ ' election-review-articles ' , ' election-review ' ], [ ' points-of-departure ' , ' points-of-depar ' ], [ ' guiltless-victims ' , ' guiltless-victi ' ], [ ' singularity-summit-2008 ' , ' singularity-sum ' ], [ ' spinspotter ' , ' spinspotter ' ], [ ' anyone-who-thinks-the-large-hadron-collider-will-destroy-the-world-is-a-tt ' , ' anyone-who-thin ' ], [ ' is-carbon-lost-cause ' , ' carbon-is-lost ' ], [ ' rationality-quotes-16 ' , ' quotes-16 ' ], [ ' aaronson-on-singularity ' , ' aaronson-on-sin ' ], [ ' rationality-quotes-15 ' , ' quotes-15 ' ], [ ' hating-economists ' , ' hating-economis ' ], [ ' rationality-quotes-14 ' , ' quotes-14 ' ], [ ' disagreement-is-disrespect ' , ' disagreement-is ' ], [ ' the-truly-iterated-prisoners-dilemma ' , ' iterated-tpd ' ], [ ' aping-insight ' , ' aping-insight ' ], [ ' the-true-prisoners-dilemma ' , ' true-pd ' ], [ ' mirrored-lives ' , ' mirrored-lives ' ], [ ' rationality-quotes-13 ' , ' rationality-quo ' ], [ ' risk-is-physical ' , ' risk-is-physica ' ], [ ' rationality-quotes-12 ' , ' rationality-q-1 ' ], [ ' open-thread ' , ' open-thread ' ], [ ' mundane-magic ' , ' mundane-magic ' ], [ ' fhi-emulation-roadmap-out ' , ' fhi-emulation-r ' ], [ ' porn-vs-romance-novels ' , ' porn-vs-romance ' ], [ ' intelligence-in-economics ' , ' intelligence-in ' ], [ ' does-intelligence-float ' , ' does-intelligen ' ], [ ' economic-definition-of-intelligence ' , ' economic-defini ' ], [ ' anti-edgy ' , ' anti-edgy ' ], [ ' efficient-cross-domain-optimization ' , ' efficient-cross ' ], [ ' wanting-to-want ' , ' wanting-to-want ' ], [ ' measuring-optimization-power ' , ' measuring-optim ' ], [ ' transparent-characters ' , ' transparent-cha ' ], [ ' aiming-at-the-target ' , ' aiming-at-the-t ' ], [ ' trust-us ' , ' trust-us ' ], [ ' quotes-from-singularity-summit-2008 ' , ' summit-quotes ' ], [ ' belief-in-intelligence ' , ' belief-in-intel ' ], [ ' expected-creative-surprises ' , ' expected-creati ' ], [ ' trust-but-dont-verify ' , ' trust-but-dont ' ], [ ' san-jose-meetup-sat-1025-730pm ' , ' san-jose-meetup ' ], [ ' inner-goodness ' , ' inner-morality ' ], [ ' obama-donors-as-news ' , ' donations-as-ne ' ], [ ' which-parts-are-me ' , ' which-parts-am ' ], [ ' if-you-snooze-you-lose ' , ' if-you-snooze-y ' ], [ ' ethics-notes ' , ' ethics-notes ' ], [ ' howard-stern-on-voter-rationalization ' , ' howard-stern-on ' ], [ ' prices-or-bindings ' , ' infinite-price ' ], [ ' toilets-arent-about-not-dying-of-disease ' , ' toilets-arent-a ' ], [ ' ethical-injunctions ' , ' ethical-injunct ' ], [ ' informed-voters-choose-worse ' , ' informed-voters ' ], [ ' ethical-inhibitions ' , ' ethical-inhibit ' ], [ ' protected-from-myself ' , ' protected-from ' ], [ ' last-post-requests ' , ' last-post-reque ' ], [ ' dark-side-epistemology ' , ' the-dark-side ' ], [ ' preventive-health-care ' , ' preventive-heal ' ], [ ' traditional-capitalist-values ' , ' traditional-cap ' ], [ ' us-help-red-china-revolt ' , ' us-aid-chinese ' ], [ ' entangled-truths-contagious-lies ' , ' lies-contagious ' ], [ ' conspiracys-uncanny-valley ' , ' conspiracys-unc ' ], [ ' ends-dont-justify-means-among-humans ' , ' ends-dont-justi ' ], [ ' why-voter-drives ' , ' why-voter-drive ' ], [ ' election-gambling-history ' , ' election-gambli ' ], [ ' why-does-power-corrupt ' , ' power-corrupts ' ], [ ' big-daddy-isnt-saving-you ' , ' big-daddy-isnt ' ], [ ' behold-our-ancestors ' , ' behold-our-ance ' ], [ ' rationality-quotes-19 ' , ' quotes-19 ' ], [ ' grateful-for-bad-news ' , ' grateful-for-ba ' ], [ ' the-ritual ' , ' the-question ' ], [ ' crisis-of-faith ' , ' got-crisis ' ], [ ' the-wire ' , ' the-wire ' ], [ ' ais-and-gatekeepers-unite ' , ' ais-and-gatekee ' ], [ ' bad-faith-voter-drives ' , ' weathersons-bad ' ], [ ' shut-up-and-do-the-impossible ' , ' shut-up-and-do ' ], [ ' academics-in-clown-suits ' , ' academics-in-cl ' ], [ ' gullibility-and-control ' , ' guilibility-and ' ], [ ' terror-politics-isnt-about-policy ' , ' terror-politics ' ], [ ' make-an-extraordinary-effort ' , ' isshokenmei ' ], [ ' more-deafening-silence ' , ' more-deafening ' ], [ ' on-doing-the-impossible ' , ' try-persevere ' ], [ ' bay-area-meetup-for-singularity-summit ' , ' bay-area-meetup ' ], [ ' insincere-cheers ' , ' football-lesson ' ], [ ' my-bayesian-enlightenment ' , ' my-bayesian-enl ' ], [ ' political-harassment ' , ' political-haras ' ], [ ' beyond-the-reach-of-god ' , ' beyond-god ' ], [ ' rationality-quotes-18 ' , ' rationality-quo ' ], [ ' equally-shallow-genders ' , ' equallly-shallo ' ], [ ' open-thread ' , ' open-thread ' ], [ ' political-parties-are-not-about-policy ' , ' political-parti ' ], [ ' use-the-try-harder-luke ' , ' use-the-try-har ' ], [ ' no-rose-colored-dating-glasses ' , ' no-rose-colored ' ], [ ' trying-to-try ' , ' trying-to-try ' ], [ ' intrade-and-the-dow-drop ' , ' intrade-and-the ' ], [ ' awww-a-zebra ' , ' awww-a-zebra ' ], [ ' singletons-rule-ok ' , ' singletons-rule ' ], [ ' total-tech-wars ' , ' total-tech-wars ' ], [ ' chaotic-inversion ' , ' chaotic-inversi ' ], [ ' luck-pessimism ' , ' luck-pessimism ' ], [ ' thanksgiving-prayer ' , ' thanksgiving-pr ' ], [ ' dreams-of-autarky ' , ' dreams-of-autar ' ], [ ' modern-depressions ' , ' modern-depressi ' ], [ ' total-nano-domination ' , ' nanotech-asplod ' ], [ ' beliefs-require-reasons-or-is-the-pope-catholic-should-he-be ' , ' beliefs-require ' ], [ ' engelbart-insufficiently-recursive ' , ' mouse-no-go-foo ' ], [ ' abstractdistant-future-bias ' , ' abstractdistant ' ], [ ' the-complete-idiots-guide-to-ad-hominem ' , ' the-complete-id ' ], [ ' physicists-held-to-lower-standard ' , ' physicists-held ' ], [ ' thinking-helps ' , ' thinking-helps ' ], [ ' recursion-magic ' , ' recursion-magic ' ], [ ' when-life-is-cheap-death-is-cheap ' , ' when-life-is-ch ' ], [ ' polisci-stats-biased ' , ' polisci-journal ' ], [ ' cascades-cycles-insight ' , ' cascades-cycles ' ], [ ' evicting-brain-emulations ' , ' suppose-that-ro ' ], [ ' are-you-dreaming ' , ' are-you-dreamin ' ], [ ' surprised-by-brains ' , ' brains ' ], [ ' the-second-swan ' , ' swan-2 ' ], [ ' billion-dollar-bots ' , ' billion-dollar ' ], [ ' brain-emulation-and-hard-takeoff ' , ' brain-emulation ' ], [ ' emulations-go-foom ' , ' emulations-go-f ' ], [ ' lifes-story-continues ' , ' the-age-of-nonr ' ], [ ' observing-optimization ' , ' observing-optim ' ], [ ' ai-go-foom ' , ' ai-go-foom ' ], [ ' whence-your-abstractions ' , ' abstractions-re ' ], [ ' abstraction-not-analogy ' , ' abstraction-vs ' ], [ ' the-first-world-takeover ' , ' 1st-world-takeo ' ], [ ' setting-the-stage ' , ' setting-the-sta ' ], [ ' cheap-wine-tastes-fine ' , ' cheap-wine-tast ' ], [ ' animal-experimentation-morally-acceptable-or-just-the-way-things-always-have-been ' , ' animal-experime ' ], [ ' the-weak-inside-view ' , ' the-weak-inside ' ], [ ' convenient-overconfidence ' , ' convenient-over ' ], [ ' loud-subtext ' , ' loud-subtext ' ], [ ' failure-by-affective-analogy ' , ' affective-analo ' ], [ ' failure-by-analogy ' , ' failure-by-anal ' ], [ ' whither-ob ' , ' whither-ob ' ], [ ' all-are-skill-unaware ' , ' all-are-unaware ' ], [ ' logical-or-connectionist-ai ' , ' logical-or-conn ' ], [ ' friendliness-factors ' , ' friendliness-fa ' ], [ ' boston-area-meetup-111808-9pm-mitcambridge ' , ' boston-area-mee ' ], [ ' positive-vs-optimal ' , ' positive-vs-opt ' ], [ ' friendly-teams ' , ' englebart-not-r ' ], [ ' the-nature-of-logic ' , ' first-order-log ' ], [ ' diamond-palace-survive ' , ' whether-diamond ' ], [ ' selling-nonapples ' , ' selling-nonappl ' ], [ ' engelbart-as-ubertool ' , ' engelbarts-uber ' ], [ ' bay-area-meetup-1117-8pm-menlo-park ' , ' bay-area-meetup ' ], [ ' the-weighted-majority-algorithm ' , ' the-weighted-ma ' ], [ ' fund-ubertool ' , ' fund-ubertool ' ], [ ' worse-than-random ' , ' worse-than-rand ' ], [ ' conformity-shows-loyalty ' , ' conformity-show ' ], [ ' incompetence-vs-self-interest ' , ' incompetence-vs ' ], [ ' lawful-uncertainty ' , ' lawful-uncertai ' ], [ ' what-belief-conformity ' , ' what-conformity ' ], [ ' ask-ob-leaving-the-fold ' , ' leaving-the-fol ' ], [ ' depressed-inoti-more-accurate ' , ' depressed-not-m ' ], [ ' lawful-creativity ' , ' lawful-creativi ' ], [ ' visionary-news ' , ' visionary-news ' ], [ ' recognizing-intelligence ' , ' recognizing-int ' ], [ ' equal-cheats ' , ' equal-cheats ' ], [ ' back-up-and-ask-whether-not-why ' , ' back-up-and-ask ' ], [ ' beware-i-believe ' , ' beware-i-believ ' ], [ ' hanging-out-my-speakers-shingle ' , ' now-speaking ' ], [ ' disagreement-debate-status ' , ' disagreement-de ' ], [ ' beware-the-prescient ' , ' beware-the-pres ' ], [ ' todays-inspirational-tale ' , ' todays-inspirat ' ], [ ' the-evil-pleasure ' , ' evil-diversity ' ], [ ' complexity-and-intelligence ' , ' complexity-and ' ], [ ' building-something-smarter ' , ' building-someth ' ], [ ' open-thread ' , ' open-thread ' ], [ ' bhtv-jaron-lanier-and-yudkowsky ' , ' jaron-lanier-an ' ], [ ' a-new-day ' , ' a-new-day ' ], [ ' against-interesting-details ' , ' against-interesting-presentations ' ], [ ' dunbars-function ' , ' dunbars-function ' ], [ ' amputation-of-destiny ' , ' theft-of-destiny ' ], [ ' the-meta-human-condition ' , ' the-metahuman-condition ' ], [ ' it-is-simply-no-longer-possible-to-believe ' , ' it-is-simply-no-longer-possible-to-believe ' ], [ ' friendship-is-relative ' , ' friendship-is-relative ' ], [ ' cant-unbirth-a-child ' , ' no-unbirthing ' ], [ ' nonsentient-bloggers ' , ' nonsentient-bloggers ' ], [ ' nonsentient-optimizers ' , ' unpersons ' ], [ ' nonperson-predicates ' , ' model-citizens ' ], [ ' alien-bad-guy-bias ' , ' alien-bad-guy-bias ' ], [ ' devils-offers ' , ' devils-offers ' ], [ ' harmful-options ' , ' harmful-options ' ], [ ' the-longshot-bias ' , ' the-longshot-bias ' ], [ ' imaginary-positions ' , ' imaginary-positions ' ], [ ' coherent-futures ' , ' coherent-futures ' ], [ ' rationality-quotes-20 ' , ' quotes-20 ' ], [ ' no-overconfidence ' , ' no-overconfidence ' ], [ ' show-off-bias ' , ' showoff-bias ' ], [ ' living-by-your-own-strength ' , ' by-your-own-strength ' ], [ ' sensual-experience ' , ' sensual-experience ' ], [ ' presuming-bets-are-bad ' , ' presuming-bets-are-bad ' ], [ ' futarchy-is-nyt-buzzword-of-08 ' , ' futarchy-is-nyt-buzzword-of-08 ' ], [ ' experts-are-for-certainty ' , ' experts-are-for-certainty ' ], [ ' complex-novelty ' , ' complex-novelty ' ], [ ' high-challenge ' , ' high-challenge ' ], [ ' weak-social-theories ' , ' weak-social-theories ' ], [ ' christmas-signaling ' , ' christmas-signaling ' ], [ ' prolegomena-to-a-theory-of-fun ' , ' fun-theory ' ], [ ' the-right-thing ' , ' the-right-thing ' ], [ ' who-cheers-the-referee ' , ' who-cheers-the-referee ' ], [ ' visualizing-eutopia ' , ' visualizing-eutopia ' ], [ ' ill-think-of-a-reason-later ' , ' ill-think-of-a-reason-later ' ], [ ' utopia-unimaginable ' , ' utopia-vs-eutopia ' ], [ ' tyler-on-cryonics ' , ' tyler-on-cryonics ' ], [ ' not-taking-over-the-world ' , ' not-taking-over ' ], [ ' entrepreneurs-are-not-overconfident ' , ' entrepreneurs-are-not-overconfident ' ], [ ' distrusting-drama ' , ' types-of-distru ' ], [ ' for-the-people-who-are-still-alive ' , ' who-are-still-alive ' ], [ ' trade-with-the-future ' , ' trade-with-the-future ' ], [ ' bhtv-de-grey-and-yudkowsky ' , ' bhtv-de-grey-and-yudkowsky ' ], [ ' hated-because-it-might-work ' , ' hated-because-it-might-work ' ], [ ' cryonics-is-cool ' , ' cryonics-is-cool ' ], [ ' you-only-live-twice ' , ' you-only-live-twice ' ], [ ' we-agree-get-froze ' , ' we-agree-get-froze ' ], [ ' what-i-think-if-not-why ' , ' what-i-think ' ], [ ' what-core-argument ' , ' what-core-argument ' ], [ ' a-vision-of-precision ' , ' a-vision-of-pre ' ], [ ' the-linear-scaling-error ' , ' the-linear-scal ' ], [ ' the-mechanics-of-disagreement ' , ' the-mechanics-o ' ], [ ' two-visions-of-heritage ' , ' two-visions-of ' ], [ ' bay-area-meetup-wed-1210-8pm ' , ' bay-area-meetup ' ], [ ' are-ais-homo-economicus ' , ' are-ais-homo-ec ' ], [ ' disjunctions-antipredictions-etc ' , ' disjunctions-an ' ], [ ' the-bad-guy-bias ' , ' the-bad-guy-bia ' ], [ ' true-sources-of-disagreement ' , ' true-sources-of ' ], [ ' us-tv-censorship ' , ' us-tv-censorshi ' ], [ ' wrapping-up ' , ' wrapping-up ' ], [ ' artificial-mysterious-intelligence ' , ' artificial-myst ' ], [ ' incommunicable-meta-insight ' , ' incommunicable ' ], [ ' false-false-dichotomies ' , ' false-false-dic ' ], [ ' shared-ai-wins ' , ' shared-ai-wins ' ], [ ' is-that-your-true-rejection ' , ' your-true-rejec ' ], [ ' friendly-projects-vs-products ' , ' friendly-projec ' ], [ ' sustained-strong-recursion ' , ' sustained-recur ' ], [ ' recursive-mind-designers ' , ' recursive-mind ' ], [ ' evolved-desires ' , ' evolved-desires ' ], [ ' gas-arbitrage ' , ' gas-artibrage ' ], [ ' -eternal-inflation-and-the-probability-that-you-are-living-in-a-computer-simulation ' , ' eternal-inflati ' ], [ ' drexler-blogs ' , ' drexler-blogs ' ], [ ' beware-hockey-stick-plans ' , ' beware-hockey-s ' ], [ ' underconstrained-abstractions ' , ' underconstraine ' ], [ ' rationality-of-voting-etc ' , ' rationality-of ' ], [ ' permitted-possibilities-locality ' , ' permitted-possi ' ], [ ' the-hypocrisy-charge-bias ' , ' the-hypocrisy-c ' ], [ ' test-near-apply-far ' , ' test-near-apply ' ], [ ' hard-takeoff ' , ' hard-takeoff ' ], [ ' voting-kills ' , ' voting-kills ' ], [ ' whither-manufacturing ' , ' whither-manufac ' ], [ ' recursive-self-improvement ' , ' recursive-self ' ], [ ' open-thread ' , ' open-thread ' ], [ ' i-heart-cyc ' , ' i-heart-cyc ' ], [ ' disappointment-in-the-future ' , ' disappointment ' ], [ ' stuck-in-throat ' , ' stuck-in-throat ' ], [ ' war-andor-peace-28 ' , ' war-andor-peace ' ], [ ' the-baby-eating-aliens-18 ' , ' the-babyeating-aliens ' ], [ ' three-worlds-collide-08 ' , ' three-worlds-collide ' ], [ ' dreams-as-evidence ' , ' dreams-as-evidence ' ], [ ' institution-design-is-like-martial-arts ' , ' why-market-economics-is-like-martial-arts ' ], [ ' academic-ideals ' , ' academic-ideals ' ], [ ' value-is-fragile ' , ' fragile-value ' ], [ ' roberts-bias-therapy ' , ' roberts-bias-therapy ' ], [ ' rationality-quotes-25 ' , ' quotes-25 ' ], [ ' different-meanings-of-bayesian-statistics ' , ' different-meanings-of-bayesian-statistics ' ], [ ' ob-status-update ' , ' ob-status-update ' ], [ ' 31-laws-of-fun ' , ' fun-theory-laws ' ], [ ' bhtv-yudkowsky-wilkinson ' , ' bhtv-yudkowsky-wilkinson ' ], [ ' the-fun-theory-sequence ' , ' fun-theory-sequence ' ], [ ' avoid-vena-cava-filters ' , ' avoid-vena-cava-filters ' ], [ ' rationality-quotes-24 ' , ' quotes-24 ' ], [ ' higher-purpose ' , ' higher-purpose ' ], [ ' investing-for-the-long-slump ' , ' the-long-slump ' ], [ ' tribal-biases-and-the-inauguration ' , ' tribal-biases-and-the-inauguration ' ], [ ' who-likes-what-movies ' , ' who-likes-what-movies ' ], [ ' failed-utopia-4-2 ' , ' failed-utopia-42 ' ], [ ' sunnyvale-meetup-saturday ' , ' bay-area-meetup-saturday ' ], [ ' set-obamas-bar ' , ' set-obamas-bar ' ], [ ' interpersonal-entanglement ' , ' no-catgirls ' ], [ ' predictible-fakers ' , ' predictible-fakers ' ], [ ' sympathetic-minds ' , ' sympathetic-minds ' ], [ ' the-surprising-power-of-rote-cognition ' , ' the-surprising-power-of-rote-cognition ' ], [ ' in-praise-of-boredom ' , ' boredom ' ], [ ' beware-detached-detail ' , ' beware-detached-detail ' ], [ ' getting-nearer ' , ' getting-nearer ' ], [ ' a-tale-of-two-tradeoffs ' , ' a-tale-of-two-tradeoffs ' ], [ ' seduced-by-imagination ' , ' souleating-dreams ' ], [ ' data-on-fictional-lies ' , ' new-data-on-fiction ' ], [ ' justified-expectation-of-pleasant-surprises ' , ' vague-hopes ' ], [ ' disagreement-is-near-far-bias ' , ' disagreement-is-nearfar-bias ' ], [ ' ishei-has-joined-the-conspiracy ' , ' kimiko ' ], [ ' building-weirdtopia ' , ' weirdtopia ' ], [ ' eutopia-is-scary ' , ' scary-eutopia ' ],
isiri/wordpress_import
ce081c59893f6ec616c3a01d50b0e410d2864ac1
url mapping fixes
diff --git a/url_mapping.rb b/url_mapping.rb index 7613419..841dd4f 100755 --- a/url_mapping.rb +++ b/url_mapping.rb @@ -1,1351 +1,1351 @@ def url_mapping_arr [ [ ' macro-shares-prediction-markets-via-stock-exchanges ' , ' macro_shares_pr ' ], [ ' thank-you-maam-may-i-have-another ' , ' thank_you_maam_ ' ], [ ' beware-of-disagreeing-with-lewis ' , ' beware_of_disag ' ], [ ' incautious-defense-of-bias ' , ' incautious_defe ' ], [ ' pascalian-meditations ' , ' pascalian_medit ' ], [ ' are-the-big-four-econ-errors-biases ' , ' the_big_four_ec ' ], [ ' surprisingly-friendly-suburbs ' , ' surprisingly_fr ' ], [ ' beware-amateur-science-history ' , ' beware_amateur_ ' ], [ ' whats-a-bias-again ' , ' whats_a_bias_ag ' ], [ ' why-truth-and ' , ' why_truth_and ' ], [ ' asymmetric-paternalism ' , ' asymmetric_pate ' ], [ ' to-the-barricades-against-what-exactly ' , ' to_the_barricad ' ], [ ' foxes-vs-hedgehogs-predictive-success ' , ' foxes_vs_hedgho ' ], [ ' follow-the-crowd ' , ' follow_the_crow ' ], [ ' what-exactly-is-bias ' , ' what_exactly_is ' ], [ ' moral-overconfidence ' , ' moral_hypocricy ' ], [ ' why-are-academics-liberal ' , ' the_cause_of_is ' ], [ ' a-1990-corporate-prediction-market ' , ' first_known_bus ' ], [ ' the-martial-art-of-rationality ' , ' the_martial_art ' ], [ ' beware-heritable-beliefs ' , ' beware_heritabl ' ], [ ' the-wisdom-of-bromides ' , ' the_wisdom_of_b ' ], [ ' the-movie-click ' , ' click_christmas ' ], [ ' quiz-fox-or-hedgehog ' , ' quiz_fox_or_hed ' ], [ ' hide-sociobiology-like-sex ' , ' does_sociobiolo ' ], [ ' how-to-join ' , ' introduction ' ], [ ' normative-bayesianism-and-disagreement ' , ' normative_bayes ' ], [ ' vulcan-logic ' , ' vulcan_logic ' ], [ ' benefit-of-doubt-bias ' , ' benefit_of_doub ' ], [ ' see-but-dont-believe ' , ' see_but_dont_be ' ], [ ' the-future-of-oil-prices-2-option-probabilities ' , ' the_future_of_o_1 ' ], [ ' resolving-your-hypocrisy ' , ' resolving_your_ ' ], [ ' academic-overconfidence ' , ' academic_overco ' ], [ ' gnosis ' , ' gnosis ' ], [ ' ads-that-hurt ' , ' ads_that_hurt ' ], [ ' gifts-hurt ' , ' gifts_hurt ' ], [ ' advertisers-vs-teachers-ii ' , ' advertisers_vs_ ' ], [ ' why-common-priors ' , ' why_common_prio ' ], [ ' the-future-of-oil-prices ' , ' the_future_of_o ' ], [ ' a-fable-of-science-and-politics ' , ' a_fable_of_scie ' ], [ ' a-christmas-gift-for-rationalists ' , ' a_christmas_gif ' ], [ ' when-truth-is-a-trap ' , ' when_truth_is_a ' ], [ ' you-will-age-and-die ' , ' you_will_age_an ' ], [ ' contributors-be-half-accessible ' , ' contributors_be ' ], [ ' i-dont-know ' , ' i_dont_know ' ], [ ' you-are-never-entitled-to-your-opinion ' , ' you_are_never_e ' ], [ ' a-decent-respect ' , ' a_decent_respec ' ], [ ' why-not-impossible-worlds ' , ' why_not_impossi ' ], [ ' modesty-in-a-disagreeable-world ' , ' modesty_in_a_di ' ], [ ' to-win-press-feign-surprise ' , ' to_win_press_fe ' ], [ ' advertisers-vs-teachers ' , ' suppose_that_co ' ], [ ' when-error-is-high-simplify ' , ' when_error_is_h ' ], [ ' finding-the-truth-in-controversies ' , ' finding_the_tru ' ], [ ' bias-in-christmas-shopping ' , ' bias_in_christm ' ], [ ' does-the-modesty-argument-apply-to-moral-claims ' , ' does_the_modest ' ], [ ' philosophers-on-moral-bias ' , ' philosophers_on ' ], [ ' meme-lineages-and-expert-consensus ' , ' meme_lineages_a ' ], [ ' the-conspiracy-against-cuckolds ' , ' the_conspiracy_ ' ], [ ' malatesta-estimator ' , ' malatesta_estim ' ], [ ' fillers-neglect-framers ' , ' fillers_neglect ' ], [ ' the-80-forecasting-solution ' , ' the_80_forecast ' ], [ ' ignorance-of-frankenfoods ' , ' ignorance_of_fr ' ], [ ' do-helping-professions-help-more ' , ' do_helping_prof ' ], [ ' should-prediction-markets-be-charities ' , ' should_predicti ' ], [ ' we-are-smarter-than-me ' , ' we_are_smarter_ ' ], [ ' law-as-no-bias-theatre ' , ' law_as_nobias_t ' ], [ ' the-modesty-argument ' , ' the_modesty_arg ' ], [ ' agreeing-to-agree ' , ' agreeing_to_agr ' ], [ ' time-on-risk ' , ' time_on_risk ' ], [ ' leamers-1986-idea-futures-proposal ' , ' leamers_1986_id ' ], [ ' alas-amateur-futurism ' , ' alas_amateur_fu ' ], [ ' the-wisdom-of-crowds ' , ' the_wisdom_of_c ' ], [ ' reasonable-disagreement ' , ' reasonable_disa ' ], [ ' math-zero-vs-political-zero ' , ' math_zero_vs_po ' ], [ ' bosses-prefer-overconfident-managers ' , ' bosses_prefer_o ' ], [ ' seen-vs-unseen-biases ' , ' seen_vs_unseen_ ' ], [ ' future-selves ' , ' future_selves ' ], [ ' does-profit-rate-insight-best ' , ' does_profit_rat ' ], [ ' bias-well-being-and-the-placebo-effect ' , ' bias_wellbeing_ ' ], [ ' biases-of-science-fiction ' , ' biases_of_scien ' ], [ ' the-proper-use-of-humility ' , ' the_proper_use_ ' ], [ ' the-onion-on-bias-duh ' , ' the_onion_on_bi ' ], [ ' prizes-versus-grants ' , ' prizes_versus_g ' ], [ ' wanted-a-meta-poll ' , ' wanted_a_metapo ' ], [ ' excess-signaling-example ' , ' excess_signalin ' ], [ ' rationalization ' , ' rationalization ' ], [ ' against-admirable-activities ' , ' against_admirab ' ], [ ' effects-of-ideological-media-persuasion ' , ' effects_of_ideo ' ], [ ' whats-the-right-rule-for-a-juror ' , ' whats_the_right ' ], [ ' galt-on-abortion-and-bias ' , ' galt_on_abortio ' ], [ ' -the-procrastinators-clock ' , ' the_procrastina ' ], [ ' keeping-score ' , ' keeping_score ' ], [ ' agree-with-young-duplicate ' , ' agree_with_your ' ], [ ' sick-of-textbook-errors ' , ' sick_of_textboo ' ], [ ' manipulating-jury-biases ' , ' manipulating_ju ' ], [ ' what-insight-in-innocence ' , ' what_insight_in ' ], [ ' on-policy-fact-experts-ignore-facts ' , ' on_policy_fact_ ' ], [ ' the-butler-did-it-of-course ' , ' the_butler_did_ ' ], [ ' no-death-of-a-buyerman ' , ' no_death_of_a_b ' ], [ ' is-there-such-a-thing-as-bigotry ' , ' is_there_such_a ' ], [ ' moby-dick-seeks-thee-not ' , ' moby_dick_seeks ' ], [ ' morale-markets-vs-decision-markets ' , ' morale_markets_ ' ], [ ' follow-your-passion-from-a-distance ' , ' follow_your_pas ' ], [ ' a-model-of-extraordinary-claims ' , ' a_model_of_extr ' ], [ ' socially-influenced-beliefs ' , ' socially_influe ' ], [ ' agree-with-yesterdays-duplicate ' , ' agree_with_yest ' ], [ ' outside-the-laboratory ' , ' outside_the_lab ' ], [ ' symmetry-is-not-pretty ' , ' symmetry_is_not ' ], [ ' some-claims-are-just-too-extraordinary ' , ' some_claims_are ' ], [ ' womens-mathematical-abilities ' , ' womens_mathemat ' ], [ ' benefits-of-cost-benefit-analyis ' , ' benefits_of_cos ' ], [ ' godless-professors ' , ' godless_profess ' ], [ ' how-to-not-spend-money ' , ' suppose_youre_a ' ], [ ' sometimes-the-facts-are-irrelevant ' , ' sometimes_the_f ' ], [ ' extraordinary-claims-are-extraordinary-evidence ' , ' extraordinary_c ' ], [ ' ' , ' in_a_recent_pos ' ], [ ' 70-for-me-30-for-you ' , ' 70_for_me_30_fo ' ], [ ' some-people-just-wont-quit ' , ' some_people_jus ' ], [ ' statistical-discrimination-is-probably-bad ' , ' statistical_dis ' ], [ ' costbenefit-analysis ' , ' costbenefit_ana ' ], [ ' smoking-warning-labels ' , ' smoking_warning ' ], [ ' conclusion-blind-review ' , ' conclusionblind ' ], [ ' is-more-information-always-better ' , ' is_more_informa ' ], [ ' should-we-defer-to-secret-evidence ' , ' should_we_defer ' ], [ ' peaceful-speculation ' , ' peaceful_specul ' ], [ ' supping-with-the-devil ' , ' supping_with_th ' ], [ ' disagree-with-suicide-rock ' , ' disagree_with_s ' ], [ ' biased-courtship ' , ' biased_courtshi ' ], [ ' reject-your-personalitys-politics ' , ' reject_your_pol ' ], [ ' laws-of-bias-in-science ' , ' laws_of_bias_in ' ], [ ' epidemics-are-98-below-average ' , ' epidemics_are_9 ' ], [ ' bias-not-a-bug-but-a-feature ' , ' bias_not_a_bug_ ' ], [ ' a-game-for-self-calibration ' , ' a_game_for_self ' ], [ ' why-allow-referee-bias ' , ' why_is_referee_ ' ], [ ' disagreement-at-thoughts-arguments-and-rants ' , ' disagreement_at ' ], [ ' hobgoblins-of-voter-minds ' , ' hobgoblins_of_v ' ], [ ' how-are-we-doing ' , ' how_are_we_doin ' ], [ ' avoiding-truth ' , ' avoiding_truth ' ], [ ' conspicuous-consumption-of-info ' , ' conspicuous_con ' ], [ ' we-cant-foresee-to-disagree ' , ' we_cant_foresee ' ], [ ' do-biases-favor-hawks ' , ' do_biases_favor ' ], [ ' convenient-bias-theories ' , ' convenient_bias ' ], [ ' fair-betting-odds-and-prediction-market-prices ' , ' fair_betting_od ' ], [ ' the-cognitive-architecture-of-bias ' , ' the_cognitive_a ' ], [ ' poll-on-nanofactories ' , ' poll_on_nanofac ' ], [ ' all-bias-is-signed ' , ' all_bias_is_sig ' ], [ ' two-cheers-for-ignoring-plain-facts ' , ' two_cheers_for_ ' ], [ ' what-if-everybody-overcame-bias ' , ' what_if_everybo ' ], [ ' discussions-of-bias-in-answers-to-the-edge-2007-question ' , ' media_biases_us ' ], [ ' why-dont-the-young-learn-from-the-old ' , ' why_dont_the_yo ' ], [ ' the-coin-guessing-game ' , ' the_coin_guessi ' ], [ ' a-honest-doctor-sort-of ' , ' a_honest_doctor ' ], [ ' medical-study-biases ' , ' medical_study_b ' ], [ ' this-is-my-dataset-there-are-many-datasets-like-it-but-this-one-is-mine ' , ' this_is_my_data ' ], [ ' professors-progress-like-ads-advise ' , ' ads_advise_prof ' ], [ ' disagreement-case-study-1 ' , ' disagreement_ca ' ], [ ' marginally-revolved-biases ' , ' marginally_revo ' ], [ ' calibrate-your-ad-response ' , ' calibrate_your_ ' ], [ ' disagreement-case-studies ' , ' seeking_disagre ' ], [ ' just-lose-hope-already ' , ' a_time_to_lose_ ' ], [ ' less-biased-memories ' , ' unbiased_memori ' ], [ ' think-frequencies-not-probabilities ' , ' think_frequenci ' ], [ ' fig-leaf-models ' , ' fig_leaf_models ' ], [ ' do-we-get-used-to-stuff-but-not-friends ' , ' do_we_get_used_ ' ], [ ' buss-on-true-love ' , ' buss_on_true_lo ' ], [ ' is-overcoming-bias-male ' , ' is_overcoming_b ' ], [ ' bias-in-the-classroom ' , ' bias_in_the_cla ' ], [ ' our-house-my-rules ' , ' our_house_my_ru ' ], [ ' how-paranoid-should-i-be-the-limits-of-overcoming-bias ' , ' how_paranoid_sh ' ], [ ' evidence-based-medicine-backlash ' , ' evidencebased_m ' ], [ ' politics-is-the-mind-killer ' , ' politics_is_the ' ], [ ' disagreement-on-inflation ' , ' disagreement_on ' ], [ ' moderate-moderation ' , ' moderate_modera ' ], [ ' bias-toward-certainty ' , ' bias_toward_cer ' ], [ ' multi-peaked-distributions ' , ' multipeaked_dis ' ], [ ' selection-bias-in-economic-theory ' , ' selection_bias_ ' ], [ ' induce-presidential-candidates-to-take-iq-tests ' , ' induce_presiden ' ], [ ' crackpot-people-and-crackpot-ideas ' , ' crackpot_people ' ], [ ' press-confirms-your-health-fears ' , ' press_confirms_ ' ], [ ' too-many-loner-theorists ' , ' too_many_loner_ ' ], [ ' words-for-love-and-sex ' , ' words_for_love_ ' ], [ ' its-sad-when-bad-ideas-drive-out-good-ones ' , ' its_sad_when_ba ' ], [ ' truth-is-stranger-than-fiction ' , ' truth_is_strang ' ], [ ' posterity-review-comes-cheap ' , ' posterity_revie ' ], [ ' reputation-commitment-mechanism ' , ' reputation_comm ' ], [ ' more-lying ' , ' more_lying ' ], [ ' is-truth-in-the-hump-or-the-tails ' , ' is_truth_in_the ' ], [ ' what-opinion-game-do-we-play ' , ' what_opinion_ga ' ], [ ' philip-tetlocks-long-now-talk ' , ' philip_tetlocks ' ], [ ' the-more-amazing-penn ' , ' the_more_amazin ' ], [ ' when-are-weak-clues-uncomfortable ' , ' when_are_weak_c ' ], [ ' detecting-lies ' , ' detecting_lies ' ], [ ' how-and-when-to-listen-to-the-crowd ' , ' how_and_when_to ' ], [ ' institutions-as-levers ' , ' institutions_as ' ], [ ' one-reason-why-power-corrupts ' , ' one_reason_why_ ' ], [ ' will-blog-posts-get-credit ' , ' will_blog_posts ' ], [ ' needed-cognitive-forensics ' , ' wanted_cognitiv ' ], [ ' control-variables-avoid-bias ' , ' control_variabl ' ], [ ' dare-to-deprogram-me ' , ' dare_to_deprogr ' ], [ ' bias-and-health-care ' , ' bias_and_health ' ], [ ' just-world-bias-and-inequality ' , ' just_world_bias_1 ' ], [ ' subduction-phrases ' , ' subduction_phra ' ], [ ' what-evidence-in-silence-or-confusion ' , ' what_evidence_i ' ], [ ' gender-profiling ' , ' gender_profilin ' ], [ ' unequal-inequality ' , ' unequal_inequal ' ], [ ' academic-tool-overconfidence ' , ' academic_tool_o ' ], [ ' why-are-there-no-comforting-words-that-arent-also-factual-statements ' , ' why_are_there_n ' ], [ ' big-issues-vs-small-issues ' , ' big_issues_vs_s ' ], [ ' tolstoy-on-patriotism ' , ' tolstoy_on_patr ' ], [ ' statistical-bias ' , ' statistical_bia ' ], [ ' explain-your-wins ' , ' explain_your_wi ' ], [ ' beware-of-information-porn ' , ' beware_of_infor ' ], [ ' info-has-no-trend ' , ' info_has_no_tre ' ], [ ' tsuyoku-vs-the-egalitarian-instinct ' , ' tsuyoku_vs_the_ ' ], [ ' libertarian-purity-duels ' , ' libertarian_pur ' ], [ ' tsuyoku-naritai-i-want-to-become-stronger ' , ' tsuyoku_naritai ' ], [ ' reporting-chains-swallow-extraordinary-evidence ' , ' reporting_chain ' ], [ ' self-deception-hypocrisy-or-akrasia ' , ' selfdeception_h ' ], [ ' the-very-worst-kind-of-bias ' , ' the_very_worst_ ' ], [ ' home-sweet-home-bias ' , ' home_sweet_home ' ], [ ' norms-of-reason-and-the-prospects-for-technologies-and-policies-of-debiasing ' , ' ways_of_debiasi ' ], [ ' useful-bias ' , ' useful_bias ' ], [ ' chronophone-motivations ' , ' chronophone_mot ' ], [ ' archimedess-chronophone ' , ' archimedess_chr ' ], [ ' masking-expert-disagreement ' , ' masking_expert_ ' ], [ ' archimedess-binding-dilemma ' , ' archimedess_bin ' ], [ ' morality-of-the-future ' , ' morality_of_the ' ], [ ' moral-progress-and-scope-of-moral-concern ' , ' moral_progress_ ' ], [ ' awareness-of-intimate-bias ' , ' awareness_of_in ' ], [ ' all-ethics-roads-lead-to-ours ' , ' all_ethics_road ' ], [ ' challenges-of-majoritarianism ' , ' challenges_of_m ' ], [ ' classic-bias-doubts ' , ' classic_bias_do ' ], [ ' philosophical-majoritarianism ' , ' on_majoritarian ' ], [ ' useless-medical-disclaimers ' , ' useless_medical ' ], [ ' arguments-and-duels ' , ' arguments_and_d ' ], [ ' believing-in-todd ' , ' believing_in_to ' ], [ ' ideologues-or-fools ' , ' ideologues_or_f ' ], [ ' bias-caused-by-fear-of-islamic-extremists ' , ' bias_caused_by_ ' ], [ ' bias-on-self-control-bias ' , ' selfcontrol_bia ' ], [ ' multipolar-disagreements-hals-religious-quandry ' , ' multipolar_disa ' ], [ ' superstimuli-and-the-collapse-of-western-civilization ' , ' superstimuli_an ' ], [ ' good-news-only-please ' , ' good_news_only_ ' ], [ ' blue-or-green-on-regulation ' , ' blue_or_green_o ' ], [ ' 100000-visits ' , ' 100000_visits ' ], [ ' disagreement-case-study-robin-hanson-and-david-balan ' , ' disagreement_ca_2 ' ], [ ' the-trouble-with-track-records ' , ' the_trouble_wit ' ], [ ' genetics-and-cognitive-bias ' , ' genetics_and_co ' ], [ ' marketing-as-asymmetrical-warfare ' , ' marketing_as_as ' ], [ ' disagreement-case-study---balan-and-i ' , ' disagreement_ca_1 ' ], [ ' moral-dilemmas-criticism-plumping ' , ' moral_dilemmas_ ' ], [ ' the-scales-of-justice-the-notebook-of-rationality ' , ' the_scales_of_j ' ], [ ' none-evil-or-all-evil ' , ' none_evil_or_al ' ], [ ' biases-by-and-large ' , ' biases_by_and_l ' ], [ ' disagreement-case-study---hawk-bias ' , ' disagreement_ca ' ], [ ' overcome-cognitive-bias-with-multiple-selves ' , ' overcome_cognit ' ], [ ' extreme-paternalism ' , ' extreme_paterna ' ], [ ' learn-from-politicians-personal-failings ' , ' learn_from_poli ' ], [ ' whose-framing ' , ' whose_framing ' ], [ ' who-are-the-god-experts ' , ' who_are_the_god ' ], [ ' bias-against-introverts ' , ' bias_against_in ' ], [ ' paternal-policies-fight-cognitive-bias-slash-information-costs-and-privelege-responsible-subselves ' , ' paternal_polici ' ], [ ' the-fog-of-disagreement ' , ' the_fog_of_disa ' ], [ ' burchs-law ' , ' burchs_law ' ], [ ' lets-get-ready-to-rumble ' , ' heres_my_openin ' ], [ ' rational-agent-paternalism ' , ' rational_agent_ ' ], [ ' the-give-us-more-money-bias ' , ' the_give_us_mor ' ], [ ' white-collar-crime-and-moral-freeloading ' , ' whitecollar_cri ' ], [ ' happy-capital-day ' , ' happy_capital_d ' ], [ ' outlandish-pundits ' , ' outlandish_pund ' ], [ ' policy-debates-should-not-appear-one-sided ' , ' policy_debates_ ' ], [ ' romantic-predators ' , ' romantic_predat ' ], [ ' swinging-for-the-fences-when-you-should-bunt ' , ' swinging_for_th ' ], [ ' paternalism-is-about-bias ' , ' paternalism_is_ ' ], [ ' you-are-not-hiring-the-top-1 ' , ' you_are_not_hir ' ], [ ' morality-or-manipulation ' , ' morality_or_man ' ], [ ' accountable-financial-regulation ' , ' accountable_fin ' ], [ ' today-is-honesty-day ' , ' today_is_honest ' ], [ ' more-on-future-self-paternalism ' , ' more_on_future_ ' ], [ ' universal-law ' , ' universal_law ' ], [ ' universal-fire ' , ' universal_fire ' ], [ ' the-fallacy-fallacy ' , ' the_fallacy_fal ' ], [ ' to-learn-or-credential ' , ' to_learn_or_cre ' ], [ ' feeling-rational ' , ' feeling_rationa ' ], [ ' overconfidence-erases-doc-advantage ' , ' overconfidence_ ' ], [ ' the-bleeding-edge-of-innovation ' , ' the_bleeding_ed ' ], [ ' expert-at-versus-expert-on ' , ' expert_at_versu ' ], [ ' meta-majoritarianism ' , ' meta_majoritari ' ], [ ' future-self-paternalism ' , ' future_self_pat ' ], [ ' popularity-is-random ' , ' popularity_is_r ' ], [ ' holocaust-denial ' , ' holocaust_denia ' ], [ ' exercise-sizzle-works-sans-steak ' , ' exercise_sizzle ' ], [ ' the-shame-of-tax-loopholing ' , ' the_shame_of_ta ' ], [ ' vonnegut-on-overcoming-fiction ' , ' vonnegut_on_ove ' ], [ ' consolidated-nature-of-morality-thread ' , ' consolidated_na ' ], [ ' irrationality-or-igustibusi ' , ' irrationality_o ' ], [ ' your-rationality-is-my-business ' , ' your_rationalit ' ], [ ' statistical-inefficiency-bias-or-increasing-efficiency-will-reduce-bias-on-average-or-there-is-no-bias-variance-tradeoff ' , ' statistical_ine ' ], [ ' new-improved-lottery ' , ' new_improved_lo ' ], [ ' non-experts-need-documentation ' , ' nonexperts_need ' ], [ ' overconfident-evaluation ' , ' overconfident_e ' ], [ ' lotteries-a-waste-of-hope ' , ' lotteries_a_was ' ], [ ' just-a-smile ' , ' just_a_smile ' ], [ ' priors-as-mathematical-objects ' , ' priors_as_mathe ' ], [ ' predicting-the-future-with-futures ' , ' predicting_the_ ' ], [ ' the-future-is-glamorous ' , ' the_future_is_g ' ], [ ' marginally-zero-sum-efforts ' , ' marginally_zero ' ], [ ' overcoming-credulity ' , ' overcoming_cred ' ], [ ' urgent-and-important-not ' , ' very_important_ ' ], [ ' futuristic-predictions-as-consumable-goods ' , ' futuristic_pred ' ], [ ' suggested-posts ' , ' suggested_posts ' ], [ ' modular-argument ' , ' modular_argumen ' ], [ ' inductive-bias ' , ' inductive_bias ' ], [ ' debiasing-as-non-self-destruction ' , ' debiasing_as_no ' ], [ ' overcoming-bias---what-is-it-good-for ' , ' overcoming_bias ' ], [ ' as-good-as-it-gets ' , ' as_good_as_it_g ' ], [ ' driving-while-red ' , ' driving_while_r ' ], [ ' media-bias ' , ' media_bias ' ], [ ' could-gambling-save-science ' , ' could_gambling_ ' ], [ ' casanova-on-innocence ' , ' casanova_on_inn ' ], [ ' black-swans-from-the-future ' , ' black_swans_fro ' ], [ ' having-to-do-something-wrong ' , ' having_to_do_so ' ], [ ' knowing-about-biases-can-hurt-people ' , ' knowing_about_b ' ], [ ' a-tough-balancing-act ' , ' a_tough_balanci ' ], [ ' mapping-academia ' , ' mapping_academi ' ], [ ' the-majority-is-always-wrong ' , ' the_majority_is ' ], [ ' overcoming-fiction ' , ' overcoming_fict ' ], [ ' the-error-of-crowds ' , ' the_error_of_cr ' ], [ ' do-moral-systems-have-to-make-sense ' , ' do_moral_system ' ], [ ' useful-statistical-biases ' , ' useful_statisti ' ], [ ' is-there-manipulation-in-the-hillary-clinton-prediction-market ' , ' is_there_manipu ' ], [ ' shock-response-futures ' , ' shock_response_ ' ], [ ' free-money-going-fast ' , ' free_money_goin ' ], [ ' arrogance-as-virtue ' , ' arrogance_as_vi ' ], [ ' are-any-human-cognitive-biases-genetically-universal ' , ' are_any_human_c_1 ' ], [ ' hofstadters-law ' , ' hofstadters_law ' ], [ ' the-agency-problem ' , ' the_agency_prob ' ], [ ' cryonics ' , ' cryonics ' ], [ ' my-podcast-with-russ-roberts ' , ' my_podcast_with ' ], [ ' truly-worth-honoring ' , ' truly_worth_hon ' ], [ ' scientists-as-parrots ' , ' scientists_as_p ' ], [ ' in-obscurity-errors-remain ' , ' in_obscurity_er ' ], [ ' requesting-honesty ' , ' requesting_hone ' ], [ ' winning-at-rock-paper-scissors ' , ' winning_at_rock ' ], [ ' policy-tug-o-war ' , ' policy_tugowar ' ], [ ' why-pretty-hs-play-leads ' , ' why_pretty_hs_p ' ], [ ' the-perils-of-being-clearer-than-truth ' , ' the_perils_of_b ' ], [ ' when-differences-make-a-difference ' , ' when_difference ' ], [ ' you-felt-sorry-for-her ' , ' you_felt_sorry_ ' ], [ ' do-androids-dream-of-electric-rabbit-feet ' , ' do_androids_dre ' ], [ ' one-life-against-the-world ' , ' one_life_agains ' ], [ ' cheating-as-status-symbol ' , ' cheating_as_sta ' ], [ ' underconfident-experts ' , ' underconfident_ ' ], [ ' are-almost-all-investors-biased ' , ' are_almost_all_ ' ], [ ' data-management ' , ' data_management ' ], [ ' are-any-human-cognitive-biases-genetic ' , ' are_any_human_c ' ], [ ' is-your-rationality-on-standby ' , ' is_your_rationa ' ], [ ' joke ' , ' joke ' ], [ ' opinions-of-the-politically-informed ' , ' opinions_of_the ' ], [ ' the-case-for-dangerous-testing ' , ' the_case_for_da ' ], [ ' i-had-the-same-idea-as-david-brin-sort-of ' , ' i_had_the_same_ ' ], [ ' disagreement-case-study----genetics-of-free-trade-and-a-new-cognitive-bias ' , ' disagreement_ca ' ], [ ' rand-experiment-ii-petition ' , ' rand_experiment ' ], [ ' skepticism-about-skepticism ' , ' skepticism_abou ' ], [ ' scope-insensitivity ' , ' scope_insensiti ' ], [ ' medicine-as-scandal ' , ' medicine_as_sca ' ], [ ' the-us-should-bet-against-iran-testing-a-nuclear-weapon ' , ' the_us_should_b ' ], [ ' medicare-train-wreck ' , ' medicare_train_ ' ], [ ' eclipsing-nobel ' , ' eclipsing_nobel ' ], [ ' what-speaks-silence ' , ' what_speaks_sil ' ], [ ' the-worst-youve-seen-isnt-the-worst-there-is ' , ' the_worst_youve ' ], [ ' rand-health-insurance-experiment-ii ' , ' rand_health_ins_1 ' ], [ ' the-conspiracy-glitch ' , ' the_conspiracy_ ' ], [ ' doubting-thomas-and-pious-pete ' , ' doubting_thomas ' ], [ ' rand-health-insurance-experiment ' , ' rand_health_ins ' ], [ ' third-alternatives-for-afterlife-ism ' , ' third_alternati ' ], [ ' scope-neglect-hits-a-new-low ' , ' scope_neglect_h ' ], [ ' motivated-stopping-in-philanthropy ' , ' early_stopping_ ' ], [ ' cold-fusion-continues ' , ' cold_fusion_con ' ], [ ' feel-lucky-punk ' , ' feel_luck_punk ' ], [ ' the-third-alternative ' , ' the_third_alter ' ], [ ' academics-against-evangelicals ' , ' academics_again ' ], [ ' race-bias-of-nba-refs ' , ' race_bias_of_nb ' ], [ ' brave-us-tv-news-not ' , ' brave_us_tv_new ' ], [ ' beware-the-unsurprised ' , ' beware_the_unsu ' ], [ ' academic-self-interest-bias ' , ' selfinterest_bi ' ], [ ' the-bias-in-please-and-thank-you ' , ' the_bias_in_ple ' ], [ ' social-norms-need-neutrality-simplicity ' , ' social_norms_ne ' ], [ ' think-like-reality ' , ' think_like_real ' ], [ ' overcoming-bias-on-the-simpsons ' , ' overcoming_bias ' ], [ ' eh-hunt-helped-lbj-kill-jfk ' , ' eh_hunt_helped_ ' ], [ ' myth-of-the-rational-academic ' , ' myth_of_the_rat ' ], [ ' biases-are-fattening ' , ' biases-are-fatt ' ], [ ' true-love-and-unicorns ' , ' true_love_and_u ' ], [ ' bayes-radical-liberal-or-conservative ' , ' bayes-radical-l ' ], [ ' global-warming-blowhards ' , ' global-warming ' ], [ ' extraordinary-physics ' , ' extraordinary_c ' ], [ ' are-your-enemies-innately-evil ' , ' are-your-enemie ' ], [ ' how-to-be-radical ' , ' how_to_be_radic ' ], [ ' auctioning-book-royalties ' , ' auctioning-book ' ], [ ' fair-landowner-coffee ' , ' fair-landownert ' ], [ ' death-risk-biases ' , ' death_risk_bias ' ], -[ ' correspondence-bias ' , ' correspondence- ' ], +[ ' correspondence-bias ' , ' correspondence ' ], [ ' applaud-info-not-agreement ' , ' applaud-info-no ' ], [ ' risk-free-bonds-arent ' , ' risk-free-bonds ' ], [ ' adam-smith-on-overconfidence ' , ' adam_smith_on_o ' ], [ ' ethics-applied-vs-meta ' , ' ethics_applied_ ' ], [ ' wandering-philosophers ' , ' wandering_philo ' ], [ ' randomly-review-criminal-cases ' , ' randomly_review ' ], [ ' functional-is-not-optimal ' , ' functional_is_n ' ], [ ' were-people-better-off-in-the-middle-ages-than-they-are-now ' , ' politics_and_ec ' ], [ ' selling-overcoming-bias ' , ' selling_overcom ' ], [ ' tell-me-your-politics-and-i-can-tell-you-what-you-think-about-nanotechnology ' , ' tell_me_your_po ' ], [ ' beware-neuroscience-stories ' , ' beware_neurosci ' ], [ ' against-free-thinkers ' , ' against_free_th ' ], [ ' 1-2-3-infinity ' , ' 1_2_3_infinity ' ], [ ' total-vs-marginal-effects-or-are-the-overall-benefits-of-health-care-probably-minor ' , ' total_vs_margin ' ], [ ' one-reason-why-plans-are-good ' , ' one_reason_why_ ' ], [ ' 200000-visits ' , ' 200000_visits ' ], [ ' choose-credit-or-influence ' , ' choose_credit_o ' ], [ ' disagreement-case-study-hanson-and-hughes ' , ' disagreement_ca_1 ' ], [ ' odd-kid-names ' , ' odd_kid_names ' ], [ ' uncovering-rational-irrationalities ' , ' uncovering_rati ' ], [ ' blind-elites ' , ' blind_elites ' ], [ ' blind-winners ' , ' blind_winners ' ], [ ' disagreement-case-study-hanson-and-cutler ' , ' disagreement_ca ' ], [ ' why-not-pre-debate-talk ' , ' why_not_predeba ' ], [ ' nutritional-prediction-markets ' , ' nutritional_pre ' ], [ ' progress-is-not-enough ' , ' progress_is_not ' ], [ ' two-meanings-of-overcoming-bias-for-one-focus-is-fundamental-for-second ' , ' two-meanings-of ' ], [ ' only-losers-overcome-bias ' , ' only-losers-ove ' ], [ ' bayesian-judo ' , ' bayesian-judo ' ], [ ' self-interest-intent-deceit ' , ' self-interest-i ' ], [ ' colorful-characters ' , ' color-character ' ], [ ' belief-in-belief ' , ' belief-in-belie ' ], [ ' phone-shy-ufos ' , ' phone-shy-ufos ' ], -[ ' making-beliefs-pay-rent-in-anticipated-experiences ' , ' making-beliefs- ' ], +[ ' making-beliefs-pay-rent-in-anticipated-experiences ' , ' making-beliefs ' ], [ ' ts-eliot-quote ' , ' ts-eliot-quote ' ], [ ' not-every-negative-judgment-is-a-bias ' , ' not-every-negat ' ], [ ' schools-that-dont-want-to-be-graded ' , ' schools-that-do ' ], [ ' the-judo-principle ' , ' the-judo-princi ' ], [ ' beware-the-inside-view ' , ' beware-the-insi ' ], [ ' goofy-best-friend ' , ' goofy-best-frie ' ], [ ' meta-textbooks ' , ' meta-textbooks ' ], [ ' fantasys-essence ' , ' fantasys-essens ' ], [ ' clever-controls ' , ' clever-controls ' ], [ ' investing-in-index-funds-a-tangible-reward-of-overcoming-bias ' , ' investing-in-in ' ], [ ' bad-balance-bias ' , ' bad-balance-bia ' ], [ ' raging-memories ' , ' raging-memories ' ], [ ' calibration-in-chess ' , ' calibration-in ' ], [ ' theyre-telling-you-theyre-lying ' , ' theyre-telling ' ], [ ' on-lying ' , ' on-lying ' ], [ ' gullible-then-skeptical ' , ' gullible-then-s ' ], [ ' how-biases-save-us-from-giving-in-to-terrorism ' , ' how-biases-save ' ], [ ' privacy-rights-and-cognitive-bias ' , ' privacy-rights ' ], [ ' conspiracy-believers ' , ' conspiracy-beli ' ], [ ' overcoming-bias-sometimes-makes-us-change-our-minds-but-sometimes-not ' , ' overcoming-bias ' ], [ ' blogging-doubts ' , ' blogging-doubts ' ], [ ' should-charges-of-cognitive-bias-ever-make-us-change-our-minds-a-global-warming-case-study ' , ' should-charges- ' ], [ ' radical-research-evaluation ' , ' radical-researc ' ], [ ' a-real-life-quandry ' , ' a-real-life-qua ' ], [ ' looking-for-a-hard-headed-blogger ' , ' looking-for-a-h ' ], [ ' goals-and-plans-in-decision-making ' , ' goals-and-plans ' ], [ ' 7707-weddings ' , ' 7707-weddings ' ], [ ' just-take-the-average ' , ' just-take-the-a ' ], [ ' two-more-things-to-unlearn-from-school ' , ' two-more-things ' ], [ ' introducing-ramone ' , ' introducing-ram ' ], [ ' tell-your-anti-story ' , ' tell-your-anti ' ], [ ' reviewing-caplans-reviewers ' , ' reviewing-capla ' ], [ ' how-should-unproven-findings-be-publicized ' , ' how-should-unpr ' ], [ ' global-warming-skeptics-charge-believers-with-more-cognitive-biases-than-believers-do-skeptics-why-the-asymmetry ' , ' global-warming ' ], [ ' what-is-public-info ' , ' what-is-public ' ], [ ' take-our-survey ' , ' take-our-survey ' ], [ ' lets-bet-on-talk ' , ' lets-bet-on-tal ' ], [ ' more-possible-political-biases-relative-vs-absolute-well-being ' , ' more-possible-p ' ], [ ' what-signals-what ' , ' what-signals-wh ' ], [ ' reply-to-libertarian-optimism-bias ' , ' in-this-entry-o ' ], [ ' biased-birth-rates ' , ' biased-birth-ra ' ], [ ' libertarian-optimism-bias-vs-statist-pessimism-bias ' , ' libertarian-opt ' ], [ ' painfully-honest ' , ' painfully-hones ' ], [ ' biased-revenge ' , ' biased-revenge ' ], [ ' the-road-not-taken ' , ' the_road_not_ta ' ], [ ' open-thread ' , ' open-thread ' ], -[ ' making-history-available ' , ' making-history- ' ], +[ ' making-history-available ' , ' making-history ' ], [ ' we-are-not-unbaised ' , ' we-are-not-unba ' ], [ ' failing-to-learn-from-history ' , ' failing-to-lear ' ], [ ' seeking-unbiased-game-host ' , ' seeking-unbiase ' ], [ ' my-wild-and-reckless-youth ' , ' my-wild-and-rec ' ], [ ' kind-right-handers ' , ' kind-right-hand ' ], [ ' say-not-complexity ' , ' say-not-complex ' ], [ ' the-function-of-prizes ' , ' the-function-of ' ], [ ' positive-bias-look-into-the-dark ' , ' positive-bias-l ' ], [ ' the-way-is-subtle ' , ' the-way-is-subt ' ], [ ' is-overcoming-bias-important ' , ' how-important-i ' ], [ ' the-futility-of-emergence ' , ' the-futility-of ' ], [ ' bias-as-objectification ' , ' bias-as-objecti ' ], [ ' mysterious-answers-to-mysterious-questions ' , ' mysterious-answ ' ], [ ' bias-against-torture ' , ' bias-against-to ' ], [ ' semantic-stopsigns ' , ' semantic-stopsi ' ], [ ' exccess-trust-in-experts ' , ' exccess-trust-i ' ], [ ' fake-causality ' , ' fake-causality ' ], [ ' is-hybrid-vigor-iq-warm-and-fuzzy ' , ' is-hybrid-vigor ' ], [ ' science-as-attire ' , ' science-as-lite ' ], [ ' moral-bias-as-group-glue ' , ' moral-bias-as-g ' ], [ ' guessing-the-teachers-password ' , ' guessing-the-te ' ], [ ' nerds-as-bad-connivers ' , ' post ' ], [ ' why-do-corporations-buy-insurance ' , ' why-do-corporat ' ], [ ' fake-explanations ' , ' fake-explanatio ' ], [ ' media-risk-bias-feedback ' , ' media-risk-bias ' ], [ ' irrational-investment-disagreement ' , ' irrational-inve ' ], [ ' is-molecular-nanotechnology-scientific ' , ' is-molecular-na ' ], [ ' what-evidence-is-brevity ' , ' what-evidence-i ' ], [ ' are-more-complicated-revelations-less-probable ' , ' are-more-compli ' ], [ ' scientific-evidence-legal-evidence-rational-evidence ' , ' scientific-evid ' ], [ ' pseudo-criticism ' , ' pseudo-criticis ' ], [ ' are-brilliant-scientists-less-likely-to-cheat ' , ' are-brilliant-s ' ], [ ' hindsight-devalues-science ' , ' hindsight-deval ' ], [ ' sometimes-learning-is-very-slow ' , ' sometimes-learn ' ], [ ' hindsight-bias ' , ' hindsight-bias ' ], [ ' truth---the-neglected-virtue ' , ' truth---the-neg ' ], [ ' one-argument-against-an-army ' , ' one-argument--1 ' ], [ ' strangeness-heuristic ' , ' strangeness-heu ' ], [ ' never-ever-forget-there-are-maniacs-out-there ' , ' never-ever-forg ' ], [ ' update-yourself-incrementally ' , ' update-yourself ' ], [ ' harry-potter-the-truth-seeker ' , ' harry-potter-th ' ], [ ' dangers-of-political-betting-markets ' , ' dangers-of-poli ' ], [ ' conservation-of-expected-evidence ' , ' conservation-of ' ], [ ' biases-of-biography ' , ' biases-of-biogr ' ], [ ' absence-of-evidence-iisi-evidence-of-absence ' , ' absence-of-evid ' ], [ ' confident-proposer-bias ' , ' confident-propo ' ], [ ' i-defy-the-data ' , ' i-defy-the-data ' ], [ ' what-is-a-taboo-question ' , ' what-is-a-taboo ' ], [ ' your-strength-as-a-rationalist ' , ' your-strength-a ' ], [ ' accountable-public-opinion ' , ' accountable-pub ' ], [ ' truth-bias ' , ' truth-bias ' ], -[ ' the-apocalypse-bet ' , ' the-apocalypse- ' ], +[ ' the-apocalypse-bet ' , ' the-apocalypse ' ], [ ' spencer-vs-wilde-on-truth-vs-lie ' , ' spencer-vs-wild ' ], [ ' you-icani-face-reality ' , ' you-can-face-re ' ], [ ' food-vs-sex-charity ' , ' food-vs-sex-cha ' ], [ ' the-virtue-of-narrowness ' , ' the-virtue-of-n ' ], [ ' wishful-investing ' , ' wishful-investi ' ], -[ ' the-proper-use-of-doubt ' , ' the-proper-use- ' ], +[ ' the-proper-use-of-doubt ' , ' the-proper-use ' ], [ ' academic-political-bias ' , ' academic-politi ' ], [ ' focus-your-uncertainty ' , ' focus-your-unce ' ], [ ' disagreeing-about-cognitive-style-or-personality ' , ' disagreeing-abo ' ], -[ ' the-importance-of-saying-oops ' , ' the-importance- ' ], +[ ' the-importance-of-saying-oops ' , ' the-importance ' ], [ ' the-real-inter-disciplinary-barrier ' , ' the-real-inter ' ], [ ' religions-claim-to-be-non-disprovable ' , ' religions-claim ' ], -[ ' is-advertising-the-playground-of-cognitive-bias ' , ' is-advertising- ' ], +[ ' is-advertising-the-playground-of-cognitive-bias ' , ' is-advertising ' ], [ ' anonymous-review-matters ' , ' anonymous-revie ' ], -[ ' if-you-wouldnt-want-profits-to-influence-this-blog-you-shouldnt-want-for-profit-schools ' , ' if-you-wouldnt- ' ], +[ ' if-you-wouldnt-want-profits-to-influence-this-blog-you-shouldnt-want-for-profit-schools ' , ' if-you-wouldnt ' ], [ ' belief-as-attire ' , ' belief-as-attir ' ], [ ' overcoming-bias-hobby-virtue-or-moral-obligation ' , ' overcoming-bias ' ], [ ' the-dogmatic-defense ' , ' dogmatism ' ], -[ ' professing-and-cheering ' , ' professing-and- ' ], +[ ' professing-and-cheering ' , ' professing-and ' ], [ ' how-to-torture-a-reluctant-disagreer ' , ' how-to-torture ' ], [ ' open-thread ' , ' open-thread ' ], [ ' rationalization ' , ' rationalization ' ], [ ' lies-about-sex ' , ' lies-about-sex ' ], [ ' what-evidence-filtered-evidence ' , ' what-evidence-f ' ], [ ' a-moral-conundrum ' , ' a-moral-conundr ' ], [ ' jewish-people-and-israel ' , ' jewish-people-a ' ], [ ' the-bottom-line ' , ' the-bottom-line ' ], [ ' false-findings-unretracted ' , ' false-findings ' ], [ ' how-to-convince-me-that-2-2-3 ' , ' how-to-convince ' ], [ ' elusive-conflict-experts ' , ' elusive-conflic ' ], [ ' 926-is-petrov-day ' , ' 926-is-petrov-d ' ], [ ' drinking-our-own-kool-aid ' , ' drinking-our-ow ' ], [ ' occams-razor ' , ' occams-razor ' ], [ ' even-when-contrarians-win-they-lose ' , ' even-when-contr ' ], [ ' einsteins-arrogance ' , ' einsteins-arrog ' ], [ ' history-is-written-by-the-dissenters ' , ' history-is-writ ' ], [ ' the-bright-side-of-life ' , ' always-look-on ' ], [ ' how-much-evidence-does-it-take ' , ' how-much-eviden ' ], [ ' treat-me-like-a-statistic-but-please-be-nice-to-me ' , ' treat-me-like-a ' ], [ ' small-business-overconfidence ' , ' small-business ' ], [ ' the-lens-that-sees-its-flaws ' , ' the-lens-that-s ' ], [ ' why-so-little-model-checking-done-in-statistics ' , ' one-thing-that ' ], [ ' bounded-rationality-and-the-conjunction-fallacy ' , ' bounded-rationa ' ], [ ' what-is-evidence ' , ' what-is-evidenc ' ], [ ' radically-honest-meetings ' , ' radically-hones ' ], [ ' burdensome-details ' , ' burdensome-deta ' ], [ ' wielding-occams-razor ' , ' wielding-occams ' ], [ ' your-future-has-detail ' , ' in-the-sept-7-s ' ], [ ' medicine-has-been-overcoming-bias-too ' , ' medicine-has-be ' ], [ ' conjunction-controversy-or-how-they-nail-it-down ' , ' conjunction-con ' ], [ ' why-not-cut-medicine-all-the-way-to-zero ' , ' why-not-cut-med ' ], [ ' why-teen-paternalism ' , ' why-teen-patern ' ], [ ' conjunction-fallacy ' , ' conjunction-fal ' ], [ ' beware-monkey-traps ' , ' beware-monkey-t ' ], [ ' outputs-require-inputs ' , ' to-judge-output ' ], [ ' kahnemans-planning-anecdote ' , ' kahnemans-plann ' ], [ ' epidemiology-doubts ' , ' health-epidemio ' ], [ ' planning-fallacy ' , ' planning-fallac ' ], [ ' seven-sources-of-disagreement-cant-be-eliminated-by-overcoming-cognitive-bias ' , ' seven-sources-o ' ], [ ' dont-trust-your-lying-eyes ' , ' dont-trust-your ' ], [ ' scott-adams-on-bias ' , ' scott-adams-on ' ], [ ' naive-small-investors ' , ' naive-small-inv ' ], [ ' not-open-to-compromise ' , ' not-open-to-com ' ], [ ' why-im-blooking ' , ' why-im-blooking ' ], [ ' noise-in-the-courtroom ' , ' noise-in-the-co ' ], [ ' bias-awareness-bias-or-was-91101-a-black-swan ' , ' bias-awareness ' ], [ ' doublethink-choosing-to-be-biased ' , ' doublethink-cho ' ], [ ' acquisitions-signal-ceo-dominance ' , ' acquisitions-si ' ], -[ ' human-evil-and-muddled-thinking ' , ' human-evil-and- ' ], +[ ' human-evil-and-muddled-thinking ' , ' human-evil-and ' ], [ ' gotchas-are-not-biases ' , ' gotchas-are-not ' ], [ ' rationality-and-the-english-language ' , ' rationality-and ' ], [ ' never-confuse-could-and-would ' , ' never-confuse-c ' ], [ ' what-evidence-reluctant-authors ' , ' what-evidence-r ' ], [ ' applause-lights ' , ' applause-lights ' ], [ ' what-evidence-dry-one-sided-arguments ' , ' what-evidence-d ' ], [ ' bad-college-quality-incentives ' , ' bad-college-qua ' ], [ ' case-study-of-cognitive-bias-induced-disagreements-on-petraeus-crocker ' , ' case-study-of-c ' ], -[ ' we-dont-really-want-your-participation ' , ' we-dont-really- ' ], +[ ' we-dont-really-want-your-participation ' , ' we-dont-really ' ], [ ' tyler-finds-overcoming-bias-iisi-important-for-others ' , ' tyler-cowen-fin ' ], [ ' cut-medicine-in-half ' , ' cut-medicine-in ' ], [ ' radical-honesty ' , ' radical-honesty ' ], [ ' no-press-release-no-retraction ' , ' no-press-releas ' ], [ ' the-crackpot-offer ' , ' the-crackpot-of ' ], [ ' anchoring-and-adjustment ' , ' anchoring-and-a ' ], [ ' what-evidence-bad-arguments ' , ' what-evidence-b ' ], [ ' why-is-the-future-so-absurd ' , ' why-is-the-futu ' ], [ ' strength-to-doubt-or-believe ' , ' strength-to-dou ' ], [ ' availability ' , ' availability ' ], [ ' the-deniers-dilemna ' , ' the-deniers-con ' ], [ ' absurdity-heuristic-absurdity-bias ' , ' absurdity-heuri ' ], [ ' medical-quality-bias ' , ' medical-quality ' ], [ ' science-as-curiosity-stopper ' , ' science-as-curi ' ], -[ ' basic-research-as-signal ' , ' basic-research- ' ], +[ ' basic-research-as-signal ' , ' basic-research ' ], [ ' ueuxplainuwuorshipuiugnore ' , ' explainworshipi ' ], [ ' the-pinch-hitter-syndrome-a-general-principle ' , ' the-pinch-hitte ' ], [ ' what-evidence-ease-of-imagination ' , ' what-evidence-e ' ], [ ' stranger-than-history ' , ' stranger-than-h ' ], [ ' bias-as-objectification-ii ' , ' bias-as-objecti ' ], [ ' open-thread ' , ' open-thread ' ], [ ' what-wisdom-tradition ' , ' what-wisdom-tra ' ], [ ' random-vs-certain-death ' , ' random-vs-certa ' ], [ ' who-told-you-moral-questions-would-be-easy ' , ' who-told-you-mo ' ], [ ' a-case-study-of-motivated-continuation ' , ' a-case-study-of ' ], [ ' double-or-nothing-lawsuits-ten-years-on ' , ' double-or-nothi ' ], [ ' torture-vs-dust-specks ' , ' torture-vs-dust ' ], [ ' college-choice-futures ' , ' college-choice ' ], [ ' motivated-stopping-and-motivated-continuation ' , ' motivated-stopp ' ], [ ' bay-area-bayesians-unite ' , ' meetup ' ], [ ' dan-kahneman-puzzles-with-us ' , ' dan-kahneman-pu ' ], [ ' why-are-individual-iq-differences-ok ' , ' why-is-individu ' ], [ ' if-not-data-what ' , ' if-not-data-wha ' ], [ ' no-one-knows-what-science-doesnt-know ' , ' no-one-knows-wh ' ], [ ' dennetts-special-pleading ' , ' special-pleadin ' ], [ ' double-illusion-of-transparency ' , ' double-illusion ' ], [ ' why-im-betting-on-the-red-sox ' , ' why-im-betting ' ], [ ' intrade-nominee-advice ' , ' intrade-nominee ' ], [ ' explainers-shoot-high-aim-low ' , ' explainers-shoo ' ], [ ' distrust-effect-names ' , ' distrust-effect ' ], [ ' the-fallacy-of-the-one-sided-bet-for-example-risk-god-torture-and-lottery-tickets ' , ' the-fallacy-of ' ], [ ' expecting-short-inferential-distances ' , ' inferential-dis ' ], [ ' marriage-futures ' , ' marriage-future ' ], [ ' self-anchoring ' , ' self-anchoring ' ], [ ' how-close-lifes-birth ' , ' how-close-lifes ' ], [ ' illusion-of-transparency-why-no-one-understands-you ' , ' illusion-of-tra ' ], [ ' a-valid-concern ' , ' a-valid-concern ' ], [ ' pascals-mugging-tiny-probabilities-of-vast-utilities ' , ' pascals-mugging ' ], [ ' should-we-simplify-ourselves ' , ' should-we-simpl ' ], [ ' hanson-joins-cult ' , ' hanson-joins-cu ' ], [ ' congratulations-to-paris-hilton ' , ' congratulations ' ], [ ' cut-us-military-in-half ' , ' cut-us-military ' ], [ ' cant-say-no-spending ' , ' cant-say-no-spe ' ], [ ' share-your-original-wisdom ' , ' original-wisdom ' ], [ ' buy-health-not-medicine ' , ' buy-health-not ' ], [ ' hold-off-on-proposing-solutions ' , ' hold-off-solvin ' ], [ ' doctors-kill ' , ' doctors-kill ' ], [ ' the-logical-fallacy-of-generalization-from-fictional-evidence ' , ' fictional-evide ' ], [ ' my-local-hospital ' , ' my-local-hospit ' ], [ ' how-to-seem-and-be-deep ' , ' how-to-seem-and ' ], [ ' megan-has-a-point ' , ' megan-has-a-poi ' ], [ ' original-seeing ' , ' original-seeing ' ], [ ' fatty-food-is-healthy ' , ' fatty-food-is-h ' ], [ ' the-outside-the-box-box ' , ' outside-the-box ' ], [ ' meta-honesty ' , ' meta-honesty ' ], [ ' cached-thoughts ' , ' cached-thoughts ' ], [ ' health-hopes-spring-eternal ' , ' health-hope-spr ' ], [ ' do-we-believe-ieverythingi-were-told ' , ' do-we-believe-e ' ], [ ' chinks-in-the-bayesian-armor ' , ' chinks-in-the-b ' ], [ ' priming-and-contamination ' , ' priming-and-con ' ], [ ' what-evidence-intuition ' , ' what-evidence-i ' ], [ ' a-priori ' , ' a-priori ' ], [ ' regulation-ratchet ' , ' what-evidence-b ' ], [ ' no-one-can-exempt-you-from-rationalitys-laws ' , ' its-the-law ' ], [ ' flexible-legal-similarity ' , ' flexible-legal ' ], [ ' singlethink ' , ' singlethink ' ], [ ' what-evidence-divergent-explanations ' , ' what-evidence-d ' ], [ ' the-meditation-on-curiosity ' , ' curiosity ' ], [ ' pleasant-beliefs ' , ' pleasant-belief ' ], [ ' isshoukenmei-make-a-desperate-effort ' , ' isshoukenmei-ma ' ], [ ' author-misreads-expert-re-crowds ' , ' author-misreads ' ], [ ' avoiding-your-beliefs-real-weak-points ' , ' avoiding-your-b ' ], [ ' got-crisis ' , ' got-crisis ' ], [ ' why-more-history-than-futurism ' , ' why-more-histor ' ], [ ' we-change-our-minds-less-often-than-we-think ' , ' we-change-our-m ' ], [ ' why-not-dating-coaches ' , ' why-not-dating ' ], [ ' a-rational-argument ' , ' a-rational-argu ' ], [ ' can-school-debias ' , ' can-education-d ' ], [ ' recommended-rationalist-reading ' , ' recommended-rat ' ], [ ' confession-errors ' , ' confession-erro ' ], [ ' open-thread ' , ' open-thread ' ], [ ' precious-silence-lost ' , ' precious-silenc ' ], [ ' leader-gender-bias ' , ' leader-gender-b ' ], [ ' the-halo-effect ' , ' halo-effect ' ], [ ' unbounded-scales-huge-jury-awards-futurism ' , ' unbounded-scale ' ], [ ' what-insight-literature ' , ' what-insight-li ' ], [ ' evaluability-and-cheap-holiday-shopping ' , ' evaluability ' ], [ ' the-affect-heuristic ' , ' affect-heuristi ' ], [ ' academia-clumps ' , ' academia-clumps ' ], [ ' purpose-and-pragmatism ' , ' purpose-and-pra ' ], [ ' lost-purposes ' , ' lost-purposes ' ], [ ' intrade-fee-structure-discourages-selling-the-tails ' , ' intrade-fee-str ' ], [ ' growing-into-atheism ' , ' growing-into-at ' ], [ ' the-hidden-complexity-of-wishes ' , ' complex-wishes ' ], [ ' aliens-among-us ' , ' aliens-among-us ' ], [ ' leaky-generalizations ' , ' leaky-generaliz ' ], [ ' good-intrade-bets ' , ' good-intrade-be ' ], [ ' not-for-the-sake-of-happiness-alone ' , ' not-for-the-sak ' ], [ ' interpreting-the-fed ' , ' interpreting-th ' ], [ ' merry-hallowthankmas-eve ' , ' merry-hallowmas ' ], [ ' truly-part-of-you ' , ' truly-part-of-y ' ], [ ' overcoming-bias-after-one-year ' , ' overcoming-bi-1 ' ], [ ' artificial-addition ' , ' artificial-addi ' ], [ ' publication-bias-and-the-death-penalty ' , ' publication-bia ' ], [ ' development-futures ' , ' development-fut ' ], [ ' conjuring-an-evolution-to-serve-you ' , ' conjuring-an-ev ' ], [ ' us-south-had-42-chance ' , ' us-south-had-42 ' ], [ ' towards-a-typology-of-bias ' , ' towards-a-typol ' ], [ ' the-simple-math-of-everything ' , ' the-simple-math ' ], [ ' my-guatemala-interviews ' , ' my-guatemala-in ' ], [ ' no-evolutions-for-corporations-or-nanodevices ' , ' no-evolution-fo ' ], [ ' inaturei-endorses-human-extinction ' , ' terrible-optimi ' ], [ ' evolving-to-extinction ' , ' evolving-to-ext ' ], [ ' dont-do-something ' , ' dont-do-somethi ' ], [ ' terminal-values-and-instrumental-values ' , ' terminal-values ' ], [ ' treatment-futures ' , ' treatment-futur ' ], [ ' thou-art-godshatter ' , ' thou-art-godsha ' ], [ ' implicit-conditionals ' , ' implicit-condit ' ], [ ' protein-reinforcement-and-dna-consequentialism ' , ' protein-reinfor ' ], [ ' polarized-usa ' , ' polarized-usa ' ], [ ' evolutionary-psychology ' , ' evolutionary-ps ' ], [ ' adaptation-executers-not-fitness-maximizers ' , ' adaptation-exec ' ], [ ' overcoming-bias-at-work-for-engineers ' , ' overcoming-bias ' ], [ ' fake-optimization-criteria ' , ' fake-optimizati ' ], [ ' dawes-on-therapy ' , ' dawes-on-psycho ' ], [ ' friendly-ai-guide ' , ' fake-utility-fu ' ], [ ' fake-morality ' , ' fake-morality ' ], [ ' seat-belts-work ' , ' seat-belts-work ' ], [ ' fake-selfishness ' , ' fake-selfishnes ' ], [ ' inconsistent-paternalism ' , ' inconsistent-pa ' ], [ ' the-tragedy-of-group-selectionism ' , ' group-selection ' ], [ ' are-the-self-righteous-righteous ' , ' are-the-self-ri ' ], [ ' beware-of-stephen-j-gould ' , ' beware-of-gould ' ], [ ' college-admission-futures ' , ' college-admissi ' ], [ ' natural-selections-speed-limit-and-complexity-bound ' , ' natural-selecti ' ], [ ' -a-test-for-political-prediction-markets ' , ' a-test-for-poli ' ], [ ' passionately-wrong ' , ' passionately-wr ' ], -[ ' evolutions-are-stupid-but-work-anyway ' , ' evolutions-are- ' ], +[ ' evolutions-are-stupid-but-work-anyway ' , ' evolutions-are ' ], [ ' serious-unconventional-de-grey ' , ' serious-unconve ' ], [ ' the-wonder-of-evolution ' , ' the-wonder-of-e ' ], [ ' hospice-beats-hospital ' , ' hospice-beats-h ' ], [ ' an-alien-god ' , ' an-alien-god ' ], [ ' open-thread ' , ' open-thread ' ], -[ ' how-much-defer-to-experts ' , ' how-much-defer- ' ], +[ ' how-much-defer-to-experts ' , ' how-much-defer ' ], [ ' the-right-belief-for-the-wrong-reasons ' , ' the-right-belie ' ], [ ' fake-justification ' , ' fake-justificat ' ], [ ' a-terrifying-halloween-costume ' , ' a-terrifying-ha ' ], [ ' honest-teen-paternalism ' , ' teen-paternalis ' ], [ ' my-strange-beliefs ' , ' my-strange-beli ' ], [ ' cultish-countercultishness ' , ' cultish-counter ' ], [ ' to-lead-you-must-stand-up ' , ' stand-to-lead ' ], [ ' econ-of-longer-lives ' , ' neglected-pro-l ' ], [ ' lonely-dissent ' , ' lonely-dissent ' ], [ ' on-expressing-your-concerns ' , ' express-concern ' ], [ ' too-much-hope ' , ' too-much-hope ' ], [ ' aschs-conformity-experiment ' , ' aschs-conformit ' ], [ ' the-amazing-virgin-pregnancy ' , ' amazing-virgin ' ], [ ' procrastination ' , ' procrastination ' ], [ ' testing-hillary-clintons-oil-claim ' , ' testing-hillary ' ], [ ' zen-and-the-art-of-rationality ' , ' zen-and-the-art ' ], [ ' effortless-technique ' , ' effortless-tech ' ], [ ' false-laughter ' , ' false-laughter ' ], [ ' obligatory-self-mockery ' , ' obligatory-self ' ], [ ' the-greatest-gift-the-best-exercise ' , ' the-best-exerci ' ], [ ' two-cult-koans ' , ' cult-koans ' ], [ ' interior-economics ' , ' interior-econom ' ], [ ' politics-and-awful-art ' , ' politics-and-aw ' ], [ ' judgment-can-add-accuracy ' , ' judgment-can-ad ' ], [ ' the-litany-against-gurus ' , ' the-litany-agai ' ], [ ' the-root-of-all-political-stupidity ' , ' the-root-of-all ' ], [ ' guardians-of-ayn-rand ' , ' ayn-rand ' ], [ ' power-corrupts ' , ' power-corrupts ' ], [ ' teen-revolution-and-evolutionary-psychology ' , ' teen-revolution ' ], [ ' gender-tax ' , ' gender-tax ' ], [ ' guardians-of-the-gene-pool ' , ' guardians-of--1 ' ], [ ' battle-of-the-election-forecasters ' , ' battle-of-the-e ' ], [ ' guardians-of-the-truth ' , ' guardians-of-th ' ], [ ' hug-the-query ' , ' hug-the-query ' ], [ ' economist-judgment ' , ' economist-judgm ' ], [ ' justly-acquired-endowment-taxing-as-punishment-or-as-a-way-to-raise-money ' , ' justly-acquired ' ], [ ' argument-screens-off-authority ' , ' argument-screen ' ], [ ' give-juries-video-recordings-of-testimony ' , ' give-juries-vid ' ], [ ' reversed-stupidity-is-not-intelligence ' , ' reversed-stupid ' ], [ ' tax-the-tall ' , ' tax-the-tall ' ], [ ' every-cause-wants-to-be-a-cult ' , ' every-cause-wan ' ], [ ' does-healthcare-do-any-good-at-all ' , ' does-healthcare ' ], [ ' art-and-moral-responsibility ' , ' art-and-moral-r ' ], [ ' misc-meta ' , ' misc-meta ' ], [ ' it-is-good-to-exist ' , ' it-is-good-to-e ' ], [ ' the-robbers-cave-experiment ' , ' the-robbers-cav ' ], [ ' medicine-has-been-overcoming-bias-too ' , ' medicine-has-be ' ], [ ' when-none-dare-urge-restraint ' , ' when-none-dare ' ], [ ' modules-signals-and-guilt ' , ' modules-signals ' ], [ ' evaporative-cooling-of-group-beliefs ' , ' evaporative-coo ' ], [ ' doctor-hypocrisy ' , ' doctors-lie ' ], [ ' fake-utility-functions ' , ' fake-utility-fu ' ], [ ' open-thread ' , ' open-thread ' ], [ ' fake-fake-utility-functions ' , ' fake-fake-utili ' ], [ ' ethical-shortsightedness ' , ' ethical-shortsi ' ], [ ' heroic-job-bias ' , ' heroic-job-bias ' ], [ ' uncritical-supercriticality ' , ' supercritical-u ' ], [ ' resist-the-happy-death-spiral ' , ' resist-the-happ ' ], [ ' baby-selling ' , ' baby-selling ' ], [ ' affective-death-spirals ' , ' affective-death ' ], [ ' mere-messiahs ' , ' mere-messiahs ' ], [ ' superhero-bias ' , ' superhero-bias ' ], [ ' ob-meetup-millbrae-thu-21-feb-7pm ' , ' ob-meetup-millb ' ], [ ' newcombs-problem-and-regret-of-rationality ' , ' newcombs-proble ' ], [ ' dark-police ' , ' privacy-lost ' ], [ ' contingent-truth-value ' , ' contingent-trut ' ], [ ' deliberative-prediction-markets----a-reply ' , ' deliberative-pr ' ], [ ' something-to-protect ' , ' something-to-pr ' ], [ ' deliberation-in-prediction-markets ' , ' deliberation-in ' ], [ ' trust-in-bayes ' , ' trust-in-bayes ' ], -[ ' predictocracy----a-preliminary-response ' , ' predictocracy- ' ], +[ ' predictocracy----a-preliminary-response ' , ' predictocracy ' ], [ ' the-intuitions-behind-utilitarianism ' , ' the-intuitions ' ], [ ' voters-want-simplicity ' , ' voters-want-sim ' ], [ ' predictocracy ' , ' predictocracy ' ], [ ' rationality-quotes-9 ' , ' quotes-9 ' ], [ ' knowing-your-argumentative-limitations-or-one-rationalists-modus-ponens-is-anothers-modus-tollens ' , ' knowing-your-ar ' ], [ ' problems-with-prizes ' , ' problems-with-p ' ], [ ' rationality-quotes-8 ' , ' quotes-8 ' ], [ ' acceptable-casualties ' , ' acceptable-casu ' ], [ ' rationality-quotes-7 ' , ' quotes-7 ' ], [ ' cfo-overconfidence ' , ' ceo-overconfide ' ], [ ' rationality-quotes-6 ' , ' quotes-6 ' ], [ ' rationality-quotes-5 ' , ' quotes-5 ' ], [ ' connections-versus-insight ' , ' connections-ver ' ], [ ' circular-altruism ' , ' circular-altrui ' ], [ ' for-discount-rates ' , ' protecting-acro ' ], [ ' against-discount-rates ' , ' against-discoun ' ], [ ' allais-malaise ' , ' allais-malaise ' ], [ ' mandatory-sensitivity-training-fails ' , ' mandatory-sensi ' ], [ ' rationality-quotes-4 ' , ' quotes-4 ' ], [ ' zut-allais ' , ' zut-allais ' ], [ ' the-allais-paradox ' , ' allais-paradox ' ], [ ' nesse-on-academia ' , ' nesse-on-academ ' ], [ ' antidepressant-publication-bias ' , ' antidepressant ' ], [ ' rationality-quotes-3 ' , ' rationality-quo ' ], [ ' rationality-quotes-2 ' , ' quotes-2 ' ], [ ' just-enough-expertise ' , ' trolls-on-exper ' ], [ ' rationality-quotes-1 ' , ' quotes-1 ' ], [ ' trust-in-math ' , ' trust-in-math ' ], [ ' economist-as-scrooge ' , ' economist-as-sc ' ], [ ' beautiful-probability ' , ' beautiful-proba ' ], [ ' leading-bias-researcher-turns-out-to-be-biased-renounces-result ' , ' leading-bias-re ' ], [ ' is-reality-ugly ' , ' is-reality-ugly ' ], [ ' dont-choose-a-president-the-way-youd-choose-an-assistant-regional-manager ' , ' dont-choose-a-p ' ], [ ' expecting-beauty ' , ' expecting-beaut ' ], [ ' how-to-fix-wage-bias ' , ' profit-by-corre ' ], [ ' beautiful-math ' , ' beautiful-math ' ], [ ' 0-and-1-are-not-probabilities ' , ' 0-and-1-are-not ' ], [ ' once-more-with-feeling ' , ' once-more-with ' ], [ ' political-inequality ' , ' political-inequ ' ], [ ' infinite-certainty ' , ' infinite-certai ' ], [ ' more-presidential-decision-markets ' , ' more-presidenti ' ], [ ' experiencing-the-endowment-effect ' , ' experiencing-th ' ], [ ' absolute-authority ' , ' absolute-author ' ], [ ' social-scientists-know-lots ' , ' social-scientis ' ], [ ' the-fallacy-of-gray ' , ' gray-fallacy ' ], [ ' are-we-just-pumping-against-entropy-or-can-we-win ' , ' are-we-just-pum ' ], [ ' art-trust-and-betrayal ' , ' art-trust-and-b ' ], [ ' nuked-us-futures ' , ' nuked-us-future ' ], [ ' but-theres-still-a-chance-right ' , ' still-a-chance ' ], [ ' a-failed-just-so-story ' , ' a-failed-just-s ' ], [ ' presidential-decision-markets ' , ' presidential-de ' ], [ ' open-thread ' , ' open-thread ' ], [ ' rational-vs-scientific-ev-psych ' , ' rational-vs-sci ' ], [ ' weekly-exercises ' , ' weekly-exercise ' ], [ ' yes-it-can-be-rational-to-vote-in-presidential-elections ' , ' yes-it-can-be-r ' ], [ ' debugging-comments ' , ' debugging-comme ' ], [ ' stop-voting-for-nincompoops ' , ' stop-voting-for ' ], [ ' i-dare-you-bunzl ' , ' in-yesterdays-p ' ], [ ' the-american-system-and-misleading-labels ' , ' the-american-sy ' ], [ ' some-structural-biases-of-the-political-system ' , ' some-structural ' ], [ ' a-politicians-job ' , ' a-politicians-j ' ], [ ' the-ordering-of-authors-names-in-academic-publications ' , ' the-ordering-of ' ], [ ' the-two-party-swindle ' , ' the-two-party-s ' ], [ ' posting-on-politics ' , ' posting-on-poli ' ], [ ' searching-for-bayes-structure ' , ' bayes-structure ' ], [ ' perpetual-motion-beliefs ' , ' perpetual-motio ' ], [ ' ignoring-advice ' , ' ignoring-advice ' ], [ ' the-second-law-of-thermodynamics-and-engines-of-cognition ' , ' second-law ' ], [ ' leave-a-line-of-retreat ' , ' leave-retreat ' ], [ ' more-referee-bias ' , ' more-referee-bi ' ], [ ' superexponential-conceptspace-and-simple-words ' , ' superexp-concep ' ], [ ' my-favorite-liar ' , ' my-favorite-lia ' ], [ ' mutual-information-and-density-in-thingspace ' , ' mutual-informat ' ], [ ' if-self-fulfilling-optimism-is-wrong-i-dont-wanna-be-right ' , ' if-self-fulfill ' ], [ ' entropy-and-short-codes ' , ' entropy-codes ' ], [ ' more-moral-wiggle-room ' , ' more-moral-wigg ' ], [ ' where-to-draw-the-boundary ' , ' where-boundary ' ], [ ' the-hawthorne-effect ' , ' the-hawthorne-e ' ], [ ' categories-and-information-theory ' , ' a-bayesian-view ' ], [ ' arguing-by-definition ' , ' arguing-by-defi ' ], [ ' against-polish ' , ' against-polish ' ], [ ' colorful-character-again ' , ' colorful-charac ' ], [ ' sneaking-in-connotations ' , ' sneak-connotati ' ], [ ' nephew-versus-nepal-charity ' , ' nephews-versus ' ], [ ' categorizing-has-consequences ' , ' category-conseq ' ], [ ' the-public-intellectual-plunge ' , ' the-public-inte ' ], [ ' fallacies-of-compression ' , ' compress-fallac ' ], [ ' with-blame-comes-hope ' , ' with-blame-come ' ], [ ' relative-vs-absolute-rationality ' , ' relative-vs-abs ' ], [ ' replace-the-symbol-with-the-substance ' , ' replace-symbol ' ], [ ' talking-versus-trading ' , ' comparing-delib ' ], [ ' taboo-your-words ' , ' taboo-words ' ], [ ' why-just-believe ' , ' why-just-believ ' ], [ ' classic-sichuan-in-millbrae-thu-feb-21-7pm ' , ' millbrae-thu-fe ' ], [ ' empty-labels ' , ' empty-labels ' ], [ ' is-love-something-more ' , ' is-love-somethi ' ], [ ' the-argument-from-common-usage ' , ' common-usage ' ], [ ' pod-people-paternalism ' , ' pod-people-pate ' ], [ ' feel-the-meaning ' , ' feel-meaning ' ], [ ' dinos-on-the-moon ' , ' dinos-on-the-mo ' ], [ ' disputing-definitions ' , ' disputing-defin ' ], [ ' what-is-worth-study ' , ' what-is-worth-s ' ], [ ' how-an-algorithm-feels-from-inside ' , ' algorithm-feels ' ], [ ' nanotech-views-value-driven ' , ' nanotech-views ' ], [ ' neural-categories ' , ' neural-categori ' ], [ ' believing-too-little ' , ' believing-too-l ' ], [ ' disguised-queries ' , ' disguised-queri ' ], [ ' eternal-medicine ' , ' eternal-medicin ' ], [ ' the-cluster-structure-of-thingspace ' , ' thingspace-clus ' ], [ ' typicality-and-asymmetrical-similarity ' , ' typicality-and ' ], [ ' what-wisdom-silence ' , ' what-wisdom-sil ' ], [ ' similarity-clusters ' , ' similarity-clus ' ], [ ' buy-now-or-forever-hold-your-peace ' , ' buy-now-or-fore ' ], [ ' extensions-and-intensions ' , ' extensions-inte ' ], [ ' lets-do-like-them ' , ' lets-do-like-th ' ], [ ' words-as-hidden-inferences ' , ' words-as-hidden ' ], [ ' predictocracy-vs-futarchy ' , ' predictocracy-v ' ], [ ' the-parable-of-hemlock ' , ' hemlock-parable ' ], [ ' merger-decision-markets ' , ' merger-decision ' ], [ ' open-thread ' , ' open-thread ' ], [ ' the-parable-of-the-dagger ' , ' dagger-parable ' ], [ ' futarchy-vs-predictocracy ' , ' futarchy-vs-pre ' ], [ ' against-news ' , ' against-news ' ], [ ' angry-atoms ' , ' angry-atoms ' ], [ ' hand-vs-fingers ' , ' hand-vs-fingers ' ], [ ' impotence-of-belief-in-bias ' , ' impotence-of-be ' ], [ ' initiation-ceremony ' , ' initiation-cere ' ], [ ' cash-increases-accuracy ' , ' cash-clears-the ' ], [ ' to-spread-science-keep-it-secret ' , ' spread-science ' ], [ ' ancient-political-self-deception ' , ' ancient-politic ' ], [ ' scarcity ' , ' scarcity ' ], [ ' fantasy-and-reality-substitutes-or-complements ' , ' fantasy-and-rea ' ], [ ' is-humanism-a-religion-substitute ' , ' is-humanism-rel ' ], [ ' showing-that-you-care ' , ' showing-that-yo ' ], [ ' amazing-breakthrough-day-april-1st ' , ' amazing-breakth ' ], [ ' correction-ny-ob-meetup-13-astor-place-25 ' , ' correction-ny-o ' ], [ ' religious-cohesion ' , ' religious-cohes ' ], [ ' the-beauty-of-settled-science ' , ' beauty-settled ' ], [ ' where-want-fewer-women ' , ' where-want-less ' ], [ ' new-york-ob-meetup-ad-hoc-on-monday-mar-24-6pm ' , ' new-york-ob-mee ' ], [ ' if-you-demand-magic-magic-wont-help ' , ' against-magic ' ], [ ' biases-in-processing-political-information ' , ' biases-in-proce ' ], [ ' bind-yourself-to-reality ' , ' bind-yourself-t ' ], [ ' boards-of-advisors-dont-advise-do-board ' , ' boards-of-advis ' ], [ ' joy-in-discovery ' , ' joy-in-discover ' ], [ ' joy-in-the-merely-real ' , ' joy-in-the-real ' ], [ ' sincerity-is-overrated ' , ' sincerity-is-wa ' ], [ ' rationalists-lets-make-a-movie ' , ' rationalists-le ' ], [ ' savanna-poets ' , ' savanna-poets ' ], [ ' biases-and-investing ' , ' biases-and-inve ' ], [ ' morality-is-overrated ' , ' unwanted-morali ' ], [ ' fake-reductionism ' , ' fake-reductioni ' ], [ ' theyre-only-tokens ' , ' theyre-only-tok ' ], [ ' explaining-vs-explaining-away ' , ' explaining-away ' ], [ ' reductionism ' , ' reductionism ' ], [ ' a-few-quick-links ' , ' a-few-quick-lin ' ], [ ' qualitatively-confused ' , ' qualitatively-c ' ], [ ' the-kind-of-project-to-watch ' , ' the-project-to ' ], [ ' penguicon-blook ' , ' penguicon-blook ' ], [ ' one-million-visits ' , ' one-million-vis ' ], [ ' distinguish-info-analysis-belief-action ' , ' distinguish-inf ' ], [ ' the-quotation-is-not-the-referent ' , ' quote-not-refer ' ], [ ' neglecting-conceptual-research ' , ' scott-aaronson ' ], [ ' probability-is-in-the-mind ' , ' mind-probabilit ' ], [ ' limits-to-physics-insight ' , ' limits-to-physi ' ], [ ' mind-projection-fallacy ' , ' mind-projection ' ], [ ' mind-projection-by-default ' , ' mpf-by-default ' ], [ ' uninformative-experience ' , ' uninformative-e ' ], [ ' righting-a-wrong-question ' , ' righting-a-wron ' ], [ ' wrong-questions ' , ' wrong-questions ' ], [ ' dissolving-the-question ' , ' dissolving-the ' ], [ ' bias-and-power ' , ' biased-for-and ' ], [ ' gary-gygax-annihilated-at-69 ' , ' gary-gygax-anni ' ], [ ' wilkinson-on-paternalism ' , ' wilkinson-on-pa ' ], [ ' 37-ways-that-words-can-be-wrong ' , ' wrong-words ' ], [ ' overvaluing-ideas ' , ' overvaluing-ide ' ], [ ' reject-random-beliefs ' , ' reject-random-b ' ], [ ' variable-question-fallacies ' , ' variable-questi ' ], [ ' rationality-quotes-11 ' , ' rationality-q-1 ' ], [ ' human-capital-puzzle-explained ' , ' human-capital-p ' ], [ ' rationality-quotes-10 ' , ' rationality-quo ' ], [ ' words-as-mental-paintbrush-handles ' , ' mental-paintbru ' ], [ ' open-thread ' , ' open-thread ' ], [ ' framing-problems-as-separate-from-people ' , ' framing-problem ' ], [ ' conditional-independence-and-naive-bayes ' , ' conditional-ind ' ], [ ' be-biased-to-be-happy ' , ' be-biased-to-be ' ], [ ' optimism-bias-desired ' , ' optimism-bias-d ' ], [ ' decoherent-essences ' , ' decoherent-esse ' ], [ ' self-copying-factories ' , ' replication-bre ' ], [ ' decoherence-is-pointless ' , ' pointless-decoh ' ], [ ' charm-beats-accuracy ' , ' charm-beats-acc ' ], [ ' the-conscious-sorites-paradox ' , ' conscious-sorit ' ], [ ' decoherent-details ' , ' decoherent-deta ' ], [ ' on-being-decoherent ' , ' on-being-decohe ' ], [ ' quantum-orthodoxy ' , ' quantum-quotes ' ], [ ' if-i-had-a-million ' , ' if-i-had-a-mill ' ], [ ' where-experience-confuses-physicists ' , ' where-experienc ' ], [ ' thou-art-decoherent ' , ' the-born-probab ' ], [ ' blaming-the-unlucky ' , ' blaming-the-unl ' ], [ ' where-physics-meets-experience ' , ' physics-meets-e ' ], [ ' early-scientists-chose-influence-over-credit ' , ' early-scientist ' ], [ ' which-basis-is-more-fundamental ' , ' which-basis-is ' ], [ ' a-model-disagreement ' , ' a-model-disagre ' ], [ ' the-so-called-heisenberg-uncertainty-principle ' , ' heisenberg ' ], [ ' caplan-pulls-along-ropes ' , ' caplan-pulls-al ' ], [ ' decoherence ' , ' decoherence ' ], [ ' paternalism-parable ' , ' paternalism-par ' ], [ ' three-dialogues-on-identity ' , ' identity-dialog ' ], [ ' on-philosophers ' , ' on-philosophers ' ], [ ' zombies-the-movie ' , ' zombie-movie ' ], [ ' schwitzgebel-thoughts ' , ' schwitzgebel-th ' ], [ ' identity-isnt-in-specific-atoms ' , ' identity-isnt-i ' ], [ ' elevator-myths ' , ' elevator-myths ' ], [ ' no-individual-particles ' , ' no-individual-p ' ], [ ' is-she-just-friendly ' , ' is-she-just-bei ' ], [ ' feynman-paths ' , ' feynman-paths ' ], [ ' kids-parents-disagree-on-spouses ' , ' kids-parents-di ' ], [ ' the-quantum-arena ' , ' quantum-arena ' ], [ ' classical-configuration-spaces ' , ' conf-space ' ], [ ' how-to-vs-what-to ' , ' how-to-vs-what ' ], [ ' can-you-prove-two-particles-are-identical ' , ' identical-parti ' ], [ ' naming-beliefs ' , ' naming-beliefs ' ], [ ' where-philosophy-meets-science ' , ' philosophy-meet ' ], [ ' distinct-configurations ' , ' distinct-config ' ], [ ' conformity-questions ' , ' conformity-ques ' ], [ ' conformity-myths ' , ' conformity-myth ' ], [ ' joint-configurations ' , ' joint-configura ' ], [ ' configurations-and-amplitude ' , ' configurations ' ], [ ' prevention-costs ' , ' prevention-cost ' ], [ ' quantum-explanations ' , ' quantum-explana ' ], [ ' inhuman-rationality ' , ' inhuman-rationa ' ], [ ' belief-in-the-implied-invisible ' , ' implied-invisib ' ], [ ' endearing-sincerity ' , ' sincerity-i-lik ' ], [ ' gazp-vs-glut ' , ' gazp-vs-glut ' ], [ ' the-generalized-anti-zombie-principle ' , ' anti-zombie-pri ' ], [ ' anxiety-about-what-is-true ' , ' anxiety-about-w ' ], [ ' ramone-on-knowing-god ' , ' ramone-on-knowi ' ], [ ' zombie-responses ' , ' zombies-ii ' ], [ ' brownlee-on-selling-anxiety ' , ' brownlee-on-sel ' ], [ ' zombies-zombies ' , ' zombies ' ], [ ' reductive-reference ' , ' reductive-refer ' ], [ ' arbitrary-silliness ' , ' arbitrary-silli ' ], [ ' brain-breakthrough-its-made-of-neurons ' , ' brain-breakthro ' ], [ ' open-thread ' , ' open-thread ' ], [ ' why-i-dont-like-bayesian-statistics ' , ' why-i-dont-like ' ], [ ' beware-of-brain-images ' , ' beware-of-brain ' ], [ ' heat-vs-motion ' , ' heat-vs-motion ' ], [ ' physics-your-brain-and-you ' , ' physics-your-br ' ], [ ' a-premature-word-on-ai ' , ' an-ai-new-timer ' ], [ ' ai-old-timers ' , ' roger-shank-ai ' ], [ ' empty-space ' , ' empty-space ' ], [ ' class-project ' , ' class-project ' ], [ ' einsteins-superpowers ' , ' einsteins-super ' ], [ ' intro-to-innovation ' , ' intro-to-innova ' ], [ ' timeless-causality ' , ' timeless-causal ' ], [ ' overconfidence-paternalism ' , ' paul-graham-off ' ], [ ' timeless-beauty ' , ' timeless-beauty ' ], [ ' lazy-lineup-study ' , ' why-is-this-so ' ], [ ' timeless-physics ' , ' timeless-physic ' ], [ ' the-end-of-time ' , ' the-end-of-time ' ], [ ' 2nd-annual-roberts-podcast ' , ' 2nd-annual-robe ' ], [ ' who-shall-we-honor ' , ' who-should-we-h ' ], [ ' relative-configuration-space ' , ' relative-config ' ], [ ' beware-identity ' , ' beware-identity ' ], [ ' prediction-markets-and-insider-trading ' , ' prediction-mark ' ], [ ' a-broken-koan ' , ' a-broken-koan ' ], [ ' machs-principle-anti-epiphenomenal-physics ' , ' machs-principle ' ], [ ' lying-to-kids ' , ' lying-to-kids ' ], [ ' my-childhood-role-model ' , ' my-childhood-ro ' ], [ ' that-alien-message ' , ' faster-than-ein ' ], [ ' anthropic-breakthrough ' , ' anthropic-break ' ], [ ' einsteins-speed ' , ' einsteins-speed ' ], [ ' transcend-or-die ' , ' transcend-or-di ' ], [ ' far-future-disagreement ' , ' far-future-disa ' ], [ ' faster-than-science ' , ' faster-than-sci ' ], [ ' conference-on-global-catastrophic-risks ' , ' conference-on-g ' ], [ ' biting-evolution-bullets ' , ' biting-evolutio ' ], [ ' changing-the-definition-of-science ' , ' changing-the-de ' ], [ ' no-safe-defense-not-even-science ' , ' no-defenses ' ], [ ' bounty-slander ' , ' bounty-slander ' ], [ ' idea-futures-in-lumpaland ' , ' idea-futures-in ' ], [ ' do-scientists-already-know-this-stuff ' , ' do-scientists-a ' ], [ ' lobbying-for-prediction-markets ' , ' lobbying-for-pr ' ], [ ' science-isnt-strict-ienoughi ' , ' science-isnt-st ' ], [ ' lumpaland-parable ' , ' lumpaland-parab ' ], [ ' when-science-cant-help ' , ' when-science-ca ' ], [ ' honest-politics ' , ' honest-politics ' ], [ ' science-doesnt-trust-your-rationality ' , ' science-doesnt ' ], [ ' sleepy-fools ' , ' sleepy-fools ' ], [ ' the-dilemma-science-or-bayes ' , ' science-or-baye ' ], [ ' the-failures-of-eld-science ' , ' eld-science ' ], [ ' condemned-to-repeat-finance-past ' , ' condemned-to-re ' ], [ ' many-worlds-one-best-guess ' , ' many-worlds-one ' ], [ ' why-quantum ' , ' why-quantum ' ], [ ' happy-conservatives ' , ' happy-conservat ' ], [ ' if-many-worlds-had-come-first ' , ' if-many-worlds ' ], [ ' elusive-placebos ' , ' elusive-placebo ' ], [ ' collapse-postulates ' , ' collapse-postul ' ], [ ' faith-in-docs ' , ' faith-in-docs ' ], [ ' quantum-non-realism ' , ' eppur-si-moon ' ], [ ' iexpelledi-beats-isickoi ' , ' expelled-beats ' ], [ ' decoherence-is-falsifiable-and-testable ' , ' mwi-is-falsifia ' ], [ ' guilt-by-association ' , ' guilt-and-all-b ' ], [ ' decoherence-is-simple ' , ' mwi-is-simple ' ], [ ' keeping-math-real ' , ' keeping-math-re ' ], [ ' spooky-action-at-a-distance-the-no-communication-theorem ' , ' spooky-action-a ' ], [ ' walking-on-grass-others ' , ' walking-on-gras ' ], [ ' bells-theorem-no-epr-reality ' , ' bells-theorem-n ' ], [ ' beware-transfusions ' , ' beware-blood-tr ' ], [ ' entangled-photons ' , ' entangled-photo ' ], [ ' beware-supplements ' , ' beware-suppleme ' ], [ ' decoherence-as-projection ' , ' projection ' ], [ ' open-thread ' , ' open-thread ' ], [ ' im-in-boston ' , ' im-in-boston ' ], [ ' the-born-probabilities ' , ' the-born-prob-1 ' ], [ ' experience-increases-overconfidence ' , ' the-latest-jour ' ], [ ' the-moral-void ' , ' moral-void ' ], [ ' what-would-you-do-without-morality ' , ' without-moralit ' ], [ ' average-your-guesses ' , ' average-your-gu ' ], [ ' the-opposite-sex ' , ' opposite-sex ' ], [ ' the-conversation-so-far ' , ' the-conversatio ' ], [ ' glory-vs-relations ' , ' glory-vs-relati ' ], [ ' 2-place-and-1-place-words ' , ' 2-place-and-1-p ' ], [ ' caution-kills-when-fighting-malaria ' , ' caution-kills-w ' ], [ ' to-what-expose-kids ' , ' to-what-expose ' ], [ ' no-universally-compelling-arguments ' , ' no-universally ' ], [ ' the-design-space-of-minds-in-general ' , ' minds-in-genera ' ], [ ' should-bad-boys-win ' , ' why-do-psychopa ' ], [ ' the-psychological-unity-of-humankind ' , ' psychological-u ' ], [ ' eliezers-meta-level-determinism ' , ' eliezers-meta-l ' ], [ ' optimization-and-the-singularity ' , ' optimization-an ' ], [ ' tyler-vid-on-disagreement ' , ' tyler-vid-on-di ' ], [ ' are-meta-views-outside-views ' , ' are-meta-views ' ], [ ' surface-analogies-and-deep-causes ' , ' surface-analogi ' ], [ ' parsing-the-parable ' , ' parsing-the-par ' ], [ ' the-outside-views-domain ' , ' when-outside-vi ' ], [ ' outside-view-of-singularity ' , ' singularity-out ' ], [ ' heading-toward-morality ' , ' toward-morality ' ], [ ' la-602-vs-rhic-review ' , ' la-602-vs-rhic ' ], [ ' history-of-transition-inequality ' , ' singularity-ine ' ], [ ' britain-was-too-small ' , ' britain-was-too ' ], [ ' natural-genocide ' , ' natural-genocid ' ], [ ' what-is-the-probability-of-the-large-hadron-collider-destroying-the-universe ' , ' what-is-the-pro ' ], [ ' ghosts-in-the-machine ' , ' ghosts-in-the-m ' ], [ ' gratitude-decay ' , ' gratitude-decay ' ], [ ' loud-bumpers ' , ' loud-bumpers ' ], [ ' grasping-slippery-things ' , ' grasping-slippe ' ], [ ' in-bias-meta-is-max ' , ' meta-is-max---b ' ], [ ' passing-the-recursive-buck ' , ' pass-recursive ' ], [ ' in-innovation-meta-is-max ' , ' meta-is-max---i ' ], [ ' the-ultimate-source ' , ' the-ultimate-so ' ], [ ' possibility-and-could-ness ' , ' possibility-and ' ], [ ' joe-epstein-on-youth ' , ' joe-epstein-on ' ], [ ' causality-and-moral-responsibility ' , ' causality-and-r ' ], [ ' anti-depressants-fail ' , ' anti-depressant ' ], [ ' quantum-mechanics-and-personal-identity ' , ' qm-and-identity ' ], [ ' and-the-winner-is-many-worlds ' , ' mwi-wins ' ], [ ' quantum-physics-revealed-as-non-mysterious ' , ' quantum-physics ' ], [ ' an-intuitive-explanation-of-quantum-mechanics ' , ' an-intuitive-ex ' ], [ ' prediction-market-based-electoral-map-forecast ' , ' prediction-mark ' ], [ ' tv-is-porn ' , ' tv-is-porn ' ], [ ' the-quantum-physics-sequence ' , ' the-quantum-phy ' ], [ ' never-is-a-long-time ' , ' never-is-a-long ' ], [ ' eliezers-post-dependencies-book-notification-graphic-designer-wanted ' , ' eliezers-post-d ' ], [ ' anti-foreign-bias ' , ' tyler-in-the-ny ' ], [ ' against-devils-advocacy ' , ' against-devils ' ], [ ' the-future-of-oil-prices-3-nonrenewable-resource-pricing ' , ' the-future-of-o ' ], [ ' meetup-in-nyc-wed ' , ' meetup-in-nyc-w ' ], [ ' how-honest-with-kids ' , ' how-honest-with ' ], [ ' bloggingheads-yudkowsky-and-horgan ' , ' bloggingheads-y ' ], [ ' oil-scapegoats ' , ' manipulation-go ' ], [ ' timeless-control ' , ' timeless-contro ' ], [ ' how-to-add-2-to-gdp ' , ' how-to-increase ' ], [ ' thou-art-physics ' , ' thou-art-physic ' ], [ ' overcoming-disagreement ' , ' overcoming-disa ' ], [ ' living-in-many-worlds ' , ' living-in-many ' ], [ ' wait-for-it ' , ' wait-for-it ' ], [ ' why-quantum ' , ' why-quantum ' ], [ ' against-disclaimers ' , ' against-disclai ' ], [ ' timeless-identity ' , ' timeless-identi ' ], [ ' exploration-as-status ' , ' exploration-as ' ], [ ' principles-of-disagreement ' , ' principles-of-d ' ], [ ' the-rhythm-of-disagreement ' , ' the-rhythm-of-d ' ], [ ' open-thread ' , ' open-thread ' ], [ ' singularity-economics ' , ' economics-of-si ' ], [ ' detached-lever-fallacy ' , ' detached-lever ' ], [ ' ok-now-im-worried ' , ' ok-im-worried ' ], [ ' humans-in-funny-suits ' , ' humans-in-funny ' ], [ ' touching-vs-understanding ' , ' touching-vs-und ' ], [ ' intrades-conditional-prediction-markets ' , ' intrades-condit ' ], [ ' when-to-think-critically ' , ' when-to-think-c ' ], [ ' interpersonal-morality ' , ' interpersonal-m ' ], [ ' the-meaning-of-right ' , ' the-meaning-of ' ], [ ' funding-bias ' , ' funding-bias ' ], [ ' setting-up-metaethics ' , ' setting-up-meta ' ], [ ' bias-against-the-unseen ' , ' biased-against ' ], [ ' changing-your-metaethics ' , ' retreat-from-me ' ], [ ' is-ideology-about-status ' , ' is-ideology-abo ' ], [ ' gary-taubes-good-calories-bad-calories ' , ' gary-taubes-goo ' ], [ ' does-your-morality-care-what-you-think ' , ' does-morality-c ' ], [ ' refuge-markets ' , ' refuge-markets ' ], [ ' math-is-subjunctively-objective ' , ' math-is-subjunc ' ], [ ' can-counterfactuals-be-true ' , ' counterfactual ' ], [ ' when-not-to-use-probabilities ' , ' when-not-to-use ' ], [ ' banning-bad-news ' , ' banning-bad-new ' ], [ ' your-morality-doesnt-care-what-you-think ' , ' moral-counterfa ' ], [ ' fake-norms-or-truth-vs-truth ' , ' fake-norms-or-t ' ], [ ' loving-loyalty ' , ' loving-loyalty ' ], [ ' should-we-ban-physics ' , ' should-we-ban-p ' ], [ ' touching-the-old ' , ' touching-the-ol ' ], [ ' existential-angst-factory ' , ' existential-ang ' ], [ ' corporate-assassins ' , ' corporate-assas ' ], [ ' could-anything-be-right ' , ' anything-right ' ], [ ' doxastic-voluntarism-and-some-puzzles-about-rationality ' , ' doxastic-volunt ' ], [ ' disaster-bias ' , ' disaster-bias ' ], [ ' the-gift-we-give-to-tomorrow ' , ' moral-miracle-o ' ], [ ' world-welfare-state ' , ' world-welfare-s ' ], [ ' whither-moral-progress ' , ' whither-moral-p ' ], [ ' posting-may-slow ' , ' posting-may-slo ' ], [ ' bias-in-political-conversation ' , ' bias-in-politic ' ], [ ' lawrence-watt-evanss-fiction ' , ' lawrence-watt-e ' ], [ ' fear-god-and-state ' , ' fear-god-and-st ' ], [ ' probability-is-subjectively-objective ' , ' probability-is ' ], [ ' rebelling-within-nature ' , ' rebelling-withi ' ], [ ' ask-for-help ' , ' ask-for-help ' ], [ ' fundamental-doubts ' , ' fundamental-dou ' ], [ ' biases-of-elite-education ' , ' biases-of-elite ' ], [ ' the-genetic-fallacy ' , ' genetic-fallacy ' ], [ ' my-kind-of-reflection ' , ' my-kind-of-refl ' ], [ ' helsinki-meetup ' , ' helsinki-meetup ' ], [ ' poker-vs-chess ' , ' poker-vs-chess ' ], [ ' cloud-seeding-markets ' , ' cloud-seeding-m ' ], [ ' the-fear-of-common-knowledge ' , ' fear-of-ck ' ], [ ' where-recursive-justification-hits-bottom ' , ' recursive-justi ' ], [ ' artificial-volcanoes ' , ' artificial-volc ' ], [ ' cftc-event-market-comment ' , ' my-cftc-event-c ' ], [ ' will-as-thou-wilt ' , ' will-as-thou-wi ' ], [ ' rationalist-origin-stories ' , ' rationalist-ori ' ], [ ' all-hail-info-theory ' , ' all-hail-info-t ' ], [ ' morality-is-subjectively-objective ' , ' subjectively-ob ' ], [ ' bloggingheads-hanson-wilkinson ' , ' bloggingheads-m ' ], [ ' is-morality-given ' , ' is-morality-giv ' ], [ ' the-most-amazing-productivity-tip-ever ' , ' the-most-amazin ' ], [ ' is-morality-preference ' , ' is-morality-pre ' ], [ ' rah-my-country ' , ' yeah-my-country ' ], [ ' moral-complexities ' , ' moral-complexit ' ], [ ' 2-of-10-not-3-total ' , ' 2-of-10-not-3-t ' ], [ ' overconfident-investing ' , ' overconfident-i ' ], [ ' the-bedrock-of-fairness ' , ' bedrock-fairnes ' ], [ ' sex-nerds-and-entitlement ' , ' sex-nerds-and-e ' ], [ ' break-it-down ' , ' break-it-down ' ], [ ' why-argue-values ' , ' why-argue-value ' ], [ ' id-take-it ' , ' id-take-it ' ], [ ' distraction-overcomes-moral-hypocrisy ' , ' distraction-ove ' ], [ ' open-thread ' , ' open-thread ' ], [ ' overcoming-our-vs-others-biases ' , ' overcoming-our ' ], [ ' created-already-in-motion ' , ' moral-ponens ' ], [ ' morality-made-easy ' , ' morality-made-e ' ], [ ' brief-break ' , ' brief-break ' ], [ ' dreams-of-friendliness ' , ' dreams-of-frien ' ], [ ' fake-fish ' , ' fake-fish ' ], [ ' qualitative-strategies-of-friendliness ' , ' qualitative-str ' ], [ ' cowen-hanson-bloggingheads-topics ' , ' cowen-hanson-bl ' ], [ ' moral-false-consensus ' , ' moral-false-con ' ], [ ' harder-choices-matter-less ' , ' harder-choices ' ], [ ' the-complexity-critique ' , ' the-complexity ' ], [ ' against-modal-logics ' , ' against-modal-l ' ], [ ' top-teachers-ineffective ' , ' certified-teach ' ], [ ' dreams-of-ai-design ' , ' dreams-of-ai-de ' ], [ ' top-docs-no-healthier ' , ' top-school-docs ' ], [ ' three-fallacies-of-teleology ' , ' teleology ' ], [ ' use-the-native-architecture ' , ' use-the-native ' ], [ ' cowen-disses-futarchy ' , ' cowen-dises-fut ' ], [ ' magical-categories ' , ' magical-categor ' ], [ ' randomised-controlled-trials-of-parachutes ' , ' randomised-cont ' ], [ ' unnatural-categories ' , ' unnatural-categ ' ], [ ' good-medicine-in-merry-old-england ' , ' good-medicine-i ' ], [ ' mirrors-and-paintings ' , ' mirrors-and-pai ' ], [ ' beauty-bias ' , ' ignore-beauty ' ], [ ' invisible-frameworks ' , ' invisible-frame ' ], [ ' dark-dreams ' , ' dark-dreams ' ], [ ' no-license-to-be-human ' , ' no-human-licens ' ], [ ' are-ufos-aliens ' , ' are-ufos-aliens ' ], [ ' you-provably-cant-trust-yourself ' , ' no-self-trust ' ], [ ' caplan-gums-bullet ' , ' caplan-gums-bul ' ], [ ' dumb-deplaning ' , ' dumb-deplaning ' ], [ ' mundane-dishonesty ' , ' mundane-dishone ' ], [ ' the-cartoon-guide-to-lbs-theorem ' , ' lobs-theorem ' ], [ ' bias-in-real-life-a-personal-story ' , ' bias-in-real-li ' ], [ ' when-anthropomorphism-became-stupid ' , ' when-anthropomo ' ], [ ' hot-air-doesnt-disagree ' , ' hot-air-doesnt ' ], [ ' the-baby-eating-aliens-13 ' , ' baby-eaters ' ], [ ' manipulators-as-mirrors ' , ' manipulators-as ' ], [ ' the-bedrock-of-morality-arbitrary ' , ' arbitrary-bedro ' ], [ ' is-fairness-arbitrary ' , ' arbitrarily-fai ' ], [ ' self-indication-solves-time-asymmetry ' , ' self-indication ' ], [ ' schelling-and-the-nuclear-taboo ' , ' schelling-and-t ' ], [ ' arbitrary ' , ' unjustified ' ], [ ' new-best-game-theory ' , ' new-best-game-t ' ], [ ' abstracted-idealized-dynamics ' , ' computations ' ], [ ' future-altruism-not ' , ' future-altruism ' ], [ ' moral-error-and-moral-disagreement ' , ' moral-disagreem ' ], [ ' doctor-there-are-two-kinds-of-no-evidence ' , ' doctor-there-ar ' ], [ ' suspiciously-vague-lhc-forecasts ' , ' suspiciously-va ' ], [ ' sorting-pebbles-into-correct-heaps ' , ' pebblesorting-p ' ], [ ' the-problem-at-the-heart-of-pascals-wager ' , ' the-problem-at ' ], [ ' inseparably-right-or-joy-in-the-merely-good ' , ' rightness-redux ' ], [ ' baxters-ifloodi ' , ' baxters-flood ' ], [ ' morality-as-fixed-computation ' , ' morality-as-fix ' ], [ ' our-comet-ancestors ' , ' our-comet-ances ' ], [ ' hiroshima-day ' , ' hiroshima-day ' ], [ ' the-robots-rebellion ' , ' the-robots-rebe ' ],
isiri/wordpress_import
c2349ec4ac92959a74df1c7d039a4b895202915d
modified: fix_broken_url.rb
diff --git a/fix_broken_url.rb b/fix_broken_url.rb index 0f37dde..02078bd 100755 --- a/fix_broken_url.rb +++ b/fix_broken_url.rb @@ -1,51 +1,51 @@ def fix_broken_url logger = Logger.new('broken_url_fix.log') all_posts = WpPost.find(:all) broken_url_match = ['http://en.wikipedia.org/wiki/Hawthorne_effect', 'http://www.nytimes.com/library/review/120698science-myths-review.html', ] all_posts.each do |post| html_doc = Nokogiri::HTML(post.post_content) (html_doc/"a").each do |link| link_ref = link.attributes['href'].to_s if link_ref.match(Regexp.new(broken_url_match[0])) link.attributes['href'].value = broken_url_match[0] post.post_content = html_doc.inner_html puts "Updating post content for -#{post.post_name} - #{link.attributes['href']}" logger.error "Updating post content for -#{post.post_name} - #{link.attributes['href']}" post.save end if link_ref.match(Regexp.new(broken_url_match[1])) link.attributes['href'].value = broken_url_match[1] post.post_content = html_doc.inner_html puts "Updating post content for -#{post.post_name} - #{link.attributes['href']}" logger.error "Updating post content for -#{post.post_name} - #{link.attributes['href']}" post.save end if link_ref.to_s.strip.match(/^www/) link.attributes['href'].value = "#http://{link.attributes['href']}" post.post_content = html_doc.inner_html puts "Updating post content for -#{post.post_name}" logger.error "Updating post content for -#{post.post_name} - #{link.attributes['href']}" post.save end end end all_comments = WpComment.find(:all) all_comments.each do |comment| html_doc = Nokogiri::HTML(comment.comment_content) (html_doc/"a").each do |link| link_ref = link.attributes['href'].to_s if link_ref.to_s.strip.match(/^www/) - link.attributes['href'].value = "#http://#{link.attributes['href']}" + link.attributes['href'].value = "http://#{link.attributes['href']}" comment.comment_content = html_doc.inner_html puts "Updating comment content for -#{comment.comment_ID} - #{link.attributes['href']}" logger.error "Updating post content for -#{comment.comment_ID} - #{link.attributes['href']}" comment.save end end end end
isiri/wordpress_import
1cb9e870fa484d71856196d7110aacb3a3f931ff
modified: fix_broken_url.rb
diff --git a/fix_broken_url.rb b/fix_broken_url.rb index 5542f72..0f37dde 100755 --- a/fix_broken_url.rb +++ b/fix_broken_url.rb @@ -1,51 +1,51 @@ def fix_broken_url logger = Logger.new('broken_url_fix.log') all_posts = WpPost.find(:all) broken_url_match = ['http://en.wikipedia.org/wiki/Hawthorne_effect', 'http://www.nytimes.com/library/review/120698science-myths-review.html', ] all_posts.each do |post| html_doc = Nokogiri::HTML(post.post_content) (html_doc/"a").each do |link| link_ref = link.attributes['href'].to_s if link_ref.match(Regexp.new(broken_url_match[0])) link.attributes['href'].value = broken_url_match[0] post.post_content = html_doc.inner_html puts "Updating post content for -#{post.post_name} - #{link.attributes['href']}" logger.error "Updating post content for -#{post.post_name} - #{link.attributes['href']}" post.save end if link_ref.match(Regexp.new(broken_url_match[1])) link.attributes['href'].value = broken_url_match[1] post.post_content = html_doc.inner_html puts "Updating post content for -#{post.post_name} - #{link.attributes['href']}" logger.error "Updating post content for -#{post.post_name} - #{link.attributes['href']}" post.save end if link_ref.to_s.strip.match(/^www/) link.attributes['href'].value = "#http://{link.attributes['href']}" post.post_content = html_doc.inner_html puts "Updating post content for -#{post.post_name}" logger.error "Updating post content for -#{post.post_name} - #{link.attributes['href']}" post.save end end end all_comments = WpComment.find(:all) all_comments.each do |comment| html_doc = Nokogiri::HTML(comment.comment_content) (html_doc/"a").each do |link| link_ref = link.attributes['href'].to_s if link_ref.to_s.strip.match(/^www/) - link.attributes['href'].value = "#http://{link.attributes['href']}" + link.attributes['href'].value = "#http://#{link.attributes['href']}" comment.comment_content = html_doc.inner_html puts "Updating comment content for -#{comment.comment_ID} - #{link.attributes['href']}" logger.error "Updating post content for -#{comment.comment_ID} - #{link.attributes['href']}" comment.save end end end end
isiri/wordpress_import
563d68a15ef3c0194a937c005b1edfcf07e94b7a
url fixes
diff --git a/fix_broken_url.rb b/fix_broken_url.rb new file mode 100755 index 0000000..5542f72 --- /dev/null +++ b/fix_broken_url.rb @@ -0,0 +1,51 @@ +def fix_broken_url + logger = Logger.new('broken_url_fix.log') + all_posts = WpPost.find(:all) + + broken_url_match = ['http://en.wikipedia.org/wiki/Hawthorne_effect', + 'http://www.nytimes.com/library/review/120698science-myths-review.html', + ] + + all_posts.each do |post| + html_doc = Nokogiri::HTML(post.post_content) + (html_doc/"a").each do |link| + link_ref = link.attributes['href'].to_s + if link_ref.match(Regexp.new(broken_url_match[0])) + link.attributes['href'].value = broken_url_match[0] + post.post_content = html_doc.inner_html + puts "Updating post content for -#{post.post_name} - #{link.attributes['href']}" + logger.error "Updating post content for -#{post.post_name} - #{link.attributes['href']}" + post.save + end + if link_ref.match(Regexp.new(broken_url_match[1])) + link.attributes['href'].value = broken_url_match[1] + post.post_content = html_doc.inner_html + puts "Updating post content for -#{post.post_name} - #{link.attributes['href']}" + logger.error "Updating post content for -#{post.post_name} - #{link.attributes['href']}" + post.save + end + if link_ref.to_s.strip.match(/^www/) + link.attributes['href'].value = "#http://{link.attributes['href']}" + post.post_content = html_doc.inner_html + puts "Updating post content for -#{post.post_name}" + logger.error "Updating post content for -#{post.post_name} - #{link.attributes['href']}" + post.save + end + end + end + + all_comments = WpComment.find(:all) + all_comments.each do |comment| + html_doc = Nokogiri::HTML(comment.comment_content) + (html_doc/"a").each do |link| + link_ref = link.attributes['href'].to_s + if link_ref.to_s.strip.match(/^www/) + link.attributes['href'].value = "#http://{link.attributes['href']}" + comment.comment_content = html_doc.inner_html + puts "Updating comment content for -#{comment.comment_ID} - #{link.attributes['href']}" + logger.error "Updating post content for -#{comment.comment_ID} - #{link.attributes['href']}" + comment.save + end + end + end +end diff --git a/global_settings_example.rb b/global_settings_example.rb index a1a6c08..54ca45f 100755 --- a/global_settings_example.rb +++ b/global_settings_example.rb @@ -1,64 +1,69 @@ #Rename this file to global_settings.rb and update the below configurations. #TODO: cleaning up some of the duplication #Global settings require 'rubygems' require 'activerecord' require 'logger' require 'open-uri' require 'pathname' require 'ftools' require 'mechanize' require 'fileutils' #absoulte paths $wordpress_root = '/var/www' $wordpress_installation_path = '/var/www/wordpress' $image_path = '/wp-contents/uploads' $wordpress_import_file = '/var/www/wordpress/wp-content/mt-export.txt' #relative paths $split_file_path = 'splitted_files' #file names $wordpress_export_filename = 'mt-export.txt' $split_filename = 'mt_export_txt_' # split files will be as mt_export_txt_0, mt_export_txt_1 etc. #urls $base_url = 'http://localhost/wordpress' $root_url = 'http://localhost' $site_root = '/wordpress/wp-content/uploads' #downloaded image store folder #others $allowed_length = 5000000 #size of individual files after splitting the export file. (splitting is done to avoid php memory limit error) $wordpress_username = 'admin' #wordpress blog admin username $wordpress_password = '' #wordpress blog admin password ActiveRecord::Base.establish_connection( :adapter => "", :database => "", :username => "", :password => "", :socket => '' ) class WpPost < ActiveRecord::Base set_primary_key 'ID' set_table_name "wp_posts" end class WpUser < ActiveRecord::Base set_primary_key 'ID' set_table_name "wp_users" end +class WpComment < ActiveRecord::Base + set_primary_key 'comment_ID' + set_table_name "wp_comments" +end + #moneky patch to avoid timeout error module Net class BufferedIO def rbuf_fill #timeout(@read_timeout,ProtocolError) { @rbuf << @io.sysread(1024) #} end end end diff --git a/process_script.rb b/process_script.rb index 485a8a9..efd4510 100755 --- a/process_script.rb +++ b/process_script.rb @@ -1,35 +1,39 @@ require 'global_settings' require 'importer.rb' require 'splitter.rb' require 'image_parse.rb' require 'update_links.rb' require 'configure_wordpress.rb' require 'update_users.rb' +require 'fix_broken_url.rb' puts "Starting import file split" dest_files = split($wordpress_export_filename, $split_file_path, $allowed_length) puts "Successfully split the files into #{dest_files.join(',')}" dest_files.each do |dest_file| puts "Starting import of #{dest_file}..." dest_path = File.join($split_file_path, dest_file) File.copy(dest_path, $wordpress_import_file) start_import puts "Finished importing the file #{dest_file}" end puts "Import process done." puts "Updating permalinks" update_permalinks puts "Done updating permalinks" puts "Processing images" process_images puts "Configuring wordpress" configure_wordpress +puts "Fixing broken urls" +fix_broken_url +
isiri/wordpress_import
a40e703b4288b82bc983857b5d35110197545ff5
image parse fix
diff --git a/image_parse.rb b/image_parse.rb index 132e698..1d22bbf 100755 --- a/image_parse.rb +++ b/image_parse.rb @@ -1,31 +1,42 @@ def process_images - + logger = Logger.new('error_image_parse.log') all_posts = WpPost.find(:all) all_posts.each do |post| html_doc = Nokogiri::HTML(post.post_content) (html_doc/"img").each do |img| img_src = img.attributes['src'].to_s img_name = img_src.split('/').last img_str = '' - img_src = "#{$root_url}/#{img_src}" unless img_src.match(/http/) - open(img_src.gsub(/ /,'%20')) { - |f| - img_str = f.read - } - img_root = "/#{post.post_date.year}/#{"%02d" % post.post_date.month}" - dest_save_dir = "#{$wordpress_root}#{$site_root}/#{img_root}" - FileUtils.mkdir_p dest_save_dir - dest_save_image = "#{dest_save_dir}/#{img_name}" - dest_site_image = "#{$site_root}#{img_root}/#{img_name}" - File.open(dest_save_image, 'w') {|f| f.write(img_str) } - img.attributes['src'].value = dest_site_image - if img.parent.node_name == 'a' - img.parent.attributes['href'].value = dest_site_image + unless (img_src.match(/overcomingbias/) or img_src.match(/robinhanson/)) + logger.error "NOT Downloading image for - #{img_src}" + puts "NOT Downloading image for - #{img_src}" + next + end + logger.error "Downloading image for - #{img_src}" + puts "Downloading image for - #{img_src}" + begin + open(img_src.gsub(/ /,'%20')) { + |f| + img_str = f.read + } + img_root = "/#{post.post_date.year}/#{"%02d" % post.post_date.month}" + dest_save_dir = "#{$wordpress_root}#{$site_root}/#{img_root}" + FileUtils.mkdir_p dest_save_dir + dest_save_image = "#{dest_save_dir}/#{img_name}" + dest_site_image = "#{$site_root}#{img_root}/#{img_name}" + File.open(dest_save_image, 'w') {|f| f.write(img_str) } + img.attributes['src'].value = dest_site_image + if img.parent.node_name == 'a' + img.parent.attributes['href'].value = dest_site_image + end + post.post_content = html_doc.inner_html + post.save + rescue + puts "Could not download image for : #{img_src}" + logger.error "Could not download image for : #{img_src}" end - post.post_content = html_doc.inner_html - post.save end end end
isiri/wordpress_import
6329625f9c667a194d0c1f1c4e6cd0f97741cdc8
modified: url_mapping.rb
diff --git a/url_mapping.rb b/url_mapping.rb index 443511a..7613419 100755 --- a/url_mapping.rb +++ b/url_mapping.rb @@ -1,1808 +1,1808 @@ def url_mapping_arr [ [ ' macro-shares-prediction-markets-via-stock-exchanges ' , ' macro_shares_pr ' ], [ ' thank-you-maam-may-i-have-another ' , ' thank_you_maam_ ' ], [ ' beware-of-disagreeing-with-lewis ' , ' beware_of_disag ' ], [ ' incautious-defense-of-bias ' , ' incautious_defe ' ], [ ' pascalian-meditations ' , ' pascalian_medit ' ], [ ' are-the-big-four-econ-errors-biases ' , ' the_big_four_ec ' ], [ ' surprisingly-friendly-suburbs ' , ' surprisingly_fr ' ], [ ' beware-amateur-science-history ' , ' beware_amateur_ ' ], [ ' whats-a-bias-again ' , ' whats_a_bias_ag ' ], [ ' why-truth-and ' , ' why_truth_and ' ], [ ' asymmetric-paternalism ' , ' asymmetric_pate ' ], [ ' to-the-barricades-against-what-exactly ' , ' to_the_barricad ' ], [ ' foxes-vs-hedgehogs-predictive-success ' , ' foxes_vs_hedgho ' ], [ ' follow-the-crowd ' , ' follow_the_crow ' ], [ ' what-exactly-is-bias ' , ' what_exactly_is ' ], [ ' moral-overconfidence ' , ' moral_hypocricy ' ], [ ' why-are-academics-liberal ' , ' the_cause_of_is ' ], [ ' a-1990-corporate-prediction-market ' , ' first_known_bus ' ], [ ' the-martial-art-of-rationality ' , ' the_martial_art ' ], [ ' beware-heritable-beliefs ' , ' beware_heritabl ' ], [ ' the-wisdom-of-bromides ' , ' the_wisdom_of_b ' ], [ ' the-movie-click ' , ' click_christmas ' ], [ ' quiz-fox-or-hedgehog ' , ' quiz_fox_or_hed ' ], [ ' hide-sociobiology-like-sex ' , ' does_sociobiolo ' ], [ ' how-to-join ' , ' introduction ' ], [ ' normative-bayesianism-and-disagreement ' , ' normative_bayes ' ], [ ' vulcan-logic ' , ' vulcan_logic ' ], [ ' benefit-of-doubt-bias ' , ' benefit_of_doub ' ], [ ' see-but-dont-believe ' , ' see_but_dont_be ' ], [ ' the-future-of-oil-prices-2-option-probabilities ' , ' the_future_of_o_1 ' ], [ ' resolving-your-hypocrisy ' , ' resolving_your_ ' ], [ ' academic-overconfidence ' , ' academic_overco ' ], [ ' gnosis ' , ' gnosis ' ], [ ' ads-that-hurt ' , ' ads_that_hurt ' ], [ ' gifts-hurt ' , ' gifts_hurt ' ], [ ' advertisers-vs-teachers-ii ' , ' advertisers_vs_ ' ], [ ' why-common-priors ' , ' why_common_prio ' ], [ ' the-future-of-oil-prices ' , ' the_future_of_o ' ], [ ' a-fable-of-science-and-politics ' , ' a_fable_of_scie ' ], [ ' a-christmas-gift-for-rationalists ' , ' a_christmas_gif ' ], [ ' when-truth-is-a-trap ' , ' when_truth_is_a ' ], [ ' you-will-age-and-die ' , ' you_will_age_an ' ], [ ' contributors-be-half-accessible ' , ' contributors_be ' ], [ ' i-dont-know ' , ' i_dont_know ' ], [ ' you-are-never-entitled-to-your-opinion ' , ' you_are_never_e ' ], [ ' a-decent-respect ' , ' a_decent_respec ' ], [ ' why-not-impossible-worlds ' , ' why_not_impossi ' ], [ ' modesty-in-a-disagreeable-world ' , ' modesty_in_a_di ' ], [ ' to-win-press-feign-surprise ' , ' to_win_press_fe ' ], [ ' advertisers-vs-teachers ' , ' suppose_that_co ' ], [ ' when-error-is-high-simplify ' , ' when_error_is_h ' ], [ ' finding-the-truth-in-controversies ' , ' finding_the_tru ' ], [ ' bias-in-christmas-shopping ' , ' bias_in_christm ' ], [ ' does-the-modesty-argument-apply-to-moral-claims ' , ' does_the_modest ' ], [ ' philosophers-on-moral-bias ' , ' philosophers_on ' ], [ ' meme-lineages-and-expert-consensus ' , ' meme_lineages_a ' ], [ ' the-conspiracy-against-cuckolds ' , ' the_conspiracy_ ' ], [ ' malatesta-estimator ' , ' malatesta_estim ' ], [ ' fillers-neglect-framers ' , ' fillers_neglect ' ], [ ' the-80-forecasting-solution ' , ' the_80_forecast ' ], [ ' ignorance-of-frankenfoods ' , ' ignorance_of_fr ' ], [ ' do-helping-professions-help-more ' , ' do_helping_prof ' ], [ ' should-prediction-markets-be-charities ' , ' should_predicti ' ], [ ' we-are-smarter-than-me ' , ' we_are_smarter_ ' ], [ ' law-as-no-bias-theatre ' , ' law_as_nobias_t ' ], [ ' the-modesty-argument ' , ' the_modesty_arg ' ], [ ' agreeing-to-agree ' , ' agreeing_to_agr ' ], [ ' time-on-risk ' , ' time_on_risk ' ], [ ' leamers-1986-idea-futures-proposal ' , ' leamers_1986_id ' ], [ ' alas-amateur-futurism ' , ' alas_amateur_fu ' ], [ ' the-wisdom-of-crowds ' , ' the_wisdom_of_c ' ], [ ' reasonable-disagreement ' , ' reasonable_disa ' ], [ ' math-zero-vs-political-zero ' , ' math_zero_vs_po ' ], [ ' bosses-prefer-overconfident-managers ' , ' bosses_prefer_o ' ], [ ' seen-vs-unseen-biases ' , ' seen_vs_unseen_ ' ], [ ' future-selves ' , ' future_selves ' ], [ ' does-profit-rate-insight-best ' , ' does_profit_rat ' ], [ ' bias-well-being-and-the-placebo-effect ' , ' bias_wellbeing_ ' ], [ ' biases-of-science-fiction ' , ' biases_of_scien ' ], [ ' the-proper-use-of-humility ' , ' the_proper_use_ ' ], [ ' the-onion-on-bias-duh ' , ' the_onion_on_bi ' ], [ ' prizes-versus-grants ' , ' prizes_versus_g ' ], [ ' wanted-a-meta-poll ' , ' wanted_a_metapo ' ], [ ' excess-signaling-example ' , ' excess_signalin ' ], [ ' rationalization ' , ' rationalization ' ], [ ' against-admirable-activities ' , ' against_admirab ' ], [ ' effects-of-ideological-media-persuasion ' , ' effects_of_ideo ' ], [ ' whats-the-right-rule-for-a-juror ' , ' whats_the_right ' ], [ ' galt-on-abortion-and-bias ' , ' galt_on_abortio ' ], [ ' -the-procrastinators-clock ' , ' the_procrastina ' ], [ ' keeping-score ' , ' keeping_score ' ], [ ' agree-with-young-duplicate ' , ' agree_with_your ' ], [ ' sick-of-textbook-errors ' , ' sick_of_textboo ' ], [ ' manipulating-jury-biases ' , ' manipulating_ju ' ], [ ' what-insight-in-innocence ' , ' what_insight_in ' ], [ ' on-policy-fact-experts-ignore-facts ' , ' on_policy_fact_ ' ], [ ' the-butler-did-it-of-course ' , ' the_butler_did_ ' ], [ ' no-death-of-a-buyerman ' , ' no_death_of_a_b ' ], [ ' is-there-such-a-thing-as-bigotry ' , ' is_there_such_a ' ], [ ' moby-dick-seeks-thee-not ' , ' moby_dick_seeks ' ], [ ' morale-markets-vs-decision-markets ' , ' morale_markets_ ' ], [ ' follow-your-passion-from-a-distance ' , ' follow_your_pas ' ], [ ' a-model-of-extraordinary-claims ' , ' a_model_of_extr ' ], [ ' socially-influenced-beliefs ' , ' socially_influe ' ], [ ' agree-with-yesterdays-duplicate ' , ' agree_with_yest ' ], [ ' outside-the-laboratory ' , ' outside_the_lab ' ], [ ' symmetry-is-not-pretty ' , ' symmetry_is_not ' ], [ ' some-claims-are-just-too-extraordinary ' , ' some_claims_are ' ], [ ' womens-mathematical-abilities ' , ' womens_mathemat ' ], [ ' benefits-of-cost-benefit-analyis ' , ' benefits_of_cos ' ], [ ' godless-professors ' , ' godless_profess ' ], [ ' how-to-not-spend-money ' , ' suppose_youre_a ' ], [ ' sometimes-the-facts-are-irrelevant ' , ' sometimes_the_f ' ], [ ' extraordinary-claims-are-extraordinary-evidence ' , ' extraordinary_c ' ], [ ' ' , ' in_a_recent_pos ' ], [ ' 70-for-me-30-for-you ' , ' 70_for_me_30_fo ' ], [ ' some-people-just-wont-quit ' , ' some_people_jus ' ], [ ' statistical-discrimination-is-probably-bad ' , ' statistical_dis ' ], [ ' costbenefit-analysis ' , ' costbenefit_ana ' ], [ ' smoking-warning-labels ' , ' smoking_warning ' ], [ ' conclusion-blind-review ' , ' conclusionblind ' ], [ ' is-more-information-always-better ' , ' is_more_informa ' ], [ ' should-we-defer-to-secret-evidence ' , ' should_we_defer ' ], [ ' peaceful-speculation ' , ' peaceful_specul ' ], [ ' supping-with-the-devil ' , ' supping_with_th ' ], [ ' disagree-with-suicide-rock ' , ' disagree_with_s ' ], [ ' biased-courtship ' , ' biased_courtshi ' ], [ ' reject-your-personalitys-politics ' , ' reject_your_pol ' ], [ ' laws-of-bias-in-science ' , ' laws_of_bias_in ' ], [ ' epidemics-are-98-below-average ' , ' epidemics_are_9 ' ], [ ' bias-not-a-bug-but-a-feature ' , ' bias_not_a_bug_ ' ], [ ' a-game-for-self-calibration ' , ' a_game_for_self ' ], [ ' why-allow-referee-bias ' , ' why_is_referee_ ' ], [ ' disagreement-at-thoughts-arguments-and-rants ' , ' disagreement_at ' ], [ ' hobgoblins-of-voter-minds ' , ' hobgoblins_of_v ' ], [ ' how-are-we-doing ' , ' how_are_we_doin ' ], [ ' avoiding-truth ' , ' avoiding_truth ' ], [ ' conspicuous-consumption-of-info ' , ' conspicuous_con ' ], [ ' we-cant-foresee-to-disagree ' , ' we_cant_foresee ' ], [ ' do-biases-favor-hawks ' , ' do_biases_favor ' ], [ ' convenient-bias-theories ' , ' convenient_bias ' ], [ ' fair-betting-odds-and-prediction-market-prices ' , ' fair_betting_od ' ], [ ' the-cognitive-architecture-of-bias ' , ' the_cognitive_a ' ], [ ' poll-on-nanofactories ' , ' poll_on_nanofac ' ], [ ' all-bias-is-signed ' , ' all_bias_is_sig ' ], [ ' two-cheers-for-ignoring-plain-facts ' , ' two_cheers_for_ ' ], [ ' what-if-everybody-overcame-bias ' , ' what_if_everybo ' ], [ ' discussions-of-bias-in-answers-to-the-edge-2007-question ' , ' media_biases_us ' ], [ ' why-dont-the-young-learn-from-the-old ' , ' why_dont_the_yo ' ], [ ' the-coin-guessing-game ' , ' the_coin_guessi ' ], [ ' a-honest-doctor-sort-of ' , ' a_honest_doctor ' ], [ ' medical-study-biases ' , ' medical_study_b ' ], [ ' this-is-my-dataset-there-are-many-datasets-like-it-but-this-one-is-mine ' , ' this_is_my_data ' ], [ ' professors-progress-like-ads-advise ' , ' ads_advise_prof ' ], [ ' disagreement-case-study-1 ' , ' disagreement_ca ' ], [ ' marginally-revolved-biases ' , ' marginally_revo ' ], [ ' calibrate-your-ad-response ' , ' calibrate_your_ ' ], [ ' disagreement-case-studies ' , ' seeking_disagre ' ], [ ' just-lose-hope-already ' , ' a_time_to_lose_ ' ], [ ' less-biased-memories ' , ' unbiased_memori ' ], [ ' think-frequencies-not-probabilities ' , ' think_frequenci ' ], [ ' fig-leaf-models ' , ' fig_leaf_models ' ], [ ' do-we-get-used-to-stuff-but-not-friends ' , ' do_we_get_used_ ' ], [ ' buss-on-true-love ' , ' buss_on_true_lo ' ], [ ' is-overcoming-bias-male ' , ' is_overcoming_b ' ], [ ' bias-in-the-classroom ' , ' bias_in_the_cla ' ], [ ' our-house-my-rules ' , ' our_house_my_ru ' ], [ ' how-paranoid-should-i-be-the-limits-of-overcoming-bias ' , ' how_paranoid_sh ' ], [ ' evidence-based-medicine-backlash ' , ' evidencebased_m ' ], [ ' politics-is-the-mind-killer ' , ' politics_is_the ' ], [ ' disagreement-on-inflation ' , ' disagreement_on ' ], [ ' moderate-moderation ' , ' moderate_modera ' ], [ ' bias-toward-certainty ' , ' bias_toward_cer ' ], [ ' multi-peaked-distributions ' , ' multipeaked_dis ' ], [ ' selection-bias-in-economic-theory ' , ' selection_bias_ ' ], [ ' induce-presidential-candidates-to-take-iq-tests ' , ' induce_presiden ' ], [ ' crackpot-people-and-crackpot-ideas ' , ' crackpot_people ' ], [ ' press-confirms-your-health-fears ' , ' press_confirms_ ' ], [ ' too-many-loner-theorists ' , ' too_many_loner_ ' ], [ ' words-for-love-and-sex ' , ' words_for_love_ ' ], [ ' its-sad-when-bad-ideas-drive-out-good-ones ' , ' its_sad_when_ba ' ], [ ' truth-is-stranger-than-fiction ' , ' truth_is_strang ' ], [ ' posterity-review-comes-cheap ' , ' posterity_revie ' ], [ ' reputation-commitment-mechanism ' , ' reputation_comm ' ], [ ' more-lying ' , ' more_lying ' ], [ ' is-truth-in-the-hump-or-the-tails ' , ' is_truth_in_the ' ], [ ' what-opinion-game-do-we-play ' , ' what_opinion_ga ' ], [ ' philip-tetlocks-long-now-talk ' , ' philip_tetlocks ' ], [ ' the-more-amazing-penn ' , ' the_more_amazin ' ], [ ' when-are-weak-clues-uncomfortable ' , ' when_are_weak_c ' ], [ ' detecting-lies ' , ' detecting_lies ' ], [ ' how-and-when-to-listen-to-the-crowd ' , ' how_and_when_to ' ], [ ' institutions-as-levers ' , ' institutions_as ' ], [ ' one-reason-why-power-corrupts ' , ' one_reason_why_ ' ], [ ' will-blog-posts-get-credit ' , ' will_blog_posts ' ], [ ' needed-cognitive-forensics ' , ' wanted_cognitiv ' ], [ ' control-variables-avoid-bias ' , ' control_variabl ' ], [ ' dare-to-deprogram-me ' , ' dare_to_deprogr ' ], [ ' bias-and-health-care ' , ' bias_and_health ' ], [ ' just-world-bias-and-inequality ' , ' just_world_bias_1 ' ], [ ' subduction-phrases ' , ' subduction_phra ' ], [ ' what-evidence-in-silence-or-confusion ' , ' what_evidence_i ' ], [ ' gender-profiling ' , ' gender_profilin ' ], [ ' unequal-inequality ' , ' unequal_inequal ' ], [ ' academic-tool-overconfidence ' , ' academic_tool_o ' ], [ ' why-are-there-no-comforting-words-that-arent-also-factual-statements ' , ' why_are_there_n ' ], [ ' big-issues-vs-small-issues ' , ' big_issues_vs_s ' ], [ ' tolstoy-on-patriotism ' , ' tolstoy_on_patr ' ], [ ' statistical-bias ' , ' statistical_bia ' ], [ ' explain-your-wins ' , ' explain_your_wi ' ], [ ' beware-of-information-porn ' , ' beware_of_infor ' ], [ ' info-has-no-trend ' , ' info_has_no_tre ' ], [ ' tsuyoku-vs-the-egalitarian-instinct ' , ' tsuyoku_vs_the_ ' ], [ ' libertarian-purity-duels ' , ' libertarian_pur ' ], [ ' tsuyoku-naritai-i-want-to-become-stronger ' , ' tsuyoku_naritai ' ], [ ' reporting-chains-swallow-extraordinary-evidence ' , ' reporting_chain ' ], [ ' self-deception-hypocrisy-or-akrasia ' , ' selfdeception_h ' ], [ ' the-very-worst-kind-of-bias ' , ' the_very_worst_ ' ], [ ' home-sweet-home-bias ' , ' home_sweet_home ' ], [ ' norms-of-reason-and-the-prospects-for-technologies-and-policies-of-debiasing ' , ' ways_of_debiasi ' ], [ ' useful-bias ' , ' useful_bias ' ], [ ' chronophone-motivations ' , ' chronophone_mot ' ], [ ' archimedess-chronophone ' , ' archimedess_chr ' ], [ ' masking-expert-disagreement ' , ' masking_expert_ ' ], [ ' archimedess-binding-dilemma ' , ' archimedess_bin ' ], [ ' morality-of-the-future ' , ' morality_of_the ' ], [ ' moral-progress-and-scope-of-moral-concern ' , ' moral_progress_ ' ], [ ' awareness-of-intimate-bias ' , ' awareness_of_in ' ], [ ' all-ethics-roads-lead-to-ours ' , ' all_ethics_road ' ], [ ' challenges-of-majoritarianism ' , ' challenges_of_m ' ], [ ' classic-bias-doubts ' , ' classic_bias_do ' ], [ ' philosophical-majoritarianism ' , ' on_majoritarian ' ], [ ' useless-medical-disclaimers ' , ' useless_medical ' ], [ ' arguments-and-duels ' , ' arguments_and_d ' ], [ ' believing-in-todd ' , ' believing_in_to ' ], [ ' ideologues-or-fools ' , ' ideologues_or_f ' ], [ ' bias-caused-by-fear-of-islamic-extremists ' , ' bias_caused_by_ ' ], [ ' bias-on-self-control-bias ' , ' selfcontrol_bia ' ], [ ' multipolar-disagreements-hals-religious-quandry ' , ' multipolar_disa ' ], [ ' superstimuli-and-the-collapse-of-western-civilization ' , ' superstimuli_an ' ], [ ' good-news-only-please ' , ' good_news_only_ ' ], [ ' blue-or-green-on-regulation ' , ' blue_or_green_o ' ], [ ' 100000-visits ' , ' 100000_visits ' ], [ ' disagreement-case-study-robin-hanson-and-david-balan ' , ' disagreement_ca_2 ' ], [ ' the-trouble-with-track-records ' , ' the_trouble_wit ' ], [ ' genetics-and-cognitive-bias ' , ' genetics_and_co ' ], [ ' marketing-as-asymmetrical-warfare ' , ' marketing_as_as ' ], [ ' disagreement-case-study---balan-and-i ' , ' disagreement_ca_1 ' ], [ ' moral-dilemmas-criticism-plumping ' , ' moral_dilemmas_ ' ], [ ' the-scales-of-justice-the-notebook-of-rationality ' , ' the_scales_of_j ' ], [ ' none-evil-or-all-evil ' , ' none_evil_or_al ' ], [ ' biases-by-and-large ' , ' biases_by_and_l ' ], [ ' disagreement-case-study---hawk-bias ' , ' disagreement_ca ' ], [ ' overcome-cognitive-bias-with-multiple-selves ' , ' overcome_cognit ' ], [ ' extreme-paternalism ' , ' extreme_paterna ' ], [ ' learn-from-politicians-personal-failings ' , ' learn_from_poli ' ], [ ' whose-framing ' , ' whose_framing ' ], [ ' who-are-the-god-experts ' , ' who_are_the_god ' ], [ ' bias-against-introverts ' , ' bias_against_in ' ], [ ' paternal-policies-fight-cognitive-bias-slash-information-costs-and-privelege-responsible-subselves ' , ' paternal_polici ' ], [ ' the-fog-of-disagreement ' , ' the_fog_of_disa ' ], [ ' burchs-law ' , ' burchs_law ' ], [ ' lets-get-ready-to-rumble ' , ' heres_my_openin ' ], [ ' rational-agent-paternalism ' , ' rational_agent_ ' ], [ ' the-give-us-more-money-bias ' , ' the_give_us_mor ' ], [ ' white-collar-crime-and-moral-freeloading ' , ' whitecollar_cri ' ], [ ' happy-capital-day ' , ' happy_capital_d ' ], [ ' outlandish-pundits ' , ' outlandish_pund ' ], [ ' policy-debates-should-not-appear-one-sided ' , ' policy_debates_ ' ], [ ' romantic-predators ' , ' romantic_predat ' ], [ ' swinging-for-the-fences-when-you-should-bunt ' , ' swinging_for_th ' ], [ ' paternalism-is-about-bias ' , ' paternalism_is_ ' ], [ ' you-are-not-hiring-the-top-1 ' , ' you_are_not_hir ' ], [ ' morality-or-manipulation ' , ' morality_or_man ' ], [ ' accountable-financial-regulation ' , ' accountable_fin ' ], [ ' today-is-honesty-day ' , ' today_is_honest ' ], [ ' more-on-future-self-paternalism ' , ' more_on_future_ ' ], [ ' universal-law ' , ' universal_law ' ], [ ' universal-fire ' , ' universal_fire ' ], [ ' the-fallacy-fallacy ' , ' the_fallacy_fal ' ], [ ' to-learn-or-credential ' , ' to_learn_or_cre ' ], [ ' feeling-rational ' , ' feeling_rationa ' ], [ ' overconfidence-erases-doc-advantage ' , ' overconfidence_ ' ], [ ' the-bleeding-edge-of-innovation ' , ' the_bleeding_ed ' ], [ ' expert-at-versus-expert-on ' , ' expert_at_versu ' ], [ ' meta-majoritarianism ' , ' meta_majoritari ' ], [ ' future-self-paternalism ' , ' future_self_pat ' ], [ ' popularity-is-random ' , ' popularity_is_r ' ], [ ' holocaust-denial ' , ' holocaust_denia ' ], [ ' exercise-sizzle-works-sans-steak ' , ' exercise_sizzle ' ], [ ' the-shame-of-tax-loopholing ' , ' the_shame_of_ta ' ], [ ' vonnegut-on-overcoming-fiction ' , ' vonnegut_on_ove ' ], [ ' consolidated-nature-of-morality-thread ' , ' consolidated_na ' ], [ ' irrationality-or-igustibusi ' , ' irrationality_o ' ], [ ' your-rationality-is-my-business ' , ' your_rationalit ' ], [ ' statistical-inefficiency-bias-or-increasing-efficiency-will-reduce-bias-on-average-or-there-is-no-bias-variance-tradeoff ' , ' statistical_ine ' ], [ ' new-improved-lottery ' , ' new_improved_lo ' ], [ ' non-experts-need-documentation ' , ' nonexperts_need ' ], [ ' overconfident-evaluation ' , ' overconfident_e ' ], [ ' lotteries-a-waste-of-hope ' , ' lotteries_a_was ' ], [ ' just-a-smile ' , ' just_a_smile ' ], [ ' priors-as-mathematical-objects ' , ' priors_as_mathe ' ], [ ' predicting-the-future-with-futures ' , ' predicting_the_ ' ], [ ' the-future-is-glamorous ' , ' the_future_is_g ' ], [ ' marginally-zero-sum-efforts ' , ' marginally_zero ' ], [ ' overcoming-credulity ' , ' overcoming_cred ' ], [ ' urgent-and-important-not ' , ' very_important_ ' ], [ ' futuristic-predictions-as-consumable-goods ' , ' futuristic_pred ' ], [ ' suggested-posts ' , ' suggested_posts ' ], [ ' modular-argument ' , ' modular_argumen ' ], [ ' inductive-bias ' , ' inductive_bias ' ], [ ' debiasing-as-non-self-destruction ' , ' debiasing_as_no ' ], [ ' overcoming-bias---what-is-it-good-for ' , ' overcoming_bias ' ], [ ' as-good-as-it-gets ' , ' as_good_as_it_g ' ], [ ' driving-while-red ' , ' driving_while_r ' ], [ ' media-bias ' , ' media_bias ' ], [ ' could-gambling-save-science ' , ' could_gambling_ ' ], [ ' casanova-on-innocence ' , ' casanova_on_inn ' ], [ ' black-swans-from-the-future ' , ' black_swans_fro ' ], [ ' having-to-do-something-wrong ' , ' having_to_do_so ' ], [ ' knowing-about-biases-can-hurt-people ' , ' knowing_about_b ' ], [ ' a-tough-balancing-act ' , ' a_tough_balanci ' ], [ ' mapping-academia ' , ' mapping_academi ' ], [ ' the-majority-is-always-wrong ' , ' the_majority_is ' ], [ ' overcoming-fiction ' , ' overcoming_fict ' ], [ ' the-error-of-crowds ' , ' the_error_of_cr ' ], [ ' do-moral-systems-have-to-make-sense ' , ' do_moral_system ' ], [ ' useful-statistical-biases ' , ' useful_statisti ' ], [ ' is-there-manipulation-in-the-hillary-clinton-prediction-market ' , ' is_there_manipu ' ], [ ' shock-response-futures ' , ' shock_response_ ' ], [ ' free-money-going-fast ' , ' free_money_goin ' ], [ ' arrogance-as-virtue ' , ' arrogance_as_vi ' ], [ ' are-any-human-cognitive-biases-genetically-universal ' , ' are_any_human_c_1 ' ], [ ' hofstadters-law ' , ' hofstadters_law ' ], [ ' the-agency-problem ' , ' the_agency_prob ' ], [ ' cryonics ' , ' cryonics ' ], [ ' my-podcast-with-russ-roberts ' , ' my_podcast_with ' ], [ ' truly-worth-honoring ' , ' truly_worth_hon ' ], [ ' scientists-as-parrots ' , ' scientists_as_p ' ], [ ' in-obscurity-errors-remain ' , ' in_obscurity_er ' ], [ ' requesting-honesty ' , ' requesting_hone ' ], [ ' winning-at-rock-paper-scissors ' , ' winning_at_rock ' ], [ ' policy-tug-o-war ' , ' policy_tugowar ' ], [ ' why-pretty-hs-play-leads ' , ' why_pretty_hs_p ' ], [ ' the-perils-of-being-clearer-than-truth ' , ' the_perils_of_b ' ], [ ' when-differences-make-a-difference ' , ' when_difference ' ], [ ' you-felt-sorry-for-her ' , ' you_felt_sorry_ ' ], [ ' do-androids-dream-of-electric-rabbit-feet ' , ' do_androids_dre ' ], [ ' one-life-against-the-world ' , ' one_life_agains ' ], [ ' cheating-as-status-symbol ' , ' cheating_as_sta ' ], [ ' underconfident-experts ' , ' underconfident_ ' ], [ ' are-almost-all-investors-biased ' , ' are_almost_all_ ' ], [ ' data-management ' , ' data_management ' ], [ ' are-any-human-cognitive-biases-genetic ' , ' are_any_human_c ' ], [ ' is-your-rationality-on-standby ' , ' is_your_rationa ' ], [ ' joke ' , ' joke ' ], [ ' opinions-of-the-politically-informed ' , ' opinions_of_the ' ], [ ' the-case-for-dangerous-testing ' , ' the_case_for_da ' ], [ ' i-had-the-same-idea-as-david-brin-sort-of ' , ' i_had_the_same_ ' ], [ ' disagreement-case-study----genetics-of-free-trade-and-a-new-cognitive-bias ' , ' disagreement_ca ' ], [ ' rand-experiment-ii-petition ' , ' rand_experiment ' ], [ ' skepticism-about-skepticism ' , ' skepticism_abou ' ], [ ' scope-insensitivity ' , ' scope_insensiti ' ], [ ' medicine-as-scandal ' , ' medicine_as_sca ' ], [ ' the-us-should-bet-against-iran-testing-a-nuclear-weapon ' , ' the_us_should_b ' ], [ ' medicare-train-wreck ' , ' medicare_train_ ' ], [ ' eclipsing-nobel ' , ' eclipsing_nobel ' ], [ ' what-speaks-silence ' , ' what_speaks_sil ' ], [ ' the-worst-youve-seen-isnt-the-worst-there-is ' , ' the_worst_youve ' ], [ ' rand-health-insurance-experiment-ii ' , ' rand_health_ins_1 ' ], [ ' the-conspiracy-glitch ' , ' the_conspiracy_ ' ], [ ' doubting-thomas-and-pious-pete ' , ' doubting_thomas ' ], [ ' rand-health-insurance-experiment ' , ' rand_health_ins ' ], [ ' third-alternatives-for-afterlife-ism ' , ' third_alternati ' ], [ ' scope-neglect-hits-a-new-low ' , ' scope_neglect_h ' ], [ ' motivated-stopping-in-philanthropy ' , ' early_stopping_ ' ], [ ' cold-fusion-continues ' , ' cold_fusion_con ' ], [ ' feel-lucky-punk ' , ' feel_luck_punk ' ], [ ' the-third-alternative ' , ' the_third_alter ' ], [ ' academics-against-evangelicals ' , ' academics_again ' ], [ ' race-bias-of-nba-refs ' , ' race_bias_of_nb ' ], [ ' brave-us-tv-news-not ' , ' brave_us_tv_new ' ], [ ' beware-the-unsurprised ' , ' beware_the_unsu ' ], [ ' academic-self-interest-bias ' , ' selfinterest_bi ' ], [ ' the-bias-in-please-and-thank-you ' , ' the_bias_in_ple ' ], [ ' social-norms-need-neutrality-simplicity ' , ' social_norms_ne ' ], [ ' think-like-reality ' , ' think_like_real ' ], [ ' overcoming-bias-on-the-simpsons ' , ' overcoming_bias ' ], [ ' eh-hunt-helped-lbj-kill-jfk ' , ' eh_hunt_helped_ ' ], [ ' myth-of-the-rational-academic ' , ' myth_of_the_rat ' ], [ ' biases-are-fattening ' , ' biases-are-fatt ' ], [ ' true-love-and-unicorns ' , ' true_love_and_u ' ], [ ' bayes-radical-liberal-or-conservative ' , ' bayes-radical-l ' ], -[ ' global-warming-blowhards ' , ' global-warming- ' ], +[ ' global-warming-blowhards ' , ' global-warming ' ], [ ' extraordinary-physics ' , ' extraordinary_c ' ], [ ' are-your-enemies-innately-evil ' , ' are-your-enemie ' ], [ ' how-to-be-radical ' , ' how_to_be_radic ' ], [ ' auctioning-book-royalties ' , ' auctioning-book ' ], -[ ' fair-landowner-coffee ' , ' fair-landowner- ' ], +[ ' fair-landowner-coffee ' , ' fair-landownert ' ], [ ' death-risk-biases ' , ' death_risk_bias ' ], [ ' correspondence-bias ' , ' correspondence- ' ], [ ' applaud-info-not-agreement ' , ' applaud-info-no ' ], [ ' risk-free-bonds-arent ' , ' risk-free-bonds ' ], [ ' adam-smith-on-overconfidence ' , ' adam_smith_on_o ' ], [ ' ethics-applied-vs-meta ' , ' ethics_applied_ ' ], [ ' wandering-philosophers ' , ' wandering_philo ' ], [ ' randomly-review-criminal-cases ' , ' randomly_review ' ], [ ' functional-is-not-optimal ' , ' functional_is_n ' ], [ ' were-people-better-off-in-the-middle-ages-than-they-are-now ' , ' politics_and_ec ' ], [ ' selling-overcoming-bias ' , ' selling_overcom ' ], [ ' tell-me-your-politics-and-i-can-tell-you-what-you-think-about-nanotechnology ' , ' tell_me_your_po ' ], [ ' beware-neuroscience-stories ' , ' beware_neurosci ' ], [ ' against-free-thinkers ' , ' against_free_th ' ], [ ' 1-2-3-infinity ' , ' 1_2_3_infinity ' ], [ ' total-vs-marginal-effects-or-are-the-overall-benefits-of-health-care-probably-minor ' , ' total_vs_margin ' ], [ ' one-reason-why-plans-are-good ' , ' one_reason_why_ ' ], [ ' 200000-visits ' , ' 200000_visits ' ], [ ' choose-credit-or-influence ' , ' choose_credit_o ' ], [ ' disagreement-case-study-hanson-and-hughes ' , ' disagreement_ca_1 ' ], [ ' odd-kid-names ' , ' odd_kid_names ' ], [ ' uncovering-rational-irrationalities ' , ' uncovering_rati ' ], [ ' blind-elites ' , ' blind_elites ' ], [ ' blind-winners ' , ' blind_winners ' ], [ ' disagreement-case-study-hanson-and-cutler ' , ' disagreement_ca ' ], [ ' why-not-pre-debate-talk ' , ' why_not_predeba ' ], [ ' nutritional-prediction-markets ' , ' nutritional_pre ' ], [ ' progress-is-not-enough ' , ' progress_is_not ' ], [ ' two-meanings-of-overcoming-bias-for-one-focus-is-fundamental-for-second ' , ' two-meanings-of ' ], [ ' only-losers-overcome-bias ' , ' only-losers-ove ' ], [ ' bayesian-judo ' , ' bayesian-judo ' ], [ ' self-interest-intent-deceit ' , ' self-interest-i ' ], [ ' colorful-characters ' , ' color-character ' ], [ ' belief-in-belief ' , ' belief-in-belie ' ], [ ' phone-shy-ufos ' , ' phone-shy-ufos ' ], [ ' making-beliefs-pay-rent-in-anticipated-experiences ' , ' making-beliefs- ' ], [ ' ts-eliot-quote ' , ' ts-eliot-quote ' ], [ ' not-every-negative-judgment-is-a-bias ' , ' not-every-negat ' ], [ ' schools-that-dont-want-to-be-graded ' , ' schools-that-do ' ], [ ' the-judo-principle ' , ' the-judo-princi ' ], [ ' beware-the-inside-view ' , ' beware-the-insi ' ], [ ' goofy-best-friend ' , ' goofy-best-frie ' ], [ ' meta-textbooks ' , ' meta-textbooks ' ], [ ' fantasys-essence ' , ' fantasys-essens ' ], [ ' clever-controls ' , ' clever-controls ' ], [ ' investing-in-index-funds-a-tangible-reward-of-overcoming-bias ' , ' investing-in-in ' ], [ ' bad-balance-bias ' , ' bad-balance-bia ' ], [ ' raging-memories ' , ' raging-memories ' ], -[ ' calibration-in-chess ' , ' calibration-in- ' ], -[ ' theyre-telling-you-theyre-lying ' , ' theyre-telling- ' ], +[ ' calibration-in-chess ' , ' calibration-in ' ], +[ ' theyre-telling-you-theyre-lying ' , ' theyre-telling ' ], [ ' on-lying ' , ' on-lying ' ], [ ' gullible-then-skeptical ' , ' gullible-then-s ' ], [ ' how-biases-save-us-from-giving-in-to-terrorism ' , ' how-biases-save ' ], -[ ' privacy-rights-and-cognitive-bias ' , ' privacy-rights- ' ], +[ ' privacy-rights-and-cognitive-bias ' , ' privacy-rights ' ], [ ' conspiracy-believers ' , ' conspiracy-beli ' ], [ ' overcoming-bias-sometimes-makes-us-change-our-minds-but-sometimes-not ' , ' overcoming-bias ' ], [ ' blogging-doubts ' , ' blogging-doubts ' ], [ ' should-charges-of-cognitive-bias-ever-make-us-change-our-minds-a-global-warming-case-study ' , ' should-charges- ' ], [ ' radical-research-evaluation ' , ' radical-researc ' ], [ ' a-real-life-quandry ' , ' a-real-life-qua ' ], [ ' looking-for-a-hard-headed-blogger ' , ' looking-for-a-h ' ], [ ' goals-and-plans-in-decision-making ' , ' goals-and-plans ' ], [ ' 7707-weddings ' , ' 7707-weddings ' ], [ ' just-take-the-average ' , ' just-take-the-a ' ], [ ' two-more-things-to-unlearn-from-school ' , ' two-more-things ' ], [ ' introducing-ramone ' , ' introducing-ram ' ], -[ ' tell-your-anti-story ' , ' tell-your-anti- ' ], +[ ' tell-your-anti-story ' , ' tell-your-anti ' ], [ ' reviewing-caplans-reviewers ' , ' reviewing-capla ' ], [ ' how-should-unproven-findings-be-publicized ' , ' how-should-unpr ' ], -[ ' global-warming-skeptics-charge-believers-with-more-cognitive-biases-than-believers-do-skeptics-why-the-asymmetry ' , ' global-warming- ' ], -[ ' what-is-public-info ' , ' what-is-public- ' ], +[ ' global-warming-skeptics-charge-believers-with-more-cognitive-biases-than-believers-do-skeptics-why-the-asymmetry ' , ' global-warming ' ], +[ ' what-is-public-info ' , ' what-is-public ' ], [ ' take-our-survey ' , ' take-our-survey ' ], [ ' lets-bet-on-talk ' , ' lets-bet-on-tal ' ], [ ' more-possible-political-biases-relative-vs-absolute-well-being ' , ' more-possible-p ' ], [ ' what-signals-what ' , ' what-signals-wh ' ], [ ' reply-to-libertarian-optimism-bias ' , ' in-this-entry-o ' ], [ ' biased-birth-rates ' , ' biased-birth-ra ' ], [ ' libertarian-optimism-bias-vs-statist-pessimism-bias ' , ' libertarian-opt ' ], [ ' painfully-honest ' , ' painfully-hones ' ], [ ' biased-revenge ' , ' biased-revenge ' ], [ ' the-road-not-taken ' , ' the_road_not_ta ' ], [ ' open-thread ' , ' open-thread ' ], [ ' making-history-available ' , ' making-history- ' ], [ ' we-are-not-unbaised ' , ' we-are-not-unba ' ], [ ' failing-to-learn-from-history ' , ' failing-to-lear ' ], [ ' seeking-unbiased-game-host ' , ' seeking-unbiase ' ], [ ' my-wild-and-reckless-youth ' , ' my-wild-and-rec ' ], [ ' kind-right-handers ' , ' kind-right-hand ' ], [ ' say-not-complexity ' , ' say-not-complex ' ], [ ' the-function-of-prizes ' , ' the-function-of ' ], [ ' positive-bias-look-into-the-dark ' , ' positive-bias-l ' ], [ ' the-way-is-subtle ' , ' the-way-is-subt ' ], [ ' is-overcoming-bias-important ' , ' how-important-i ' ], [ ' the-futility-of-emergence ' , ' the-futility-of ' ], [ ' bias-as-objectification ' , ' bias-as-objecti ' ], [ ' mysterious-answers-to-mysterious-questions ' , ' mysterious-answ ' ], [ ' bias-against-torture ' , ' bias-against-to ' ], [ ' semantic-stopsigns ' , ' semantic-stopsi ' ], [ ' exccess-trust-in-experts ' , ' exccess-trust-i ' ], [ ' fake-causality ' , ' fake-causality ' ], [ ' is-hybrid-vigor-iq-warm-and-fuzzy ' , ' is-hybrid-vigor ' ], [ ' science-as-attire ' , ' science-as-lite ' ], [ ' moral-bias-as-group-glue ' , ' moral-bias-as-g ' ], [ ' guessing-the-teachers-password ' , ' guessing-the-te ' ], [ ' nerds-as-bad-connivers ' , ' post ' ], [ ' why-do-corporations-buy-insurance ' , ' why-do-corporat ' ], [ ' fake-explanations ' , ' fake-explanatio ' ], [ ' media-risk-bias-feedback ' , ' media-risk-bias ' ], [ ' irrational-investment-disagreement ' , ' irrational-inve ' ], [ ' is-molecular-nanotechnology-scientific ' , ' is-molecular-na ' ], [ ' what-evidence-is-brevity ' , ' what-evidence-i ' ], [ ' are-more-complicated-revelations-less-probable ' , ' are-more-compli ' ], [ ' scientific-evidence-legal-evidence-rational-evidence ' , ' scientific-evid ' ], [ ' pseudo-criticism ' , ' pseudo-criticis ' ], [ ' are-brilliant-scientists-less-likely-to-cheat ' , ' are-brilliant-s ' ], [ ' hindsight-devalues-science ' , ' hindsight-deval ' ], [ ' sometimes-learning-is-very-slow ' , ' sometimes-learn ' ], [ ' hindsight-bias ' , ' hindsight-bias ' ], [ ' truth---the-neglected-virtue ' , ' truth---the-neg ' ], [ ' one-argument-against-an-army ' , ' one-argument--1 ' ], [ ' strangeness-heuristic ' , ' strangeness-heu ' ], [ ' never-ever-forget-there-are-maniacs-out-there ' , ' never-ever-forg ' ], [ ' update-yourself-incrementally ' , ' update-yourself ' ], [ ' harry-potter-the-truth-seeker ' , ' harry-potter-th ' ], [ ' dangers-of-political-betting-markets ' , ' dangers-of-poli ' ], [ ' conservation-of-expected-evidence ' , ' conservation-of ' ], [ ' biases-of-biography ' , ' biases-of-biogr ' ], [ ' absence-of-evidence-iisi-evidence-of-absence ' , ' absence-of-evid ' ], [ ' confident-proposer-bias ' , ' confident-propo ' ], [ ' i-defy-the-data ' , ' i-defy-the-data ' ], [ ' what-is-a-taboo-question ' , ' what-is-a-taboo ' ], [ ' your-strength-as-a-rationalist ' , ' your-strength-a ' ], [ ' accountable-public-opinion ' , ' accountable-pub ' ], [ ' truth-bias ' , ' truth-bias ' ], [ ' the-apocalypse-bet ' , ' the-apocalypse- ' ], [ ' spencer-vs-wilde-on-truth-vs-lie ' , ' spencer-vs-wild ' ], [ ' you-icani-face-reality ' , ' you-can-face-re ' ], [ ' food-vs-sex-charity ' , ' food-vs-sex-cha ' ], [ ' the-virtue-of-narrowness ' , ' the-virtue-of-n ' ], [ ' wishful-investing ' , ' wishful-investi ' ], [ ' the-proper-use-of-doubt ' , ' the-proper-use- ' ], [ ' academic-political-bias ' , ' academic-politi ' ], [ ' focus-your-uncertainty ' , ' focus-your-unce ' ], [ ' disagreeing-about-cognitive-style-or-personality ' , ' disagreeing-abo ' ], [ ' the-importance-of-saying-oops ' , ' the-importance- ' ], -[ ' the-real-inter-disciplinary-barrier ' , ' the-real-inter- ' ], +[ ' the-real-inter-disciplinary-barrier ' , ' the-real-inter ' ], [ ' religions-claim-to-be-non-disprovable ' , ' religions-claim ' ], [ ' is-advertising-the-playground-of-cognitive-bias ' , ' is-advertising- ' ], [ ' anonymous-review-matters ' , ' anonymous-revie ' ], [ ' if-you-wouldnt-want-profits-to-influence-this-blog-you-shouldnt-want-for-profit-schools ' , ' if-you-wouldnt- ' ], [ ' belief-as-attire ' , ' belief-as-attir ' ], [ ' overcoming-bias-hobby-virtue-or-moral-obligation ' , ' overcoming-bias ' ], [ ' the-dogmatic-defense ' , ' dogmatism ' ], [ ' professing-and-cheering ' , ' professing-and- ' ], -[ ' how-to-torture-a-reluctant-disagreer ' , ' how-to-torture- ' ], +[ ' how-to-torture-a-reluctant-disagreer ' , ' how-to-torture ' ], [ ' open-thread ' , ' open-thread ' ], [ ' rationalization ' , ' rationalization ' ], [ ' lies-about-sex ' , ' lies-about-sex ' ], [ ' what-evidence-filtered-evidence ' , ' what-evidence-f ' ], [ ' a-moral-conundrum ' , ' a-moral-conundr ' ], [ ' jewish-people-and-israel ' , ' jewish-people-a ' ], [ ' the-bottom-line ' , ' the-bottom-line ' ], -[ ' false-findings-unretracted ' , ' false-findings- ' ], +[ ' false-findings-unretracted ' , ' false-findings ' ], [ ' how-to-convince-me-that-2-2-3 ' , ' how-to-convince ' ], [ ' elusive-conflict-experts ' , ' elusive-conflic ' ], [ ' 926-is-petrov-day ' , ' 926-is-petrov-d ' ], [ ' drinking-our-own-kool-aid ' , ' drinking-our-ow ' ], [ ' occams-razor ' , ' occams-razor ' ], [ ' even-when-contrarians-win-they-lose ' , ' even-when-contr ' ], [ ' einsteins-arrogance ' , ' einsteins-arrog ' ], [ ' history-is-written-by-the-dissenters ' , ' history-is-writ ' ], -[ ' the-bright-side-of-life ' , ' always-look-on- ' ], +[ ' the-bright-side-of-life ' , ' always-look-on ' ], [ ' how-much-evidence-does-it-take ' , ' how-much-eviden ' ], [ ' treat-me-like-a-statistic-but-please-be-nice-to-me ' , ' treat-me-like-a ' ], -[ ' small-business-overconfidence ' , ' small-business- ' ], +[ ' small-business-overconfidence ' , ' small-business ' ], [ ' the-lens-that-sees-its-flaws ' , ' the-lens-that-s ' ], -[ ' why-so-little-model-checking-done-in-statistics ' , ' one-thing-that- ' ], +[ ' why-so-little-model-checking-done-in-statistics ' , ' one-thing-that ' ], [ ' bounded-rationality-and-the-conjunction-fallacy ' , ' bounded-rationa ' ], [ ' what-is-evidence ' , ' what-is-evidenc ' ], [ ' radically-honest-meetings ' , ' radically-hones ' ], [ ' burdensome-details ' , ' burdensome-deta ' ], [ ' wielding-occams-razor ' , ' wielding-occams ' ], [ ' your-future-has-detail ' , ' in-the-sept-7-s ' ], [ ' medicine-has-been-overcoming-bias-too ' , ' medicine-has-be ' ], [ ' conjunction-controversy-or-how-they-nail-it-down ' , ' conjunction-con ' ], [ ' why-not-cut-medicine-all-the-way-to-zero ' , ' why-not-cut-med ' ], [ ' why-teen-paternalism ' , ' why-teen-patern ' ], [ ' conjunction-fallacy ' , ' conjunction-fal ' ], [ ' beware-monkey-traps ' , ' beware-monkey-t ' ], [ ' outputs-require-inputs ' , ' to-judge-output ' ], [ ' kahnemans-planning-anecdote ' , ' kahnemans-plann ' ], [ ' epidemiology-doubts ' , ' health-epidemio ' ], [ ' planning-fallacy ' , ' planning-fallac ' ], [ ' seven-sources-of-disagreement-cant-be-eliminated-by-overcoming-cognitive-bias ' , ' seven-sources-o ' ], [ ' dont-trust-your-lying-eyes ' , ' dont-trust-your ' ], -[ ' scott-adams-on-bias ' , ' scott-adams-on- ' ], +[ ' scott-adams-on-bias ' , ' scott-adams-on ' ], [ ' naive-small-investors ' , ' naive-small-inv ' ], [ ' not-open-to-compromise ' , ' not-open-to-com ' ], [ ' why-im-blooking ' , ' why-im-blooking ' ], [ ' noise-in-the-courtroom ' , ' noise-in-the-co ' ], -[ ' bias-awareness-bias-or-was-91101-a-black-swan ' , ' bias-awareness- ' ], +[ ' bias-awareness-bias-or-was-91101-a-black-swan ' , ' bias-awareness ' ], [ ' doublethink-choosing-to-be-biased ' , ' doublethink-cho ' ], [ ' acquisitions-signal-ceo-dominance ' , ' acquisitions-si ' ], [ ' human-evil-and-muddled-thinking ' , ' human-evil-and- ' ], [ ' gotchas-are-not-biases ' , ' gotchas-are-not ' ], [ ' rationality-and-the-english-language ' , ' rationality-and ' ], [ ' never-confuse-could-and-would ' , ' never-confuse-c ' ], [ ' what-evidence-reluctant-authors ' , ' what-evidence-r ' ], [ ' applause-lights ' , ' applause-lights ' ], [ ' what-evidence-dry-one-sided-arguments ' , ' what-evidence-d ' ], [ ' bad-college-quality-incentives ' , ' bad-college-qua ' ], [ ' case-study-of-cognitive-bias-induced-disagreements-on-petraeus-crocker ' , ' case-study-of-c ' ], [ ' we-dont-really-want-your-participation ' , ' we-dont-really- ' ], [ ' tyler-finds-overcoming-bias-iisi-important-for-others ' , ' tyler-cowen-fin ' ], [ ' cut-medicine-in-half ' , ' cut-medicine-in ' ], [ ' radical-honesty ' , ' radical-honesty ' ], [ ' no-press-release-no-retraction ' , ' no-press-releas ' ], [ ' the-crackpot-offer ' , ' the-crackpot-of ' ], [ ' anchoring-and-adjustment ' , ' anchoring-and-a ' ], [ ' what-evidence-bad-arguments ' , ' what-evidence-b ' ], [ ' why-is-the-future-so-absurd ' , ' why-is-the-futu ' ], [ ' strength-to-doubt-or-believe ' , ' strength-to-dou ' ], [ ' availability ' , ' availability ' ], [ ' the-deniers-dilemna ' , ' the-deniers-con ' ], [ ' absurdity-heuristic-absurdity-bias ' , ' absurdity-heuri ' ], [ ' medical-quality-bias ' , ' medical-quality ' ], [ ' science-as-curiosity-stopper ' , ' science-as-curi ' ], [ ' basic-research-as-signal ' , ' basic-research- ' ], [ ' ueuxplainuwuorshipuiugnore ' , ' explainworshipi ' ], [ ' the-pinch-hitter-syndrome-a-general-principle ' , ' the-pinch-hitte ' ], [ ' what-evidence-ease-of-imagination ' , ' what-evidence-e ' ], [ ' stranger-than-history ' , ' stranger-than-h ' ], [ ' bias-as-objectification-ii ' , ' bias-as-objecti ' ], [ ' open-thread ' , ' open-thread ' ], [ ' what-wisdom-tradition ' , ' what-wisdom-tra ' ], [ ' random-vs-certain-death ' , ' random-vs-certa ' ], [ ' who-told-you-moral-questions-would-be-easy ' , ' who-told-you-mo ' ], [ ' a-case-study-of-motivated-continuation ' , ' a-case-study-of ' ], [ ' double-or-nothing-lawsuits-ten-years-on ' , ' double-or-nothi ' ], [ ' torture-vs-dust-specks ' , ' torture-vs-dust ' ], -[ ' college-choice-futures ' , ' college-choice- ' ], +[ ' college-choice-futures ' , ' college-choice ' ], [ ' motivated-stopping-and-motivated-continuation ' , ' motivated-stopp ' ], [ ' bay-area-bayesians-unite ' , ' meetup ' ], [ ' dan-kahneman-puzzles-with-us ' , ' dan-kahneman-pu ' ], [ ' why-are-individual-iq-differences-ok ' , ' why-is-individu ' ], [ ' if-not-data-what ' , ' if-not-data-wha ' ], [ ' no-one-knows-what-science-doesnt-know ' , ' no-one-knows-wh ' ], [ ' dennetts-special-pleading ' , ' special-pleadin ' ], [ ' double-illusion-of-transparency ' , ' double-illusion ' ], -[ ' why-im-betting-on-the-red-sox ' , ' why-im-betting- ' ], +[ ' why-im-betting-on-the-red-sox ' , ' why-im-betting ' ], [ ' intrade-nominee-advice ' , ' intrade-nominee ' ], [ ' explainers-shoot-high-aim-low ' , ' explainers-shoo ' ], [ ' distrust-effect-names ' , ' distrust-effect ' ], -[ ' the-fallacy-of-the-one-sided-bet-for-example-risk-god-torture-and-lottery-tickets ' , ' the-fallacy-of- ' ], +[ ' the-fallacy-of-the-one-sided-bet-for-example-risk-god-torture-and-lottery-tickets ' , ' the-fallacy-of ' ], [ ' expecting-short-inferential-distances ' , ' inferential-dis ' ], [ ' marriage-futures ' , ' marriage-future ' ], [ ' self-anchoring ' , ' self-anchoring ' ], [ ' how-close-lifes-birth ' , ' how-close-lifes ' ], [ ' illusion-of-transparency-why-no-one-understands-you ' , ' illusion-of-tra ' ], [ ' a-valid-concern ' , ' a-valid-concern ' ], [ ' pascals-mugging-tiny-probabilities-of-vast-utilities ' , ' pascals-mugging ' ], [ ' should-we-simplify-ourselves ' , ' should-we-simpl ' ], [ ' hanson-joins-cult ' , ' hanson-joins-cu ' ], [ ' congratulations-to-paris-hilton ' , ' congratulations ' ], [ ' cut-us-military-in-half ' , ' cut-us-military ' ], [ ' cant-say-no-spending ' , ' cant-say-no-spe ' ], [ ' share-your-original-wisdom ' , ' original-wisdom ' ], -[ ' buy-health-not-medicine ' , ' buy-health-not- ' ], +[ ' buy-health-not-medicine ' , ' buy-health-not ' ], [ ' hold-off-on-proposing-solutions ' , ' hold-off-solvin ' ], [ ' doctors-kill ' , ' doctors-kill ' ], [ ' the-logical-fallacy-of-generalization-from-fictional-evidence ' , ' fictional-evide ' ], [ ' my-local-hospital ' , ' my-local-hospit ' ], [ ' how-to-seem-and-be-deep ' , ' how-to-seem-and ' ], [ ' megan-has-a-point ' , ' megan-has-a-poi ' ], [ ' original-seeing ' , ' original-seeing ' ], [ ' fatty-food-is-healthy ' , ' fatty-food-is-h ' ], [ ' the-outside-the-box-box ' , ' outside-the-box ' ], [ ' meta-honesty ' , ' meta-honesty ' ], [ ' cached-thoughts ' , ' cached-thoughts ' ], [ ' health-hopes-spring-eternal ' , ' health-hope-spr ' ], [ ' do-we-believe-ieverythingi-were-told ' , ' do-we-believe-e ' ], [ ' chinks-in-the-bayesian-armor ' , ' chinks-in-the-b ' ], [ ' priming-and-contamination ' , ' priming-and-con ' ], [ ' what-evidence-intuition ' , ' what-evidence-i ' ], [ ' a-priori ' , ' a-priori ' ], [ ' regulation-ratchet ' , ' what-evidence-b ' ], [ ' no-one-can-exempt-you-from-rationalitys-laws ' , ' its-the-law ' ], -[ ' flexible-legal-similarity ' , ' flexible-legal- ' ], +[ ' flexible-legal-similarity ' , ' flexible-legal ' ], [ ' singlethink ' , ' singlethink ' ], [ ' what-evidence-divergent-explanations ' , ' what-evidence-d ' ], [ ' the-meditation-on-curiosity ' , ' curiosity ' ], [ ' pleasant-beliefs ' , ' pleasant-belief ' ], [ ' isshoukenmei-make-a-desperate-effort ' , ' isshoukenmei-ma ' ], [ ' author-misreads-expert-re-crowds ' , ' author-misreads ' ], [ ' avoiding-your-beliefs-real-weak-points ' , ' avoiding-your-b ' ], [ ' got-crisis ' , ' got-crisis ' ], [ ' why-more-history-than-futurism ' , ' why-more-histor ' ], [ ' we-change-our-minds-less-often-than-we-think ' , ' we-change-our-m ' ], -[ ' why-not-dating-coaches ' , ' why-not-dating- ' ], +[ ' why-not-dating-coaches ' , ' why-not-dating ' ], [ ' a-rational-argument ' , ' a-rational-argu ' ], [ ' can-school-debias ' , ' can-education-d ' ], [ ' recommended-rationalist-reading ' , ' recommended-rat ' ], [ ' confession-errors ' , ' confession-erro ' ], [ ' open-thread ' , ' open-thread ' ], [ ' precious-silence-lost ' , ' precious-silenc ' ], [ ' leader-gender-bias ' , ' leader-gender-b ' ], [ ' the-halo-effect ' , ' halo-effect ' ], [ ' unbounded-scales-huge-jury-awards-futurism ' , ' unbounded-scale ' ], [ ' what-insight-literature ' , ' what-insight-li ' ], [ ' evaluability-and-cheap-holiday-shopping ' , ' evaluability ' ], [ ' the-affect-heuristic ' , ' affect-heuristi ' ], [ ' academia-clumps ' , ' academia-clumps ' ], [ ' purpose-and-pragmatism ' , ' purpose-and-pra ' ], [ ' lost-purposes ' , ' lost-purposes ' ], [ ' intrade-fee-structure-discourages-selling-the-tails ' , ' intrade-fee-str ' ], [ ' growing-into-atheism ' , ' growing-into-at ' ], [ ' the-hidden-complexity-of-wishes ' , ' complex-wishes ' ], [ ' aliens-among-us ' , ' aliens-among-us ' ], [ ' leaky-generalizations ' , ' leaky-generaliz ' ], [ ' good-intrade-bets ' , ' good-intrade-be ' ], [ ' not-for-the-sake-of-happiness-alone ' , ' not-for-the-sak ' ], [ ' interpreting-the-fed ' , ' interpreting-th ' ], [ ' merry-hallowthankmas-eve ' , ' merry-hallowmas ' ], [ ' truly-part-of-you ' , ' truly-part-of-y ' ], [ ' overcoming-bias-after-one-year ' , ' overcoming-bi-1 ' ], [ ' artificial-addition ' , ' artificial-addi ' ], [ ' publication-bias-and-the-death-penalty ' , ' publication-bia ' ], [ ' development-futures ' , ' development-fut ' ], [ ' conjuring-an-evolution-to-serve-you ' , ' conjuring-an-ev ' ], [ ' us-south-had-42-chance ' , ' us-south-had-42 ' ], [ ' towards-a-typology-of-bias ' , ' towards-a-typol ' ], [ ' the-simple-math-of-everything ' , ' the-simple-math ' ], [ ' my-guatemala-interviews ' , ' my-guatemala-in ' ], [ ' no-evolutions-for-corporations-or-nanodevices ' , ' no-evolution-fo ' ], [ ' inaturei-endorses-human-extinction ' , ' terrible-optimi ' ], [ ' evolving-to-extinction ' , ' evolving-to-ext ' ], [ ' dont-do-something ' , ' dont-do-somethi ' ], [ ' terminal-values-and-instrumental-values ' , ' terminal-values ' ], [ ' treatment-futures ' , ' treatment-futur ' ], [ ' thou-art-godshatter ' , ' thou-art-godsha ' ], [ ' implicit-conditionals ' , ' implicit-condit ' ], [ ' protein-reinforcement-and-dna-consequentialism ' , ' protein-reinfor ' ], [ ' polarized-usa ' , ' polarized-usa ' ], [ ' evolutionary-psychology ' , ' evolutionary-ps ' ], [ ' adaptation-executers-not-fitness-maximizers ' , ' adaptation-exec ' ], [ ' overcoming-bias-at-work-for-engineers ' , ' overcoming-bias ' ], [ ' fake-optimization-criteria ' , ' fake-optimizati ' ], [ ' dawes-on-therapy ' , ' dawes-on-psycho ' ], [ ' friendly-ai-guide ' , ' fake-utility-fu ' ], [ ' fake-morality ' , ' fake-morality ' ], [ ' seat-belts-work ' , ' seat-belts-work ' ], [ ' fake-selfishness ' , ' fake-selfishnes ' ], [ ' inconsistent-paternalism ' , ' inconsistent-pa ' ], [ ' the-tragedy-of-group-selectionism ' , ' group-selection ' ], [ ' are-the-self-righteous-righteous ' , ' are-the-self-ri ' ], [ ' beware-of-stephen-j-gould ' , ' beware-of-gould ' ], [ ' college-admission-futures ' , ' college-admissi ' ], [ ' natural-selections-speed-limit-and-complexity-bound ' , ' natural-selecti ' ], [ ' -a-test-for-political-prediction-markets ' , ' a-test-for-poli ' ], [ ' passionately-wrong ' , ' passionately-wr ' ], [ ' evolutions-are-stupid-but-work-anyway ' , ' evolutions-are- ' ], [ ' serious-unconventional-de-grey ' , ' serious-unconve ' ], [ ' the-wonder-of-evolution ' , ' the-wonder-of-e ' ], [ ' hospice-beats-hospital ' , ' hospice-beats-h ' ], [ ' an-alien-god ' , ' an-alien-god ' ], [ ' open-thread ' , ' open-thread ' ], [ ' how-much-defer-to-experts ' , ' how-much-defer- ' ], [ ' the-right-belief-for-the-wrong-reasons ' , ' the-right-belie ' ], [ ' fake-justification ' , ' fake-justificat ' ], [ ' a-terrifying-halloween-costume ' , ' a-terrifying-ha ' ], [ ' honest-teen-paternalism ' , ' teen-paternalis ' ], [ ' my-strange-beliefs ' , ' my-strange-beli ' ], [ ' cultish-countercultishness ' , ' cultish-counter ' ], [ ' to-lead-you-must-stand-up ' , ' stand-to-lead ' ], [ ' econ-of-longer-lives ' , ' neglected-pro-l ' ], [ ' lonely-dissent ' , ' lonely-dissent ' ], [ ' on-expressing-your-concerns ' , ' express-concern ' ], [ ' too-much-hope ' , ' too-much-hope ' ], [ ' aschs-conformity-experiment ' , ' aschs-conformit ' ], [ ' the-amazing-virgin-pregnancy ' , ' amazing-virgin ' ], [ ' procrastination ' , ' procrastination ' ], [ ' testing-hillary-clintons-oil-claim ' , ' testing-hillary ' ], [ ' zen-and-the-art-of-rationality ' , ' zen-and-the-art ' ], [ ' effortless-technique ' , ' effortless-tech ' ], [ ' false-laughter ' , ' false-laughter ' ], [ ' obligatory-self-mockery ' , ' obligatory-self ' ], [ ' the-greatest-gift-the-best-exercise ' , ' the-best-exerci ' ], [ ' two-cult-koans ' , ' cult-koans ' ], [ ' interior-economics ' , ' interior-econom ' ], [ ' politics-and-awful-art ' , ' politics-and-aw ' ], [ ' judgment-can-add-accuracy ' , ' judgment-can-ad ' ], [ ' the-litany-against-gurus ' , ' the-litany-agai ' ], [ ' the-root-of-all-political-stupidity ' , ' the-root-of-all ' ], [ ' guardians-of-ayn-rand ' , ' ayn-rand ' ], [ ' power-corrupts ' , ' power-corrupts ' ], [ ' teen-revolution-and-evolutionary-psychology ' , ' teen-revolution ' ], [ ' gender-tax ' , ' gender-tax ' ], [ ' guardians-of-the-gene-pool ' , ' guardians-of--1 ' ], [ ' battle-of-the-election-forecasters ' , ' battle-of-the-e ' ], [ ' guardians-of-the-truth ' , ' guardians-of-th ' ], [ ' hug-the-query ' , ' hug-the-query ' ], [ ' economist-judgment ' , ' economist-judgm ' ], [ ' justly-acquired-endowment-taxing-as-punishment-or-as-a-way-to-raise-money ' , ' justly-acquired ' ], [ ' argument-screens-off-authority ' , ' argument-screen ' ], [ ' give-juries-video-recordings-of-testimony ' , ' give-juries-vid ' ], [ ' reversed-stupidity-is-not-intelligence ' , ' reversed-stupid ' ], [ ' tax-the-tall ' , ' tax-the-tall ' ], [ ' every-cause-wants-to-be-a-cult ' , ' every-cause-wan ' ], [ ' does-healthcare-do-any-good-at-all ' , ' does-healthcare ' ], [ ' art-and-moral-responsibility ' , ' art-and-moral-r ' ], [ ' misc-meta ' , ' misc-meta ' ], [ ' it-is-good-to-exist ' , ' it-is-good-to-e ' ], [ ' the-robbers-cave-experiment ' , ' the-robbers-cav ' ], [ ' medicine-has-been-overcoming-bias-too ' , ' medicine-has-be ' ], [ ' when-none-dare-urge-restraint ' , ' when-none-dare ' ], [ ' modules-signals-and-guilt ' , ' modules-signals ' ], [ ' evaporative-cooling-of-group-beliefs ' , ' evaporative-coo ' ], [ ' doctor-hypocrisy ' , ' doctors-lie ' ], [ ' fake-utility-functions ' , ' fake-utility-fu ' ], [ ' open-thread ' , ' open-thread ' ], [ ' fake-fake-utility-functions ' , ' fake-fake-utili ' ], [ ' ethical-shortsightedness ' , ' ethical-shortsi ' ], [ ' heroic-job-bias ' , ' heroic-job-bias ' ], [ ' uncritical-supercriticality ' , ' supercritical-u ' ], [ ' resist-the-happy-death-spiral ' , ' resist-the-happ ' ], [ ' baby-selling ' , ' baby-selling ' ], [ ' affective-death-spirals ' , ' affective-death ' ], [ ' mere-messiahs ' , ' mere-messiahs ' ], [ ' superhero-bias ' , ' superhero-bias ' ], [ ' ob-meetup-millbrae-thu-21-feb-7pm ' , ' ob-meetup-millb ' ], [ ' newcombs-problem-and-regret-of-rationality ' , ' newcombs-proble ' ], [ ' dark-police ' , ' privacy-lost ' ], [ ' contingent-truth-value ' , ' contingent-trut ' ], [ ' deliberative-prediction-markets----a-reply ' , ' deliberative-pr ' ], [ ' something-to-protect ' , ' something-to-pr ' ], [ ' deliberation-in-prediction-markets ' , ' deliberation-in ' ], [ ' trust-in-bayes ' , ' trust-in-bayes ' ], [ ' predictocracy----a-preliminary-response ' , ' predictocracy- ' ], [ ' the-intuitions-behind-utilitarianism ' , ' the-intuitions ' ], [ ' voters-want-simplicity ' , ' voters-want-sim ' ], [ ' predictocracy ' , ' predictocracy ' ], [ ' rationality-quotes-9 ' , ' quotes-9 ' ], [ ' knowing-your-argumentative-limitations-or-one-rationalists-modus-ponens-is-anothers-modus-tollens ' , ' knowing-your-ar ' ], [ ' problems-with-prizes ' , ' problems-with-p ' ], [ ' rationality-quotes-8 ' , ' quotes-8 ' ], [ ' acceptable-casualties ' , ' acceptable-casu ' ], [ ' rationality-quotes-7 ' , ' quotes-7 ' ], [ ' cfo-overconfidence ' , ' ceo-overconfide ' ], [ ' rationality-quotes-6 ' , ' quotes-6 ' ], [ ' rationality-quotes-5 ' , ' quotes-5 ' ], [ ' connections-versus-insight ' , ' connections-ver ' ], [ ' circular-altruism ' , ' circular-altrui ' ], [ ' for-discount-rates ' , ' protecting-acro ' ], [ ' against-discount-rates ' , ' against-discoun ' ], [ ' allais-malaise ' , ' allais-malaise ' ], [ ' mandatory-sensitivity-training-fails ' , ' mandatory-sensi ' ], [ ' rationality-quotes-4 ' , ' quotes-4 ' ], [ ' zut-allais ' , ' zut-allais ' ], [ ' the-allais-paradox ' , ' allais-paradox ' ], [ ' nesse-on-academia ' , ' nesse-on-academ ' ], [ ' antidepressant-publication-bias ' , ' antidepressant ' ], [ ' rationality-quotes-3 ' , ' rationality-quo ' ], [ ' rationality-quotes-2 ' , ' quotes-2 ' ], [ ' just-enough-expertise ' , ' trolls-on-exper ' ], [ ' rationality-quotes-1 ' , ' quotes-1 ' ], [ ' trust-in-math ' , ' trust-in-math ' ], [ ' economist-as-scrooge ' , ' economist-as-sc ' ], [ ' beautiful-probability ' , ' beautiful-proba ' ], [ ' leading-bias-researcher-turns-out-to-be-biased-renounces-result ' , ' leading-bias-re ' ], [ ' is-reality-ugly ' , ' is-reality-ugly ' ], [ ' dont-choose-a-president-the-way-youd-choose-an-assistant-regional-manager ' , ' dont-choose-a-p ' ], [ ' expecting-beauty ' , ' expecting-beaut ' ], [ ' how-to-fix-wage-bias ' , ' profit-by-corre ' ], [ ' beautiful-math ' , ' beautiful-math ' ], [ ' 0-and-1-are-not-probabilities ' , ' 0-and-1-are-not ' ], [ ' once-more-with-feeling ' , ' once-more-with ' ], [ ' political-inequality ' , ' political-inequ ' ], [ ' infinite-certainty ' , ' infinite-certai ' ], [ ' more-presidential-decision-markets ' , ' more-presidenti ' ], [ ' experiencing-the-endowment-effect ' , ' experiencing-th ' ], [ ' absolute-authority ' , ' absolute-author ' ], [ ' social-scientists-know-lots ' , ' social-scientis ' ], [ ' the-fallacy-of-gray ' , ' gray-fallacy ' ], [ ' are-we-just-pumping-against-entropy-or-can-we-win ' , ' are-we-just-pum ' ], [ ' art-trust-and-betrayal ' , ' art-trust-and-b ' ], [ ' nuked-us-futures ' , ' nuked-us-future ' ], [ ' but-theres-still-a-chance-right ' , ' still-a-chance ' ], [ ' a-failed-just-so-story ' , ' a-failed-just-s ' ], [ ' presidential-decision-markets ' , ' presidential-de ' ], [ ' open-thread ' , ' open-thread ' ], [ ' rational-vs-scientific-ev-psych ' , ' rational-vs-sci ' ], [ ' weekly-exercises ' , ' weekly-exercise ' ], [ ' yes-it-can-be-rational-to-vote-in-presidential-elections ' , ' yes-it-can-be-r ' ], [ ' debugging-comments ' , ' debugging-comme ' ], [ ' stop-voting-for-nincompoops ' , ' stop-voting-for ' ], [ ' i-dare-you-bunzl ' , ' in-yesterdays-p ' ], [ ' the-american-system-and-misleading-labels ' , ' the-american-sy ' ], [ ' some-structural-biases-of-the-political-system ' , ' some-structural ' ], [ ' a-politicians-job ' , ' a-politicians-j ' ], [ ' the-ordering-of-authors-names-in-academic-publications ' , ' the-ordering-of ' ], [ ' the-two-party-swindle ' , ' the-two-party-s ' ], [ ' posting-on-politics ' , ' posting-on-poli ' ], [ ' searching-for-bayes-structure ' , ' bayes-structure ' ], [ ' perpetual-motion-beliefs ' , ' perpetual-motio ' ], [ ' ignoring-advice ' , ' ignoring-advice ' ], [ ' the-second-law-of-thermodynamics-and-engines-of-cognition ' , ' second-law ' ], [ ' leave-a-line-of-retreat ' , ' leave-retreat ' ], [ ' more-referee-bias ' , ' more-referee-bi ' ], [ ' superexponential-conceptspace-and-simple-words ' , ' superexp-concep ' ], [ ' my-favorite-liar ' , ' my-favorite-lia ' ], [ ' mutual-information-and-density-in-thingspace ' , ' mutual-informat ' ], [ ' if-self-fulfilling-optimism-is-wrong-i-dont-wanna-be-right ' , ' if-self-fulfill ' ], [ ' entropy-and-short-codes ' , ' entropy-codes ' ], [ ' more-moral-wiggle-room ' , ' more-moral-wigg ' ], [ ' where-to-draw-the-boundary ' , ' where-boundary ' ], [ ' the-hawthorne-effect ' , ' the-hawthorne-e ' ], [ ' categories-and-information-theory ' , ' a-bayesian-view ' ], [ ' arguing-by-definition ' , ' arguing-by-defi ' ], [ ' against-polish ' , ' against-polish ' ], [ ' colorful-character-again ' , ' colorful-charac ' ], [ ' sneaking-in-connotations ' , ' sneak-connotati ' ], [ ' nephew-versus-nepal-charity ' , ' nephews-versus ' ], [ ' categorizing-has-consequences ' , ' category-conseq ' ], [ ' the-public-intellectual-plunge ' , ' the-public-inte ' ], [ ' fallacies-of-compression ' , ' compress-fallac ' ], [ ' with-blame-comes-hope ' , ' with-blame-come ' ], [ ' relative-vs-absolute-rationality ' , ' relative-vs-abs ' ], [ ' replace-the-symbol-with-the-substance ' , ' replace-symbol ' ], [ ' talking-versus-trading ' , ' comparing-delib ' ], [ ' taboo-your-words ' , ' taboo-words ' ], [ ' why-just-believe ' , ' why-just-believ ' ], [ ' classic-sichuan-in-millbrae-thu-feb-21-7pm ' , ' millbrae-thu-fe ' ], [ ' empty-labels ' , ' empty-labels ' ], [ ' is-love-something-more ' , ' is-love-somethi ' ], [ ' the-argument-from-common-usage ' , ' common-usage ' ], [ ' pod-people-paternalism ' , ' pod-people-pate ' ], [ ' feel-the-meaning ' , ' feel-meaning ' ], [ ' dinos-on-the-moon ' , ' dinos-on-the-mo ' ], [ ' disputing-definitions ' , ' disputing-defin ' ], [ ' what-is-worth-study ' , ' what-is-worth-s ' ], [ ' how-an-algorithm-feels-from-inside ' , ' algorithm-feels ' ], [ ' nanotech-views-value-driven ' , ' nanotech-views ' ], [ ' neural-categories ' , ' neural-categori ' ], [ ' believing-too-little ' , ' believing-too-l ' ], [ ' disguised-queries ' , ' disguised-queri ' ], [ ' eternal-medicine ' , ' eternal-medicin ' ], [ ' the-cluster-structure-of-thingspace ' , ' thingspace-clus ' ], [ ' typicality-and-asymmetrical-similarity ' , ' typicality-and ' ], [ ' what-wisdom-silence ' , ' what-wisdom-sil ' ], [ ' similarity-clusters ' , ' similarity-clus ' ], [ ' buy-now-or-forever-hold-your-peace ' , ' buy-now-or-fore ' ], [ ' extensions-and-intensions ' , ' extensions-inte ' ], [ ' lets-do-like-them ' , ' lets-do-like-th ' ], [ ' words-as-hidden-inferences ' , ' words-as-hidden ' ], [ ' predictocracy-vs-futarchy ' , ' predictocracy-v ' ], [ ' the-parable-of-hemlock ' , ' hemlock-parable ' ], [ ' merger-decision-markets ' , ' merger-decision ' ], [ ' open-thread ' , ' open-thread ' ], [ ' the-parable-of-the-dagger ' , ' dagger-parable ' ], [ ' futarchy-vs-predictocracy ' , ' futarchy-vs-pre ' ], [ ' against-news ' , ' against-news ' ], [ ' angry-atoms ' , ' angry-atoms ' ], [ ' hand-vs-fingers ' , ' hand-vs-fingers ' ], [ ' impotence-of-belief-in-bias ' , ' impotence-of-be ' ], [ ' initiation-ceremony ' , ' initiation-cere ' ], [ ' cash-increases-accuracy ' , ' cash-clears-the ' ], [ ' to-spread-science-keep-it-secret ' , ' spread-science ' ], [ ' ancient-political-self-deception ' , ' ancient-politic ' ], [ ' scarcity ' , ' scarcity ' ], [ ' fantasy-and-reality-substitutes-or-complements ' , ' fantasy-and-rea ' ], [ ' is-humanism-a-religion-substitute ' , ' is-humanism-rel ' ], [ ' showing-that-you-care ' , ' showing-that-yo ' ], [ ' amazing-breakthrough-day-april-1st ' , ' amazing-breakth ' ], [ ' correction-ny-ob-meetup-13-astor-place-25 ' , ' correction-ny-o ' ], [ ' religious-cohesion ' , ' religious-cohes ' ], [ ' the-beauty-of-settled-science ' , ' beauty-settled ' ], [ ' where-want-fewer-women ' , ' where-want-less ' ], [ ' new-york-ob-meetup-ad-hoc-on-monday-mar-24-6pm ' , ' new-york-ob-mee ' ], [ ' if-you-demand-magic-magic-wont-help ' , ' against-magic ' ], [ ' biases-in-processing-political-information ' , ' biases-in-proce ' ], [ ' bind-yourself-to-reality ' , ' bind-yourself-t ' ], [ ' boards-of-advisors-dont-advise-do-board ' , ' boards-of-advis ' ], [ ' joy-in-discovery ' , ' joy-in-discover ' ], [ ' joy-in-the-merely-real ' , ' joy-in-the-real ' ], [ ' sincerity-is-overrated ' , ' sincerity-is-wa ' ], [ ' rationalists-lets-make-a-movie ' , ' rationalists-le ' ], [ ' savanna-poets ' , ' savanna-poets ' ], [ ' biases-and-investing ' , ' biases-and-inve ' ], [ ' morality-is-overrated ' , ' unwanted-morali ' ], [ ' fake-reductionism ' , ' fake-reductioni ' ], [ ' theyre-only-tokens ' , ' theyre-only-tok ' ], [ ' explaining-vs-explaining-away ' , ' explaining-away ' ], [ ' reductionism ' , ' reductionism ' ], [ ' a-few-quick-links ' , ' a-few-quick-lin ' ], [ ' qualitatively-confused ' , ' qualitatively-c ' ], [ ' the-kind-of-project-to-watch ' , ' the-project-to ' ], [ ' penguicon-blook ' , ' penguicon-blook ' ], [ ' one-million-visits ' , ' one-million-vis ' ], [ ' distinguish-info-analysis-belief-action ' , ' distinguish-inf ' ], [ ' the-quotation-is-not-the-referent ' , ' quote-not-refer ' ], [ ' neglecting-conceptual-research ' , ' scott-aaronson ' ], [ ' probability-is-in-the-mind ' , ' mind-probabilit ' ], [ ' limits-to-physics-insight ' , ' limits-to-physi ' ], [ ' mind-projection-fallacy ' , ' mind-projection ' ], [ ' mind-projection-by-default ' , ' mpf-by-default ' ], [ ' uninformative-experience ' , ' uninformative-e ' ], [ ' righting-a-wrong-question ' , ' righting-a-wron ' ], [ ' wrong-questions ' , ' wrong-questions ' ], [ ' dissolving-the-question ' , ' dissolving-the ' ], [ ' bias-and-power ' , ' biased-for-and ' ], [ ' gary-gygax-annihilated-at-69 ' , ' gary-gygax-anni ' ], [ ' wilkinson-on-paternalism ' , ' wilkinson-on-pa ' ], [ ' 37-ways-that-words-can-be-wrong ' , ' wrong-words ' ], [ ' overvaluing-ideas ' , ' overvaluing-ide ' ], [ ' reject-random-beliefs ' , ' reject-random-b ' ], [ ' variable-question-fallacies ' , ' variable-questi ' ], [ ' rationality-quotes-11 ' , ' rationality-q-1 ' ], [ ' human-capital-puzzle-explained ' , ' human-capital-p ' ], [ ' rationality-quotes-10 ' , ' rationality-quo ' ], [ ' words-as-mental-paintbrush-handles ' , ' mental-paintbru ' ], [ ' open-thread ' , ' open-thread ' ], [ ' framing-problems-as-separate-from-people ' , ' framing-problem ' ], [ ' conditional-independence-and-naive-bayes ' , ' conditional-ind ' ], [ ' be-biased-to-be-happy ' , ' be-biased-to-be ' ], [ ' optimism-bias-desired ' , ' optimism-bias-d ' ], [ ' decoherent-essences ' , ' decoherent-esse ' ], [ ' self-copying-factories ' , ' replication-bre ' ], [ ' decoherence-is-pointless ' , ' pointless-decoh ' ], [ ' charm-beats-accuracy ' , ' charm-beats-acc ' ], [ ' the-conscious-sorites-paradox ' , ' conscious-sorit ' ], [ ' decoherent-details ' , ' decoherent-deta ' ], [ ' on-being-decoherent ' , ' on-being-decohe ' ], [ ' quantum-orthodoxy ' , ' quantum-quotes ' ], [ ' if-i-had-a-million ' , ' if-i-had-a-mill ' ], [ ' where-experience-confuses-physicists ' , ' where-experienc ' ], [ ' thou-art-decoherent ' , ' the-born-probab ' ], [ ' blaming-the-unlucky ' , ' blaming-the-unl ' ], [ ' where-physics-meets-experience ' , ' physics-meets-e ' ], [ ' early-scientists-chose-influence-over-credit ' , ' early-scientist ' ], [ ' which-basis-is-more-fundamental ' , ' which-basis-is ' ], [ ' a-model-disagreement ' , ' a-model-disagre ' ], [ ' the-so-called-heisenberg-uncertainty-principle ' , ' heisenberg ' ], [ ' caplan-pulls-along-ropes ' , ' caplan-pulls-al ' ], [ ' decoherence ' , ' decoherence ' ], [ ' paternalism-parable ' , ' paternalism-par ' ], [ ' three-dialogues-on-identity ' , ' identity-dialog ' ], [ ' on-philosophers ' , ' on-philosophers ' ], [ ' zombies-the-movie ' , ' zombie-movie ' ], [ ' schwitzgebel-thoughts ' , ' schwitzgebel-th ' ], [ ' identity-isnt-in-specific-atoms ' , ' identity-isnt-i ' ], [ ' elevator-myths ' , ' elevator-myths ' ], [ ' no-individual-particles ' , ' no-individual-p ' ], [ ' is-she-just-friendly ' , ' is-she-just-bei ' ], [ ' feynman-paths ' , ' feynman-paths ' ], [ ' kids-parents-disagree-on-spouses ' , ' kids-parents-di ' ], [ ' the-quantum-arena ' , ' quantum-arena ' ], [ ' classical-configuration-spaces ' , ' conf-space ' ], [ ' how-to-vs-what-to ' , ' how-to-vs-what ' ], [ ' can-you-prove-two-particles-are-identical ' , ' identical-parti ' ], [ ' naming-beliefs ' , ' naming-beliefs ' ], [ ' where-philosophy-meets-science ' , ' philosophy-meet ' ], [ ' distinct-configurations ' , ' distinct-config ' ], [ ' conformity-questions ' , ' conformity-ques ' ], [ ' conformity-myths ' , ' conformity-myth ' ], [ ' joint-configurations ' , ' joint-configura ' ], [ ' configurations-and-amplitude ' , ' configurations ' ], [ ' prevention-costs ' , ' prevention-cost ' ], [ ' quantum-explanations ' , ' quantum-explana ' ], [ ' inhuman-rationality ' , ' inhuman-rationa ' ], [ ' belief-in-the-implied-invisible ' , ' implied-invisib ' ], [ ' endearing-sincerity ' , ' sincerity-i-lik ' ], [ ' gazp-vs-glut ' , ' gazp-vs-glut ' ], [ ' the-generalized-anti-zombie-principle ' , ' anti-zombie-pri ' ], [ ' anxiety-about-what-is-true ' , ' anxiety-about-w ' ], [ ' ramone-on-knowing-god ' , ' ramone-on-knowi ' ], [ ' zombie-responses ' , ' zombies-ii ' ], [ ' brownlee-on-selling-anxiety ' , ' brownlee-on-sel ' ], [ ' zombies-zombies ' , ' zombies ' ], [ ' reductive-reference ' , ' reductive-refer ' ], [ ' arbitrary-silliness ' , ' arbitrary-silli ' ], [ ' brain-breakthrough-its-made-of-neurons ' , ' brain-breakthro ' ], [ ' open-thread ' , ' open-thread ' ], [ ' why-i-dont-like-bayesian-statistics ' , ' why-i-dont-like ' ], [ ' beware-of-brain-images ' , ' beware-of-brain ' ], [ ' heat-vs-motion ' , ' heat-vs-motion ' ], [ ' physics-your-brain-and-you ' , ' physics-your-br ' ], [ ' a-premature-word-on-ai ' , ' an-ai-new-timer ' ], [ ' ai-old-timers ' , ' roger-shank-ai ' ], [ ' empty-space ' , ' empty-space ' ], [ ' class-project ' , ' class-project ' ], [ ' einsteins-superpowers ' , ' einsteins-super ' ], [ ' intro-to-innovation ' , ' intro-to-innova ' ], [ ' timeless-causality ' , ' timeless-causal ' ], [ ' overconfidence-paternalism ' , ' paul-graham-off ' ], [ ' timeless-beauty ' , ' timeless-beauty ' ], [ ' lazy-lineup-study ' , ' why-is-this-so ' ], [ ' timeless-physics ' , ' timeless-physic ' ], [ ' the-end-of-time ' , ' the-end-of-time ' ], [ ' 2nd-annual-roberts-podcast ' , ' 2nd-annual-robe ' ], [ ' who-shall-we-honor ' , ' who-should-we-h ' ], [ ' relative-configuration-space ' , ' relative-config ' ], [ ' beware-identity ' , ' beware-identity ' ], [ ' prediction-markets-and-insider-trading ' , ' prediction-mark ' ], [ ' a-broken-koan ' , ' a-broken-koan ' ], [ ' machs-principle-anti-epiphenomenal-physics ' , ' machs-principle ' ], [ ' lying-to-kids ' , ' lying-to-kids ' ], [ ' my-childhood-role-model ' , ' my-childhood-ro ' ], [ ' that-alien-message ' , ' faster-than-ein ' ], [ ' anthropic-breakthrough ' , ' anthropic-break ' ], [ ' einsteins-speed ' , ' einsteins-speed ' ], [ ' transcend-or-die ' , ' transcend-or-di ' ], [ ' far-future-disagreement ' , ' far-future-disa ' ], [ ' faster-than-science ' , ' faster-than-sci ' ], [ ' conference-on-global-catastrophic-risks ' , ' conference-on-g ' ], [ ' biting-evolution-bullets ' , ' biting-evolutio ' ], [ ' changing-the-definition-of-science ' , ' changing-the-de ' ], [ ' no-safe-defense-not-even-science ' , ' no-defenses ' ], [ ' bounty-slander ' , ' bounty-slander ' ], [ ' idea-futures-in-lumpaland ' , ' idea-futures-in ' ], [ ' do-scientists-already-know-this-stuff ' , ' do-scientists-a ' ], [ ' lobbying-for-prediction-markets ' , ' lobbying-for-pr ' ], [ ' science-isnt-strict-ienoughi ' , ' science-isnt-st ' ], [ ' lumpaland-parable ' , ' lumpaland-parab ' ], [ ' when-science-cant-help ' , ' when-science-ca ' ], [ ' honest-politics ' , ' honest-politics ' ], [ ' science-doesnt-trust-your-rationality ' , ' science-doesnt ' ], [ ' sleepy-fools ' , ' sleepy-fools ' ], [ ' the-dilemma-science-or-bayes ' , ' science-or-baye ' ], [ ' the-failures-of-eld-science ' , ' eld-science ' ], [ ' condemned-to-repeat-finance-past ' , ' condemned-to-re ' ], [ ' many-worlds-one-best-guess ' , ' many-worlds-one ' ], [ ' why-quantum ' , ' why-quantum ' ], [ ' happy-conservatives ' , ' happy-conservat ' ], [ ' if-many-worlds-had-come-first ' , ' if-many-worlds ' ], [ ' elusive-placebos ' , ' elusive-placebo ' ], [ ' collapse-postulates ' , ' collapse-postul ' ], [ ' faith-in-docs ' , ' faith-in-docs ' ], [ ' quantum-non-realism ' , ' eppur-si-moon ' ], [ ' iexpelledi-beats-isickoi ' , ' expelled-beats ' ], [ ' decoherence-is-falsifiable-and-testable ' , ' mwi-is-falsifia ' ], [ ' guilt-by-association ' , ' guilt-and-all-b ' ], [ ' decoherence-is-simple ' , ' mwi-is-simple ' ], [ ' keeping-math-real ' , ' keeping-math-re ' ], [ ' spooky-action-at-a-distance-the-no-communication-theorem ' , ' spooky-action-a ' ], [ ' walking-on-grass-others ' , ' walking-on-gras ' ], [ ' bells-theorem-no-epr-reality ' , ' bells-theorem-n ' ], [ ' beware-transfusions ' , ' beware-blood-tr ' ], [ ' entangled-photons ' , ' entangled-photo ' ], [ ' beware-supplements ' , ' beware-suppleme ' ], [ ' decoherence-as-projection ' , ' projection ' ], [ ' open-thread ' , ' open-thread ' ], [ ' im-in-boston ' , ' im-in-boston ' ], [ ' the-born-probabilities ' , ' the-born-prob-1 ' ], [ ' experience-increases-overconfidence ' , ' the-latest-jour ' ], [ ' the-moral-void ' , ' moral-void ' ], [ ' what-would-you-do-without-morality ' , ' without-moralit ' ], [ ' average-your-guesses ' , ' average-your-gu ' ], [ ' the-opposite-sex ' , ' opposite-sex ' ], [ ' the-conversation-so-far ' , ' the-conversatio ' ], [ ' glory-vs-relations ' , ' glory-vs-relati ' ], [ ' 2-place-and-1-place-words ' , ' 2-place-and-1-p ' ], [ ' caution-kills-when-fighting-malaria ' , ' caution-kills-w ' ], [ ' to-what-expose-kids ' , ' to-what-expose ' ], [ ' no-universally-compelling-arguments ' , ' no-universally ' ], [ ' the-design-space-of-minds-in-general ' , ' minds-in-genera ' ], [ ' should-bad-boys-win ' , ' why-do-psychopa ' ], [ ' the-psychological-unity-of-humankind ' , ' psychological-u ' ], [ ' eliezers-meta-level-determinism ' , ' eliezers-meta-l ' ], [ ' optimization-and-the-singularity ' , ' optimization-an ' ], [ ' tyler-vid-on-disagreement ' , ' tyler-vid-on-di ' ], [ ' are-meta-views-outside-views ' , ' are-meta-views ' ], [ ' surface-analogies-and-deep-causes ' , ' surface-analogi ' ], [ ' parsing-the-parable ' , ' parsing-the-par ' ], [ ' the-outside-views-domain ' , ' when-outside-vi ' ], [ ' outside-view-of-singularity ' , ' singularity-out ' ], [ ' heading-toward-morality ' , ' toward-morality ' ], [ ' la-602-vs-rhic-review ' , ' la-602-vs-rhic ' ], [ ' history-of-transition-inequality ' , ' singularity-ine ' ], [ ' britain-was-too-small ' , ' britain-was-too ' ], [ ' natural-genocide ' , ' natural-genocid ' ], [ ' what-is-the-probability-of-the-large-hadron-collider-destroying-the-universe ' , ' what-is-the-pro ' ], [ ' ghosts-in-the-machine ' , ' ghosts-in-the-m ' ], [ ' gratitude-decay ' , ' gratitude-decay ' ], [ ' loud-bumpers ' , ' loud-bumpers ' ], [ ' grasping-slippery-things ' , ' grasping-slippe ' ], [ ' in-bias-meta-is-max ' , ' meta-is-max---b ' ], [ ' passing-the-recursive-buck ' , ' pass-recursive ' ], [ ' in-innovation-meta-is-max ' , ' meta-is-max---i ' ], [ ' the-ultimate-source ' , ' the-ultimate-so ' ], [ ' possibility-and-could-ness ' , ' possibility-and ' ], [ ' joe-epstein-on-youth ' , ' joe-epstein-on ' ], [ ' causality-and-moral-responsibility ' , ' causality-and-r ' ], [ ' anti-depressants-fail ' , ' anti-depressant ' ], [ ' quantum-mechanics-and-personal-identity ' , ' qm-and-identity ' ], [ ' and-the-winner-is-many-worlds ' , ' mwi-wins ' ], [ ' quantum-physics-revealed-as-non-mysterious ' , ' quantum-physics ' ], [ ' an-intuitive-explanation-of-quantum-mechanics ' , ' an-intuitive-ex ' ], [ ' prediction-market-based-electoral-map-forecast ' , ' prediction-mark ' ], [ ' tv-is-porn ' , ' tv-is-porn ' ], [ ' the-quantum-physics-sequence ' , ' the-quantum-phy ' ], [ ' never-is-a-long-time ' , ' never-is-a-long ' ], [ ' eliezers-post-dependencies-book-notification-graphic-designer-wanted ' , ' eliezers-post-d ' ], [ ' anti-foreign-bias ' , ' tyler-in-the-ny ' ], [ ' against-devils-advocacy ' , ' against-devils ' ], [ ' the-future-of-oil-prices-3-nonrenewable-resource-pricing ' , ' the-future-of-o ' ], [ ' meetup-in-nyc-wed ' , ' meetup-in-nyc-w ' ], [ ' how-honest-with-kids ' , ' how-honest-with ' ], [ ' bloggingheads-yudkowsky-and-horgan ' , ' bloggingheads-y ' ], [ ' oil-scapegoats ' , ' manipulation-go ' ], [ ' timeless-control ' , ' timeless-contro ' ], [ ' how-to-add-2-to-gdp ' , ' how-to-increase ' ], [ ' thou-art-physics ' , ' thou-art-physic ' ], [ ' overcoming-disagreement ' , ' overcoming-disa ' ], [ ' living-in-many-worlds ' , ' living-in-many ' ], [ ' wait-for-it ' , ' wait-for-it ' ], [ ' why-quantum ' , ' why-quantum ' ], [ ' against-disclaimers ' , ' against-disclai ' ], [ ' timeless-identity ' , ' timeless-identi ' ], [ ' exploration-as-status ' , ' exploration-as ' ], [ ' principles-of-disagreement ' , ' principles-of-d ' ], [ ' the-rhythm-of-disagreement ' , ' the-rhythm-of-d ' ], [ ' open-thread ' , ' open-thread ' ], [ ' singularity-economics ' , ' economics-of-si ' ], [ ' detached-lever-fallacy ' , ' detached-lever ' ], [ ' ok-now-im-worried ' , ' ok-im-worried ' ], [ ' humans-in-funny-suits ' , ' humans-in-funny ' ], [ ' touching-vs-understanding ' , ' touching-vs-und ' ], [ ' intrades-conditional-prediction-markets ' , ' intrades-condit ' ], [ ' when-to-think-critically ' , ' when-to-think-c ' ], [ ' interpersonal-morality ' , ' interpersonal-m ' ], [ ' the-meaning-of-right ' , ' the-meaning-of ' ], [ ' funding-bias ' , ' funding-bias ' ], [ ' setting-up-metaethics ' , ' setting-up-meta ' ], [ ' bias-against-the-unseen ' , ' biased-against ' ], [ ' changing-your-metaethics ' , ' retreat-from-me ' ], [ ' is-ideology-about-status ' , ' is-ideology-abo ' ], [ ' gary-taubes-good-calories-bad-calories ' , ' gary-taubes-goo ' ], [ ' does-your-morality-care-what-you-think ' , ' does-morality-c ' ], [ ' refuge-markets ' , ' refuge-markets ' ], [ ' math-is-subjunctively-objective ' , ' math-is-subjunc ' ], [ ' can-counterfactuals-be-true ' , ' counterfactual ' ], [ ' when-not-to-use-probabilities ' , ' when-not-to-use ' ], [ ' banning-bad-news ' , ' banning-bad-new ' ], [ ' your-morality-doesnt-care-what-you-think ' , ' moral-counterfa ' ], [ ' fake-norms-or-truth-vs-truth ' , ' fake-norms-or-t ' ], [ ' loving-loyalty ' , ' loving-loyalty ' ], [ ' should-we-ban-physics ' , ' should-we-ban-p ' ], [ ' touching-the-old ' , ' touching-the-ol ' ], [ ' existential-angst-factory ' , ' existential-ang ' ], [ ' corporate-assassins ' , ' corporate-assas ' ], [ ' could-anything-be-right ' , ' anything-right ' ], [ ' doxastic-voluntarism-and-some-puzzles-about-rationality ' , ' doxastic-volunt ' ], [ ' disaster-bias ' , ' disaster-bias ' ], [ ' the-gift-we-give-to-tomorrow ' , ' moral-miracle-o ' ], [ ' world-welfare-state ' , ' world-welfare-s ' ], [ ' whither-moral-progress ' , ' whither-moral-p ' ], [ ' posting-may-slow ' , ' posting-may-slo ' ], [ ' bias-in-political-conversation ' , ' bias-in-politic ' ], [ ' lawrence-watt-evanss-fiction ' , ' lawrence-watt-e ' ], [ ' fear-god-and-state ' , ' fear-god-and-st ' ], [ ' probability-is-subjectively-objective ' , ' probability-is ' ], [ ' rebelling-within-nature ' , ' rebelling-withi ' ], [ ' ask-for-help ' , ' ask-for-help ' ], [ ' fundamental-doubts ' , ' fundamental-dou ' ], [ ' biases-of-elite-education ' , ' biases-of-elite ' ], [ ' the-genetic-fallacy ' , ' genetic-fallacy ' ], [ ' my-kind-of-reflection ' , ' my-kind-of-refl ' ], [ ' helsinki-meetup ' , ' helsinki-meetup ' ], [ ' poker-vs-chess ' , ' poker-vs-chess ' ], [ ' cloud-seeding-markets ' , ' cloud-seeding-m ' ], [ ' the-fear-of-common-knowledge ' , ' fear-of-ck ' ], [ ' where-recursive-justification-hits-bottom ' , ' recursive-justi ' ], [ ' artificial-volcanoes ' , ' artificial-volc ' ], [ ' cftc-event-market-comment ' , ' my-cftc-event-c ' ], [ ' will-as-thou-wilt ' , ' will-as-thou-wi ' ], [ ' rationalist-origin-stories ' , ' rationalist-ori ' ], [ ' all-hail-info-theory ' , ' all-hail-info-t ' ], [ ' morality-is-subjectively-objective ' , ' subjectively-ob ' ], [ ' bloggingheads-hanson-wilkinson ' , ' bloggingheads-m ' ], [ ' is-morality-given ' , ' is-morality-giv ' ], [ ' the-most-amazing-productivity-tip-ever ' , ' the-most-amazin ' ], [ ' is-morality-preference ' , ' is-morality-pre ' ], [ ' rah-my-country ' , ' yeah-my-country ' ], [ ' moral-complexities ' , ' moral-complexit ' ], [ ' 2-of-10-not-3-total ' , ' 2-of-10-not-3-t ' ], [ ' overconfident-investing ' , ' overconfident-i ' ], [ ' the-bedrock-of-fairness ' , ' bedrock-fairnes ' ], [ ' sex-nerds-and-entitlement ' , ' sex-nerds-and-e ' ], [ ' break-it-down ' , ' break-it-down ' ], [ ' why-argue-values ' , ' why-argue-value ' ], [ ' id-take-it ' , ' id-take-it ' ], [ ' distraction-overcomes-moral-hypocrisy ' , ' distraction-ove ' ], [ ' open-thread ' , ' open-thread ' ], [ ' overcoming-our-vs-others-biases ' , ' overcoming-our ' ], [ ' created-already-in-motion ' , ' moral-ponens ' ], [ ' morality-made-easy ' , ' morality-made-e ' ], [ ' brief-break ' , ' brief-break ' ], [ ' dreams-of-friendliness ' , ' dreams-of-frien ' ], [ ' fake-fish ' , ' fake-fish ' ], [ ' qualitative-strategies-of-friendliness ' , ' qualitative-str ' ], [ ' cowen-hanson-bloggingheads-topics ' , ' cowen-hanson-bl ' ], [ ' moral-false-consensus ' , ' moral-false-con ' ], [ ' harder-choices-matter-less ' , ' harder-choices ' ], [ ' the-complexity-critique ' , ' the-complexity ' ], [ ' against-modal-logics ' , ' against-modal-l ' ], [ ' top-teachers-ineffective ' , ' certified-teach ' ], [ ' dreams-of-ai-design ' , ' dreams-of-ai-de ' ], [ ' top-docs-no-healthier ' , ' top-school-docs ' ], [ ' three-fallacies-of-teleology ' , ' teleology ' ], [ ' use-the-native-architecture ' , ' use-the-native ' ], [ ' cowen-disses-futarchy ' , ' cowen-dises-fut ' ], [ ' magical-categories ' , ' magical-categor ' ], [ ' randomised-controlled-trials-of-parachutes ' , ' randomised-cont ' ], [ ' unnatural-categories ' , ' unnatural-categ ' ], [ ' good-medicine-in-merry-old-england ' , ' good-medicine-i ' ], [ ' mirrors-and-paintings ' , ' mirrors-and-pai ' ], [ ' beauty-bias ' , ' ignore-beauty ' ], [ ' invisible-frameworks ' , ' invisible-frame ' ], [ ' dark-dreams ' , ' dark-dreams ' ], [ ' no-license-to-be-human ' , ' no-human-licens ' ], [ ' are-ufos-aliens ' , ' are-ufos-aliens ' ], [ ' you-provably-cant-trust-yourself ' , ' no-self-trust ' ], [ ' caplan-gums-bullet ' , ' caplan-gums-bul ' ], [ ' dumb-deplaning ' , ' dumb-deplaning ' ], [ ' mundane-dishonesty ' , ' mundane-dishone ' ], [ ' the-cartoon-guide-to-lbs-theorem ' , ' lobs-theorem ' ], [ ' bias-in-real-life-a-personal-story ' , ' bias-in-real-li ' ], [ ' when-anthropomorphism-became-stupid ' , ' when-anthropomo ' ], [ ' hot-air-doesnt-disagree ' , ' hot-air-doesnt ' ], [ ' the-baby-eating-aliens-13 ' , ' baby-eaters ' ], [ ' manipulators-as-mirrors ' , ' manipulators-as ' ], [ ' the-bedrock-of-morality-arbitrary ' , ' arbitrary-bedro ' ], [ ' is-fairness-arbitrary ' , ' arbitrarily-fai ' ], [ ' self-indication-solves-time-asymmetry ' , ' self-indication ' ], [ ' schelling-and-the-nuclear-taboo ' , ' schelling-and-t ' ], [ ' arbitrary ' , ' unjustified ' ], [ ' new-best-game-theory ' , ' new-best-game-t ' ], [ ' abstracted-idealized-dynamics ' , ' computations ' ], [ ' future-altruism-not ' , ' future-altruism ' ], [ ' moral-error-and-moral-disagreement ' , ' moral-disagreem ' ], [ ' doctor-there-are-two-kinds-of-no-evidence ' , ' doctor-there-ar ' ], [ ' suspiciously-vague-lhc-forecasts ' , ' suspiciously-va ' ], [ ' sorting-pebbles-into-correct-heaps ' , ' pebblesorting-p ' ], [ ' the-problem-at-the-heart-of-pascals-wager ' , ' the-problem-at ' ], [ ' inseparably-right-or-joy-in-the-merely-good ' , ' rightness-redux ' ], [ ' baxters-ifloodi ' , ' baxters-flood ' ], [ ' morality-as-fixed-computation ' , ' morality-as-fix ' ], [ ' our-comet-ancestors ' , ' our-comet-ances ' ], [ ' hiroshima-day ' , ' hiroshima-day ' ], [ ' the-robots-rebellion ' , ' the-robots-rebe ' ], [ ' ignore-prostate-cancer ' , ' ignore-cancer ' ], [ ' contaminated-by-optimism ' , ' contaminated-by ' ], [ ' anthropology-patrons ' , ' anthropology-pa ' ], [ ' anthropomorphic-optimism ' , ' anthropomorph-1 ' ], [ ' now-im-scared ' , ' now-im-scared ' ], [ ' incomplete-analysis ' , ' incomplete-anal ' ], [ ' no-logical-positivist-i ' , ' no-logical-posi ' ], [ ' bias-against-some-types-of-foreign-wives ' , ' bias-against-so ' ], [ ' where-does-pascals-wager-fail ' , ' where-does-pasc ' ], [ ' the-comedy-of-behaviorism ' , ' behaviorism ' ], [ ' anthropomorphism-as-formal-fallacy ' , ' anthropomorphic ' ], [ ' variance-induced-test-bias ' , ' variance-induce ' ], [ ' a-genius-for-destruction ' , ' destructive-gen ' ], [ ' open-thread ' , ' open-thread ' ], [ ' the-magnitude-of-his-own-folly ' , ' it-was-pretty-b ' ], [ ' the-hope-premium ' , ' the-hope-premiu ' ], [ ' dangerous-species-warnings ' , ' species-protect ' ], [ ' friedmans-prediction-vs-explanation ' , ' friedmans-predi ' ], [ ' above-average-ai-scientists ' , ' above-average-s ' ], [ ' competent-elites ' , ' stratified-by-c ' ], [ ' bank-politics-is-not-about-bank-policy ' , ' bank-politics-i ' ], [ ' the-level-above-mine ' , ' level-above ' ], [ ' doable-green ' , ' saveable-nature ' ], [ ' give-it-to-me-straight-i-swear-i-wont-be-mad ' , ' give-it-to-me-s ' ], [ ' my-naturalistic-awakening ' , ' naturalistic-aw ' ], [ ' pundits-as-moles ' , ' pundits-as-mole ' ], [ ' fighting-a-rearguard-action-against-the-truth ' , ' fighting-a-rear ' ], [ ' white-swans-painted-black ' , ' white-swans-p-1 ' ], [ ' correcting-biases-once-youve-identified-them ' , ' correcting-bias ' ], [ ' that-tiny-note-of-discord ' , ' tiny-note-of-di ' ], [ ' noble-lies ' , ' noble-lies ' ], [ ' horrible-lhc-inconsistency ' , ' horrible-lhc-in ' ], [ ' certainty-effects-and-credit-default-swaps ' , ' certainty-effec ' ], [ ' politics-isnt-about-policy ' , ' politics-isnt-a ' ], [ ' how-many-lhc-failures-is-too-many ' , ' how-many-lhc-fa ' ], [ ' ban-the-bear ' , ' ban-the-bear ' ], [ ' say-it-loud ' , ' say-it-loud ' ], [ ' bad-news-ban-is-very-bad-news ' , ' bad-news-ban-is ' ], [ ' overconfidence-is-stylish ' , ' overconfidence ' ], [ ' the-sheer-folly-of-callow-youth ' , ' youth-folly ' ], [ ' isshoukenmei ' , ' isshoukenmei ' ], [ ' who-to-blame ' , ' who-to-blame ' ], [ ' a-prodigy-of-refutation ' , ' refutation-prod ' ], [ ' money-is-serious ' , ' money-frames ' ], [ ' raised-in-technophilia ' , ' raised-in-sf ' ], [ ' pharmaceutical-freedom-for-those-who-have-overcome-many-of-their-biases ' , ' pharmaceutical ' ], [ ' deafening-silence ' , ' deafening-silen ' ], [ ' my-best-and-worst-mistake ' , ' my-best-and-wor ' ], [ ' noble-abstention ' , ' noble-abstentio ' ], [ ' my-childhood-death-spiral ' , ' childhood-spira ' ], [ ' maturity-bias ' , ' maturity-bias ' ], [ ' serious-music ' , ' serious-music ' ], [ ' optimization ' , ' optimization ' ], [ ' beware-high-standards ' , ' beware-high-sta ' ], [ ' lemon-glazing-fallacy ' , ' lemon-glazing-f ' ], [ ' psychic-powers ' , ' psychic-powers ' ], [ ' immodest-caplan ' , ' immodest-caplan ' ], [ ' excluding-the-supernatural ' , ' excluding-the-s ' ], [ ' intelligent-design-honesty ' , ' intelligent-des ' ], [ ' rationality-quotes-17 ' , ' quotes-17 ' ], [ ' election-review-articles ' , ' election-review ' ], [ ' points-of-departure ' , ' points-of-depar ' ], [ ' guiltless-victims ' , ' guiltless-victi ' ], [ ' singularity-summit-2008 ' , ' singularity-sum ' ], [ ' spinspotter ' , ' spinspotter ' ], [ ' anyone-who-thinks-the-large-hadron-collider-will-destroy-the-world-is-a-tt ' , ' anyone-who-thin ' ], [ ' is-carbon-lost-cause ' , ' carbon-is-lost ' ], [ ' rationality-quotes-16 ' , ' quotes-16 ' ], [ ' aaronson-on-singularity ' , ' aaronson-on-sin ' ], [ ' rationality-quotes-15 ' , ' quotes-15 ' ], [ ' hating-economists ' , ' hating-economis ' ], [ ' rationality-quotes-14 ' , ' quotes-14 ' ], [ ' disagreement-is-disrespect ' , ' disagreement-is ' ], [ ' the-truly-iterated-prisoners-dilemma ' , ' iterated-tpd ' ], [ ' aping-insight ' , ' aping-insight ' ], [ ' the-true-prisoners-dilemma ' , ' true-pd ' ], [ ' mirrored-lives ' , ' mirrored-lives ' ], [ ' rationality-quotes-13 ' , ' rationality-quo ' ], [ ' risk-is-physical ' , ' risk-is-physica ' ], [ ' rationality-quotes-12 ' , ' rationality-q-1 ' ], [ ' open-thread ' , ' open-thread ' ], [ ' mundane-magic ' , ' mundane-magic ' ], [ ' fhi-emulation-roadmap-out ' , ' fhi-emulation-r ' ], [ ' porn-vs-romance-novels ' , ' porn-vs-romance ' ], [ ' intelligence-in-economics ' , ' intelligence-in ' ], [ ' does-intelligence-float ' , ' does-intelligen ' ], [ ' economic-definition-of-intelligence ' , ' economic-defini ' ], [ ' anti-edgy ' , ' anti-edgy ' ], [ ' efficient-cross-domain-optimization ' , ' efficient-cross ' ], [ ' wanting-to-want ' , ' wanting-to-want ' ], [ ' measuring-optimization-power ' , ' measuring-optim ' ], [ ' transparent-characters ' , ' transparent-cha ' ], [ ' aiming-at-the-target ' , ' aiming-at-the-t ' ], [ ' trust-us ' , ' trust-us ' ], [ ' quotes-from-singularity-summit-2008 ' , ' summit-quotes ' ], [ ' belief-in-intelligence ' , ' belief-in-intel ' ], [ ' expected-creative-surprises ' , ' expected-creati ' ], [ ' trust-but-dont-verify ' , ' trust-but-dont ' ], [ ' san-jose-meetup-sat-1025-730pm ' , ' san-jose-meetup ' ], [ ' inner-goodness ' , ' inner-morality ' ], [ ' obama-donors-as-news ' , ' donations-as-ne ' ], [ ' which-parts-are-me ' , ' which-parts-am ' ], [ ' if-you-snooze-you-lose ' , ' if-you-snooze-y ' ], [ ' ethics-notes ' , ' ethics-notes ' ], [ ' howard-stern-on-voter-rationalization ' , ' howard-stern-on ' ], [ ' prices-or-bindings ' , ' infinite-price ' ], [ ' toilets-arent-about-not-dying-of-disease ' , ' toilets-arent-a ' ], [ ' ethical-injunctions ' , ' ethical-injunct ' ], [ ' informed-voters-choose-worse ' , ' informed-voters ' ], [ ' ethical-inhibitions ' , ' ethical-inhibit ' ], [ ' protected-from-myself ' , ' protected-from ' ], [ ' last-post-requests ' , ' last-post-reque ' ], [ ' dark-side-epistemology ' , ' the-dark-side ' ], [ ' preventive-health-care ' , ' preventive-heal ' ], [ ' traditional-capitalist-values ' , ' traditional-cap ' ], [ ' us-help-red-china-revolt ' , ' us-aid-chinese ' ], [ ' entangled-truths-contagious-lies ' , ' lies-contagious ' ], [ ' conspiracys-uncanny-valley ' , ' conspiracys-unc ' ], [ ' ends-dont-justify-means-among-humans ' , ' ends-dont-justi ' ], [ ' why-voter-drives ' , ' why-voter-drive ' ], [ ' election-gambling-history ' , ' election-gambli ' ], [ ' why-does-power-corrupt ' , ' power-corrupts ' ], [ ' big-daddy-isnt-saving-you ' , ' big-daddy-isnt ' ], [ ' behold-our-ancestors ' , ' behold-our-ance ' ], [ ' rationality-quotes-19 ' , ' quotes-19 ' ], [ ' grateful-for-bad-news ' , ' grateful-for-ba ' ], [ ' the-ritual ' , ' the-question ' ], [ ' crisis-of-faith ' , ' got-crisis ' ], [ ' the-wire ' , ' the-wire ' ], [ ' ais-and-gatekeepers-unite ' , ' ais-and-gatekee ' ], [ ' bad-faith-voter-drives ' , ' weathersons-bad ' ], [ ' shut-up-and-do-the-impossible ' , ' shut-up-and-do ' ], [ ' academics-in-clown-suits ' , ' academics-in-cl ' ], [ ' gullibility-and-control ' , ' guilibility-and ' ], [ ' terror-politics-isnt-about-policy ' , ' terror-politics ' ], [ ' make-an-extraordinary-effort ' , ' isshokenmei ' ], [ ' more-deafening-silence ' , ' more-deafening ' ], [ ' on-doing-the-impossible ' , ' try-persevere ' ], [ ' bay-area-meetup-for-singularity-summit ' , ' bay-area-meetup ' ], [ ' insincere-cheers ' , ' football-lesson ' ], [ ' my-bayesian-enlightenment ' , ' my-bayesian-enl ' ], [ ' political-harassment ' , ' political-haras ' ], [ ' beyond-the-reach-of-god ' , ' beyond-god ' ], [ ' rationality-quotes-18 ' , ' rationality-quo ' ], [ ' equally-shallow-genders ' , ' equallly-shallo ' ], [ ' open-thread ' , ' open-thread ' ], [ ' political-parties-are-not-about-policy ' , ' political-parti ' ], [ ' use-the-try-harder-luke ' , ' use-the-try-har ' ], [ ' no-rose-colored-dating-glasses ' , ' no-rose-colored ' ], [ ' trying-to-try ' , ' trying-to-try ' ], [ ' intrade-and-the-dow-drop ' , ' intrade-and-the ' ], [ ' awww-a-zebra ' , ' awww-a-zebra ' ], [ ' singletons-rule-ok ' , ' singletons-rule ' ], [ ' total-tech-wars ' , ' total-tech-wars ' ], [ ' chaotic-inversion ' , ' chaotic-inversi ' ], [ ' luck-pessimism ' , ' luck-pessimism ' ], [ ' thanksgiving-prayer ' , ' thanksgiving-pr ' ], [ ' dreams-of-autarky ' , ' dreams-of-autar ' ], [ ' modern-depressions ' , ' modern-depressi ' ], [ ' total-nano-domination ' , ' nanotech-asplod ' ], [ ' beliefs-require-reasons-or-is-the-pope-catholic-should-he-be ' , ' beliefs-require ' ], [ ' engelbart-insufficiently-recursive ' , ' mouse-no-go-foo ' ], [ ' abstractdistant-future-bias ' , ' abstractdistant ' ], [ ' the-complete-idiots-guide-to-ad-hominem ' , ' the-complete-id ' ], [ ' physicists-held-to-lower-standard ' , ' physicists-held ' ], [ ' thinking-helps ' , ' thinking-helps ' ], [ ' recursion-magic ' , ' recursion-magic ' ], [ ' when-life-is-cheap-death-is-cheap ' , ' when-life-is-ch ' ], [ ' polisci-stats-biased ' , ' polisci-journal ' ], [ ' cascades-cycles-insight ' , ' cascades-cycles ' ], [ ' evicting-brain-emulations ' , ' suppose-that-ro ' ], [ ' are-you-dreaming ' , ' are-you-dreamin ' ], [ ' surprised-by-brains ' , ' brains ' ], [ ' the-second-swan ' , ' swan-2 ' ], [ ' billion-dollar-bots ' , ' billion-dollar ' ], [ ' brain-emulation-and-hard-takeoff ' , ' brain-emulation ' ], [ ' emulations-go-foom ' , ' emulations-go-f ' ], [ ' lifes-story-continues ' , ' the-age-of-nonr ' ], [ ' observing-optimization ' , ' observing-optim ' ], [ ' ai-go-foom ' , ' ai-go-foom ' ], [ ' whence-your-abstractions ' , ' abstractions-re ' ], [ ' abstraction-not-analogy ' , ' abstraction-vs ' ], [ ' the-first-world-takeover ' , ' 1st-world-takeo ' ], [ ' setting-the-stage ' , ' setting-the-sta ' ], [ ' cheap-wine-tastes-fine ' , ' cheap-wine-tast ' ], [ ' animal-experimentation-morally-acceptable-or-just-the-way-things-always-have-been ' , ' animal-experime ' ], [ ' the-weak-inside-view ' , ' the-weak-inside ' ], [ ' convenient-overconfidence ' , ' convenient-over ' ], [ ' loud-subtext ' , ' loud-subtext ' ], [ ' failure-by-affective-analogy ' , ' affective-analo ' ], [ ' failure-by-analogy ' , ' failure-by-anal ' ], [ ' whither-ob ' , ' whither-ob ' ], [ ' all-are-skill-unaware ' , ' all-are-unaware ' ], [ ' logical-or-connectionist-ai ' , ' logical-or-conn ' ], [ ' friendliness-factors ' , ' friendliness-fa ' ], [ ' boston-area-meetup-111808-9pm-mitcambridge ' , ' boston-area-mee ' ], [ ' positive-vs-optimal ' , ' positive-vs-opt ' ], [ ' friendly-teams ' , ' englebart-not-r ' ], [ ' the-nature-of-logic ' , ' first-order-log ' ], [ ' diamond-palace-survive ' , ' whether-diamond ' ], [ ' selling-nonapples ' , ' selling-nonappl ' ], [ ' engelbart-as-ubertool ' , ' engelbarts-uber ' ], [ ' bay-area-meetup-1117-8pm-menlo-park ' , ' bay-area-meetup ' ], [ ' the-weighted-majority-algorithm ' , ' the-weighted-ma ' ], [ ' fund-ubertool ' , ' fund-ubertool ' ], [ ' worse-than-random ' , ' worse-than-rand ' ], [ ' conformity-shows-loyalty ' , ' conformity-show ' ], [ ' incompetence-vs-self-interest ' , ' incompetence-vs ' ], [ ' lawful-uncertainty ' , ' lawful-uncertai ' ], [ ' what-belief-conformity ' , ' what-conformity ' ], [ ' ask-ob-leaving-the-fold ' , ' leaving-the-fol ' ], [ ' depressed-inoti-more-accurate ' , ' depressed-not-m ' ], [ ' lawful-creativity ' , ' lawful-creativi ' ], [ ' visionary-news ' , ' visionary-news ' ], [ ' recognizing-intelligence ' , ' recognizing-int ' ], [ ' equal-cheats ' , ' equal-cheats ' ], [ ' back-up-and-ask-whether-not-why ' , ' back-up-and-ask ' ], [ ' beware-i-believe ' , ' beware-i-believ ' ], [ ' hanging-out-my-speakers-shingle ' , ' now-speaking ' ], [ ' disagreement-debate-status ' , ' disagreement-de ' ], [ ' beware-the-prescient ' , ' beware-the-pres ' ], [ ' todays-inspirational-tale ' , ' todays-inspirat ' ], [ ' the-evil-pleasure ' , ' evil-diversity ' ], [ ' complexity-and-intelligence ' , ' complexity-and ' ], [ ' building-something-smarter ' , ' building-someth ' ], [ ' open-thread ' , ' open-thread ' ], [ ' bhtv-jaron-lanier-and-yudkowsky ' , ' jaron-lanier-an ' ], [ ' a-new-day ' , ' a-new-day ' ], [ ' against-interesting-details ' , ' against-interesting-presentations ' ], [ ' dunbars-function ' , ' dunbars-function ' ], [ ' amputation-of-destiny ' , ' theft-of-destiny ' ], [ ' the-meta-human-condition ' , ' the-metahuman-condition ' ], [ ' it-is-simply-no-longer-possible-to-believe ' , ' it-is-simply-no-longer-possible-to-believe ' ], [ ' friendship-is-relative ' , ' friendship-is-relative ' ], [ ' cant-unbirth-a-child ' , ' no-unbirthing ' ], [ ' nonsentient-bloggers ' , ' nonsentient-bloggers ' ], [ ' nonsentient-optimizers ' , ' unpersons ' ], [ ' nonperson-predicates ' , ' model-citizens ' ], [ ' alien-bad-guy-bias ' , ' alien-bad-guy-bias ' ], [ ' devils-offers ' , ' devils-offers ' ], [ ' harmful-options ' , ' harmful-options ' ], -[ ' the-longshot-bias ' , ' the-longshot-bias- ' ], +[ ' the-longshot-bias ' , ' the-longshot-bias ' ], [ ' imaginary-positions ' , ' imaginary-positions ' ], [ ' coherent-futures ' , ' coherent-futures ' ], [ ' rationality-quotes-20 ' , ' quotes-20 ' ], [ ' no-overconfidence ' , ' no-overconfidence ' ], [ ' show-off-bias ' , ' showoff-bias ' ], [ ' living-by-your-own-strength ' , ' by-your-own-strength ' ], [ ' sensual-experience ' , ' sensual-experience ' ], [ ' presuming-bets-are-bad ' , ' presuming-bets-are-bad ' ], [ ' futarchy-is-nyt-buzzword-of-08 ' , ' futarchy-is-nyt-buzzword-of-08 ' ], [ ' experts-are-for-certainty ' , ' experts-are-for-certainty ' ], [ ' complex-novelty ' , ' complex-novelty ' ], [ ' high-challenge ' , ' high-challenge ' ], [ ' weak-social-theories ' , ' weak-social-theories ' ], [ ' christmas-signaling ' , ' christmas-signaling ' ], [ ' prolegomena-to-a-theory-of-fun ' , ' fun-theory ' ], [ ' the-right-thing ' , ' the-right-thing ' ], [ ' who-cheers-the-referee ' , ' who-cheers-the-referee ' ], [ ' visualizing-eutopia ' , ' visualizing-eutopia ' ], [ ' ill-think-of-a-reason-later ' , ' ill-think-of-a-reason-later ' ], [ ' utopia-unimaginable ' , ' utopia-vs-eutopia ' ], [ ' tyler-on-cryonics ' , ' tyler-on-cryonics ' ], [ ' not-taking-over-the-world ' , ' not-taking-over ' ], [ ' entrepreneurs-are-not-overconfident ' , ' entrepreneurs-are-not-overconfident ' ], [ ' distrusting-drama ' , ' types-of-distru ' ], [ ' for-the-people-who-are-still-alive ' , ' who-are-still-alive ' ], [ ' trade-with-the-future ' , ' trade-with-the-future ' ], [ ' bhtv-de-grey-and-yudkowsky ' , ' bhtv-de-grey-and-yudkowsky ' ], [ ' hated-because-it-might-work ' , ' hated-because-it-might-work ' ], [ ' cryonics-is-cool ' , ' cryonics-is-cool ' ], [ ' you-only-live-twice ' , ' you-only-live-twice ' ], [ ' we-agree-get-froze ' , ' we-agree-get-froze ' ], [ ' what-i-think-if-not-why ' , ' what-i-think ' ], [ ' what-core-argument ' , ' what-core-argument ' ], [ ' a-vision-of-precision ' , ' a-vision-of-pre ' ], [ ' the-linear-scaling-error ' , ' the-linear-scal ' ], [ ' the-mechanics-of-disagreement ' , ' the-mechanics-o ' ], [ ' two-visions-of-heritage ' , ' two-visions-of ' ], [ ' bay-area-meetup-wed-1210-8pm ' , ' bay-area-meetup ' ], [ ' are-ais-homo-economicus ' , ' are-ais-homo-ec ' ], [ ' disjunctions-antipredictions-etc ' , ' disjunctions-an ' ], [ ' the-bad-guy-bias ' , ' the-bad-guy-bia ' ], [ ' true-sources-of-disagreement ' , ' true-sources-of ' ], [ ' us-tv-censorship ' , ' us-tv-censorshi ' ], [ ' wrapping-up ' , ' wrapping-up ' ], [ ' artificial-mysterious-intelligence ' , ' artificial-myst ' ], [ ' incommunicable-meta-insight ' , ' incommunicable ' ], [ ' false-false-dichotomies ' , ' false-false-dic ' ], [ ' shared-ai-wins ' , ' shared-ai-wins ' ], [ ' is-that-your-true-rejection ' , ' your-true-rejec ' ], [ ' friendly-projects-vs-products ' , ' friendly-projec ' ], [ ' sustained-strong-recursion ' , ' sustained-recur ' ], [ ' recursive-mind-designers ' , ' recursive-mind ' ], [ ' evolved-desires ' , ' evolved-desires ' ], [ ' gas-arbitrage ' , ' gas-artibrage ' ], [ ' -eternal-inflation-and-the-probability-that-you-are-living-in-a-computer-simulation ' , ' eternal-inflati ' ], [ ' drexler-blogs ' , ' drexler-blogs ' ], [ ' beware-hockey-stick-plans ' , ' beware-hockey-s ' ], [ ' underconstrained-abstractions ' , ' underconstraine ' ], [ ' rationality-of-voting-etc ' , ' rationality-of ' ], [ ' permitted-possibilities-locality ' , ' permitted-possi ' ], [ ' the-hypocrisy-charge-bias ' , ' the-hypocrisy-c ' ], [ ' test-near-apply-far ' , ' test-near-apply ' ], [ ' hard-takeoff ' , ' hard-takeoff ' ], [ ' voting-kills ' , ' voting-kills ' ], [ ' whither-manufacturing ' , ' whither-manufac ' ], [ ' recursive-self-improvement ' , ' recursive-self ' ], [ ' open-thread ' , ' open-thread ' ], [ ' i-heart-cyc ' , ' i-heart-cyc ' ], [ ' disappointment-in-the-future ' , ' disappointment ' ], [ ' stuck-in-throat ' , ' stuck-in-throat ' ], [ ' war-andor-peace-28 ' , ' war-andor-peace ' ], [ ' the-baby-eating-aliens-18 ' , ' the-babyeating-aliens ' ], [ ' three-worlds-collide-08 ' , ' three-worlds-collide ' ], [ ' dreams-as-evidence ' , ' dreams-as-evidence ' ], [ ' institution-design-is-like-martial-arts ' , ' why-market-economics-is-like-martial-arts ' ], [ ' academic-ideals ' , ' academic-ideals ' ], [ ' value-is-fragile ' , ' fragile-value ' ], [ ' roberts-bias-therapy ' , ' roberts-bias-therapy ' ], [ ' rationality-quotes-25 ' , ' quotes-25 ' ], [ ' different-meanings-of-bayesian-statistics ' , ' different-meanings-of-bayesian-statistics ' ], [ ' ob-status-update ' , ' ob-status-update ' ], [ ' 31-laws-of-fun ' , ' fun-theory-laws ' ], [ ' bhtv-yudkowsky-wilkinson ' , ' bhtv-yudkowsky-wilkinson ' ], [ ' the-fun-theory-sequence ' , ' fun-theory-sequence ' ], [ ' avoid-vena-cava-filters ' , ' avoid-vena-cava-filters ' ], [ ' rationality-quotes-24 ' , ' quotes-24 ' ], [ ' higher-purpose ' , ' higher-purpose ' ], [ ' investing-for-the-long-slump ' , ' the-long-slump ' ], [ ' tribal-biases-and-the-inauguration ' , ' tribal-biases-and-the-inauguration ' ], [ ' who-likes-what-movies ' , ' who-likes-what-movies ' ], [ ' failed-utopia-4-2 ' , ' failed-utopia-42 ' ], [ ' sunnyvale-meetup-saturday ' , ' bay-area-meetup-saturday ' ], [ ' set-obamas-bar ' , ' set-obamas-bar ' ], [ ' interpersonal-entanglement ' , ' no-catgirls ' ], [ ' predictible-fakers ' , ' predictible-fakers ' ], [ ' sympathetic-minds ' , ' sympathetic-minds ' ], [ ' the-surprising-power-of-rote-cognition ' , ' the-surprising-power-of-rote-cognition ' ], [ ' in-praise-of-boredom ' , ' boredom ' ], [ ' beware-detached-detail ' , ' beware-detached-detail ' ], [ ' getting-nearer ' , ' getting-nearer ' ], [ ' a-tale-of-two-tradeoffs ' , ' a-tale-of-two-tradeoffs ' ], [ ' seduced-by-imagination ' , ' souleating-dreams ' ], [ ' data-on-fictional-lies ' , ' new-data-on-fiction ' ], [ ' justified-expectation-of-pleasant-surprises ' , ' vague-hopes ' ], [ ' disagreement-is-near-far-bias ' , ' disagreement-is-nearfar-bias ' ], [ ' ishei-has-joined-the-conspiracy ' , ' kimiko ' ], [ ' building-weirdtopia ' , ' weirdtopia ' ], [ ' eutopia-is-scary ' , ' scary-eutopia ' ], [ ' bad-news-predictor-jailed ' , ' korean-bad-news-predictor-jailed ' ], [ ' continuous-improvement ' , ' better-and-better ' ], [ ' why-we-like-middle-options-small-menus ' , ' why-we-like-middle-options-small-menus ' ], [ ' rationality-quotes-23 ' , ' quotes-23 ' ], [ ' serious-stories ' , ' serious-stories ' ], [ ' the-metaethics-sequence ' , ' metaethics ' ], [ ' why-love-is-vague ' , ' why-love-is-vague ' ], [ ' rationality-quotes-22 ' , ' quotes-22 ' ], [ ' free-docs-not-help-poor-kids ' , ' free-medicine-no-help-for-ghanaian-kids ' ], [ ' emotional-involvement ' , ' emotional-involvement ' ], [ ' why-fiction-lies ' , ' why-fiction-lies ' ], [ ' rationality-quotes-21 ' , ' quotes-21 ' ], [ ' changing-emotions ' , ' changing-emotions ' ], [ ' growing-up-is-hard ' , ' growing-up-is-hard ' ], [ ' a-world-without-lies ' , ' a-world-without-lies ' ], [ ' the-uses-of-fun-theory ' , ' the-uses-of-fun-theory ' ], [ ' open-thread ' , ' open-thread ' ], [ ' disagreeing-about-idoubti ' , ' doubt-survey ' ], [ ' free-to-optimize ' , ' free-to-optimize ' ], [ ' moral-uncertainty---towards-a-solution ' , ' moral-uncertainty-towards-a-solution ' ], [ ' the-most-frequently-useful-thing ' , ' most-frequently-useful ' ], [ ' the-most-important-thing-you-learned ' , ' the-most-important-thing ' ], [ ' avoid-identifying-with-anything ' , ' avoid-identifying-with-anything ' ], [ ' self-experimentation-and-placebo-testing ' , ' selfexperimentation-and-placebo-testing ' ], [ ' tell-your-rationalist-origin-story-at-less-wrong ' , ' rationalist-origins-at-lw ' ], [ ' what-is-gossip-for ' , ' gossip-is-for-status ' ], [ ' markets-are-anti-inductive ' , ' markets-are-antiinductive ' ], [ ' libel-slander-blackmail ' , ' libel-slander-blackmail ' ], [ ' formative-youth ' , ' formative-youth ' ], [ ' what-do-schools-sell ' , ' what-do-schools-sell ' ], [ ' on-not-having-an-advance-abyssal-plan ' , ' on-not-having-a-plan ' ], [ ' who-are-macro-experts ' , ' who-are-macro-experts ' ], [ ' what-is-medical-quality ' , ' what-is-medical-quality ' ], [ ' fairness-vs-goodness ' , ' fairness-vs-goodness ' ], [ ' rationality-quotes-27 ' , ' quotes-27 ' ], [ ' write-your-hypothetical-apostasy ' , ' write-your-hypothetical-apostasy ' ], [ ' wise-pretensions-v0 ' , ' wise-pretensions-v0 ' ], [ ' pretending-to-be-wise ' , ' pretending-to-be-wise ' ], [ ' spotty-deference ' , ' spotty-deference ' ], [ ' the-intervention-and-the-checklist-two-paradigms-for-improvement ' , ' the-intervention-and-the-checklist-two-paradigms-for-improvement ' ], [ ' against-maturity ' , ' against-maturity ' ], [ ' good-idealistic-books-are-rare ' , ' good-idealistic-books ' ], [ ' seeking-a-cynics-library ' , ' seeking-a-cynics-library ' ], [ ' cynical-about-cynicism ' , ' cynical-about-cynicism ' ], [ ' beware-value-talk ' , ' the-cost-of-talking-values ' ], [ ' the-ethic-of-hand-washing-and-community-epistemic-practice ' , ' accuracyimproving-communities-and-the-ethics-of-handwashing ' ], [ ' an-african-folktale ' , ' an-african-folktale ' ], [ ' rationality-quotes-26 ' , ' quotes-26 ' ], [ ' an-especially-elegant-evpsych-experiment ' , ' elegant-evpsych ' ], [ ' the-evolutionary-cognitive-boundary ' , ' the-evolutionarycognitive-boundary ' ], [ ' beware-ideal-screen-theories ' , ' beware-ideal-screen-theories ' ], [ ' signaling-math ' , ' signaling-math ' ], [ ' cynicism-in-ev-psych-and-econ ' , ' cynicism-in-evpsych-and-econ ' ], [ ' informers-and-persuaders ' , ' informers-and-persuaders ' ], -[ ' against-propaganda ' , ' against-propaganda- ' ], +[ ' against-propaganda ' , ' against-propaganda ' ], [ ' moral-truth-in-fiction ' , ' truth-from-fiction ' ], [ ' ask-ob-how-can-i-measure-rationality ' , ' testing-rationality ' ], [ ' and-say-no-more-of-it ' , ' and-say-no-more-of-it ' ], [ ' different-meanings-of-bayesian-statistics-another-try ' , ' different-meanings-of-bayesian-statistics-another-try ' ], [ ' the-thing-that-i-protect ' , ' the-thing-that-i-protect ' ], [ ' our-biggest-surprise ' , ' our-biggest-surprise ' ], [ ' epilogue-atonement-88 ' , ' atonement ' ], [ ' share-likelihood-ratios-not-posterior-beliefs ' , ' share-likelihood-ratios-not-posterior-beliefs ' ], [ ' true-ending-sacrificial-fire-78 ' , ' sacrificial-fire ' ], [ ' conscious-control ' , ' is-consciousness-in-charge ' ], [ ' normal-ending-last-tears-68 ' , ' last-tears ' ], -[ ' lying-stimuli ' , ' lying-stimuli- ' ], +[ ' lying-stimuli ' , ' lying-stimuli ' ], [ ' three-worlds-decide-58 ' , ' three-worlds-decide ' ], [ ' thoughtful-music ' , ' thoughtful-music ' ], [ ' interlude-with-the-confessor-48 ' , ' interlude-with-the-confessor ' ], [ ' open-thread ' , ' open-thread ' ], [ ' the-super-happy-people-38 ' , ' super-happy-people ' ], [ ' echo-chamber-confidence ' , ' echo-chamber-confidence ' ], [ ' minchins-mistake ' , ' at-less-wrong-vladimir-nesov-approvingly-cites-tim-minchins-poem-storm-vid-here-text-here-it-is-an-entertaining-passiona ' ], [ ' new-tech-signals ' , ' new-tech-signals ' ], [ ' toddlers-avoid-dissenters ' , ' toddlers-avoid-dissenter-opinions ' ], [ ' the-pascals-wager-fallacy-fallacy ' , ' pascals-wager-metafallacy ' ], [ ' break-cryonics-down ' , ' break-cryonics-down ' ], [ ' my-cryonics-hour ' , ' my-cryonics-hour ' ], [ ' my-bhtv-with-tyler-cowen ' , ' my-bhtv-with-tyler-cowen ' ], [ ' yes-tax-lax-ideas ' , ' yes-tax-ideas ' ], [ ' trusting-sponsored-medical-research ' , ' trusting-sponsored-medical-research ' ], [ ' kids-rights ' , ' kids-rights ' ], [ ' status-prudes ' , ' status-prudes ' ], [ ' more-getting-froze ' , ' more-getting-froze ' ], [ ' wishful-dreaming ' , ' wishful-dreaming ' ], [ ' who-likes-band-music ' , ' who-likes-band-music ' ], [ ' loving-cranks-to-death ' , ' loving-cranks-to-death ' ], [ ' distinguishing-academics-prestige-and-altruism-motivations ' , ' distinguishing-academics-prestige-and-altruism-motivations ' ], [ ' literally-voodoo-economics ' , ' literally-voodoo-economics ' ], [ ' as-ye-judge-those-who-fund-thee-ye-shall-be-judged ' , ' as-ye-judge-those-who-fund-thee-ye-shall-be-judged ' ], [ ' evaporated-cane-juice ' , ' evaporated-cane-juice ' ], [ ' be-sure-to-mind-when-you-change-your-mind ' , ' be-sure-to-mind-when-you-change-your-mind ' ], [ ' posting-now-enabled-on-less-wrong ' , ' posting-now-enabled-on-less-wrong ' ], [ ' lying-with-style ' , ' deceptive-writing-styles ' ], [ ' question-medical-findings ' , ' question-medical-findings ' ], [ ' six-months-later ' , ' six-months-later ' ], [ ' you-get-more-than-you-select-for-but-not-always ' , ' you-get-more-than-you-select-for-but-not-always ' ], [ ' what-changed ' , ' what-changed ' ], [ ' status-affiliation-puzzles ' , ' status-affiliations ' ], [ ' ob-meetup-friday-13th-7pm-springfield-va ' , ' ob-meetup-friday-13th-7pm-springfield-va ' ], [ ' augustines-paradox-of-optimal-repentance ' , ' augustines-paradox ' ], [ ' open-thread ' , ' o ' ], [ ' near-far-like-drunk-darts ' , ' nearfar-like-drunk-darts ' ], [ ' open-thread ' , ' open-thread ' ] ] end
isiri/wordpress_import
02f6c79a2c225db73dcaeddff49f16fea9e65053
removed user updation
diff --git a/process_script.rb b/process_script.rb index 6cf7cac..485a8a9 100755 --- a/process_script.rb +++ b/process_script.rb @@ -1,39 +1,35 @@ require 'global_settings' require 'importer.rb' require 'splitter.rb' require 'image_parse.rb' require 'update_links.rb' require 'configure_wordpress.rb' require 'update_users.rb' puts "Starting import file split" dest_files = split($wordpress_export_filename, $split_file_path, $allowed_length) puts "Successfully split the files into #{dest_files.join(',')}" dest_files.each do |dest_file| puts "Starting import of #{dest_file}..." dest_path = File.join($split_file_path, dest_file) File.copy(dest_path, $wordpress_import_file) start_import puts "Finished importing the file #{dest_file}" end puts "Import process done." puts "Updating permalinks" update_permalinks puts "Done updating permalinks" puts "Processing images" process_images puts "Configuring wordpress" configure_wordpress -puts "Updating users" -update_users - -
isiri/wordpress_import
e423079e26a3434c09867933bbb708e5ec2f4e58
modified: global_settings_example.rb
diff --git a/global_settings_example.rb b/global_settings_example.rb index 9fb4ef0..d9873d0 100755 --- a/global_settings_example.rb +++ b/global_settings_example.rb @@ -1,58 +1,63 @@ #Rename this file to global_settings.rb and update the below configurations. #TODO: cleaning up some of the duplication #Global settings require 'rubygems' require 'activerecord' require 'logger' require 'open-uri' require 'pathname' require 'ftools' require 'mechanize' #absoulte paths $wordpress_root = '/var/www' $wordpress_installation_path = '/var/www/wordpress' $image_path = '/wp-contents/uploads' $wordpress_import_file = '/var/www/wordpress/wp-content/mt-export.txt' #relative paths $split_file_path = 'splitted_files' #file names $wordpress_export_filename = 'mt-export.txt' $split_filename = 'mt_export_txt_' # split files will be as mt_export_txt_0, mt_export_txt_1 etc. #urls $base_url = 'http://localhost/wordpress' $root_url = 'http://localhost' $site_root = '/wordpress/wp-content/uploads' #downloaded image store folder #others $allowed_length = 5000000 #size of individual files after splitting the export file. (splitting is done to avoid php memory limit error) $wordpress_username = 'admin' #wordpress blog admin username $wordpress_password = '' #wordpress blog admin password ActiveRecord::Base.establish_connection( :adapter => "", :database => "", :username => "", :password => "", :socket => '' ) class WpPost < ActiveRecord::Base set_primary_key 'ID' set_table_name "wp_posts" end +class WpUser < ActiveRecord::Base + set_primary_key 'ID' + set_table_name "wp_users" +end + #moneky patch to avoid timeout error module Net class BufferedIO def rbuf_fill #timeout(@read_timeout,ProtocolError) { @rbuf << @io.sysread(1024) #} end end end
isiri/wordpress_import
2cac096eb49ce434fc12e0bb4d2340877f3fc321
modified: update_users.rb
diff --git a/update_users.rb b/update_users.rb index 16d387e..ecde4e9 100755 --- a/update_users.rb +++ b/update_users.rb @@ -1,26 +1,26 @@ def update_users users = WpUser.find(:all, :conditions => "user_login != '' and user_login != 'admin'") agent = WWW::Mechanize.new page = agent.get("#{$base_url}/wp-login.php/") login_form = page.form('loginform') login_form.log = $wordpress_username login_form.pwd = $wordpress_password page = agent.submit(login_form) users.each do |user| page = agent.get("#{$base_url}/wp-admin/user-edit.php?user_id=#{user.id}") user_form = page.forms[0] if ((user_form.email == "" or user_form.email.nil?) and user_form.role == 'subscriber') user_form.role = 'author' - user_form.email = 'change@me.com' + user_form.email = 'change@no_domain.com' user_form.pass1 = 'change_this_password' user_form.pass2 = 'change_this_password' page = agent.submit(user_form) end end end
isiri/wordpress_import
87e8d1ac3739af376d5e9bea8b6466941f839539
updating users
diff --git a/process_script.rb b/process_script.rb index aeeecde..6cf7cac 100755 --- a/process_script.rb +++ b/process_script.rb @@ -1,36 +1,39 @@ require 'global_settings' require 'importer.rb' require 'splitter.rb' require 'image_parse.rb' require 'update_links.rb' require 'configure_wordpress.rb' +require 'update_users.rb' puts "Starting import file split" dest_files = split($wordpress_export_filename, $split_file_path, $allowed_length) puts "Successfully split the files into #{dest_files.join(',')}" dest_files.each do |dest_file| puts "Starting import of #{dest_file}..." dest_path = File.join($split_file_path, dest_file) File.copy(dest_path, $wordpress_import_file) start_import puts "Finished importing the file #{dest_file}" end puts "Import process done." puts "Updating permalinks" update_permalinks puts "Done updating permalinks" puts "Processing images" process_images puts "Configuring wordpress" configure_wordpress +puts "Updating users" +update_users diff --git a/update_users.rb b/update_users.rb new file mode 100755 index 0000000..16d387e --- /dev/null +++ b/update_users.rb @@ -0,0 +1,26 @@ +def update_users + users = WpUser.find(:all, :conditions => "user_login != '' and user_login != 'admin'") + + agent = WWW::Mechanize.new + page = agent.get("#{$base_url}/wp-login.php/") + + login_form = page.form('loginform') + login_form.log = $wordpress_username + login_form.pwd = $wordpress_password + + page = agent.submit(login_form) + + users.each do |user| + page = agent.get("#{$base_url}/wp-admin/user-edit.php?user_id=#{user.id}") + + user_form = page.forms[0] + if ((user_form.email == "" or user_form.email.nil?) and user_form.role == 'subscriber') + user_form.role = 'author' + user_form.email = 'change@me.com' + user_form.pass1 = 'change_this_password' + user_form.pass2 = 'change_this_password' + page = agent.submit(user_form) + end + + end +end
isiri/wordpress_import
7d554b050599a1b3bcabb7060ba6e01cbab8f71b
modified: global_settings_example.rb
diff --git a/global_settings_example.rb b/global_settings_example.rb index 5a2fbf3..9fb4ef0 100755 --- a/global_settings_example.rb +++ b/global_settings_example.rb @@ -1,56 +1,58 @@ +#Rename this file to global_settings.rb and update the below configurations. +#TODO: cleaning up some of the duplication + #Global settings require 'rubygems' require 'activerecord' require 'logger' require 'open-uri' require 'pathname' require 'ftools' require 'mechanize' #absoulte paths $wordpress_root = '/var/www' $wordpress_installation_path = '/var/www/wordpress' $image_path = '/wp-contents/uploads' $wordpress_import_file = '/var/www/wordpress/wp-content/mt-export.txt' #relative paths $split_file_path = 'splitted_files' #file names $wordpress_export_filename = 'mt-export.txt' $split_filename = 'mt_export_txt_' # split files will be as mt_export_txt_0, mt_export_txt_1 etc. #urls $base_url = 'http://localhost/wordpress' $root_url = 'http://localhost' -$site_root = '/wordpress/wp-content/uploads' +$site_root = '/wordpress/wp-content/uploads' #downloaded image store folder #others -$allowed_length = 5000000 #size of individual files after splitting the export file -$wordpress_username = 'admin' -$wordpress_password = 'moR#GOZ$Ea71' -#$wordpress_password = 'wX!txqPhzcDZ' for word_press2 db +$allowed_length = 5000000 #size of individual files after splitting the export file. (splitting is done to avoid php memory limit error) +$wordpress_username = 'admin' #wordpress blog admin username +$wordpress_password = '' #wordpress blog admin password ActiveRecord::Base.establish_connection( - :adapter => "mysql", - :database => "word_press2", - :username => "root", - :password => "isiri", - :socket => '/tmp/mysql.sock' + :adapter => "", + :database => "", + :username => "", + :password => "", + :socket => '' ) class WpPost < ActiveRecord::Base set_primary_key 'ID' set_table_name "wp_posts" end #moneky patch to avoid timeout error module Net class BufferedIO def rbuf_fill #timeout(@read_timeout,ProtocolError) { @rbuf << @io.sysread(1024) #} end end end
isiri/wordpress_import
33dfd61aa96e3f0c6d019fb922919b76aa773714
changes
diff --git a/image_parse.rb b/image_parse.rb index d81f482..132e698 100755 --- a/image_parse.rb +++ b/image_parse.rb @@ -1,30 +1,31 @@ def process_images all_posts = WpPost.find(:all) all_posts.each do |post| html_doc = Nokogiri::HTML(post.post_content) (html_doc/"img").each do |img| img_src = img.attributes['src'].to_s img_name = img_src.split('/').last img_str = '' + img_src = "#{$root_url}/#{img_src}" unless img_src.match(/http/) open(img_src.gsub(/ /,'%20')) { |f| img_str = f.read } - img_root = "/#{post.post_date.year}/#{post.post_date.month}" + img_root = "/#{post.post_date.year}/#{"%02d" % post.post_date.month}" dest_save_dir = "#{$wordpress_root}#{$site_root}/#{img_root}" FileUtils.mkdir_p dest_save_dir dest_save_image = "#{dest_save_dir}/#{img_name}" - dest_site_image = "#{$site_root}/#{img_root}/#{img_name}" + dest_site_image = "#{$site_root}#{img_root}/#{img_name}" File.open(dest_save_image, 'w') {|f| f.write(img_str) } img.attributes['src'].value = dest_site_image if img.parent.node_name == 'a' img.parent.attributes['href'].value = dest_site_image end post.post_content = html_doc.inner_html post.save end end end diff --git a/importer.rb b/importer.rb index a06171e..9e97fdd 100755 --- a/importer.rb +++ b/importer.rb @@ -1,32 +1,40 @@ def start_import agent = WWW::Mechanize.new page = agent.get("#{$base_url}/wp-login.php/") login_form = page.form('loginform') login_form.log = $wordpress_username login_form.pwd = $wordpress_password page = agent.submit(login_form) page = agent.get("#{$base_url}/wp-admin/admin.php?import=mt") import_form = page.forms[1] page = agent.submit(import_form) assign_users_form = page.forms[0] i = 0 page.search('li').each do |l| if l.parent.node_name == 'form' select_list = assign_users_form.send("userselect[#{i}]") select_list = l.search('strong').inner_html i += 1 end end page = agent.submit(assign_users_form) - - return true + + state = false + page.search('h3').each do |h3_tag| + if h3_tag.inner_text.match(/All done/) + puts ("State All Done") + state = true + end + end + + return state end
isiri/wordpress_import
9b21e49e2ebf3b82e30bcaa61f390dd17d62bb3e
changes
diff --git a/configure_wordpress.rb b/configure_wordpress.rb index 3334b7b..0d802b1 100755 --- a/configure_wordpress.rb +++ b/configure_wordpress.rb @@ -1,20 +1,17 @@ -require 'rubygems' -require 'mechanize' - def configure_wordpress agent = WWW::Mechanize.new - page = agent.get('http://localhost/wordpress/wp-login.php/') + page = agent.get("#{$base_url}/wp-login.php/") login_form = page.form('loginform') - login_form.log = 'admin' - login_form.pwd = 'dNdcCwtSg9VM' + login_form.log = $wordpress_username + login_form.pwd = $wordpress_password page = agent.submit(login_form) - page = agent.get('http://localhost/wordpress/wp-admin/options-permalink.php') + page = agent.get("#{$base_url}/wp-admin/options-permalink.php") permalink_form = page.forms.first permalink_form.permalink_structure = '/%year%/%monthnum%/%postname%.html' page = agent.submit(permalink_form) end diff --git a/global_settings.rb b/global_settings.rb new file mode 100755 index 0000000..238af84 --- /dev/null +++ b/global_settings.rb @@ -0,0 +1,54 @@ +#Global settings +require 'rubygems' +require 'activerecord' +require 'logger' +require 'open-uri' +require 'pathname' +require 'ftools' +require 'mechanize' + +#absoulte paths +$wordpress_root = '/var/www' +$wordpress_installation_path = '/var/www/wordpress' +$image_path = '/wp-contents/uploads' +$wordpress_import_file = '/var/www/wordpress/wp-content/mt-export.txt' + +#relative paths +$split_file_path = 'splitted_files' + +#file names +$wordpress_export_filename = 'mt-export.txt' +$split_filename = 'mt_export_txt_' # split files will be as mt_export_txt_0, mt_export_txt_1 etc. + +#urls +$base_url = 'http://localhost/wordpress' +$site_root = '/wordpress/wp-content/uploads' + +#others +$allowed_length = 1000000 #size of individual files after splitting the export file +$wordpress_username = 'admin' +$wordpress_password = 'CwGeOAqFfCRn' + +ActiveRecord::Base.establish_connection( + :adapter => "mysql", + :database => "word_press2", + :username => "root", + :password => "isiri", + :socket => '/tmp/mysql.sock' +) + +class WpPost < ActiveRecord::Base + set_primary_key 'ID' + set_table_name "wp_posts" +end + +#moneky patch to avoid timeout error +module Net + class BufferedIO + def rbuf_fill + #timeout(@read_timeout,ProtocolError) { + @rbuf << @io.sysread(1024) + #} + end + end +end diff --git a/image_parse.rb b/image_parse.rb index 74b2528..d81f482 100755 --- a/image_parse.rb +++ b/image_parse.rb @@ -1,51 +1,30 @@ -require 'rubygems' -require 'pathname' -require 'open-uri' -require 'nokogiri' -require 'activerecord' - -ActiveRecord::Base.establish_connection( - :adapter => "mysql", - :database => "word_press2", - :username => "root", - :password => "isiri", - :socket => '/tmp/mysql.sock' -) - -class WpPost < ActiveRecord::Base - set_primary_key 'ID' - set_table_name "wp_posts" -end - def process_images all_posts = WpPost.find(:all) - wordpress_root = '/var/www' - site_root = '/wordpress/wp-content/uploads' all_posts.each do |post| html_doc = Nokogiri::HTML(post.post_content) (html_doc/"img").each do |img| img_src = img.attributes['src'].to_s img_name = img_src.split('/').last img_str = '' open(img_src.gsub(/ /,'%20')) { |f| img_str = f.read } img_root = "/#{post.post_date.year}/#{post.post_date.month}" - dest_save_dir = "#{wordpress_root}#{site_root}/#{img_root}" + dest_save_dir = "#{$wordpress_root}#{$site_root}/#{img_root}" FileUtils.mkdir_p dest_save_dir dest_save_image = "#{dest_save_dir}/#{img_name}" - dest_site_image = "#{site_root}/#{img_root}/#{img_name}" + dest_site_image = "#{$site_root}/#{img_root}/#{img_name}" File.open(dest_save_image, 'w') {|f| f.write(img_str) } img.attributes['src'].value = dest_site_image if img.parent.node_name == 'a' img.parent.attributes['href'].value = dest_site_image end post.post_content = html_doc.inner_html post.save end end end diff --git a/importer.rb b/importer.rb index 60810b1..a06171e 100755 --- a/importer.rb +++ b/importer.rb @@ -1,47 +1,32 @@ -require 'rubygems' -require 'mechanize' - - #moneky patch to avoid timeout error - module Net - class BufferedIO - def rbuf_fill - #timeout(@read_timeout,ProtocolError) { - @rbuf << @io.sysread(1024) - #} - end - end - end - - def start_import agent = WWW::Mechanize.new - page = agent.get('http://localhost/wordpress/wp-login.php/') + page = agent.get("#{$base_url}/wp-login.php/") login_form = page.form('loginform') - login_form.log = 'admin' - login_form.pwd = 'dNdcCwtSg9VM' + login_form.log = $wordpress_username + login_form.pwd = $wordpress_password page = agent.submit(login_form) - page = agent.get('http://localhost/wordpress/wp-admin/admin.php?import=mt') + page = agent.get("#{$base_url}/wp-admin/admin.php?import=mt") import_form = page.forms[1] page = agent.submit(import_form) assign_users_form = page.forms[0] i = 0 page.search('li').each do |l| if l.parent.node_name == 'form' select_list = assign_users_form.send("userselect[#{i}]") select_list = l.search('strong').inner_html i += 1 end end page = agent.submit(assign_users_form) return true end diff --git a/process_script.rb b/process_script.rb index 66480d6..aeeecde 100755 --- a/process_script.rb +++ b/process_script.rb @@ -1,44 +1,36 @@ -require 'logger' -require 'pathname' +require 'global_settings' require 'importer.rb' require 'splitter.rb' require 'image_parse.rb' -require 'update_links' +require 'update_links.rb' require 'configure_wordpress.rb' -require 'ftools' - -file_path = '/media/sda2/wordpress_import/mt-export.txt' -allowed_length = 1000000 -dest_dir = '/media/sda2/wordpress_import/splitted_files' -wordpress_import_file = '/var/www/wordpress/wp-content/mt-export.txt' puts "Starting import file split" - -dest_files = split(file_path, dest_dir, allowed_length) +dest_files = split($wordpress_export_filename, $split_file_path, $allowed_length) puts "Successfully split the files into #{dest_files.join(',')}" dest_files.each do |dest_file| puts "Starting import of #{dest_file}..." - dest_path = File.join(dest_dir, dest_file) - File.copy(dest_path, wordpress_import_file) + dest_path = File.join($split_file_path, dest_file) + File.copy(dest_path, $wordpress_import_file) start_import puts "Finished importing the file #{dest_file}" end puts "Import process done." puts "Updating permalinks" update_permalinks puts "Done updating permalinks" puts "Processing images" process_images puts "Configuring wordpress" configure_wordpress diff --git a/splitter.rb b/splitter.rb index f68260a..f1372a3 100755 --- a/splitter.rb +++ b/splitter.rb @@ -1,32 +1,29 @@ -require 'pathname' - def split(file_path, dest_dir, allowed_length = 5000000) p = Pathname.new(file_path) temp_line = '' full_line = '' i = 0 -dest_filename = 'import_txt' dest_filename_arr = [] p.each_line do |line| temp_line += line if line.match(/^--------\n$/) if ((full_line.length + temp_line.length) < allowed_length) full_line += temp_line temp_line = '' else ((full_line.length + temp_line.length) > allowed_length) if full_line == '' full_line = temp_line temp_line = '' end - File.open("#{dest_dir}/#{dest_filename}_#{i}", 'w') {|f| f.write(full_line) } - dest_filename_arr << "#{dest_filename}_#{i}" + File.open("#{dest_dir}/#{$split_filename}_#{i}", 'w') {|f| f.write(full_line) } + dest_filename_arr << "#{$split_filename}_#{i}" full_line = '' i += 1 end end end -File.open("#{dest_dir}/#{dest_filename}_#{i}", 'w') {|f| f.write(full_line) } -dest_filename_arr << "#{dest_filename}_#{i}" +File.open("#{dest_dir}/#{$split_filename}_#{i}", 'w') {|f| f.write(full_line) } +dest_filename_arr << "#{$split_filename}_#{i}" end diff --git a/update_links.rb b/update_links.rb index 4d46548..61c6ecb 100755 --- a/update_links.rb +++ b/update_links.rb @@ -1,37 +1,22 @@ require 'url_mapping.rb' -require 'rubygems' -require 'activerecord' - -ActiveRecord::Base.establish_connection( - :adapter => "mysql", - :database => "word_press2", - :username => "root", - :password => "isiri", - :socket => '/tmp/mysql.sock' -) - -class WpPost < ActiveRecord::Base - set_primary_key 'ID' - set_table_name "wp_posts" -end def update_permalinks logger = Logger.new('error.log') url_mapping_arr.each do |url_mapping| new_post_url = url_mapping[0].strip old_post_url = url_mapping[1].strip if new_post_url == '' or old_post_url == '' or new_post_url.nil? or old_post_url.nil? logger.error "ERROR UPDATING NEW-#{new_post_url}------OLD-#{old_post_url}" else wp_post = WpPost.find_by_post_name(new_post_url) unless wp_post.nil? wp_post.update_attribute(:post_name, old_post_url) else logger.error "ERROR COULD NOT FIND NEW URL - #{new_post_url}" end end end end
isiri/wordpress_import
e3bd48a942b14b99876f09ae7e6eb29329c9fd6e
configuring wordpress
diff --git a/configure_wordpress.rb b/configure_wordpress.rb new file mode 100755 index 0000000..3334b7b --- /dev/null +++ b/configure_wordpress.rb @@ -0,0 +1,20 @@ +require 'rubygems' +require 'mechanize' + +def configure_wordpress + agent = WWW::Mechanize.new + page = agent.get('http://localhost/wordpress/wp-login.php/') + + login_form = page.form('loginform') + login_form.log = 'admin' + login_form.pwd = 'dNdcCwtSg9VM' + + page = agent.submit(login_form) + + page = agent.get('http://localhost/wordpress/wp-admin/options-permalink.php') + + permalink_form = page.forms.first + permalink_form.permalink_structure = '/%year%/%monthnum%/%postname%.html' + + page = agent.submit(permalink_form) +end diff --git a/process_script.rb b/process_script.rb index b9693aa..66480d6 100755 --- a/process_script.rb +++ b/process_script.rb @@ -1,40 +1,44 @@ require 'logger' require 'pathname' require 'importer.rb' require 'splitter.rb' require 'image_parse.rb' require 'update_links' +require 'configure_wordpress.rb' require 'ftools' file_path = '/media/sda2/wordpress_import/mt-export.txt' allowed_length = 1000000 dest_dir = '/media/sda2/wordpress_import/splitted_files' wordpress_import_file = '/var/www/wordpress/wp-content/mt-export.txt' puts "Starting import file split" dest_files = split(file_path, dest_dir, allowed_length) puts "Successfully split the files into #{dest_files.join(',')}" dest_files.each do |dest_file| puts "Starting import of #{dest_file}..." dest_path = File.join(dest_dir, dest_file) File.copy(dest_path, wordpress_import_file) start_import puts "Finished importing the file #{dest_file}" end puts "Import process done." puts "Updating permalinks" update_permalinks puts "Done updating permalinks" puts "Processing images" process_images +puts "Configuring wordpress" +configure_wordpress +
isiri/wordpress_import
a31730a2c411099d60cafd4e88ae893987b1d7a7
some fixes
diff --git a/image_parse.rb b/image_parse.rb index 23172cc..74b2528 100755 --- a/image_parse.rb +++ b/image_parse.rb @@ -1,50 +1,51 @@ require 'rubygems' require 'pathname' require 'open-uri' require 'nokogiri' require 'activerecord' ActiveRecord::Base.establish_connection( :adapter => "mysql", :database => "word_press2", :username => "root", :password => "isiri", :socket => '/tmp/mysql.sock' ) class WpPost < ActiveRecord::Base set_primary_key 'ID' set_table_name "wp_posts" end def process_images all_posts = WpPost.find(:all) - root_image_folder = '/wp-content/uploads' - i = 0 + wordpress_root = '/var/www' + site_root = '/wordpress/wp-content/uploads' all_posts.each do |post| html_doc = Nokogiri::HTML(post.post_content) (html_doc/"img").each do |img| img_src = img.attributes['src'].to_s img_name = img_src.split('/').last img_str = '' open(img_src.gsub(/ /,'%20')) { |f| img_str = f.read } - dest_dir = "#{root_image_folder}/#{post.post_date.year}/#{post.post_date.month}" - FileUtils.mkdir_p dest_dir - dest_image = "#{dest_dir}/#{img_name}_#{i}" - File.open(dest_image, 'w') {|f| f.write(img_str) } - img.attributes['src'].value = dest_image + img_root = "/#{post.post_date.year}/#{post.post_date.month}" + dest_save_dir = "#{wordpress_root}#{site_root}/#{img_root}" + FileUtils.mkdir_p dest_save_dir + dest_save_image = "#{dest_save_dir}/#{img_name}" + dest_site_image = "#{site_root}/#{img_root}/#{img_name}" + File.open(dest_save_image, 'w') {|f| f.write(img_str) } + img.attributes['src'].value = dest_site_image if img.parent.node_name == 'a' - img.parent.attributes['href'].value = dest_image + img.parent.attributes['href'].value = dest_site_image end post.post_content = html_doc.inner_html post.save - i += 1 end end end diff --git a/importer.rb b/importer.rb index 74742a6..60810b1 100755 --- a/importer.rb +++ b/importer.rb @@ -1,47 +1,47 @@ require 'rubygems' require 'mechanize' #moneky patch to avoid timeout error module Net class BufferedIO def rbuf_fill #timeout(@read_timeout,ProtocolError) { @rbuf << @io.sysread(1024) #} end end end def start_import agent = WWW::Mechanize.new page = agent.get('http://localhost/wordpress/wp-login.php/') login_form = page.form('loginform') login_form.log = 'admin' - login_form.pwd = '*0&mp6#XofLm' + login_form.pwd = 'dNdcCwtSg9VM' page = agent.submit(login_form) page = agent.get('http://localhost/wordpress/wp-admin/admin.php?import=mt') import_form = page.forms[1] page = agent.submit(import_form) assign_users_form = page.forms[0] i = 0 page.search('li').each do |l| if l.parent.node_name == 'form' select_list = assign_users_form.send("userselect[#{i}]") select_list = l.search('strong').inner_html i += 1 end end page = agent.submit(assign_users_form) return true end diff --git a/process_script.rb b/process_script.rb index afedaac..b9693aa 100755 --- a/process_script.rb +++ b/process_script.rb @@ -1,40 +1,40 @@ require 'logger' require 'pathname' require 'importer.rb' require 'splitter.rb' require 'image_parse.rb' require 'update_links' require 'ftools' -file_path = '/media/sda1/wordpress_import/mt-export.txt' -allowed_length = 5000000 -dest_dir = '/media/sda1/wordpress_import/splitted_files' +file_path = '/media/sda2/wordpress_import/mt-export.txt' +allowed_length = 1000000 +dest_dir = '/media/sda2/wordpress_import/splitted_files' wordpress_import_file = '/var/www/wordpress/wp-content/mt-export.txt' puts "Starting import file split" dest_files = split(file_path, dest_dir, allowed_length) puts "Successfully split the files into #{dest_files.join(',')}" dest_files.each do |dest_file| puts "Starting import of #{dest_file}..." dest_path = File.join(dest_dir, dest_file) File.copy(dest_path, wordpress_import_file) start_import puts "Finished importing the file #{dest_file}" end puts "Import process done." puts "Updating permalinks" update_permalinks puts "Done updating permalinks" puts "Processing images" process_images
isiri/wordpress_import
2c49ba2411c5a9911aec5319eae5cf63be25cff7
modified: image_parse.rb
diff --git a/image_parse.rb b/image_parse.rb index b151a08..23172cc 100755 --- a/image_parse.rb +++ b/image_parse.rb @@ -1,52 +1,50 @@ require 'rubygems' require 'pathname' require 'open-uri' require 'nokogiri' require 'activerecord' ActiveRecord::Base.establish_connection( :adapter => "mysql", :database => "word_press2", :username => "root", :password => "isiri", :socket => '/tmp/mysql.sock' ) class WpPost < ActiveRecord::Base set_primary_key 'ID' set_table_name "wp_posts" end def process_images all_posts = WpPost.find(:all) root_image_folder = '/wp-content/uploads' i = 0 all_posts.each do |post| html_doc = Nokogiri::HTML(post.post_content) (html_doc/"img").each do |img| img_src = img.attributes['src'].to_s img_name = img_src.split('/').last img_str = '' open(img_src.gsub(/ /,'%20')) { |f| img_str = f.read } dest_dir = "#{root_image_folder}/#{post.post_date.year}/#{post.post_date.month}" FileUtils.mkdir_p dest_dir dest_image = "#{dest_dir}/#{img_name}_#{i}" File.open(dest_image, 'w') {|f| f.write(img_str) } img.attributes['src'].value = dest_image if img.parent.node_name == 'a' img.parent.attributes['href'].value = dest_image end post.post_content = html_doc.inner_html post.save i += 1 end end end - -process_images
isiri/wordpress_import
ccd211aa8bea5af6f608cbbb1e9d5b499bcba113
modified: image_parse.rb
diff --git a/image_parse.rb b/image_parse.rb index be0d036..b151a08 100755 --- a/image_parse.rb +++ b/image_parse.rb @@ -1,50 +1,52 @@ require 'rubygems' require 'pathname' require 'open-uri' require 'nokogiri' require 'activerecord' ActiveRecord::Base.establish_connection( :adapter => "mysql", :database => "word_press2", :username => "root", :password => "isiri", :socket => '/tmp/mysql.sock' ) class WpPost < ActiveRecord::Base set_primary_key 'ID' set_table_name "wp_posts" end def process_images all_posts = WpPost.find(:all) - root_image_folder = '/var/www/wordpress/wp-content/uploads' + root_image_folder = '/wp-content/uploads' i = 0 all_posts.each do |post| html_doc = Nokogiri::HTML(post.post_content) (html_doc/"img").each do |img| img_src = img.attributes['src'].to_s img_name = img_src.split('/').last img_str = '' open(img_src.gsub(/ /,'%20')) { |f| img_str = f.read } - dest_dir = "#{root_image_folder}/#{post.post_date.year}/#{post.post_date.month}" + dest_dir = "#{root_image_folder}/#{post.post_date.year}/#{post.post_date.month}" FileUtils.mkdir_p dest_dir dest_image = "#{dest_dir}/#{img_name}_#{i}" File.open(dest_image, 'w') {|f| f.write(img_str) } img.attributes['src'].value = dest_image if img.parent.node_name == 'a' img.parent.attributes['href'].value = dest_image end post.post_content = html_doc.inner_html post.save i += 1 end end end + +process_images
isiri/wordpress_import
da0c8982bc50e97e13046d54fbb2fe7c74b2b164
removed extra func. call
diff --git a/update_links.rb b/update_links.rb index e9383ed..4d46548 100755 --- a/update_links.rb +++ b/update_links.rb @@ -1,38 +1,37 @@ require 'url_mapping.rb' require 'rubygems' require 'activerecord' ActiveRecord::Base.establish_connection( :adapter => "mysql", :database => "word_press2", :username => "root", :password => "isiri", :socket => '/tmp/mysql.sock' ) class WpPost < ActiveRecord::Base set_primary_key 'ID' set_table_name "wp_posts" end def update_permalinks logger = Logger.new('error.log') url_mapping_arr.each do |url_mapping| new_post_url = url_mapping[0].strip old_post_url = url_mapping[1].strip if new_post_url == '' or old_post_url == '' or new_post_url.nil? or old_post_url.nil? logger.error "ERROR UPDATING NEW-#{new_post_url}------OLD-#{old_post_url}" else wp_post = WpPost.find_by_post_name(new_post_url) unless wp_post.nil? wp_post.update_attribute(:post_name, old_post_url) else logger.error "ERROR COULD NOT FIND NEW URL - #{new_post_url}" end end end end -update_permalinks
isiri/wordpress_import
dedf36fbbae701104cc6590b76bc76d2be5a2673
initial files
diff --git a/image_parse.rb b/image_parse.rb new file mode 100755 index 0000000..be0d036 --- /dev/null +++ b/image_parse.rb @@ -0,0 +1,50 @@ +require 'rubygems' +require 'pathname' +require 'open-uri' +require 'nokogiri' +require 'activerecord' + +ActiveRecord::Base.establish_connection( + :adapter => "mysql", + :database => "word_press2", + :username => "root", + :password => "isiri", + :socket => '/tmp/mysql.sock' +) + +class WpPost < ActiveRecord::Base + set_primary_key 'ID' + set_table_name "wp_posts" +end + +def process_images + + all_posts = WpPost.find(:all) + root_image_folder = '/var/www/wordpress/wp-content/uploads' + i = 0 + + all_posts.each do |post| + html_doc = Nokogiri::HTML(post.post_content) + (html_doc/"img").each do |img| + img_src = img.attributes['src'].to_s + img_name = img_src.split('/').last + img_str = '' + open(img_src.gsub(/ /,'%20')) { + |f| + img_str = f.read + } + dest_dir = "#{root_image_folder}/#{post.post_date.year}/#{post.post_date.month}" + FileUtils.mkdir_p dest_dir + dest_image = "#{dest_dir}/#{img_name}_#{i}" + File.open(dest_image, 'w') {|f| f.write(img_str) } + img.attributes['src'].value = dest_image + if img.parent.node_name == 'a' + img.parent.attributes['href'].value = dest_image + end + post.post_content = html_doc.inner_html + post.save + i += 1 + end + end + +end diff --git a/importer.rb b/importer.rb new file mode 100755 index 0000000..74742a6 --- /dev/null +++ b/importer.rb @@ -0,0 +1,47 @@ +require 'rubygems' +require 'mechanize' + + #moneky patch to avoid timeout error + module Net + class BufferedIO + def rbuf_fill + #timeout(@read_timeout,ProtocolError) { + @rbuf << @io.sysread(1024) + #} + end + end + end + + +def start_import + + agent = WWW::Mechanize.new + page = agent.get('http://localhost/wordpress/wp-login.php/') + + login_form = page.form('loginform') + login_form.log = 'admin' + login_form.pwd = '*0&mp6#XofLm' + + page = agent.submit(login_form) + + page = agent.get('http://localhost/wordpress/wp-admin/admin.php?import=mt') + + import_form = page.forms[1] + page = agent.submit(import_form) + + assign_users_form = page.forms[0] + + i = 0 + page.search('li').each do |l| + if l.parent.node_name == 'form' + select_list = assign_users_form.send("userselect[#{i}]") + select_list = l.search('strong').inner_html + i += 1 + end + end + + page = agent.submit(assign_users_form) + + return true + +end diff --git a/process_script.rb b/process_script.rb new file mode 100755 index 0000000..afedaac --- /dev/null +++ b/process_script.rb @@ -0,0 +1,40 @@ +require 'logger' +require 'pathname' +require 'importer.rb' +require 'splitter.rb' +require 'image_parse.rb' +require 'update_links' +require 'ftools' + +file_path = '/media/sda1/wordpress_import/mt-export.txt' +allowed_length = 5000000 +dest_dir = '/media/sda1/wordpress_import/splitted_files' +wordpress_import_file = '/var/www/wordpress/wp-content/mt-export.txt' + +puts "Starting import file split" + +dest_files = split(file_path, dest_dir, allowed_length) + +puts "Successfully split the files into #{dest_files.join(',')}" + +dest_files.each do |dest_file| + puts "Starting import of #{dest_file}..." + + dest_path = File.join(dest_dir, dest_file) + File.copy(dest_path, wordpress_import_file) + + start_import + puts "Finished importing the file #{dest_file}" +end + +puts "Import process done." + +puts "Updating permalinks" +update_permalinks +puts "Done updating permalinks" + +puts "Processing images" +process_images + + + diff --git a/splitter.rb b/splitter.rb new file mode 100755 index 0000000..f68260a --- /dev/null +++ b/splitter.rb @@ -0,0 +1,32 @@ +require 'pathname' + +def split(file_path, dest_dir, allowed_length = 5000000) +p = Pathname.new(file_path) +temp_line = '' +full_line = '' +i = 0 +dest_filename = 'import_txt' +dest_filename_arr = [] + +p.each_line do |line| + temp_line += line + if line.match(/^--------\n$/) + if ((full_line.length + temp_line.length) < allowed_length) + full_line += temp_line + temp_line = '' + else + ((full_line.length + temp_line.length) > allowed_length) + if full_line == '' + full_line = temp_line + temp_line = '' + end + File.open("#{dest_dir}/#{dest_filename}_#{i}", 'w') {|f| f.write(full_line) } + dest_filename_arr << "#{dest_filename}_#{i}" + full_line = '' + i += 1 + end + end +end +File.open("#{dest_dir}/#{dest_filename}_#{i}", 'w') {|f| f.write(full_line) } +dest_filename_arr << "#{dest_filename}_#{i}" +end diff --git a/update_links.rb b/update_links.rb new file mode 100755 index 0000000..e9383ed --- /dev/null +++ b/update_links.rb @@ -0,0 +1,38 @@ +require 'url_mapping.rb' +require 'rubygems' +require 'activerecord' + +ActiveRecord::Base.establish_connection( + :adapter => "mysql", + :database => "word_press2", + :username => "root", + :password => "isiri", + :socket => '/tmp/mysql.sock' +) + +class WpPost < ActiveRecord::Base + set_primary_key 'ID' + set_table_name "wp_posts" +end + +def update_permalinks + + logger = Logger.new('error.log') + + url_mapping_arr.each do |url_mapping| + new_post_url = url_mapping[0].strip + old_post_url = url_mapping[1].strip + if new_post_url == '' or old_post_url == '' or new_post_url.nil? or old_post_url.nil? + logger.error "ERROR UPDATING NEW-#{new_post_url}------OLD-#{old_post_url}" + else + wp_post = WpPost.find_by_post_name(new_post_url) + unless wp_post.nil? + wp_post.update_attribute(:post_name, old_post_url) + else + logger.error "ERROR COULD NOT FIND NEW URL - #{new_post_url}" + end + end + end + +end +update_permalinks diff --git a/url_mapping.rb b/url_mapping.rb new file mode 100755 index 0000000..443511a --- /dev/null +++ b/url_mapping.rb @@ -0,0 +1,1808 @@ +def url_mapping_arr +[ +[ ' macro-shares-prediction-markets-via-stock-exchanges ' , ' macro_shares_pr ' ], +[ ' thank-you-maam-may-i-have-another ' , ' thank_you_maam_ ' ], +[ ' beware-of-disagreeing-with-lewis ' , ' beware_of_disag ' ], +[ ' incautious-defense-of-bias ' , ' incautious_defe ' ], +[ ' pascalian-meditations ' , ' pascalian_medit ' ], +[ ' are-the-big-four-econ-errors-biases ' , ' the_big_four_ec ' ], +[ ' surprisingly-friendly-suburbs ' , ' surprisingly_fr ' ], +[ ' beware-amateur-science-history ' , ' beware_amateur_ ' ], +[ ' whats-a-bias-again ' , ' whats_a_bias_ag ' ], +[ ' why-truth-and ' , ' why_truth_and ' ], +[ ' asymmetric-paternalism ' , ' asymmetric_pate ' ], +[ ' to-the-barricades-against-what-exactly ' , ' to_the_barricad ' ], +[ ' foxes-vs-hedgehogs-predictive-success ' , ' foxes_vs_hedgho ' ], +[ ' follow-the-crowd ' , ' follow_the_crow ' ], +[ ' what-exactly-is-bias ' , ' what_exactly_is ' ], +[ ' moral-overconfidence ' , ' moral_hypocricy ' ], +[ ' why-are-academics-liberal ' , ' the_cause_of_is ' ], +[ ' a-1990-corporate-prediction-market ' , ' first_known_bus ' ], +[ ' the-martial-art-of-rationality ' , ' the_martial_art ' ], +[ ' beware-heritable-beliefs ' , ' beware_heritabl ' ], +[ ' the-wisdom-of-bromides ' , ' the_wisdom_of_b ' ], +[ ' the-movie-click ' , ' click_christmas ' ], +[ ' quiz-fox-or-hedgehog ' , ' quiz_fox_or_hed ' ], +[ ' hide-sociobiology-like-sex ' , ' does_sociobiolo ' ], +[ ' how-to-join ' , ' introduction ' ], +[ ' normative-bayesianism-and-disagreement ' , ' normative_bayes ' ], +[ ' vulcan-logic ' , ' vulcan_logic ' ], +[ ' benefit-of-doubt-bias ' , ' benefit_of_doub ' ], +[ ' see-but-dont-believe ' , ' see_but_dont_be ' ], +[ ' the-future-of-oil-prices-2-option-probabilities ' , ' the_future_of_o_1 ' ], +[ ' resolving-your-hypocrisy ' , ' resolving_your_ ' ], +[ ' academic-overconfidence ' , ' academic_overco ' ], +[ ' gnosis ' , ' gnosis ' ], +[ ' ads-that-hurt ' , ' ads_that_hurt ' ], +[ ' gifts-hurt ' , ' gifts_hurt ' ], +[ ' advertisers-vs-teachers-ii ' , ' advertisers_vs_ ' ], +[ ' why-common-priors ' , ' why_common_prio ' ], +[ ' the-future-of-oil-prices ' , ' the_future_of_o ' ], +[ ' a-fable-of-science-and-politics ' , ' a_fable_of_scie ' ], +[ ' a-christmas-gift-for-rationalists ' , ' a_christmas_gif ' ], +[ ' when-truth-is-a-trap ' , ' when_truth_is_a ' ], +[ ' you-will-age-and-die ' , ' you_will_age_an ' ], +[ ' contributors-be-half-accessible ' , ' contributors_be ' ], +[ ' i-dont-know ' , ' i_dont_know ' ], +[ ' you-are-never-entitled-to-your-opinion ' , ' you_are_never_e ' ], +[ ' a-decent-respect ' , ' a_decent_respec ' ], +[ ' why-not-impossible-worlds ' , ' why_not_impossi ' ], +[ ' modesty-in-a-disagreeable-world ' , ' modesty_in_a_di ' ], +[ ' to-win-press-feign-surprise ' , ' to_win_press_fe ' ], +[ ' advertisers-vs-teachers ' , ' suppose_that_co ' ], +[ ' when-error-is-high-simplify ' , ' when_error_is_h ' ], +[ ' finding-the-truth-in-controversies ' , ' finding_the_tru ' ], +[ ' bias-in-christmas-shopping ' , ' bias_in_christm ' ], +[ ' does-the-modesty-argument-apply-to-moral-claims ' , ' does_the_modest ' ], +[ ' philosophers-on-moral-bias ' , ' philosophers_on ' ], +[ ' meme-lineages-and-expert-consensus ' , ' meme_lineages_a ' ], +[ ' the-conspiracy-against-cuckolds ' , ' the_conspiracy_ ' ], +[ ' malatesta-estimator ' , ' malatesta_estim ' ], +[ ' fillers-neglect-framers ' , ' fillers_neglect ' ], +[ ' the-80-forecasting-solution ' , ' the_80_forecast ' ], +[ ' ignorance-of-frankenfoods ' , ' ignorance_of_fr ' ], +[ ' do-helping-professions-help-more ' , ' do_helping_prof ' ], +[ ' should-prediction-markets-be-charities ' , ' should_predicti ' ], +[ ' we-are-smarter-than-me ' , ' we_are_smarter_ ' ], +[ ' law-as-no-bias-theatre ' , ' law_as_nobias_t ' ], +[ ' the-modesty-argument ' , ' the_modesty_arg ' ], +[ ' agreeing-to-agree ' , ' agreeing_to_agr ' ], +[ ' time-on-risk ' , ' time_on_risk ' ], +[ ' leamers-1986-idea-futures-proposal ' , ' leamers_1986_id ' ], +[ ' alas-amateur-futurism ' , ' alas_amateur_fu ' ], +[ ' the-wisdom-of-crowds ' , ' the_wisdom_of_c ' ], +[ ' reasonable-disagreement ' , ' reasonable_disa ' ], +[ ' math-zero-vs-political-zero ' , ' math_zero_vs_po ' ], +[ ' bosses-prefer-overconfident-managers ' , ' bosses_prefer_o ' ], +[ ' seen-vs-unseen-biases ' , ' seen_vs_unseen_ ' ], +[ ' future-selves ' , ' future_selves ' ], +[ ' does-profit-rate-insight-best ' , ' does_profit_rat ' ], +[ ' bias-well-being-and-the-placebo-effect ' , ' bias_wellbeing_ ' ], +[ ' biases-of-science-fiction ' , ' biases_of_scien ' ], +[ ' the-proper-use-of-humility ' , ' the_proper_use_ ' ], +[ ' the-onion-on-bias-duh ' , ' the_onion_on_bi ' ], +[ ' prizes-versus-grants ' , ' prizes_versus_g ' ], +[ ' wanted-a-meta-poll ' , ' wanted_a_metapo ' ], +[ ' excess-signaling-example ' , ' excess_signalin ' ], +[ ' rationalization ' , ' rationalization ' ], +[ ' against-admirable-activities ' , ' against_admirab ' ], +[ ' effects-of-ideological-media-persuasion ' , ' effects_of_ideo ' ], +[ ' whats-the-right-rule-for-a-juror ' , ' whats_the_right ' ], +[ ' galt-on-abortion-and-bias ' , ' galt_on_abortio ' ], +[ ' -the-procrastinators-clock ' , ' the_procrastina ' ], +[ ' keeping-score ' , ' keeping_score ' ], +[ ' agree-with-young-duplicate ' , ' agree_with_your ' ], +[ ' sick-of-textbook-errors ' , ' sick_of_textboo ' ], +[ ' manipulating-jury-biases ' , ' manipulating_ju ' ], +[ ' what-insight-in-innocence ' , ' what_insight_in ' ], +[ ' on-policy-fact-experts-ignore-facts ' , ' on_policy_fact_ ' ], +[ ' the-butler-did-it-of-course ' , ' the_butler_did_ ' ], +[ ' no-death-of-a-buyerman ' , ' no_death_of_a_b ' ], +[ ' is-there-such-a-thing-as-bigotry ' , ' is_there_such_a ' ], +[ ' moby-dick-seeks-thee-not ' , ' moby_dick_seeks ' ], +[ ' morale-markets-vs-decision-markets ' , ' morale_markets_ ' ], +[ ' follow-your-passion-from-a-distance ' , ' follow_your_pas ' ], +[ ' a-model-of-extraordinary-claims ' , ' a_model_of_extr ' ], +[ ' socially-influenced-beliefs ' , ' socially_influe ' ], +[ ' agree-with-yesterdays-duplicate ' , ' agree_with_yest ' ], +[ ' outside-the-laboratory ' , ' outside_the_lab ' ], +[ ' symmetry-is-not-pretty ' , ' symmetry_is_not ' ], +[ ' some-claims-are-just-too-extraordinary ' , ' some_claims_are ' ], +[ ' womens-mathematical-abilities ' , ' womens_mathemat ' ], +[ ' benefits-of-cost-benefit-analyis ' , ' benefits_of_cos ' ], +[ ' godless-professors ' , ' godless_profess ' ], +[ ' how-to-not-spend-money ' , ' suppose_youre_a ' ], +[ ' sometimes-the-facts-are-irrelevant ' , ' sometimes_the_f ' ], +[ ' extraordinary-claims-are-extraordinary-evidence ' , ' extraordinary_c ' ], +[ ' ' , ' in_a_recent_pos ' ], +[ ' 70-for-me-30-for-you ' , ' 70_for_me_30_fo ' ], +[ ' some-people-just-wont-quit ' , ' some_people_jus ' ], +[ ' statistical-discrimination-is-probably-bad ' , ' statistical_dis ' ], +[ ' costbenefit-analysis ' , ' costbenefit_ana ' ], +[ ' smoking-warning-labels ' , ' smoking_warning ' ], +[ ' conclusion-blind-review ' , ' conclusionblind ' ], +[ ' is-more-information-always-better ' , ' is_more_informa ' ], +[ ' should-we-defer-to-secret-evidence ' , ' should_we_defer ' ], +[ ' peaceful-speculation ' , ' peaceful_specul ' ], +[ ' supping-with-the-devil ' , ' supping_with_th ' ], +[ ' disagree-with-suicide-rock ' , ' disagree_with_s ' ], +[ ' biased-courtship ' , ' biased_courtshi ' ], +[ ' reject-your-personalitys-politics ' , ' reject_your_pol ' ], +[ ' laws-of-bias-in-science ' , ' laws_of_bias_in ' ], +[ ' epidemics-are-98-below-average ' , ' epidemics_are_9 ' ], +[ ' bias-not-a-bug-but-a-feature ' , ' bias_not_a_bug_ ' ], +[ ' a-game-for-self-calibration ' , ' a_game_for_self ' ], +[ ' why-allow-referee-bias ' , ' why_is_referee_ ' ], +[ ' disagreement-at-thoughts-arguments-and-rants ' , ' disagreement_at ' ], +[ ' hobgoblins-of-voter-minds ' , ' hobgoblins_of_v ' ], +[ ' how-are-we-doing ' , ' how_are_we_doin ' ], +[ ' avoiding-truth ' , ' avoiding_truth ' ], +[ ' conspicuous-consumption-of-info ' , ' conspicuous_con ' ], +[ ' we-cant-foresee-to-disagree ' , ' we_cant_foresee ' ], +[ ' do-biases-favor-hawks ' , ' do_biases_favor ' ], +[ ' convenient-bias-theories ' , ' convenient_bias ' ], +[ ' fair-betting-odds-and-prediction-market-prices ' , ' fair_betting_od ' ], +[ ' the-cognitive-architecture-of-bias ' , ' the_cognitive_a ' ], +[ ' poll-on-nanofactories ' , ' poll_on_nanofac ' ], +[ ' all-bias-is-signed ' , ' all_bias_is_sig ' ], +[ ' two-cheers-for-ignoring-plain-facts ' , ' two_cheers_for_ ' ], +[ ' what-if-everybody-overcame-bias ' , ' what_if_everybo ' ], +[ ' discussions-of-bias-in-answers-to-the-edge-2007-question ' , ' media_biases_us ' ], +[ ' why-dont-the-young-learn-from-the-old ' , ' why_dont_the_yo ' ], +[ ' the-coin-guessing-game ' , ' the_coin_guessi ' ], +[ ' a-honest-doctor-sort-of ' , ' a_honest_doctor ' ], +[ ' medical-study-biases ' , ' medical_study_b ' ], +[ ' this-is-my-dataset-there-are-many-datasets-like-it-but-this-one-is-mine ' , ' this_is_my_data ' ], +[ ' professors-progress-like-ads-advise ' , ' ads_advise_prof ' ], +[ ' disagreement-case-study-1 ' , ' disagreement_ca ' ], +[ ' marginally-revolved-biases ' , ' marginally_revo ' ], +[ ' calibrate-your-ad-response ' , ' calibrate_your_ ' ], +[ ' disagreement-case-studies ' , ' seeking_disagre ' ], +[ ' just-lose-hope-already ' , ' a_time_to_lose_ ' ], +[ ' less-biased-memories ' , ' unbiased_memori ' ], +[ ' think-frequencies-not-probabilities ' , ' think_frequenci ' ], +[ ' fig-leaf-models ' , ' fig_leaf_models ' ], +[ ' do-we-get-used-to-stuff-but-not-friends ' , ' do_we_get_used_ ' ], +[ ' buss-on-true-love ' , ' buss_on_true_lo ' ], +[ ' is-overcoming-bias-male ' , ' is_overcoming_b ' ], +[ ' bias-in-the-classroom ' , ' bias_in_the_cla ' ], +[ ' our-house-my-rules ' , ' our_house_my_ru ' ], +[ ' how-paranoid-should-i-be-the-limits-of-overcoming-bias ' , ' how_paranoid_sh ' ], +[ ' evidence-based-medicine-backlash ' , ' evidencebased_m ' ], +[ ' politics-is-the-mind-killer ' , ' politics_is_the ' ], +[ ' disagreement-on-inflation ' , ' disagreement_on ' ], +[ ' moderate-moderation ' , ' moderate_modera ' ], +[ ' bias-toward-certainty ' , ' bias_toward_cer ' ], +[ ' multi-peaked-distributions ' , ' multipeaked_dis ' ], +[ ' selection-bias-in-economic-theory ' , ' selection_bias_ ' ], +[ ' induce-presidential-candidates-to-take-iq-tests ' , ' induce_presiden ' ], +[ ' crackpot-people-and-crackpot-ideas ' , ' crackpot_people ' ], +[ ' press-confirms-your-health-fears ' , ' press_confirms_ ' ], +[ ' too-many-loner-theorists ' , ' too_many_loner_ ' ], +[ ' words-for-love-and-sex ' , ' words_for_love_ ' ], +[ ' its-sad-when-bad-ideas-drive-out-good-ones ' , ' its_sad_when_ba ' ], +[ ' truth-is-stranger-than-fiction ' , ' truth_is_strang ' ], +[ ' posterity-review-comes-cheap ' , ' posterity_revie ' ], +[ ' reputation-commitment-mechanism ' , ' reputation_comm ' ], +[ ' more-lying ' , ' more_lying ' ], +[ ' is-truth-in-the-hump-or-the-tails ' , ' is_truth_in_the ' ], +[ ' what-opinion-game-do-we-play ' , ' what_opinion_ga ' ], +[ ' philip-tetlocks-long-now-talk ' , ' philip_tetlocks ' ], +[ ' the-more-amazing-penn ' , ' the_more_amazin ' ], +[ ' when-are-weak-clues-uncomfortable ' , ' when_are_weak_c ' ], +[ ' detecting-lies ' , ' detecting_lies ' ], +[ ' how-and-when-to-listen-to-the-crowd ' , ' how_and_when_to ' ], +[ ' institutions-as-levers ' , ' institutions_as ' ], +[ ' one-reason-why-power-corrupts ' , ' one_reason_why_ ' ], +[ ' will-blog-posts-get-credit ' , ' will_blog_posts ' ], +[ ' needed-cognitive-forensics ' , ' wanted_cognitiv ' ], +[ ' control-variables-avoid-bias ' , ' control_variabl ' ], +[ ' dare-to-deprogram-me ' , ' dare_to_deprogr ' ], +[ ' bias-and-health-care ' , ' bias_and_health ' ], +[ ' just-world-bias-and-inequality ' , ' just_world_bias_1 ' ], +[ ' subduction-phrases ' , ' subduction_phra ' ], +[ ' what-evidence-in-silence-or-confusion ' , ' what_evidence_i ' ], +[ ' gender-profiling ' , ' gender_profilin ' ], +[ ' unequal-inequality ' , ' unequal_inequal ' ], +[ ' academic-tool-overconfidence ' , ' academic_tool_o ' ], +[ ' why-are-there-no-comforting-words-that-arent-also-factual-statements ' , ' why_are_there_n ' ], +[ ' big-issues-vs-small-issues ' , ' big_issues_vs_s ' ], +[ ' tolstoy-on-patriotism ' , ' tolstoy_on_patr ' ], +[ ' statistical-bias ' , ' statistical_bia ' ], +[ ' explain-your-wins ' , ' explain_your_wi ' ], +[ ' beware-of-information-porn ' , ' beware_of_infor ' ], +[ ' info-has-no-trend ' , ' info_has_no_tre ' ], +[ ' tsuyoku-vs-the-egalitarian-instinct ' , ' tsuyoku_vs_the_ ' ], +[ ' libertarian-purity-duels ' , ' libertarian_pur ' ], +[ ' tsuyoku-naritai-i-want-to-become-stronger ' , ' tsuyoku_naritai ' ], +[ ' reporting-chains-swallow-extraordinary-evidence ' , ' reporting_chain ' ], +[ ' self-deception-hypocrisy-or-akrasia ' , ' selfdeception_h ' ], +[ ' the-very-worst-kind-of-bias ' , ' the_very_worst_ ' ], +[ ' home-sweet-home-bias ' , ' home_sweet_home ' ], +[ ' norms-of-reason-and-the-prospects-for-technologies-and-policies-of-debiasing ' , ' ways_of_debiasi ' ], +[ ' useful-bias ' , ' useful_bias ' ], +[ ' chronophone-motivations ' , ' chronophone_mot ' ], +[ ' archimedess-chronophone ' , ' archimedess_chr ' ], +[ ' masking-expert-disagreement ' , ' masking_expert_ ' ], +[ ' archimedess-binding-dilemma ' , ' archimedess_bin ' ], +[ ' morality-of-the-future ' , ' morality_of_the ' ], +[ ' moral-progress-and-scope-of-moral-concern ' , ' moral_progress_ ' ], +[ ' awareness-of-intimate-bias ' , ' awareness_of_in ' ], +[ ' all-ethics-roads-lead-to-ours ' , ' all_ethics_road ' ], +[ ' challenges-of-majoritarianism ' , ' challenges_of_m ' ], +[ ' classic-bias-doubts ' , ' classic_bias_do ' ], +[ ' philosophical-majoritarianism ' , ' on_majoritarian ' ], +[ ' useless-medical-disclaimers ' , ' useless_medical ' ], +[ ' arguments-and-duels ' , ' arguments_and_d ' ], +[ ' believing-in-todd ' , ' believing_in_to ' ], +[ ' ideologues-or-fools ' , ' ideologues_or_f ' ], +[ ' bias-caused-by-fear-of-islamic-extremists ' , ' bias_caused_by_ ' ], +[ ' bias-on-self-control-bias ' , ' selfcontrol_bia ' ], +[ ' multipolar-disagreements-hals-religious-quandry ' , ' multipolar_disa ' ], +[ ' superstimuli-and-the-collapse-of-western-civilization ' , ' superstimuli_an ' ], +[ ' good-news-only-please ' , ' good_news_only_ ' ], +[ ' blue-or-green-on-regulation ' , ' blue_or_green_o ' ], +[ ' 100000-visits ' , ' 100000_visits ' ], +[ ' disagreement-case-study-robin-hanson-and-david-balan ' , ' disagreement_ca_2 ' ], +[ ' the-trouble-with-track-records ' , ' the_trouble_wit ' ], +[ ' genetics-and-cognitive-bias ' , ' genetics_and_co ' ], +[ ' marketing-as-asymmetrical-warfare ' , ' marketing_as_as ' ], +[ ' disagreement-case-study---balan-and-i ' , ' disagreement_ca_1 ' ], +[ ' moral-dilemmas-criticism-plumping ' , ' moral_dilemmas_ ' ], +[ ' the-scales-of-justice-the-notebook-of-rationality ' , ' the_scales_of_j ' ], +[ ' none-evil-or-all-evil ' , ' none_evil_or_al ' ], +[ ' biases-by-and-large ' , ' biases_by_and_l ' ], +[ ' disagreement-case-study---hawk-bias ' , ' disagreement_ca ' ], +[ ' overcome-cognitive-bias-with-multiple-selves ' , ' overcome_cognit ' ], +[ ' extreme-paternalism ' , ' extreme_paterna ' ], +[ ' learn-from-politicians-personal-failings ' , ' learn_from_poli ' ], +[ ' whose-framing ' , ' whose_framing ' ], +[ ' who-are-the-god-experts ' , ' who_are_the_god ' ], +[ ' bias-against-introverts ' , ' bias_against_in ' ], +[ ' paternal-policies-fight-cognitive-bias-slash-information-costs-and-privelege-responsible-subselves ' , ' paternal_polici ' ], +[ ' the-fog-of-disagreement ' , ' the_fog_of_disa ' ], +[ ' burchs-law ' , ' burchs_law ' ], +[ ' lets-get-ready-to-rumble ' , ' heres_my_openin ' ], +[ ' rational-agent-paternalism ' , ' rational_agent_ ' ], +[ ' the-give-us-more-money-bias ' , ' the_give_us_mor ' ], +[ ' white-collar-crime-and-moral-freeloading ' , ' whitecollar_cri ' ], +[ ' happy-capital-day ' , ' happy_capital_d ' ], +[ ' outlandish-pundits ' , ' outlandish_pund ' ], +[ ' policy-debates-should-not-appear-one-sided ' , ' policy_debates_ ' ], +[ ' romantic-predators ' , ' romantic_predat ' ], +[ ' swinging-for-the-fences-when-you-should-bunt ' , ' swinging_for_th ' ], +[ ' paternalism-is-about-bias ' , ' paternalism_is_ ' ], +[ ' you-are-not-hiring-the-top-1 ' , ' you_are_not_hir ' ], +[ ' morality-or-manipulation ' , ' morality_or_man ' ], +[ ' accountable-financial-regulation ' , ' accountable_fin ' ], +[ ' today-is-honesty-day ' , ' today_is_honest ' ], +[ ' more-on-future-self-paternalism ' , ' more_on_future_ ' ], +[ ' universal-law ' , ' universal_law ' ], +[ ' universal-fire ' , ' universal_fire ' ], +[ ' the-fallacy-fallacy ' , ' the_fallacy_fal ' ], +[ ' to-learn-or-credential ' , ' to_learn_or_cre ' ], +[ ' feeling-rational ' , ' feeling_rationa ' ], +[ ' overconfidence-erases-doc-advantage ' , ' overconfidence_ ' ], +[ ' the-bleeding-edge-of-innovation ' , ' the_bleeding_ed ' ], +[ ' expert-at-versus-expert-on ' , ' expert_at_versu ' ], +[ ' meta-majoritarianism ' , ' meta_majoritari ' ], +[ ' future-self-paternalism ' , ' future_self_pat ' ], +[ ' popularity-is-random ' , ' popularity_is_r ' ], +[ ' holocaust-denial ' , ' holocaust_denia ' ], +[ ' exercise-sizzle-works-sans-steak ' , ' exercise_sizzle ' ], +[ ' the-shame-of-tax-loopholing ' , ' the_shame_of_ta ' ], +[ ' vonnegut-on-overcoming-fiction ' , ' vonnegut_on_ove ' ], +[ ' consolidated-nature-of-morality-thread ' , ' consolidated_na ' ], +[ ' irrationality-or-igustibusi ' , ' irrationality_o ' ], +[ ' your-rationality-is-my-business ' , ' your_rationalit ' ], +[ ' statistical-inefficiency-bias-or-increasing-efficiency-will-reduce-bias-on-average-or-there-is-no-bias-variance-tradeoff ' , ' statistical_ine ' ], +[ ' new-improved-lottery ' , ' new_improved_lo ' ], +[ ' non-experts-need-documentation ' , ' nonexperts_need ' ], +[ ' overconfident-evaluation ' , ' overconfident_e ' ], +[ ' lotteries-a-waste-of-hope ' , ' lotteries_a_was ' ], +[ ' just-a-smile ' , ' just_a_smile ' ], +[ ' priors-as-mathematical-objects ' , ' priors_as_mathe ' ], +[ ' predicting-the-future-with-futures ' , ' predicting_the_ ' ], +[ ' the-future-is-glamorous ' , ' the_future_is_g ' ], +[ ' marginally-zero-sum-efforts ' , ' marginally_zero ' ], +[ ' overcoming-credulity ' , ' overcoming_cred ' ], +[ ' urgent-and-important-not ' , ' very_important_ ' ], +[ ' futuristic-predictions-as-consumable-goods ' , ' futuristic_pred ' ], +[ ' suggested-posts ' , ' suggested_posts ' ], +[ ' modular-argument ' , ' modular_argumen ' ], +[ ' inductive-bias ' , ' inductive_bias ' ], +[ ' debiasing-as-non-self-destruction ' , ' debiasing_as_no ' ], +[ ' overcoming-bias---what-is-it-good-for ' , ' overcoming_bias ' ], +[ ' as-good-as-it-gets ' , ' as_good_as_it_g ' ], +[ ' driving-while-red ' , ' driving_while_r ' ], +[ ' media-bias ' , ' media_bias ' ], +[ ' could-gambling-save-science ' , ' could_gambling_ ' ], +[ ' casanova-on-innocence ' , ' casanova_on_inn ' ], +[ ' black-swans-from-the-future ' , ' black_swans_fro ' ], +[ ' having-to-do-something-wrong ' , ' having_to_do_so ' ], +[ ' knowing-about-biases-can-hurt-people ' , ' knowing_about_b ' ], +[ ' a-tough-balancing-act ' , ' a_tough_balanci ' ], +[ ' mapping-academia ' , ' mapping_academi ' ], +[ ' the-majority-is-always-wrong ' , ' the_majority_is ' ], +[ ' overcoming-fiction ' , ' overcoming_fict ' ], +[ ' the-error-of-crowds ' , ' the_error_of_cr ' ], +[ ' do-moral-systems-have-to-make-sense ' , ' do_moral_system ' ], +[ ' useful-statistical-biases ' , ' useful_statisti ' ], +[ ' is-there-manipulation-in-the-hillary-clinton-prediction-market ' , ' is_there_manipu ' ], +[ ' shock-response-futures ' , ' shock_response_ ' ], +[ ' free-money-going-fast ' , ' free_money_goin ' ], +[ ' arrogance-as-virtue ' , ' arrogance_as_vi ' ], +[ ' are-any-human-cognitive-biases-genetically-universal ' , ' are_any_human_c_1 ' ], +[ ' hofstadters-law ' , ' hofstadters_law ' ], +[ ' the-agency-problem ' , ' the_agency_prob ' ], +[ ' cryonics ' , ' cryonics ' ], +[ ' my-podcast-with-russ-roberts ' , ' my_podcast_with ' ], +[ ' truly-worth-honoring ' , ' truly_worth_hon ' ], +[ ' scientists-as-parrots ' , ' scientists_as_p ' ], +[ ' in-obscurity-errors-remain ' , ' in_obscurity_er ' ], +[ ' requesting-honesty ' , ' requesting_hone ' ], +[ ' winning-at-rock-paper-scissors ' , ' winning_at_rock ' ], +[ ' policy-tug-o-war ' , ' policy_tugowar ' ], +[ ' why-pretty-hs-play-leads ' , ' why_pretty_hs_p ' ], +[ ' the-perils-of-being-clearer-than-truth ' , ' the_perils_of_b ' ], +[ ' when-differences-make-a-difference ' , ' when_difference ' ], +[ ' you-felt-sorry-for-her ' , ' you_felt_sorry_ ' ], +[ ' do-androids-dream-of-electric-rabbit-feet ' , ' do_androids_dre ' ], +[ ' one-life-against-the-world ' , ' one_life_agains ' ], +[ ' cheating-as-status-symbol ' , ' cheating_as_sta ' ], +[ ' underconfident-experts ' , ' underconfident_ ' ], +[ ' are-almost-all-investors-biased ' , ' are_almost_all_ ' ], +[ ' data-management ' , ' data_management ' ], +[ ' are-any-human-cognitive-biases-genetic ' , ' are_any_human_c ' ], +[ ' is-your-rationality-on-standby ' , ' is_your_rationa ' ], +[ ' joke ' , ' joke ' ], +[ ' opinions-of-the-politically-informed ' , ' opinions_of_the ' ], +[ ' the-case-for-dangerous-testing ' , ' the_case_for_da ' ], +[ ' i-had-the-same-idea-as-david-brin-sort-of ' , ' i_had_the_same_ ' ], +[ ' disagreement-case-study----genetics-of-free-trade-and-a-new-cognitive-bias ' , ' disagreement_ca ' ], +[ ' rand-experiment-ii-petition ' , ' rand_experiment ' ], +[ ' skepticism-about-skepticism ' , ' skepticism_abou ' ], +[ ' scope-insensitivity ' , ' scope_insensiti ' ], +[ ' medicine-as-scandal ' , ' medicine_as_sca ' ], +[ ' the-us-should-bet-against-iran-testing-a-nuclear-weapon ' , ' the_us_should_b ' ], +[ ' medicare-train-wreck ' , ' medicare_train_ ' ], +[ ' eclipsing-nobel ' , ' eclipsing_nobel ' ], +[ ' what-speaks-silence ' , ' what_speaks_sil ' ], +[ ' the-worst-youve-seen-isnt-the-worst-there-is ' , ' the_worst_youve ' ], +[ ' rand-health-insurance-experiment-ii ' , ' rand_health_ins_1 ' ], +[ ' the-conspiracy-glitch ' , ' the_conspiracy_ ' ], +[ ' doubting-thomas-and-pious-pete ' , ' doubting_thomas ' ], +[ ' rand-health-insurance-experiment ' , ' rand_health_ins ' ], +[ ' third-alternatives-for-afterlife-ism ' , ' third_alternati ' ], +[ ' scope-neglect-hits-a-new-low ' , ' scope_neglect_h ' ], +[ ' motivated-stopping-in-philanthropy ' , ' early_stopping_ ' ], +[ ' cold-fusion-continues ' , ' cold_fusion_con ' ], +[ ' feel-lucky-punk ' , ' feel_luck_punk ' ], +[ ' the-third-alternative ' , ' the_third_alter ' ], +[ ' academics-against-evangelicals ' , ' academics_again ' ], +[ ' race-bias-of-nba-refs ' , ' race_bias_of_nb ' ], +[ ' brave-us-tv-news-not ' , ' brave_us_tv_new ' ], +[ ' beware-the-unsurprised ' , ' beware_the_unsu ' ], +[ ' academic-self-interest-bias ' , ' selfinterest_bi ' ], +[ ' the-bias-in-please-and-thank-you ' , ' the_bias_in_ple ' ], +[ ' social-norms-need-neutrality-simplicity ' , ' social_norms_ne ' ], +[ ' think-like-reality ' , ' think_like_real ' ], +[ ' overcoming-bias-on-the-simpsons ' , ' overcoming_bias ' ], +[ ' eh-hunt-helped-lbj-kill-jfk ' , ' eh_hunt_helped_ ' ], +[ ' myth-of-the-rational-academic ' , ' myth_of_the_rat ' ], +[ ' biases-are-fattening ' , ' biases-are-fatt ' ], +[ ' true-love-and-unicorns ' , ' true_love_and_u ' ], +[ ' bayes-radical-liberal-or-conservative ' , ' bayes-radical-l ' ], +[ ' global-warming-blowhards ' , ' global-warming- ' ], +[ ' extraordinary-physics ' , ' extraordinary_c ' ], +[ ' are-your-enemies-innately-evil ' , ' are-your-enemie ' ], +[ ' how-to-be-radical ' , ' how_to_be_radic ' ], +[ ' auctioning-book-royalties ' , ' auctioning-book ' ], +[ ' fair-landowner-coffee ' , ' fair-landowner- ' ], +[ ' death-risk-biases ' , ' death_risk_bias ' ], +[ ' correspondence-bias ' , ' correspondence- ' ], +[ ' applaud-info-not-agreement ' , ' applaud-info-no ' ], +[ ' risk-free-bonds-arent ' , ' risk-free-bonds ' ], +[ ' adam-smith-on-overconfidence ' , ' adam_smith_on_o ' ], +[ ' ethics-applied-vs-meta ' , ' ethics_applied_ ' ], +[ ' wandering-philosophers ' , ' wandering_philo ' ], +[ ' randomly-review-criminal-cases ' , ' randomly_review ' ], +[ ' functional-is-not-optimal ' , ' functional_is_n ' ], +[ ' were-people-better-off-in-the-middle-ages-than-they-are-now ' , ' politics_and_ec ' ], +[ ' selling-overcoming-bias ' , ' selling_overcom ' ], +[ ' tell-me-your-politics-and-i-can-tell-you-what-you-think-about-nanotechnology ' , ' tell_me_your_po ' ], +[ ' beware-neuroscience-stories ' , ' beware_neurosci ' ], +[ ' against-free-thinkers ' , ' against_free_th ' ], +[ ' 1-2-3-infinity ' , ' 1_2_3_infinity ' ], +[ ' total-vs-marginal-effects-or-are-the-overall-benefits-of-health-care-probably-minor ' , ' total_vs_margin ' ], +[ ' one-reason-why-plans-are-good ' , ' one_reason_why_ ' ], +[ ' 200000-visits ' , ' 200000_visits ' ], +[ ' choose-credit-or-influence ' , ' choose_credit_o ' ], +[ ' disagreement-case-study-hanson-and-hughes ' , ' disagreement_ca_1 ' ], +[ ' odd-kid-names ' , ' odd_kid_names ' ], +[ ' uncovering-rational-irrationalities ' , ' uncovering_rati ' ], +[ ' blind-elites ' , ' blind_elites ' ], +[ ' blind-winners ' , ' blind_winners ' ], +[ ' disagreement-case-study-hanson-and-cutler ' , ' disagreement_ca ' ], +[ ' why-not-pre-debate-talk ' , ' why_not_predeba ' ], +[ ' nutritional-prediction-markets ' , ' nutritional_pre ' ], +[ ' progress-is-not-enough ' , ' progress_is_not ' ], +[ ' two-meanings-of-overcoming-bias-for-one-focus-is-fundamental-for-second ' , ' two-meanings-of ' ], +[ ' only-losers-overcome-bias ' , ' only-losers-ove ' ], +[ ' bayesian-judo ' , ' bayesian-judo ' ], +[ ' self-interest-intent-deceit ' , ' self-interest-i ' ], +[ ' colorful-characters ' , ' color-character ' ], +[ ' belief-in-belief ' , ' belief-in-belie ' ], +[ ' phone-shy-ufos ' , ' phone-shy-ufos ' ], +[ ' making-beliefs-pay-rent-in-anticipated-experiences ' , ' making-beliefs- ' ], +[ ' ts-eliot-quote ' , ' ts-eliot-quote ' ], +[ ' not-every-negative-judgment-is-a-bias ' , ' not-every-negat ' ], +[ ' schools-that-dont-want-to-be-graded ' , ' schools-that-do ' ], +[ ' the-judo-principle ' , ' the-judo-princi ' ], +[ ' beware-the-inside-view ' , ' beware-the-insi ' ], +[ ' goofy-best-friend ' , ' goofy-best-frie ' ], +[ ' meta-textbooks ' , ' meta-textbooks ' ], +[ ' fantasys-essence ' , ' fantasys-essens ' ], +[ ' clever-controls ' , ' clever-controls ' ], +[ ' investing-in-index-funds-a-tangible-reward-of-overcoming-bias ' , ' investing-in-in ' ], +[ ' bad-balance-bias ' , ' bad-balance-bia ' ], +[ ' raging-memories ' , ' raging-memories ' ], +[ ' calibration-in-chess ' , ' calibration-in- ' ], +[ ' theyre-telling-you-theyre-lying ' , ' theyre-telling- ' ], +[ ' on-lying ' , ' on-lying ' ], +[ ' gullible-then-skeptical ' , ' gullible-then-s ' ], +[ ' how-biases-save-us-from-giving-in-to-terrorism ' , ' how-biases-save ' ], +[ ' privacy-rights-and-cognitive-bias ' , ' privacy-rights- ' ], +[ ' conspiracy-believers ' , ' conspiracy-beli ' ], +[ ' overcoming-bias-sometimes-makes-us-change-our-minds-but-sometimes-not ' , ' overcoming-bias ' ], +[ ' blogging-doubts ' , ' blogging-doubts ' ], +[ ' should-charges-of-cognitive-bias-ever-make-us-change-our-minds-a-global-warming-case-study ' , ' should-charges- ' ], +[ ' radical-research-evaluation ' , ' radical-researc ' ], +[ ' a-real-life-quandry ' , ' a-real-life-qua ' ], +[ ' looking-for-a-hard-headed-blogger ' , ' looking-for-a-h ' ], +[ ' goals-and-plans-in-decision-making ' , ' goals-and-plans ' ], +[ ' 7707-weddings ' , ' 7707-weddings ' ], +[ ' just-take-the-average ' , ' just-take-the-a ' ], +[ ' two-more-things-to-unlearn-from-school ' , ' two-more-things ' ], +[ ' introducing-ramone ' , ' introducing-ram ' ], +[ ' tell-your-anti-story ' , ' tell-your-anti- ' ], +[ ' reviewing-caplans-reviewers ' , ' reviewing-capla ' ], +[ ' how-should-unproven-findings-be-publicized ' , ' how-should-unpr ' ], +[ ' global-warming-skeptics-charge-believers-with-more-cognitive-biases-than-believers-do-skeptics-why-the-asymmetry ' , ' global-warming- ' ], +[ ' what-is-public-info ' , ' what-is-public- ' ], +[ ' take-our-survey ' , ' take-our-survey ' ], +[ ' lets-bet-on-talk ' , ' lets-bet-on-tal ' ], +[ ' more-possible-political-biases-relative-vs-absolute-well-being ' , ' more-possible-p ' ], +[ ' what-signals-what ' , ' what-signals-wh ' ], +[ ' reply-to-libertarian-optimism-bias ' , ' in-this-entry-o ' ], +[ ' biased-birth-rates ' , ' biased-birth-ra ' ], +[ ' libertarian-optimism-bias-vs-statist-pessimism-bias ' , ' libertarian-opt ' ], +[ ' painfully-honest ' , ' painfully-hones ' ], +[ ' biased-revenge ' , ' biased-revenge ' ], +[ ' the-road-not-taken ' , ' the_road_not_ta ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' making-history-available ' , ' making-history- ' ], +[ ' we-are-not-unbaised ' , ' we-are-not-unba ' ], +[ ' failing-to-learn-from-history ' , ' failing-to-lear ' ], +[ ' seeking-unbiased-game-host ' , ' seeking-unbiase ' ], +[ ' my-wild-and-reckless-youth ' , ' my-wild-and-rec ' ], +[ ' kind-right-handers ' , ' kind-right-hand ' ], +[ ' say-not-complexity ' , ' say-not-complex ' ], +[ ' the-function-of-prizes ' , ' the-function-of ' ], +[ ' positive-bias-look-into-the-dark ' , ' positive-bias-l ' ], +[ ' the-way-is-subtle ' , ' the-way-is-subt ' ], +[ ' is-overcoming-bias-important ' , ' how-important-i ' ], +[ ' the-futility-of-emergence ' , ' the-futility-of ' ], +[ ' bias-as-objectification ' , ' bias-as-objecti ' ], +[ ' mysterious-answers-to-mysterious-questions ' , ' mysterious-answ ' ], +[ ' bias-against-torture ' , ' bias-against-to ' ], +[ ' semantic-stopsigns ' , ' semantic-stopsi ' ], +[ ' exccess-trust-in-experts ' , ' exccess-trust-i ' ], +[ ' fake-causality ' , ' fake-causality ' ], +[ ' is-hybrid-vigor-iq-warm-and-fuzzy ' , ' is-hybrid-vigor ' ], +[ ' science-as-attire ' , ' science-as-lite ' ], +[ ' moral-bias-as-group-glue ' , ' moral-bias-as-g ' ], +[ ' guessing-the-teachers-password ' , ' guessing-the-te ' ], +[ ' nerds-as-bad-connivers ' , ' post ' ], +[ ' why-do-corporations-buy-insurance ' , ' why-do-corporat ' ], +[ ' fake-explanations ' , ' fake-explanatio ' ], +[ ' media-risk-bias-feedback ' , ' media-risk-bias ' ], +[ ' irrational-investment-disagreement ' , ' irrational-inve ' ], +[ ' is-molecular-nanotechnology-scientific ' , ' is-molecular-na ' ], +[ ' what-evidence-is-brevity ' , ' what-evidence-i ' ], +[ ' are-more-complicated-revelations-less-probable ' , ' are-more-compli ' ], +[ ' scientific-evidence-legal-evidence-rational-evidence ' , ' scientific-evid ' ], +[ ' pseudo-criticism ' , ' pseudo-criticis ' ], +[ ' are-brilliant-scientists-less-likely-to-cheat ' , ' are-brilliant-s ' ], +[ ' hindsight-devalues-science ' , ' hindsight-deval ' ], +[ ' sometimes-learning-is-very-slow ' , ' sometimes-learn ' ], +[ ' hindsight-bias ' , ' hindsight-bias ' ], +[ ' truth---the-neglected-virtue ' , ' truth---the-neg ' ], +[ ' one-argument-against-an-army ' , ' one-argument--1 ' ], +[ ' strangeness-heuristic ' , ' strangeness-heu ' ], +[ ' never-ever-forget-there-are-maniacs-out-there ' , ' never-ever-forg ' ], +[ ' update-yourself-incrementally ' , ' update-yourself ' ], +[ ' harry-potter-the-truth-seeker ' , ' harry-potter-th ' ], +[ ' dangers-of-political-betting-markets ' , ' dangers-of-poli ' ], +[ ' conservation-of-expected-evidence ' , ' conservation-of ' ], +[ ' biases-of-biography ' , ' biases-of-biogr ' ], +[ ' absence-of-evidence-iisi-evidence-of-absence ' , ' absence-of-evid ' ], +[ ' confident-proposer-bias ' , ' confident-propo ' ], +[ ' i-defy-the-data ' , ' i-defy-the-data ' ], +[ ' what-is-a-taboo-question ' , ' what-is-a-taboo ' ], +[ ' your-strength-as-a-rationalist ' , ' your-strength-a ' ], +[ ' accountable-public-opinion ' , ' accountable-pub ' ], +[ ' truth-bias ' , ' truth-bias ' ], +[ ' the-apocalypse-bet ' , ' the-apocalypse- ' ], +[ ' spencer-vs-wilde-on-truth-vs-lie ' , ' spencer-vs-wild ' ], +[ ' you-icani-face-reality ' , ' you-can-face-re ' ], +[ ' food-vs-sex-charity ' , ' food-vs-sex-cha ' ], +[ ' the-virtue-of-narrowness ' , ' the-virtue-of-n ' ], +[ ' wishful-investing ' , ' wishful-investi ' ], +[ ' the-proper-use-of-doubt ' , ' the-proper-use- ' ], +[ ' academic-political-bias ' , ' academic-politi ' ], +[ ' focus-your-uncertainty ' , ' focus-your-unce ' ], +[ ' disagreeing-about-cognitive-style-or-personality ' , ' disagreeing-abo ' ], +[ ' the-importance-of-saying-oops ' , ' the-importance- ' ], +[ ' the-real-inter-disciplinary-barrier ' , ' the-real-inter- ' ], +[ ' religions-claim-to-be-non-disprovable ' , ' religions-claim ' ], +[ ' is-advertising-the-playground-of-cognitive-bias ' , ' is-advertising- ' ], +[ ' anonymous-review-matters ' , ' anonymous-revie ' ], +[ ' if-you-wouldnt-want-profits-to-influence-this-blog-you-shouldnt-want-for-profit-schools ' , ' if-you-wouldnt- ' ], +[ ' belief-as-attire ' , ' belief-as-attir ' ], +[ ' overcoming-bias-hobby-virtue-or-moral-obligation ' , ' overcoming-bias ' ], +[ ' the-dogmatic-defense ' , ' dogmatism ' ], +[ ' professing-and-cheering ' , ' professing-and- ' ], +[ ' how-to-torture-a-reluctant-disagreer ' , ' how-to-torture- ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' rationalization ' , ' rationalization ' ], +[ ' lies-about-sex ' , ' lies-about-sex ' ], +[ ' what-evidence-filtered-evidence ' , ' what-evidence-f ' ], +[ ' a-moral-conundrum ' , ' a-moral-conundr ' ], +[ ' jewish-people-and-israel ' , ' jewish-people-a ' ], +[ ' the-bottom-line ' , ' the-bottom-line ' ], +[ ' false-findings-unretracted ' , ' false-findings- ' ], +[ ' how-to-convince-me-that-2-2-3 ' , ' how-to-convince ' ], +[ ' elusive-conflict-experts ' , ' elusive-conflic ' ], +[ ' 926-is-petrov-day ' , ' 926-is-petrov-d ' ], +[ ' drinking-our-own-kool-aid ' , ' drinking-our-ow ' ], +[ ' occams-razor ' , ' occams-razor ' ], +[ ' even-when-contrarians-win-they-lose ' , ' even-when-contr ' ], +[ ' einsteins-arrogance ' , ' einsteins-arrog ' ], +[ ' history-is-written-by-the-dissenters ' , ' history-is-writ ' ], +[ ' the-bright-side-of-life ' , ' always-look-on- ' ], +[ ' how-much-evidence-does-it-take ' , ' how-much-eviden ' ], +[ ' treat-me-like-a-statistic-but-please-be-nice-to-me ' , ' treat-me-like-a ' ], +[ ' small-business-overconfidence ' , ' small-business- ' ], +[ ' the-lens-that-sees-its-flaws ' , ' the-lens-that-s ' ], +[ ' why-so-little-model-checking-done-in-statistics ' , ' one-thing-that- ' ], +[ ' bounded-rationality-and-the-conjunction-fallacy ' , ' bounded-rationa ' ], +[ ' what-is-evidence ' , ' what-is-evidenc ' ], +[ ' radically-honest-meetings ' , ' radically-hones ' ], +[ ' burdensome-details ' , ' burdensome-deta ' ], +[ ' wielding-occams-razor ' , ' wielding-occams ' ], +[ ' your-future-has-detail ' , ' in-the-sept-7-s ' ], +[ ' medicine-has-been-overcoming-bias-too ' , ' medicine-has-be ' ], +[ ' conjunction-controversy-or-how-they-nail-it-down ' , ' conjunction-con ' ], +[ ' why-not-cut-medicine-all-the-way-to-zero ' , ' why-not-cut-med ' ], +[ ' why-teen-paternalism ' , ' why-teen-patern ' ], +[ ' conjunction-fallacy ' , ' conjunction-fal ' ], +[ ' beware-monkey-traps ' , ' beware-monkey-t ' ], +[ ' outputs-require-inputs ' , ' to-judge-output ' ], +[ ' kahnemans-planning-anecdote ' , ' kahnemans-plann ' ], +[ ' epidemiology-doubts ' , ' health-epidemio ' ], +[ ' planning-fallacy ' , ' planning-fallac ' ], +[ ' seven-sources-of-disagreement-cant-be-eliminated-by-overcoming-cognitive-bias ' , ' seven-sources-o ' ], +[ ' dont-trust-your-lying-eyes ' , ' dont-trust-your ' ], +[ ' scott-adams-on-bias ' , ' scott-adams-on- ' ], +[ ' naive-small-investors ' , ' naive-small-inv ' ], +[ ' not-open-to-compromise ' , ' not-open-to-com ' ], +[ ' why-im-blooking ' , ' why-im-blooking ' ], +[ ' noise-in-the-courtroom ' , ' noise-in-the-co ' ], +[ ' bias-awareness-bias-or-was-91101-a-black-swan ' , ' bias-awareness- ' ], +[ ' doublethink-choosing-to-be-biased ' , ' doublethink-cho ' ], +[ ' acquisitions-signal-ceo-dominance ' , ' acquisitions-si ' ], +[ ' human-evil-and-muddled-thinking ' , ' human-evil-and- ' ], +[ ' gotchas-are-not-biases ' , ' gotchas-are-not ' ], +[ ' rationality-and-the-english-language ' , ' rationality-and ' ], +[ ' never-confuse-could-and-would ' , ' never-confuse-c ' ], +[ ' what-evidence-reluctant-authors ' , ' what-evidence-r ' ], +[ ' applause-lights ' , ' applause-lights ' ], +[ ' what-evidence-dry-one-sided-arguments ' , ' what-evidence-d ' ], +[ ' bad-college-quality-incentives ' , ' bad-college-qua ' ], +[ ' case-study-of-cognitive-bias-induced-disagreements-on-petraeus-crocker ' , ' case-study-of-c ' ], +[ ' we-dont-really-want-your-participation ' , ' we-dont-really- ' ], +[ ' tyler-finds-overcoming-bias-iisi-important-for-others ' , ' tyler-cowen-fin ' ], +[ ' cut-medicine-in-half ' , ' cut-medicine-in ' ], +[ ' radical-honesty ' , ' radical-honesty ' ], +[ ' no-press-release-no-retraction ' , ' no-press-releas ' ], +[ ' the-crackpot-offer ' , ' the-crackpot-of ' ], +[ ' anchoring-and-adjustment ' , ' anchoring-and-a ' ], +[ ' what-evidence-bad-arguments ' , ' what-evidence-b ' ], +[ ' why-is-the-future-so-absurd ' , ' why-is-the-futu ' ], +[ ' strength-to-doubt-or-believe ' , ' strength-to-dou ' ], +[ ' availability ' , ' availability ' ], +[ ' the-deniers-dilemna ' , ' the-deniers-con ' ], +[ ' absurdity-heuristic-absurdity-bias ' , ' absurdity-heuri ' ], +[ ' medical-quality-bias ' , ' medical-quality ' ], +[ ' science-as-curiosity-stopper ' , ' science-as-curi ' ], +[ ' basic-research-as-signal ' , ' basic-research- ' ], +[ ' ueuxplainuwuorshipuiugnore ' , ' explainworshipi ' ], +[ ' the-pinch-hitter-syndrome-a-general-principle ' , ' the-pinch-hitte ' ], +[ ' what-evidence-ease-of-imagination ' , ' what-evidence-e ' ], +[ ' stranger-than-history ' , ' stranger-than-h ' ], +[ ' bias-as-objectification-ii ' , ' bias-as-objecti ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' what-wisdom-tradition ' , ' what-wisdom-tra ' ], +[ ' random-vs-certain-death ' , ' random-vs-certa ' ], +[ ' who-told-you-moral-questions-would-be-easy ' , ' who-told-you-mo ' ], +[ ' a-case-study-of-motivated-continuation ' , ' a-case-study-of ' ], +[ ' double-or-nothing-lawsuits-ten-years-on ' , ' double-or-nothi ' ], +[ ' torture-vs-dust-specks ' , ' torture-vs-dust ' ], +[ ' college-choice-futures ' , ' college-choice- ' ], +[ ' motivated-stopping-and-motivated-continuation ' , ' motivated-stopp ' ], +[ ' bay-area-bayesians-unite ' , ' meetup ' ], +[ ' dan-kahneman-puzzles-with-us ' , ' dan-kahneman-pu ' ], +[ ' why-are-individual-iq-differences-ok ' , ' why-is-individu ' ], +[ ' if-not-data-what ' , ' if-not-data-wha ' ], +[ ' no-one-knows-what-science-doesnt-know ' , ' no-one-knows-wh ' ], +[ ' dennetts-special-pleading ' , ' special-pleadin ' ], +[ ' double-illusion-of-transparency ' , ' double-illusion ' ], +[ ' why-im-betting-on-the-red-sox ' , ' why-im-betting- ' ], +[ ' intrade-nominee-advice ' , ' intrade-nominee ' ], +[ ' explainers-shoot-high-aim-low ' , ' explainers-shoo ' ], +[ ' distrust-effect-names ' , ' distrust-effect ' ], +[ ' the-fallacy-of-the-one-sided-bet-for-example-risk-god-torture-and-lottery-tickets ' , ' the-fallacy-of- ' ], +[ ' expecting-short-inferential-distances ' , ' inferential-dis ' ], +[ ' marriage-futures ' , ' marriage-future ' ], +[ ' self-anchoring ' , ' self-anchoring ' ], +[ ' how-close-lifes-birth ' , ' how-close-lifes ' ], +[ ' illusion-of-transparency-why-no-one-understands-you ' , ' illusion-of-tra ' ], +[ ' a-valid-concern ' , ' a-valid-concern ' ], +[ ' pascals-mugging-tiny-probabilities-of-vast-utilities ' , ' pascals-mugging ' ], +[ ' should-we-simplify-ourselves ' , ' should-we-simpl ' ], +[ ' hanson-joins-cult ' , ' hanson-joins-cu ' ], +[ ' congratulations-to-paris-hilton ' , ' congratulations ' ], +[ ' cut-us-military-in-half ' , ' cut-us-military ' ], +[ ' cant-say-no-spending ' , ' cant-say-no-spe ' ], +[ ' share-your-original-wisdom ' , ' original-wisdom ' ], +[ ' buy-health-not-medicine ' , ' buy-health-not- ' ], +[ ' hold-off-on-proposing-solutions ' , ' hold-off-solvin ' ], +[ ' doctors-kill ' , ' doctors-kill ' ], +[ ' the-logical-fallacy-of-generalization-from-fictional-evidence ' , ' fictional-evide ' ], +[ ' my-local-hospital ' , ' my-local-hospit ' ], +[ ' how-to-seem-and-be-deep ' , ' how-to-seem-and ' ], +[ ' megan-has-a-point ' , ' megan-has-a-poi ' ], +[ ' original-seeing ' , ' original-seeing ' ], +[ ' fatty-food-is-healthy ' , ' fatty-food-is-h ' ], +[ ' the-outside-the-box-box ' , ' outside-the-box ' ], +[ ' meta-honesty ' , ' meta-honesty ' ], +[ ' cached-thoughts ' , ' cached-thoughts ' ], +[ ' health-hopes-spring-eternal ' , ' health-hope-spr ' ], +[ ' do-we-believe-ieverythingi-were-told ' , ' do-we-believe-e ' ], +[ ' chinks-in-the-bayesian-armor ' , ' chinks-in-the-b ' ], +[ ' priming-and-contamination ' , ' priming-and-con ' ], +[ ' what-evidence-intuition ' , ' what-evidence-i ' ], +[ ' a-priori ' , ' a-priori ' ], +[ ' regulation-ratchet ' , ' what-evidence-b ' ], +[ ' no-one-can-exempt-you-from-rationalitys-laws ' , ' its-the-law ' ], +[ ' flexible-legal-similarity ' , ' flexible-legal- ' ], +[ ' singlethink ' , ' singlethink ' ], +[ ' what-evidence-divergent-explanations ' , ' what-evidence-d ' ], +[ ' the-meditation-on-curiosity ' , ' curiosity ' ], +[ ' pleasant-beliefs ' , ' pleasant-belief ' ], +[ ' isshoukenmei-make-a-desperate-effort ' , ' isshoukenmei-ma ' ], +[ ' author-misreads-expert-re-crowds ' , ' author-misreads ' ], +[ ' avoiding-your-beliefs-real-weak-points ' , ' avoiding-your-b ' ], +[ ' got-crisis ' , ' got-crisis ' ], +[ ' why-more-history-than-futurism ' , ' why-more-histor ' ], +[ ' we-change-our-minds-less-often-than-we-think ' , ' we-change-our-m ' ], +[ ' why-not-dating-coaches ' , ' why-not-dating- ' ], +[ ' a-rational-argument ' , ' a-rational-argu ' ], +[ ' can-school-debias ' , ' can-education-d ' ], +[ ' recommended-rationalist-reading ' , ' recommended-rat ' ], +[ ' confession-errors ' , ' confession-erro ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' precious-silence-lost ' , ' precious-silenc ' ], +[ ' leader-gender-bias ' , ' leader-gender-b ' ], +[ ' the-halo-effect ' , ' halo-effect ' ], +[ ' unbounded-scales-huge-jury-awards-futurism ' , ' unbounded-scale ' ], +[ ' what-insight-literature ' , ' what-insight-li ' ], +[ ' evaluability-and-cheap-holiday-shopping ' , ' evaluability ' ], +[ ' the-affect-heuristic ' , ' affect-heuristi ' ], +[ ' academia-clumps ' , ' academia-clumps ' ], +[ ' purpose-and-pragmatism ' , ' purpose-and-pra ' ], +[ ' lost-purposes ' , ' lost-purposes ' ], +[ ' intrade-fee-structure-discourages-selling-the-tails ' , ' intrade-fee-str ' ], +[ ' growing-into-atheism ' , ' growing-into-at ' ], +[ ' the-hidden-complexity-of-wishes ' , ' complex-wishes ' ], +[ ' aliens-among-us ' , ' aliens-among-us ' ], +[ ' leaky-generalizations ' , ' leaky-generaliz ' ], +[ ' good-intrade-bets ' , ' good-intrade-be ' ], +[ ' not-for-the-sake-of-happiness-alone ' , ' not-for-the-sak ' ], +[ ' interpreting-the-fed ' , ' interpreting-th ' ], +[ ' merry-hallowthankmas-eve ' , ' merry-hallowmas ' ], +[ ' truly-part-of-you ' , ' truly-part-of-y ' ], +[ ' overcoming-bias-after-one-year ' , ' overcoming-bi-1 ' ], +[ ' artificial-addition ' , ' artificial-addi ' ], +[ ' publication-bias-and-the-death-penalty ' , ' publication-bia ' ], +[ ' development-futures ' , ' development-fut ' ], +[ ' conjuring-an-evolution-to-serve-you ' , ' conjuring-an-ev ' ], +[ ' us-south-had-42-chance ' , ' us-south-had-42 ' ], +[ ' towards-a-typology-of-bias ' , ' towards-a-typol ' ], +[ ' the-simple-math-of-everything ' , ' the-simple-math ' ], +[ ' my-guatemala-interviews ' , ' my-guatemala-in ' ], +[ ' no-evolutions-for-corporations-or-nanodevices ' , ' no-evolution-fo ' ], +[ ' inaturei-endorses-human-extinction ' , ' terrible-optimi ' ], +[ ' evolving-to-extinction ' , ' evolving-to-ext ' ], +[ ' dont-do-something ' , ' dont-do-somethi ' ], +[ ' terminal-values-and-instrumental-values ' , ' terminal-values ' ], +[ ' treatment-futures ' , ' treatment-futur ' ], +[ ' thou-art-godshatter ' , ' thou-art-godsha ' ], +[ ' implicit-conditionals ' , ' implicit-condit ' ], +[ ' protein-reinforcement-and-dna-consequentialism ' , ' protein-reinfor ' ], +[ ' polarized-usa ' , ' polarized-usa ' ], +[ ' evolutionary-psychology ' , ' evolutionary-ps ' ], +[ ' adaptation-executers-not-fitness-maximizers ' , ' adaptation-exec ' ], +[ ' overcoming-bias-at-work-for-engineers ' , ' overcoming-bias ' ], +[ ' fake-optimization-criteria ' , ' fake-optimizati ' ], +[ ' dawes-on-therapy ' , ' dawes-on-psycho ' ], +[ ' friendly-ai-guide ' , ' fake-utility-fu ' ], +[ ' fake-morality ' , ' fake-morality ' ], +[ ' seat-belts-work ' , ' seat-belts-work ' ], +[ ' fake-selfishness ' , ' fake-selfishnes ' ], +[ ' inconsistent-paternalism ' , ' inconsistent-pa ' ], +[ ' the-tragedy-of-group-selectionism ' , ' group-selection ' ], +[ ' are-the-self-righteous-righteous ' , ' are-the-self-ri ' ], +[ ' beware-of-stephen-j-gould ' , ' beware-of-gould ' ], +[ ' college-admission-futures ' , ' college-admissi ' ], +[ ' natural-selections-speed-limit-and-complexity-bound ' , ' natural-selecti ' ], +[ ' -a-test-for-political-prediction-markets ' , ' a-test-for-poli ' ], +[ ' passionately-wrong ' , ' passionately-wr ' ], +[ ' evolutions-are-stupid-but-work-anyway ' , ' evolutions-are- ' ], +[ ' serious-unconventional-de-grey ' , ' serious-unconve ' ], +[ ' the-wonder-of-evolution ' , ' the-wonder-of-e ' ], +[ ' hospice-beats-hospital ' , ' hospice-beats-h ' ], +[ ' an-alien-god ' , ' an-alien-god ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' how-much-defer-to-experts ' , ' how-much-defer- ' ], +[ ' the-right-belief-for-the-wrong-reasons ' , ' the-right-belie ' ], +[ ' fake-justification ' , ' fake-justificat ' ], +[ ' a-terrifying-halloween-costume ' , ' a-terrifying-ha ' ], +[ ' honest-teen-paternalism ' , ' teen-paternalis ' ], +[ ' my-strange-beliefs ' , ' my-strange-beli ' ], +[ ' cultish-countercultishness ' , ' cultish-counter ' ], +[ ' to-lead-you-must-stand-up ' , ' stand-to-lead ' ], +[ ' econ-of-longer-lives ' , ' neglected-pro-l ' ], +[ ' lonely-dissent ' , ' lonely-dissent ' ], +[ ' on-expressing-your-concerns ' , ' express-concern ' ], +[ ' too-much-hope ' , ' too-much-hope ' ], +[ ' aschs-conformity-experiment ' , ' aschs-conformit ' ], +[ ' the-amazing-virgin-pregnancy ' , ' amazing-virgin ' ], +[ ' procrastination ' , ' procrastination ' ], +[ ' testing-hillary-clintons-oil-claim ' , ' testing-hillary ' ], +[ ' zen-and-the-art-of-rationality ' , ' zen-and-the-art ' ], +[ ' effortless-technique ' , ' effortless-tech ' ], +[ ' false-laughter ' , ' false-laughter ' ], +[ ' obligatory-self-mockery ' , ' obligatory-self ' ], +[ ' the-greatest-gift-the-best-exercise ' , ' the-best-exerci ' ], +[ ' two-cult-koans ' , ' cult-koans ' ], +[ ' interior-economics ' , ' interior-econom ' ], +[ ' politics-and-awful-art ' , ' politics-and-aw ' ], +[ ' judgment-can-add-accuracy ' , ' judgment-can-ad ' ], +[ ' the-litany-against-gurus ' , ' the-litany-agai ' ], +[ ' the-root-of-all-political-stupidity ' , ' the-root-of-all ' ], +[ ' guardians-of-ayn-rand ' , ' ayn-rand ' ], +[ ' power-corrupts ' , ' power-corrupts ' ], +[ ' teen-revolution-and-evolutionary-psychology ' , ' teen-revolution ' ], +[ ' gender-tax ' , ' gender-tax ' ], +[ ' guardians-of-the-gene-pool ' , ' guardians-of--1 ' ], +[ ' battle-of-the-election-forecasters ' , ' battle-of-the-e ' ], +[ ' guardians-of-the-truth ' , ' guardians-of-th ' ], +[ ' hug-the-query ' , ' hug-the-query ' ], +[ ' economist-judgment ' , ' economist-judgm ' ], +[ ' justly-acquired-endowment-taxing-as-punishment-or-as-a-way-to-raise-money ' , ' justly-acquired ' ], +[ ' argument-screens-off-authority ' , ' argument-screen ' ], +[ ' give-juries-video-recordings-of-testimony ' , ' give-juries-vid ' ], +[ ' reversed-stupidity-is-not-intelligence ' , ' reversed-stupid ' ], +[ ' tax-the-tall ' , ' tax-the-tall ' ], +[ ' every-cause-wants-to-be-a-cult ' , ' every-cause-wan ' ], +[ ' does-healthcare-do-any-good-at-all ' , ' does-healthcare ' ], +[ ' art-and-moral-responsibility ' , ' art-and-moral-r ' ], +[ ' misc-meta ' , ' misc-meta ' ], +[ ' it-is-good-to-exist ' , ' it-is-good-to-e ' ], +[ ' the-robbers-cave-experiment ' , ' the-robbers-cav ' ], +[ ' medicine-has-been-overcoming-bias-too ' , ' medicine-has-be ' ], +[ ' when-none-dare-urge-restraint ' , ' when-none-dare ' ], +[ ' modules-signals-and-guilt ' , ' modules-signals ' ], +[ ' evaporative-cooling-of-group-beliefs ' , ' evaporative-coo ' ], +[ ' doctor-hypocrisy ' , ' doctors-lie ' ], +[ ' fake-utility-functions ' , ' fake-utility-fu ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' fake-fake-utility-functions ' , ' fake-fake-utili ' ], +[ ' ethical-shortsightedness ' , ' ethical-shortsi ' ], +[ ' heroic-job-bias ' , ' heroic-job-bias ' ], +[ ' uncritical-supercriticality ' , ' supercritical-u ' ], +[ ' resist-the-happy-death-spiral ' , ' resist-the-happ ' ], +[ ' baby-selling ' , ' baby-selling ' ], +[ ' affective-death-spirals ' , ' affective-death ' ], +[ ' mere-messiahs ' , ' mere-messiahs ' ], +[ ' superhero-bias ' , ' superhero-bias ' ], +[ ' ob-meetup-millbrae-thu-21-feb-7pm ' , ' ob-meetup-millb ' ], +[ ' newcombs-problem-and-regret-of-rationality ' , ' newcombs-proble ' ], +[ ' dark-police ' , ' privacy-lost ' ], +[ ' contingent-truth-value ' , ' contingent-trut ' ], +[ ' deliberative-prediction-markets----a-reply ' , ' deliberative-pr ' ], +[ ' something-to-protect ' , ' something-to-pr ' ], +[ ' deliberation-in-prediction-markets ' , ' deliberation-in ' ], +[ ' trust-in-bayes ' , ' trust-in-bayes ' ], +[ ' predictocracy----a-preliminary-response ' , ' predictocracy- ' ], +[ ' the-intuitions-behind-utilitarianism ' , ' the-intuitions ' ], +[ ' voters-want-simplicity ' , ' voters-want-sim ' ], +[ ' predictocracy ' , ' predictocracy ' ], +[ ' rationality-quotes-9 ' , ' quotes-9 ' ], +[ ' knowing-your-argumentative-limitations-or-one-rationalists-modus-ponens-is-anothers-modus-tollens ' , ' knowing-your-ar ' ], +[ ' problems-with-prizes ' , ' problems-with-p ' ], +[ ' rationality-quotes-8 ' , ' quotes-8 ' ], +[ ' acceptable-casualties ' , ' acceptable-casu ' ], +[ ' rationality-quotes-7 ' , ' quotes-7 ' ], +[ ' cfo-overconfidence ' , ' ceo-overconfide ' ], +[ ' rationality-quotes-6 ' , ' quotes-6 ' ], +[ ' rationality-quotes-5 ' , ' quotes-5 ' ], +[ ' connections-versus-insight ' , ' connections-ver ' ], +[ ' circular-altruism ' , ' circular-altrui ' ], +[ ' for-discount-rates ' , ' protecting-acro ' ], +[ ' against-discount-rates ' , ' against-discoun ' ], +[ ' allais-malaise ' , ' allais-malaise ' ], +[ ' mandatory-sensitivity-training-fails ' , ' mandatory-sensi ' ], +[ ' rationality-quotes-4 ' , ' quotes-4 ' ], +[ ' zut-allais ' , ' zut-allais ' ], +[ ' the-allais-paradox ' , ' allais-paradox ' ], +[ ' nesse-on-academia ' , ' nesse-on-academ ' ], +[ ' antidepressant-publication-bias ' , ' antidepressant ' ], +[ ' rationality-quotes-3 ' , ' rationality-quo ' ], +[ ' rationality-quotes-2 ' , ' quotes-2 ' ], +[ ' just-enough-expertise ' , ' trolls-on-exper ' ], +[ ' rationality-quotes-1 ' , ' quotes-1 ' ], +[ ' trust-in-math ' , ' trust-in-math ' ], +[ ' economist-as-scrooge ' , ' economist-as-sc ' ], +[ ' beautiful-probability ' , ' beautiful-proba ' ], +[ ' leading-bias-researcher-turns-out-to-be-biased-renounces-result ' , ' leading-bias-re ' ], +[ ' is-reality-ugly ' , ' is-reality-ugly ' ], +[ ' dont-choose-a-president-the-way-youd-choose-an-assistant-regional-manager ' , ' dont-choose-a-p ' ], +[ ' expecting-beauty ' , ' expecting-beaut ' ], +[ ' how-to-fix-wage-bias ' , ' profit-by-corre ' ], +[ ' beautiful-math ' , ' beautiful-math ' ], +[ ' 0-and-1-are-not-probabilities ' , ' 0-and-1-are-not ' ], +[ ' once-more-with-feeling ' , ' once-more-with ' ], +[ ' political-inequality ' , ' political-inequ ' ], +[ ' infinite-certainty ' , ' infinite-certai ' ], +[ ' more-presidential-decision-markets ' , ' more-presidenti ' ], +[ ' experiencing-the-endowment-effect ' , ' experiencing-th ' ], +[ ' absolute-authority ' , ' absolute-author ' ], +[ ' social-scientists-know-lots ' , ' social-scientis ' ], +[ ' the-fallacy-of-gray ' , ' gray-fallacy ' ], +[ ' are-we-just-pumping-against-entropy-or-can-we-win ' , ' are-we-just-pum ' ], +[ ' art-trust-and-betrayal ' , ' art-trust-and-b ' ], +[ ' nuked-us-futures ' , ' nuked-us-future ' ], +[ ' but-theres-still-a-chance-right ' , ' still-a-chance ' ], +[ ' a-failed-just-so-story ' , ' a-failed-just-s ' ], +[ ' presidential-decision-markets ' , ' presidential-de ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' rational-vs-scientific-ev-psych ' , ' rational-vs-sci ' ], +[ ' weekly-exercises ' , ' weekly-exercise ' ], +[ ' yes-it-can-be-rational-to-vote-in-presidential-elections ' , ' yes-it-can-be-r ' ], +[ ' debugging-comments ' , ' debugging-comme ' ], +[ ' stop-voting-for-nincompoops ' , ' stop-voting-for ' ], +[ ' i-dare-you-bunzl ' , ' in-yesterdays-p ' ], +[ ' the-american-system-and-misleading-labels ' , ' the-american-sy ' ], +[ ' some-structural-biases-of-the-political-system ' , ' some-structural ' ], +[ ' a-politicians-job ' , ' a-politicians-j ' ], +[ ' the-ordering-of-authors-names-in-academic-publications ' , ' the-ordering-of ' ], +[ ' the-two-party-swindle ' , ' the-two-party-s ' ], +[ ' posting-on-politics ' , ' posting-on-poli ' ], +[ ' searching-for-bayes-structure ' , ' bayes-structure ' ], +[ ' perpetual-motion-beliefs ' , ' perpetual-motio ' ], +[ ' ignoring-advice ' , ' ignoring-advice ' ], +[ ' the-second-law-of-thermodynamics-and-engines-of-cognition ' , ' second-law ' ], +[ ' leave-a-line-of-retreat ' , ' leave-retreat ' ], +[ ' more-referee-bias ' , ' more-referee-bi ' ], +[ ' superexponential-conceptspace-and-simple-words ' , ' superexp-concep ' ], +[ ' my-favorite-liar ' , ' my-favorite-lia ' ], +[ ' mutual-information-and-density-in-thingspace ' , ' mutual-informat ' ], +[ ' if-self-fulfilling-optimism-is-wrong-i-dont-wanna-be-right ' , ' if-self-fulfill ' ], +[ ' entropy-and-short-codes ' , ' entropy-codes ' ], +[ ' more-moral-wiggle-room ' , ' more-moral-wigg ' ], +[ ' where-to-draw-the-boundary ' , ' where-boundary ' ], +[ ' the-hawthorne-effect ' , ' the-hawthorne-e ' ], +[ ' categories-and-information-theory ' , ' a-bayesian-view ' ], +[ ' arguing-by-definition ' , ' arguing-by-defi ' ], +[ ' against-polish ' , ' against-polish ' ], +[ ' colorful-character-again ' , ' colorful-charac ' ], +[ ' sneaking-in-connotations ' , ' sneak-connotati ' ], +[ ' nephew-versus-nepal-charity ' , ' nephews-versus ' ], +[ ' categorizing-has-consequences ' , ' category-conseq ' ], +[ ' the-public-intellectual-plunge ' , ' the-public-inte ' ], +[ ' fallacies-of-compression ' , ' compress-fallac ' ], +[ ' with-blame-comes-hope ' , ' with-blame-come ' ], +[ ' relative-vs-absolute-rationality ' , ' relative-vs-abs ' ], +[ ' replace-the-symbol-with-the-substance ' , ' replace-symbol ' ], +[ ' talking-versus-trading ' , ' comparing-delib ' ], +[ ' taboo-your-words ' , ' taboo-words ' ], +[ ' why-just-believe ' , ' why-just-believ ' ], +[ ' classic-sichuan-in-millbrae-thu-feb-21-7pm ' , ' millbrae-thu-fe ' ], +[ ' empty-labels ' , ' empty-labels ' ], +[ ' is-love-something-more ' , ' is-love-somethi ' ], +[ ' the-argument-from-common-usage ' , ' common-usage ' ], +[ ' pod-people-paternalism ' , ' pod-people-pate ' ], +[ ' feel-the-meaning ' , ' feel-meaning ' ], +[ ' dinos-on-the-moon ' , ' dinos-on-the-mo ' ], +[ ' disputing-definitions ' , ' disputing-defin ' ], +[ ' what-is-worth-study ' , ' what-is-worth-s ' ], +[ ' how-an-algorithm-feels-from-inside ' , ' algorithm-feels ' ], +[ ' nanotech-views-value-driven ' , ' nanotech-views ' ], +[ ' neural-categories ' , ' neural-categori ' ], +[ ' believing-too-little ' , ' believing-too-l ' ], +[ ' disguised-queries ' , ' disguised-queri ' ], +[ ' eternal-medicine ' , ' eternal-medicin ' ], +[ ' the-cluster-structure-of-thingspace ' , ' thingspace-clus ' ], +[ ' typicality-and-asymmetrical-similarity ' , ' typicality-and ' ], +[ ' what-wisdom-silence ' , ' what-wisdom-sil ' ], +[ ' similarity-clusters ' , ' similarity-clus ' ], +[ ' buy-now-or-forever-hold-your-peace ' , ' buy-now-or-fore ' ], +[ ' extensions-and-intensions ' , ' extensions-inte ' ], +[ ' lets-do-like-them ' , ' lets-do-like-th ' ], +[ ' words-as-hidden-inferences ' , ' words-as-hidden ' ], +[ ' predictocracy-vs-futarchy ' , ' predictocracy-v ' ], +[ ' the-parable-of-hemlock ' , ' hemlock-parable ' ], +[ ' merger-decision-markets ' , ' merger-decision ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' the-parable-of-the-dagger ' , ' dagger-parable ' ], +[ ' futarchy-vs-predictocracy ' , ' futarchy-vs-pre ' ], +[ ' against-news ' , ' against-news ' ], +[ ' angry-atoms ' , ' angry-atoms ' ], +[ ' hand-vs-fingers ' , ' hand-vs-fingers ' ], +[ ' impotence-of-belief-in-bias ' , ' impotence-of-be ' ], +[ ' initiation-ceremony ' , ' initiation-cere ' ], +[ ' cash-increases-accuracy ' , ' cash-clears-the ' ], +[ ' to-spread-science-keep-it-secret ' , ' spread-science ' ], +[ ' ancient-political-self-deception ' , ' ancient-politic ' ], +[ ' scarcity ' , ' scarcity ' ], +[ ' fantasy-and-reality-substitutes-or-complements ' , ' fantasy-and-rea ' ], +[ ' is-humanism-a-religion-substitute ' , ' is-humanism-rel ' ], +[ ' showing-that-you-care ' , ' showing-that-yo ' ], +[ ' amazing-breakthrough-day-april-1st ' , ' amazing-breakth ' ], +[ ' correction-ny-ob-meetup-13-astor-place-25 ' , ' correction-ny-o ' ], +[ ' religious-cohesion ' , ' religious-cohes ' ], +[ ' the-beauty-of-settled-science ' , ' beauty-settled ' ], +[ ' where-want-fewer-women ' , ' where-want-less ' ], +[ ' new-york-ob-meetup-ad-hoc-on-monday-mar-24-6pm ' , ' new-york-ob-mee ' ], +[ ' if-you-demand-magic-magic-wont-help ' , ' against-magic ' ], +[ ' biases-in-processing-political-information ' , ' biases-in-proce ' ], +[ ' bind-yourself-to-reality ' , ' bind-yourself-t ' ], +[ ' boards-of-advisors-dont-advise-do-board ' , ' boards-of-advis ' ], +[ ' joy-in-discovery ' , ' joy-in-discover ' ], +[ ' joy-in-the-merely-real ' , ' joy-in-the-real ' ], +[ ' sincerity-is-overrated ' , ' sincerity-is-wa ' ], +[ ' rationalists-lets-make-a-movie ' , ' rationalists-le ' ], +[ ' savanna-poets ' , ' savanna-poets ' ], +[ ' biases-and-investing ' , ' biases-and-inve ' ], +[ ' morality-is-overrated ' , ' unwanted-morali ' ], +[ ' fake-reductionism ' , ' fake-reductioni ' ], +[ ' theyre-only-tokens ' , ' theyre-only-tok ' ], +[ ' explaining-vs-explaining-away ' , ' explaining-away ' ], +[ ' reductionism ' , ' reductionism ' ], +[ ' a-few-quick-links ' , ' a-few-quick-lin ' ], +[ ' qualitatively-confused ' , ' qualitatively-c ' ], +[ ' the-kind-of-project-to-watch ' , ' the-project-to ' ], +[ ' penguicon-blook ' , ' penguicon-blook ' ], +[ ' one-million-visits ' , ' one-million-vis ' ], +[ ' distinguish-info-analysis-belief-action ' , ' distinguish-inf ' ], +[ ' the-quotation-is-not-the-referent ' , ' quote-not-refer ' ], +[ ' neglecting-conceptual-research ' , ' scott-aaronson ' ], +[ ' probability-is-in-the-mind ' , ' mind-probabilit ' ], +[ ' limits-to-physics-insight ' , ' limits-to-physi ' ], +[ ' mind-projection-fallacy ' , ' mind-projection ' ], +[ ' mind-projection-by-default ' , ' mpf-by-default ' ], +[ ' uninformative-experience ' , ' uninformative-e ' ], +[ ' righting-a-wrong-question ' , ' righting-a-wron ' ], +[ ' wrong-questions ' , ' wrong-questions ' ], +[ ' dissolving-the-question ' , ' dissolving-the ' ], +[ ' bias-and-power ' , ' biased-for-and ' ], +[ ' gary-gygax-annihilated-at-69 ' , ' gary-gygax-anni ' ], +[ ' wilkinson-on-paternalism ' , ' wilkinson-on-pa ' ], +[ ' 37-ways-that-words-can-be-wrong ' , ' wrong-words ' ], +[ ' overvaluing-ideas ' , ' overvaluing-ide ' ], +[ ' reject-random-beliefs ' , ' reject-random-b ' ], +[ ' variable-question-fallacies ' , ' variable-questi ' ], +[ ' rationality-quotes-11 ' , ' rationality-q-1 ' ], +[ ' human-capital-puzzle-explained ' , ' human-capital-p ' ], +[ ' rationality-quotes-10 ' , ' rationality-quo ' ], +[ ' words-as-mental-paintbrush-handles ' , ' mental-paintbru ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' framing-problems-as-separate-from-people ' , ' framing-problem ' ], +[ ' conditional-independence-and-naive-bayes ' , ' conditional-ind ' ], +[ ' be-biased-to-be-happy ' , ' be-biased-to-be ' ], +[ ' optimism-bias-desired ' , ' optimism-bias-d ' ], +[ ' decoherent-essences ' , ' decoherent-esse ' ], +[ ' self-copying-factories ' , ' replication-bre ' ], +[ ' decoherence-is-pointless ' , ' pointless-decoh ' ], +[ ' charm-beats-accuracy ' , ' charm-beats-acc ' ], +[ ' the-conscious-sorites-paradox ' , ' conscious-sorit ' ], +[ ' decoherent-details ' , ' decoherent-deta ' ], +[ ' on-being-decoherent ' , ' on-being-decohe ' ], +[ ' quantum-orthodoxy ' , ' quantum-quotes ' ], +[ ' if-i-had-a-million ' , ' if-i-had-a-mill ' ], +[ ' where-experience-confuses-physicists ' , ' where-experienc ' ], +[ ' thou-art-decoherent ' , ' the-born-probab ' ], +[ ' blaming-the-unlucky ' , ' blaming-the-unl ' ], +[ ' where-physics-meets-experience ' , ' physics-meets-e ' ], +[ ' early-scientists-chose-influence-over-credit ' , ' early-scientist ' ], +[ ' which-basis-is-more-fundamental ' , ' which-basis-is ' ], +[ ' a-model-disagreement ' , ' a-model-disagre ' ], +[ ' the-so-called-heisenberg-uncertainty-principle ' , ' heisenberg ' ], +[ ' caplan-pulls-along-ropes ' , ' caplan-pulls-al ' ], +[ ' decoherence ' , ' decoherence ' ], +[ ' paternalism-parable ' , ' paternalism-par ' ], +[ ' three-dialogues-on-identity ' , ' identity-dialog ' ], +[ ' on-philosophers ' , ' on-philosophers ' ], +[ ' zombies-the-movie ' , ' zombie-movie ' ], +[ ' schwitzgebel-thoughts ' , ' schwitzgebel-th ' ], +[ ' identity-isnt-in-specific-atoms ' , ' identity-isnt-i ' ], +[ ' elevator-myths ' , ' elevator-myths ' ], +[ ' no-individual-particles ' , ' no-individual-p ' ], +[ ' is-she-just-friendly ' , ' is-she-just-bei ' ], +[ ' feynman-paths ' , ' feynman-paths ' ], +[ ' kids-parents-disagree-on-spouses ' , ' kids-parents-di ' ], +[ ' the-quantum-arena ' , ' quantum-arena ' ], +[ ' classical-configuration-spaces ' , ' conf-space ' ], +[ ' how-to-vs-what-to ' , ' how-to-vs-what ' ], +[ ' can-you-prove-two-particles-are-identical ' , ' identical-parti ' ], +[ ' naming-beliefs ' , ' naming-beliefs ' ], +[ ' where-philosophy-meets-science ' , ' philosophy-meet ' ], +[ ' distinct-configurations ' , ' distinct-config ' ], +[ ' conformity-questions ' , ' conformity-ques ' ], +[ ' conformity-myths ' , ' conformity-myth ' ], +[ ' joint-configurations ' , ' joint-configura ' ], +[ ' configurations-and-amplitude ' , ' configurations ' ], +[ ' prevention-costs ' , ' prevention-cost ' ], +[ ' quantum-explanations ' , ' quantum-explana ' ], +[ ' inhuman-rationality ' , ' inhuman-rationa ' ], +[ ' belief-in-the-implied-invisible ' , ' implied-invisib ' ], +[ ' endearing-sincerity ' , ' sincerity-i-lik ' ], +[ ' gazp-vs-glut ' , ' gazp-vs-glut ' ], +[ ' the-generalized-anti-zombie-principle ' , ' anti-zombie-pri ' ], +[ ' anxiety-about-what-is-true ' , ' anxiety-about-w ' ], +[ ' ramone-on-knowing-god ' , ' ramone-on-knowi ' ], +[ ' zombie-responses ' , ' zombies-ii ' ], +[ ' brownlee-on-selling-anxiety ' , ' brownlee-on-sel ' ], +[ ' zombies-zombies ' , ' zombies ' ], +[ ' reductive-reference ' , ' reductive-refer ' ], +[ ' arbitrary-silliness ' , ' arbitrary-silli ' ], +[ ' brain-breakthrough-its-made-of-neurons ' , ' brain-breakthro ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' why-i-dont-like-bayesian-statistics ' , ' why-i-dont-like ' ], +[ ' beware-of-brain-images ' , ' beware-of-brain ' ], +[ ' heat-vs-motion ' , ' heat-vs-motion ' ], +[ ' physics-your-brain-and-you ' , ' physics-your-br ' ], +[ ' a-premature-word-on-ai ' , ' an-ai-new-timer ' ], +[ ' ai-old-timers ' , ' roger-shank-ai ' ], +[ ' empty-space ' , ' empty-space ' ], +[ ' class-project ' , ' class-project ' ], +[ ' einsteins-superpowers ' , ' einsteins-super ' ], +[ ' intro-to-innovation ' , ' intro-to-innova ' ], +[ ' timeless-causality ' , ' timeless-causal ' ], +[ ' overconfidence-paternalism ' , ' paul-graham-off ' ], +[ ' timeless-beauty ' , ' timeless-beauty ' ], +[ ' lazy-lineup-study ' , ' why-is-this-so ' ], +[ ' timeless-physics ' , ' timeless-physic ' ], +[ ' the-end-of-time ' , ' the-end-of-time ' ], +[ ' 2nd-annual-roberts-podcast ' , ' 2nd-annual-robe ' ], +[ ' who-shall-we-honor ' , ' who-should-we-h ' ], +[ ' relative-configuration-space ' , ' relative-config ' ], +[ ' beware-identity ' , ' beware-identity ' ], +[ ' prediction-markets-and-insider-trading ' , ' prediction-mark ' ], +[ ' a-broken-koan ' , ' a-broken-koan ' ], +[ ' machs-principle-anti-epiphenomenal-physics ' , ' machs-principle ' ], +[ ' lying-to-kids ' , ' lying-to-kids ' ], +[ ' my-childhood-role-model ' , ' my-childhood-ro ' ], +[ ' that-alien-message ' , ' faster-than-ein ' ], +[ ' anthropic-breakthrough ' , ' anthropic-break ' ], +[ ' einsteins-speed ' , ' einsteins-speed ' ], +[ ' transcend-or-die ' , ' transcend-or-di ' ], +[ ' far-future-disagreement ' , ' far-future-disa ' ], +[ ' faster-than-science ' , ' faster-than-sci ' ], +[ ' conference-on-global-catastrophic-risks ' , ' conference-on-g ' ], +[ ' biting-evolution-bullets ' , ' biting-evolutio ' ], +[ ' changing-the-definition-of-science ' , ' changing-the-de ' ], +[ ' no-safe-defense-not-even-science ' , ' no-defenses ' ], +[ ' bounty-slander ' , ' bounty-slander ' ], +[ ' idea-futures-in-lumpaland ' , ' idea-futures-in ' ], +[ ' do-scientists-already-know-this-stuff ' , ' do-scientists-a ' ], +[ ' lobbying-for-prediction-markets ' , ' lobbying-for-pr ' ], +[ ' science-isnt-strict-ienoughi ' , ' science-isnt-st ' ], +[ ' lumpaland-parable ' , ' lumpaland-parab ' ], +[ ' when-science-cant-help ' , ' when-science-ca ' ], +[ ' honest-politics ' , ' honest-politics ' ], +[ ' science-doesnt-trust-your-rationality ' , ' science-doesnt ' ], +[ ' sleepy-fools ' , ' sleepy-fools ' ], +[ ' the-dilemma-science-or-bayes ' , ' science-or-baye ' ], +[ ' the-failures-of-eld-science ' , ' eld-science ' ], +[ ' condemned-to-repeat-finance-past ' , ' condemned-to-re ' ], +[ ' many-worlds-one-best-guess ' , ' many-worlds-one ' ], +[ ' why-quantum ' , ' why-quantum ' ], +[ ' happy-conservatives ' , ' happy-conservat ' ], +[ ' if-many-worlds-had-come-first ' , ' if-many-worlds ' ], +[ ' elusive-placebos ' , ' elusive-placebo ' ], +[ ' collapse-postulates ' , ' collapse-postul ' ], +[ ' faith-in-docs ' , ' faith-in-docs ' ], +[ ' quantum-non-realism ' , ' eppur-si-moon ' ], +[ ' iexpelledi-beats-isickoi ' , ' expelled-beats ' ], +[ ' decoherence-is-falsifiable-and-testable ' , ' mwi-is-falsifia ' ], +[ ' guilt-by-association ' , ' guilt-and-all-b ' ], +[ ' decoherence-is-simple ' , ' mwi-is-simple ' ], +[ ' keeping-math-real ' , ' keeping-math-re ' ], +[ ' spooky-action-at-a-distance-the-no-communication-theorem ' , ' spooky-action-a ' ], +[ ' walking-on-grass-others ' , ' walking-on-gras ' ], +[ ' bells-theorem-no-epr-reality ' , ' bells-theorem-n ' ], +[ ' beware-transfusions ' , ' beware-blood-tr ' ], +[ ' entangled-photons ' , ' entangled-photo ' ], +[ ' beware-supplements ' , ' beware-suppleme ' ], +[ ' decoherence-as-projection ' , ' projection ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' im-in-boston ' , ' im-in-boston ' ], +[ ' the-born-probabilities ' , ' the-born-prob-1 ' ], +[ ' experience-increases-overconfidence ' , ' the-latest-jour ' ], +[ ' the-moral-void ' , ' moral-void ' ], +[ ' what-would-you-do-without-morality ' , ' without-moralit ' ], +[ ' average-your-guesses ' , ' average-your-gu ' ], +[ ' the-opposite-sex ' , ' opposite-sex ' ], +[ ' the-conversation-so-far ' , ' the-conversatio ' ], +[ ' glory-vs-relations ' , ' glory-vs-relati ' ], +[ ' 2-place-and-1-place-words ' , ' 2-place-and-1-p ' ], +[ ' caution-kills-when-fighting-malaria ' , ' caution-kills-w ' ], +[ ' to-what-expose-kids ' , ' to-what-expose ' ], +[ ' no-universally-compelling-arguments ' , ' no-universally ' ], +[ ' the-design-space-of-minds-in-general ' , ' minds-in-genera ' ], +[ ' should-bad-boys-win ' , ' why-do-psychopa ' ], +[ ' the-psychological-unity-of-humankind ' , ' psychological-u ' ], +[ ' eliezers-meta-level-determinism ' , ' eliezers-meta-l ' ], +[ ' optimization-and-the-singularity ' , ' optimization-an ' ], +[ ' tyler-vid-on-disagreement ' , ' tyler-vid-on-di ' ], +[ ' are-meta-views-outside-views ' , ' are-meta-views ' ], +[ ' surface-analogies-and-deep-causes ' , ' surface-analogi ' ], +[ ' parsing-the-parable ' , ' parsing-the-par ' ], +[ ' the-outside-views-domain ' , ' when-outside-vi ' ], +[ ' outside-view-of-singularity ' , ' singularity-out ' ], +[ ' heading-toward-morality ' , ' toward-morality ' ], +[ ' la-602-vs-rhic-review ' , ' la-602-vs-rhic ' ], +[ ' history-of-transition-inequality ' , ' singularity-ine ' ], +[ ' britain-was-too-small ' , ' britain-was-too ' ], +[ ' natural-genocide ' , ' natural-genocid ' ], +[ ' what-is-the-probability-of-the-large-hadron-collider-destroying-the-universe ' , ' what-is-the-pro ' ], +[ ' ghosts-in-the-machine ' , ' ghosts-in-the-m ' ], +[ ' gratitude-decay ' , ' gratitude-decay ' ], +[ ' loud-bumpers ' , ' loud-bumpers ' ], +[ ' grasping-slippery-things ' , ' grasping-slippe ' ], +[ ' in-bias-meta-is-max ' , ' meta-is-max---b ' ], +[ ' passing-the-recursive-buck ' , ' pass-recursive ' ], +[ ' in-innovation-meta-is-max ' , ' meta-is-max---i ' ], +[ ' the-ultimate-source ' , ' the-ultimate-so ' ], +[ ' possibility-and-could-ness ' , ' possibility-and ' ], +[ ' joe-epstein-on-youth ' , ' joe-epstein-on ' ], +[ ' causality-and-moral-responsibility ' , ' causality-and-r ' ], +[ ' anti-depressants-fail ' , ' anti-depressant ' ], +[ ' quantum-mechanics-and-personal-identity ' , ' qm-and-identity ' ], +[ ' and-the-winner-is-many-worlds ' , ' mwi-wins ' ], +[ ' quantum-physics-revealed-as-non-mysterious ' , ' quantum-physics ' ], +[ ' an-intuitive-explanation-of-quantum-mechanics ' , ' an-intuitive-ex ' ], +[ ' prediction-market-based-electoral-map-forecast ' , ' prediction-mark ' ], +[ ' tv-is-porn ' , ' tv-is-porn ' ], +[ ' the-quantum-physics-sequence ' , ' the-quantum-phy ' ], +[ ' never-is-a-long-time ' , ' never-is-a-long ' ], +[ ' eliezers-post-dependencies-book-notification-graphic-designer-wanted ' , ' eliezers-post-d ' ], +[ ' anti-foreign-bias ' , ' tyler-in-the-ny ' ], +[ ' against-devils-advocacy ' , ' against-devils ' ], +[ ' the-future-of-oil-prices-3-nonrenewable-resource-pricing ' , ' the-future-of-o ' ], +[ ' meetup-in-nyc-wed ' , ' meetup-in-nyc-w ' ], +[ ' how-honest-with-kids ' , ' how-honest-with ' ], +[ ' bloggingheads-yudkowsky-and-horgan ' , ' bloggingheads-y ' ], +[ ' oil-scapegoats ' , ' manipulation-go ' ], +[ ' timeless-control ' , ' timeless-contro ' ], +[ ' how-to-add-2-to-gdp ' , ' how-to-increase ' ], +[ ' thou-art-physics ' , ' thou-art-physic ' ], +[ ' overcoming-disagreement ' , ' overcoming-disa ' ], +[ ' living-in-many-worlds ' , ' living-in-many ' ], +[ ' wait-for-it ' , ' wait-for-it ' ], +[ ' why-quantum ' , ' why-quantum ' ], +[ ' against-disclaimers ' , ' against-disclai ' ], +[ ' timeless-identity ' , ' timeless-identi ' ], +[ ' exploration-as-status ' , ' exploration-as ' ], +[ ' principles-of-disagreement ' , ' principles-of-d ' ], +[ ' the-rhythm-of-disagreement ' , ' the-rhythm-of-d ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' singularity-economics ' , ' economics-of-si ' ], +[ ' detached-lever-fallacy ' , ' detached-lever ' ], +[ ' ok-now-im-worried ' , ' ok-im-worried ' ], +[ ' humans-in-funny-suits ' , ' humans-in-funny ' ], +[ ' touching-vs-understanding ' , ' touching-vs-und ' ], +[ ' intrades-conditional-prediction-markets ' , ' intrades-condit ' ], +[ ' when-to-think-critically ' , ' when-to-think-c ' ], +[ ' interpersonal-morality ' , ' interpersonal-m ' ], +[ ' the-meaning-of-right ' , ' the-meaning-of ' ], +[ ' funding-bias ' , ' funding-bias ' ], +[ ' setting-up-metaethics ' , ' setting-up-meta ' ], +[ ' bias-against-the-unseen ' , ' biased-against ' ], +[ ' changing-your-metaethics ' , ' retreat-from-me ' ], +[ ' is-ideology-about-status ' , ' is-ideology-abo ' ], +[ ' gary-taubes-good-calories-bad-calories ' , ' gary-taubes-goo ' ], +[ ' does-your-morality-care-what-you-think ' , ' does-morality-c ' ], +[ ' refuge-markets ' , ' refuge-markets ' ], +[ ' math-is-subjunctively-objective ' , ' math-is-subjunc ' ], +[ ' can-counterfactuals-be-true ' , ' counterfactual ' ], +[ ' when-not-to-use-probabilities ' , ' when-not-to-use ' ], +[ ' banning-bad-news ' , ' banning-bad-new ' ], +[ ' your-morality-doesnt-care-what-you-think ' , ' moral-counterfa ' ], +[ ' fake-norms-or-truth-vs-truth ' , ' fake-norms-or-t ' ], +[ ' loving-loyalty ' , ' loving-loyalty ' ], +[ ' should-we-ban-physics ' , ' should-we-ban-p ' ], +[ ' touching-the-old ' , ' touching-the-ol ' ], +[ ' existential-angst-factory ' , ' existential-ang ' ], +[ ' corporate-assassins ' , ' corporate-assas ' ], +[ ' could-anything-be-right ' , ' anything-right ' ], +[ ' doxastic-voluntarism-and-some-puzzles-about-rationality ' , ' doxastic-volunt ' ], +[ ' disaster-bias ' , ' disaster-bias ' ], +[ ' the-gift-we-give-to-tomorrow ' , ' moral-miracle-o ' ], +[ ' world-welfare-state ' , ' world-welfare-s ' ], +[ ' whither-moral-progress ' , ' whither-moral-p ' ], +[ ' posting-may-slow ' , ' posting-may-slo ' ], +[ ' bias-in-political-conversation ' , ' bias-in-politic ' ], +[ ' lawrence-watt-evanss-fiction ' , ' lawrence-watt-e ' ], +[ ' fear-god-and-state ' , ' fear-god-and-st ' ], +[ ' probability-is-subjectively-objective ' , ' probability-is ' ], +[ ' rebelling-within-nature ' , ' rebelling-withi ' ], +[ ' ask-for-help ' , ' ask-for-help ' ], +[ ' fundamental-doubts ' , ' fundamental-dou ' ], +[ ' biases-of-elite-education ' , ' biases-of-elite ' ], +[ ' the-genetic-fallacy ' , ' genetic-fallacy ' ], +[ ' my-kind-of-reflection ' , ' my-kind-of-refl ' ], +[ ' helsinki-meetup ' , ' helsinki-meetup ' ], +[ ' poker-vs-chess ' , ' poker-vs-chess ' ], +[ ' cloud-seeding-markets ' , ' cloud-seeding-m ' ], +[ ' the-fear-of-common-knowledge ' , ' fear-of-ck ' ], +[ ' where-recursive-justification-hits-bottom ' , ' recursive-justi ' ], +[ ' artificial-volcanoes ' , ' artificial-volc ' ], +[ ' cftc-event-market-comment ' , ' my-cftc-event-c ' ], +[ ' will-as-thou-wilt ' , ' will-as-thou-wi ' ], +[ ' rationalist-origin-stories ' , ' rationalist-ori ' ], +[ ' all-hail-info-theory ' , ' all-hail-info-t ' ], +[ ' morality-is-subjectively-objective ' , ' subjectively-ob ' ], +[ ' bloggingheads-hanson-wilkinson ' , ' bloggingheads-m ' ], +[ ' is-morality-given ' , ' is-morality-giv ' ], +[ ' the-most-amazing-productivity-tip-ever ' , ' the-most-amazin ' ], +[ ' is-morality-preference ' , ' is-morality-pre ' ], +[ ' rah-my-country ' , ' yeah-my-country ' ], +[ ' moral-complexities ' , ' moral-complexit ' ], +[ ' 2-of-10-not-3-total ' , ' 2-of-10-not-3-t ' ], +[ ' overconfident-investing ' , ' overconfident-i ' ], +[ ' the-bedrock-of-fairness ' , ' bedrock-fairnes ' ], +[ ' sex-nerds-and-entitlement ' , ' sex-nerds-and-e ' ], +[ ' break-it-down ' , ' break-it-down ' ], +[ ' why-argue-values ' , ' why-argue-value ' ], +[ ' id-take-it ' , ' id-take-it ' ], +[ ' distraction-overcomes-moral-hypocrisy ' , ' distraction-ove ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' overcoming-our-vs-others-biases ' , ' overcoming-our ' ], +[ ' created-already-in-motion ' , ' moral-ponens ' ], +[ ' morality-made-easy ' , ' morality-made-e ' ], +[ ' brief-break ' , ' brief-break ' ], +[ ' dreams-of-friendliness ' , ' dreams-of-frien ' ], +[ ' fake-fish ' , ' fake-fish ' ], +[ ' qualitative-strategies-of-friendliness ' , ' qualitative-str ' ], +[ ' cowen-hanson-bloggingheads-topics ' , ' cowen-hanson-bl ' ], +[ ' moral-false-consensus ' , ' moral-false-con ' ], +[ ' harder-choices-matter-less ' , ' harder-choices ' ], +[ ' the-complexity-critique ' , ' the-complexity ' ], +[ ' against-modal-logics ' , ' against-modal-l ' ], +[ ' top-teachers-ineffective ' , ' certified-teach ' ], +[ ' dreams-of-ai-design ' , ' dreams-of-ai-de ' ], +[ ' top-docs-no-healthier ' , ' top-school-docs ' ], +[ ' three-fallacies-of-teleology ' , ' teleology ' ], +[ ' use-the-native-architecture ' , ' use-the-native ' ], +[ ' cowen-disses-futarchy ' , ' cowen-dises-fut ' ], +[ ' magical-categories ' , ' magical-categor ' ], +[ ' randomised-controlled-trials-of-parachutes ' , ' randomised-cont ' ], +[ ' unnatural-categories ' , ' unnatural-categ ' ], +[ ' good-medicine-in-merry-old-england ' , ' good-medicine-i ' ], +[ ' mirrors-and-paintings ' , ' mirrors-and-pai ' ], +[ ' beauty-bias ' , ' ignore-beauty ' ], +[ ' invisible-frameworks ' , ' invisible-frame ' ], +[ ' dark-dreams ' , ' dark-dreams ' ], +[ ' no-license-to-be-human ' , ' no-human-licens ' ], +[ ' are-ufos-aliens ' , ' are-ufos-aliens ' ], +[ ' you-provably-cant-trust-yourself ' , ' no-self-trust ' ], +[ ' caplan-gums-bullet ' , ' caplan-gums-bul ' ], +[ ' dumb-deplaning ' , ' dumb-deplaning ' ], +[ ' mundane-dishonesty ' , ' mundane-dishone ' ], +[ ' the-cartoon-guide-to-lbs-theorem ' , ' lobs-theorem ' ], +[ ' bias-in-real-life-a-personal-story ' , ' bias-in-real-li ' ], +[ ' when-anthropomorphism-became-stupid ' , ' when-anthropomo ' ], +[ ' hot-air-doesnt-disagree ' , ' hot-air-doesnt ' ], +[ ' the-baby-eating-aliens-13 ' , ' baby-eaters ' ], +[ ' manipulators-as-mirrors ' , ' manipulators-as ' ], +[ ' the-bedrock-of-morality-arbitrary ' , ' arbitrary-bedro ' ], +[ ' is-fairness-arbitrary ' , ' arbitrarily-fai ' ], +[ ' self-indication-solves-time-asymmetry ' , ' self-indication ' ], +[ ' schelling-and-the-nuclear-taboo ' , ' schelling-and-t ' ], +[ ' arbitrary ' , ' unjustified ' ], +[ ' new-best-game-theory ' , ' new-best-game-t ' ], +[ ' abstracted-idealized-dynamics ' , ' computations ' ], +[ ' future-altruism-not ' , ' future-altruism ' ], +[ ' moral-error-and-moral-disagreement ' , ' moral-disagreem ' ], +[ ' doctor-there-are-two-kinds-of-no-evidence ' , ' doctor-there-ar ' ], +[ ' suspiciously-vague-lhc-forecasts ' , ' suspiciously-va ' ], +[ ' sorting-pebbles-into-correct-heaps ' , ' pebblesorting-p ' ], +[ ' the-problem-at-the-heart-of-pascals-wager ' , ' the-problem-at ' ], +[ ' inseparably-right-or-joy-in-the-merely-good ' , ' rightness-redux ' ], +[ ' baxters-ifloodi ' , ' baxters-flood ' ], +[ ' morality-as-fixed-computation ' , ' morality-as-fix ' ], +[ ' our-comet-ancestors ' , ' our-comet-ances ' ], +[ ' hiroshima-day ' , ' hiroshima-day ' ], +[ ' the-robots-rebellion ' , ' the-robots-rebe ' ], +[ ' ignore-prostate-cancer ' , ' ignore-cancer ' ], +[ ' contaminated-by-optimism ' , ' contaminated-by ' ], +[ ' anthropology-patrons ' , ' anthropology-pa ' ], +[ ' anthropomorphic-optimism ' , ' anthropomorph-1 ' ], +[ ' now-im-scared ' , ' now-im-scared ' ], +[ ' incomplete-analysis ' , ' incomplete-anal ' ], +[ ' no-logical-positivist-i ' , ' no-logical-posi ' ], +[ ' bias-against-some-types-of-foreign-wives ' , ' bias-against-so ' ], +[ ' where-does-pascals-wager-fail ' , ' where-does-pasc ' ], +[ ' the-comedy-of-behaviorism ' , ' behaviorism ' ], +[ ' anthropomorphism-as-formal-fallacy ' , ' anthropomorphic ' ], +[ ' variance-induced-test-bias ' , ' variance-induce ' ], +[ ' a-genius-for-destruction ' , ' destructive-gen ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' the-magnitude-of-his-own-folly ' , ' it-was-pretty-b ' ], +[ ' the-hope-premium ' , ' the-hope-premiu ' ], +[ ' dangerous-species-warnings ' , ' species-protect ' ], +[ ' friedmans-prediction-vs-explanation ' , ' friedmans-predi ' ], +[ ' above-average-ai-scientists ' , ' above-average-s ' ], +[ ' competent-elites ' , ' stratified-by-c ' ], +[ ' bank-politics-is-not-about-bank-policy ' , ' bank-politics-i ' ], +[ ' the-level-above-mine ' , ' level-above ' ], +[ ' doable-green ' , ' saveable-nature ' ], +[ ' give-it-to-me-straight-i-swear-i-wont-be-mad ' , ' give-it-to-me-s ' ], +[ ' my-naturalistic-awakening ' , ' naturalistic-aw ' ], +[ ' pundits-as-moles ' , ' pundits-as-mole ' ], +[ ' fighting-a-rearguard-action-against-the-truth ' , ' fighting-a-rear ' ], +[ ' white-swans-painted-black ' , ' white-swans-p-1 ' ], +[ ' correcting-biases-once-youve-identified-them ' , ' correcting-bias ' ], +[ ' that-tiny-note-of-discord ' , ' tiny-note-of-di ' ], +[ ' noble-lies ' , ' noble-lies ' ], +[ ' horrible-lhc-inconsistency ' , ' horrible-lhc-in ' ], +[ ' certainty-effects-and-credit-default-swaps ' , ' certainty-effec ' ], +[ ' politics-isnt-about-policy ' , ' politics-isnt-a ' ], +[ ' how-many-lhc-failures-is-too-many ' , ' how-many-lhc-fa ' ], +[ ' ban-the-bear ' , ' ban-the-bear ' ], +[ ' say-it-loud ' , ' say-it-loud ' ], +[ ' bad-news-ban-is-very-bad-news ' , ' bad-news-ban-is ' ], +[ ' overconfidence-is-stylish ' , ' overconfidence ' ], +[ ' the-sheer-folly-of-callow-youth ' , ' youth-folly ' ], +[ ' isshoukenmei ' , ' isshoukenmei ' ], +[ ' who-to-blame ' , ' who-to-blame ' ], +[ ' a-prodigy-of-refutation ' , ' refutation-prod ' ], +[ ' money-is-serious ' , ' money-frames ' ], +[ ' raised-in-technophilia ' , ' raised-in-sf ' ], +[ ' pharmaceutical-freedom-for-those-who-have-overcome-many-of-their-biases ' , ' pharmaceutical ' ], +[ ' deafening-silence ' , ' deafening-silen ' ], +[ ' my-best-and-worst-mistake ' , ' my-best-and-wor ' ], +[ ' noble-abstention ' , ' noble-abstentio ' ], +[ ' my-childhood-death-spiral ' , ' childhood-spira ' ], +[ ' maturity-bias ' , ' maturity-bias ' ], +[ ' serious-music ' , ' serious-music ' ], +[ ' optimization ' , ' optimization ' ], +[ ' beware-high-standards ' , ' beware-high-sta ' ], +[ ' lemon-glazing-fallacy ' , ' lemon-glazing-f ' ], +[ ' psychic-powers ' , ' psychic-powers ' ], +[ ' immodest-caplan ' , ' immodest-caplan ' ], +[ ' excluding-the-supernatural ' , ' excluding-the-s ' ], +[ ' intelligent-design-honesty ' , ' intelligent-des ' ], +[ ' rationality-quotes-17 ' , ' quotes-17 ' ], +[ ' election-review-articles ' , ' election-review ' ], +[ ' points-of-departure ' , ' points-of-depar ' ], +[ ' guiltless-victims ' , ' guiltless-victi ' ], +[ ' singularity-summit-2008 ' , ' singularity-sum ' ], +[ ' spinspotter ' , ' spinspotter ' ], +[ ' anyone-who-thinks-the-large-hadron-collider-will-destroy-the-world-is-a-tt ' , ' anyone-who-thin ' ], +[ ' is-carbon-lost-cause ' , ' carbon-is-lost ' ], +[ ' rationality-quotes-16 ' , ' quotes-16 ' ], +[ ' aaronson-on-singularity ' , ' aaronson-on-sin ' ], +[ ' rationality-quotes-15 ' , ' quotes-15 ' ], +[ ' hating-economists ' , ' hating-economis ' ], +[ ' rationality-quotes-14 ' , ' quotes-14 ' ], +[ ' disagreement-is-disrespect ' , ' disagreement-is ' ], +[ ' the-truly-iterated-prisoners-dilemma ' , ' iterated-tpd ' ], +[ ' aping-insight ' , ' aping-insight ' ], +[ ' the-true-prisoners-dilemma ' , ' true-pd ' ], +[ ' mirrored-lives ' , ' mirrored-lives ' ], +[ ' rationality-quotes-13 ' , ' rationality-quo ' ], +[ ' risk-is-physical ' , ' risk-is-physica ' ], +[ ' rationality-quotes-12 ' , ' rationality-q-1 ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' mundane-magic ' , ' mundane-magic ' ], +[ ' fhi-emulation-roadmap-out ' , ' fhi-emulation-r ' ], +[ ' porn-vs-romance-novels ' , ' porn-vs-romance ' ], +[ ' intelligence-in-economics ' , ' intelligence-in ' ], +[ ' does-intelligence-float ' , ' does-intelligen ' ], +[ ' economic-definition-of-intelligence ' , ' economic-defini ' ], +[ ' anti-edgy ' , ' anti-edgy ' ], +[ ' efficient-cross-domain-optimization ' , ' efficient-cross ' ], +[ ' wanting-to-want ' , ' wanting-to-want ' ], +[ ' measuring-optimization-power ' , ' measuring-optim ' ], +[ ' transparent-characters ' , ' transparent-cha ' ], +[ ' aiming-at-the-target ' , ' aiming-at-the-t ' ], +[ ' trust-us ' , ' trust-us ' ], +[ ' quotes-from-singularity-summit-2008 ' , ' summit-quotes ' ], +[ ' belief-in-intelligence ' , ' belief-in-intel ' ], +[ ' expected-creative-surprises ' , ' expected-creati ' ], +[ ' trust-but-dont-verify ' , ' trust-but-dont ' ], +[ ' san-jose-meetup-sat-1025-730pm ' , ' san-jose-meetup ' ], +[ ' inner-goodness ' , ' inner-morality ' ], +[ ' obama-donors-as-news ' , ' donations-as-ne ' ], +[ ' which-parts-are-me ' , ' which-parts-am ' ], +[ ' if-you-snooze-you-lose ' , ' if-you-snooze-y ' ], +[ ' ethics-notes ' , ' ethics-notes ' ], +[ ' howard-stern-on-voter-rationalization ' , ' howard-stern-on ' ], +[ ' prices-or-bindings ' , ' infinite-price ' ], +[ ' toilets-arent-about-not-dying-of-disease ' , ' toilets-arent-a ' ], +[ ' ethical-injunctions ' , ' ethical-injunct ' ], +[ ' informed-voters-choose-worse ' , ' informed-voters ' ], +[ ' ethical-inhibitions ' , ' ethical-inhibit ' ], +[ ' protected-from-myself ' , ' protected-from ' ], +[ ' last-post-requests ' , ' last-post-reque ' ], +[ ' dark-side-epistemology ' , ' the-dark-side ' ], +[ ' preventive-health-care ' , ' preventive-heal ' ], +[ ' traditional-capitalist-values ' , ' traditional-cap ' ], +[ ' us-help-red-china-revolt ' , ' us-aid-chinese ' ], +[ ' entangled-truths-contagious-lies ' , ' lies-contagious ' ], +[ ' conspiracys-uncanny-valley ' , ' conspiracys-unc ' ], +[ ' ends-dont-justify-means-among-humans ' , ' ends-dont-justi ' ], +[ ' why-voter-drives ' , ' why-voter-drive ' ], +[ ' election-gambling-history ' , ' election-gambli ' ], +[ ' why-does-power-corrupt ' , ' power-corrupts ' ], +[ ' big-daddy-isnt-saving-you ' , ' big-daddy-isnt ' ], +[ ' behold-our-ancestors ' , ' behold-our-ance ' ], +[ ' rationality-quotes-19 ' , ' quotes-19 ' ], +[ ' grateful-for-bad-news ' , ' grateful-for-ba ' ], +[ ' the-ritual ' , ' the-question ' ], +[ ' crisis-of-faith ' , ' got-crisis ' ], +[ ' the-wire ' , ' the-wire ' ], +[ ' ais-and-gatekeepers-unite ' , ' ais-and-gatekee ' ], +[ ' bad-faith-voter-drives ' , ' weathersons-bad ' ], +[ ' shut-up-and-do-the-impossible ' , ' shut-up-and-do ' ], +[ ' academics-in-clown-suits ' , ' academics-in-cl ' ], +[ ' gullibility-and-control ' , ' guilibility-and ' ], +[ ' terror-politics-isnt-about-policy ' , ' terror-politics ' ], +[ ' make-an-extraordinary-effort ' , ' isshokenmei ' ], +[ ' more-deafening-silence ' , ' more-deafening ' ], +[ ' on-doing-the-impossible ' , ' try-persevere ' ], +[ ' bay-area-meetup-for-singularity-summit ' , ' bay-area-meetup ' ], +[ ' insincere-cheers ' , ' football-lesson ' ], +[ ' my-bayesian-enlightenment ' , ' my-bayesian-enl ' ], +[ ' political-harassment ' , ' political-haras ' ], +[ ' beyond-the-reach-of-god ' , ' beyond-god ' ], +[ ' rationality-quotes-18 ' , ' rationality-quo ' ], +[ ' equally-shallow-genders ' , ' equallly-shallo ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' political-parties-are-not-about-policy ' , ' political-parti ' ], +[ ' use-the-try-harder-luke ' , ' use-the-try-har ' ], +[ ' no-rose-colored-dating-glasses ' , ' no-rose-colored ' ], +[ ' trying-to-try ' , ' trying-to-try ' ], +[ ' intrade-and-the-dow-drop ' , ' intrade-and-the ' ], +[ ' awww-a-zebra ' , ' awww-a-zebra ' ], +[ ' singletons-rule-ok ' , ' singletons-rule ' ], +[ ' total-tech-wars ' , ' total-tech-wars ' ], +[ ' chaotic-inversion ' , ' chaotic-inversi ' ], +[ ' luck-pessimism ' , ' luck-pessimism ' ], +[ ' thanksgiving-prayer ' , ' thanksgiving-pr ' ], +[ ' dreams-of-autarky ' , ' dreams-of-autar ' ], +[ ' modern-depressions ' , ' modern-depressi ' ], +[ ' total-nano-domination ' , ' nanotech-asplod ' ], +[ ' beliefs-require-reasons-or-is-the-pope-catholic-should-he-be ' , ' beliefs-require ' ], +[ ' engelbart-insufficiently-recursive ' , ' mouse-no-go-foo ' ], +[ ' abstractdistant-future-bias ' , ' abstractdistant ' ], +[ ' the-complete-idiots-guide-to-ad-hominem ' , ' the-complete-id ' ], +[ ' physicists-held-to-lower-standard ' , ' physicists-held ' ], +[ ' thinking-helps ' , ' thinking-helps ' ], +[ ' recursion-magic ' , ' recursion-magic ' ], +[ ' when-life-is-cheap-death-is-cheap ' , ' when-life-is-ch ' ], +[ ' polisci-stats-biased ' , ' polisci-journal ' ], +[ ' cascades-cycles-insight ' , ' cascades-cycles ' ], +[ ' evicting-brain-emulations ' , ' suppose-that-ro ' ], +[ ' are-you-dreaming ' , ' are-you-dreamin ' ], +[ ' surprised-by-brains ' , ' brains ' ], +[ ' the-second-swan ' , ' swan-2 ' ], +[ ' billion-dollar-bots ' , ' billion-dollar ' ], +[ ' brain-emulation-and-hard-takeoff ' , ' brain-emulation ' ], +[ ' emulations-go-foom ' , ' emulations-go-f ' ], +[ ' lifes-story-continues ' , ' the-age-of-nonr ' ], +[ ' observing-optimization ' , ' observing-optim ' ], +[ ' ai-go-foom ' , ' ai-go-foom ' ], +[ ' whence-your-abstractions ' , ' abstractions-re ' ], +[ ' abstraction-not-analogy ' , ' abstraction-vs ' ], +[ ' the-first-world-takeover ' , ' 1st-world-takeo ' ], +[ ' setting-the-stage ' , ' setting-the-sta ' ], +[ ' cheap-wine-tastes-fine ' , ' cheap-wine-tast ' ], +[ ' animal-experimentation-morally-acceptable-or-just-the-way-things-always-have-been ' , ' animal-experime ' ], +[ ' the-weak-inside-view ' , ' the-weak-inside ' ], +[ ' convenient-overconfidence ' , ' convenient-over ' ], +[ ' loud-subtext ' , ' loud-subtext ' ], +[ ' failure-by-affective-analogy ' , ' affective-analo ' ], +[ ' failure-by-analogy ' , ' failure-by-anal ' ], +[ ' whither-ob ' , ' whither-ob ' ], +[ ' all-are-skill-unaware ' , ' all-are-unaware ' ], +[ ' logical-or-connectionist-ai ' , ' logical-or-conn ' ], +[ ' friendliness-factors ' , ' friendliness-fa ' ], +[ ' boston-area-meetup-111808-9pm-mitcambridge ' , ' boston-area-mee ' ], +[ ' positive-vs-optimal ' , ' positive-vs-opt ' ], +[ ' friendly-teams ' , ' englebart-not-r ' ], +[ ' the-nature-of-logic ' , ' first-order-log ' ], +[ ' diamond-palace-survive ' , ' whether-diamond ' ], +[ ' selling-nonapples ' , ' selling-nonappl ' ], +[ ' engelbart-as-ubertool ' , ' engelbarts-uber ' ], +[ ' bay-area-meetup-1117-8pm-menlo-park ' , ' bay-area-meetup ' ], +[ ' the-weighted-majority-algorithm ' , ' the-weighted-ma ' ], +[ ' fund-ubertool ' , ' fund-ubertool ' ], +[ ' worse-than-random ' , ' worse-than-rand ' ], +[ ' conformity-shows-loyalty ' , ' conformity-show ' ], +[ ' incompetence-vs-self-interest ' , ' incompetence-vs ' ], +[ ' lawful-uncertainty ' , ' lawful-uncertai ' ], +[ ' what-belief-conformity ' , ' what-conformity ' ], +[ ' ask-ob-leaving-the-fold ' , ' leaving-the-fol ' ], +[ ' depressed-inoti-more-accurate ' , ' depressed-not-m ' ], +[ ' lawful-creativity ' , ' lawful-creativi ' ], +[ ' visionary-news ' , ' visionary-news ' ], +[ ' recognizing-intelligence ' , ' recognizing-int ' ], +[ ' equal-cheats ' , ' equal-cheats ' ], +[ ' back-up-and-ask-whether-not-why ' , ' back-up-and-ask ' ], +[ ' beware-i-believe ' , ' beware-i-believ ' ], +[ ' hanging-out-my-speakers-shingle ' , ' now-speaking ' ], +[ ' disagreement-debate-status ' , ' disagreement-de ' ], +[ ' beware-the-prescient ' , ' beware-the-pres ' ], +[ ' todays-inspirational-tale ' , ' todays-inspirat ' ], +[ ' the-evil-pleasure ' , ' evil-diversity ' ], +[ ' complexity-and-intelligence ' , ' complexity-and ' ], +[ ' building-something-smarter ' , ' building-someth ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' bhtv-jaron-lanier-and-yudkowsky ' , ' jaron-lanier-an ' ], +[ ' a-new-day ' , ' a-new-day ' ], +[ ' against-interesting-details ' , ' against-interesting-presentations ' ], +[ ' dunbars-function ' , ' dunbars-function ' ], +[ ' amputation-of-destiny ' , ' theft-of-destiny ' ], +[ ' the-meta-human-condition ' , ' the-metahuman-condition ' ], +[ ' it-is-simply-no-longer-possible-to-believe ' , ' it-is-simply-no-longer-possible-to-believe ' ], +[ ' friendship-is-relative ' , ' friendship-is-relative ' ], +[ ' cant-unbirth-a-child ' , ' no-unbirthing ' ], +[ ' nonsentient-bloggers ' , ' nonsentient-bloggers ' ], +[ ' nonsentient-optimizers ' , ' unpersons ' ], +[ ' nonperson-predicates ' , ' model-citizens ' ], +[ ' alien-bad-guy-bias ' , ' alien-bad-guy-bias ' ], +[ ' devils-offers ' , ' devils-offers ' ], +[ ' harmful-options ' , ' harmful-options ' ], +[ ' the-longshot-bias ' , ' the-longshot-bias- ' ], +[ ' imaginary-positions ' , ' imaginary-positions ' ], +[ ' coherent-futures ' , ' coherent-futures ' ], +[ ' rationality-quotes-20 ' , ' quotes-20 ' ], +[ ' no-overconfidence ' , ' no-overconfidence ' ], +[ ' show-off-bias ' , ' showoff-bias ' ], +[ ' living-by-your-own-strength ' , ' by-your-own-strength ' ], +[ ' sensual-experience ' , ' sensual-experience ' ], +[ ' presuming-bets-are-bad ' , ' presuming-bets-are-bad ' ], +[ ' futarchy-is-nyt-buzzword-of-08 ' , ' futarchy-is-nyt-buzzword-of-08 ' ], +[ ' experts-are-for-certainty ' , ' experts-are-for-certainty ' ], +[ ' complex-novelty ' , ' complex-novelty ' ], +[ ' high-challenge ' , ' high-challenge ' ], +[ ' weak-social-theories ' , ' weak-social-theories ' ], +[ ' christmas-signaling ' , ' christmas-signaling ' ], +[ ' prolegomena-to-a-theory-of-fun ' , ' fun-theory ' ], +[ ' the-right-thing ' , ' the-right-thing ' ], +[ ' who-cheers-the-referee ' , ' who-cheers-the-referee ' ], +[ ' visualizing-eutopia ' , ' visualizing-eutopia ' ], +[ ' ill-think-of-a-reason-later ' , ' ill-think-of-a-reason-later ' ], +[ ' utopia-unimaginable ' , ' utopia-vs-eutopia ' ], +[ ' tyler-on-cryonics ' , ' tyler-on-cryonics ' ], +[ ' not-taking-over-the-world ' , ' not-taking-over ' ], +[ ' entrepreneurs-are-not-overconfident ' , ' entrepreneurs-are-not-overconfident ' ], +[ ' distrusting-drama ' , ' types-of-distru ' ], +[ ' for-the-people-who-are-still-alive ' , ' who-are-still-alive ' ], +[ ' trade-with-the-future ' , ' trade-with-the-future ' ], +[ ' bhtv-de-grey-and-yudkowsky ' , ' bhtv-de-grey-and-yudkowsky ' ], +[ ' hated-because-it-might-work ' , ' hated-because-it-might-work ' ], +[ ' cryonics-is-cool ' , ' cryonics-is-cool ' ], +[ ' you-only-live-twice ' , ' you-only-live-twice ' ], +[ ' we-agree-get-froze ' , ' we-agree-get-froze ' ], +[ ' what-i-think-if-not-why ' , ' what-i-think ' ], +[ ' what-core-argument ' , ' what-core-argument ' ], +[ ' a-vision-of-precision ' , ' a-vision-of-pre ' ], +[ ' the-linear-scaling-error ' , ' the-linear-scal ' ], +[ ' the-mechanics-of-disagreement ' , ' the-mechanics-o ' ], +[ ' two-visions-of-heritage ' , ' two-visions-of ' ], +[ ' bay-area-meetup-wed-1210-8pm ' , ' bay-area-meetup ' ], +[ ' are-ais-homo-economicus ' , ' are-ais-homo-ec ' ], +[ ' disjunctions-antipredictions-etc ' , ' disjunctions-an ' ], +[ ' the-bad-guy-bias ' , ' the-bad-guy-bia ' ], +[ ' true-sources-of-disagreement ' , ' true-sources-of ' ], +[ ' us-tv-censorship ' , ' us-tv-censorshi ' ], +[ ' wrapping-up ' , ' wrapping-up ' ], +[ ' artificial-mysterious-intelligence ' , ' artificial-myst ' ], +[ ' incommunicable-meta-insight ' , ' incommunicable ' ], +[ ' false-false-dichotomies ' , ' false-false-dic ' ], +[ ' shared-ai-wins ' , ' shared-ai-wins ' ], +[ ' is-that-your-true-rejection ' , ' your-true-rejec ' ], +[ ' friendly-projects-vs-products ' , ' friendly-projec ' ], +[ ' sustained-strong-recursion ' , ' sustained-recur ' ], +[ ' recursive-mind-designers ' , ' recursive-mind ' ], +[ ' evolved-desires ' , ' evolved-desires ' ], +[ ' gas-arbitrage ' , ' gas-artibrage ' ], +[ ' -eternal-inflation-and-the-probability-that-you-are-living-in-a-computer-simulation ' , ' eternal-inflati ' ], +[ ' drexler-blogs ' , ' drexler-blogs ' ], +[ ' beware-hockey-stick-plans ' , ' beware-hockey-s ' ], +[ ' underconstrained-abstractions ' , ' underconstraine ' ], +[ ' rationality-of-voting-etc ' , ' rationality-of ' ], +[ ' permitted-possibilities-locality ' , ' permitted-possi ' ], +[ ' the-hypocrisy-charge-bias ' , ' the-hypocrisy-c ' ], +[ ' test-near-apply-far ' , ' test-near-apply ' ], +[ ' hard-takeoff ' , ' hard-takeoff ' ], +[ ' voting-kills ' , ' voting-kills ' ], +[ ' whither-manufacturing ' , ' whither-manufac ' ], +[ ' recursive-self-improvement ' , ' recursive-self ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' i-heart-cyc ' , ' i-heart-cyc ' ], +[ ' disappointment-in-the-future ' , ' disappointment ' ], +[ ' stuck-in-throat ' , ' stuck-in-throat ' ], +[ ' war-andor-peace-28 ' , ' war-andor-peace ' ], +[ ' the-baby-eating-aliens-18 ' , ' the-babyeating-aliens ' ], +[ ' three-worlds-collide-08 ' , ' three-worlds-collide ' ], +[ ' dreams-as-evidence ' , ' dreams-as-evidence ' ], +[ ' institution-design-is-like-martial-arts ' , ' why-market-economics-is-like-martial-arts ' ], +[ ' academic-ideals ' , ' academic-ideals ' ], +[ ' value-is-fragile ' , ' fragile-value ' ], +[ ' roberts-bias-therapy ' , ' roberts-bias-therapy ' ], +[ ' rationality-quotes-25 ' , ' quotes-25 ' ], +[ ' different-meanings-of-bayesian-statistics ' , ' different-meanings-of-bayesian-statistics ' ], +[ ' ob-status-update ' , ' ob-status-update ' ], +[ ' 31-laws-of-fun ' , ' fun-theory-laws ' ], +[ ' bhtv-yudkowsky-wilkinson ' , ' bhtv-yudkowsky-wilkinson ' ], +[ ' the-fun-theory-sequence ' , ' fun-theory-sequence ' ], +[ ' avoid-vena-cava-filters ' , ' avoid-vena-cava-filters ' ], +[ ' rationality-quotes-24 ' , ' quotes-24 ' ], +[ ' higher-purpose ' , ' higher-purpose ' ], +[ ' investing-for-the-long-slump ' , ' the-long-slump ' ], +[ ' tribal-biases-and-the-inauguration ' , ' tribal-biases-and-the-inauguration ' ], +[ ' who-likes-what-movies ' , ' who-likes-what-movies ' ], +[ ' failed-utopia-4-2 ' , ' failed-utopia-42 ' ], +[ ' sunnyvale-meetup-saturday ' , ' bay-area-meetup-saturday ' ], +[ ' set-obamas-bar ' , ' set-obamas-bar ' ], +[ ' interpersonal-entanglement ' , ' no-catgirls ' ], +[ ' predictible-fakers ' , ' predictible-fakers ' ], +[ ' sympathetic-minds ' , ' sympathetic-minds ' ], +[ ' the-surprising-power-of-rote-cognition ' , ' the-surprising-power-of-rote-cognition ' ], +[ ' in-praise-of-boredom ' , ' boredom ' ], +[ ' beware-detached-detail ' , ' beware-detached-detail ' ], +[ ' getting-nearer ' , ' getting-nearer ' ], +[ ' a-tale-of-two-tradeoffs ' , ' a-tale-of-two-tradeoffs ' ], +[ ' seduced-by-imagination ' , ' souleating-dreams ' ], +[ ' data-on-fictional-lies ' , ' new-data-on-fiction ' ], +[ ' justified-expectation-of-pleasant-surprises ' , ' vague-hopes ' ], +[ ' disagreement-is-near-far-bias ' , ' disagreement-is-nearfar-bias ' ], +[ ' ishei-has-joined-the-conspiracy ' , ' kimiko ' ], +[ ' building-weirdtopia ' , ' weirdtopia ' ], +[ ' eutopia-is-scary ' , ' scary-eutopia ' ], +[ ' bad-news-predictor-jailed ' , ' korean-bad-news-predictor-jailed ' ], +[ ' continuous-improvement ' , ' better-and-better ' ], +[ ' why-we-like-middle-options-small-menus ' , ' why-we-like-middle-options-small-menus ' ], +[ ' rationality-quotes-23 ' , ' quotes-23 ' ], +[ ' serious-stories ' , ' serious-stories ' ], +[ ' the-metaethics-sequence ' , ' metaethics ' ], +[ ' why-love-is-vague ' , ' why-love-is-vague ' ], +[ ' rationality-quotes-22 ' , ' quotes-22 ' ], +[ ' free-docs-not-help-poor-kids ' , ' free-medicine-no-help-for-ghanaian-kids ' ], +[ ' emotional-involvement ' , ' emotional-involvement ' ], +[ ' why-fiction-lies ' , ' why-fiction-lies ' ], +[ ' rationality-quotes-21 ' , ' quotes-21 ' ], +[ ' changing-emotions ' , ' changing-emotions ' ], +[ ' growing-up-is-hard ' , ' growing-up-is-hard ' ], +[ ' a-world-without-lies ' , ' a-world-without-lies ' ], +[ ' the-uses-of-fun-theory ' , ' the-uses-of-fun-theory ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' disagreeing-about-idoubti ' , ' doubt-survey ' ], +[ ' free-to-optimize ' , ' free-to-optimize ' ], +[ ' moral-uncertainty---towards-a-solution ' , ' moral-uncertainty-towards-a-solution ' ], +[ ' the-most-frequently-useful-thing ' , ' most-frequently-useful ' ], +[ ' the-most-important-thing-you-learned ' , ' the-most-important-thing ' ], +[ ' avoid-identifying-with-anything ' , ' avoid-identifying-with-anything ' ], +[ ' self-experimentation-and-placebo-testing ' , ' selfexperimentation-and-placebo-testing ' ], +[ ' tell-your-rationalist-origin-story-at-less-wrong ' , ' rationalist-origins-at-lw ' ], +[ ' what-is-gossip-for ' , ' gossip-is-for-status ' ], +[ ' markets-are-anti-inductive ' , ' markets-are-antiinductive ' ], +[ ' libel-slander-blackmail ' , ' libel-slander-blackmail ' ], +[ ' formative-youth ' , ' formative-youth ' ], +[ ' what-do-schools-sell ' , ' what-do-schools-sell ' ], +[ ' on-not-having-an-advance-abyssal-plan ' , ' on-not-having-a-plan ' ], +[ ' who-are-macro-experts ' , ' who-are-macro-experts ' ], +[ ' what-is-medical-quality ' , ' what-is-medical-quality ' ], +[ ' fairness-vs-goodness ' , ' fairness-vs-goodness ' ], +[ ' rationality-quotes-27 ' , ' quotes-27 ' ], +[ ' write-your-hypothetical-apostasy ' , ' write-your-hypothetical-apostasy ' ], +[ ' wise-pretensions-v0 ' , ' wise-pretensions-v0 ' ], +[ ' pretending-to-be-wise ' , ' pretending-to-be-wise ' ], +[ ' spotty-deference ' , ' spotty-deference ' ], +[ ' the-intervention-and-the-checklist-two-paradigms-for-improvement ' , ' the-intervention-and-the-checklist-two-paradigms-for-improvement ' ], +[ ' against-maturity ' , ' against-maturity ' ], +[ ' good-idealistic-books-are-rare ' , ' good-idealistic-books ' ], +[ ' seeking-a-cynics-library ' , ' seeking-a-cynics-library ' ], +[ ' cynical-about-cynicism ' , ' cynical-about-cynicism ' ], +[ ' beware-value-talk ' , ' the-cost-of-talking-values ' ], +[ ' the-ethic-of-hand-washing-and-community-epistemic-practice ' , ' accuracyimproving-communities-and-the-ethics-of-handwashing ' ], +[ ' an-african-folktale ' , ' an-african-folktale ' ], +[ ' rationality-quotes-26 ' , ' quotes-26 ' ], +[ ' an-especially-elegant-evpsych-experiment ' , ' elegant-evpsych ' ], +[ ' the-evolutionary-cognitive-boundary ' , ' the-evolutionarycognitive-boundary ' ], +[ ' beware-ideal-screen-theories ' , ' beware-ideal-screen-theories ' ], +[ ' signaling-math ' , ' signaling-math ' ], +[ ' cynicism-in-ev-psych-and-econ ' , ' cynicism-in-evpsych-and-econ ' ], +[ ' informers-and-persuaders ' , ' informers-and-persuaders ' ], +[ ' against-propaganda ' , ' against-propaganda- ' ], +[ ' moral-truth-in-fiction ' , ' truth-from-fiction ' ], +[ ' ask-ob-how-can-i-measure-rationality ' , ' testing-rationality ' ], +[ ' and-say-no-more-of-it ' , ' and-say-no-more-of-it ' ], +[ ' different-meanings-of-bayesian-statistics-another-try ' , ' different-meanings-of-bayesian-statistics-another-try ' ], +[ ' the-thing-that-i-protect ' , ' the-thing-that-i-protect ' ], +[ ' our-biggest-surprise ' , ' our-biggest-surprise ' ], +[ ' epilogue-atonement-88 ' , ' atonement ' ], +[ ' share-likelihood-ratios-not-posterior-beliefs ' , ' share-likelihood-ratios-not-posterior-beliefs ' ], +[ ' true-ending-sacrificial-fire-78 ' , ' sacrificial-fire ' ], +[ ' conscious-control ' , ' is-consciousness-in-charge ' ], +[ ' normal-ending-last-tears-68 ' , ' last-tears ' ], +[ ' lying-stimuli ' , ' lying-stimuli- ' ], +[ ' three-worlds-decide-58 ' , ' three-worlds-decide ' ], +[ ' thoughtful-music ' , ' thoughtful-music ' ], +[ ' interlude-with-the-confessor-48 ' , ' interlude-with-the-confessor ' ], +[ ' open-thread ' , ' open-thread ' ], +[ ' the-super-happy-people-38 ' , ' super-happy-people ' ], +[ ' echo-chamber-confidence ' , ' echo-chamber-confidence ' ], +[ ' minchins-mistake ' , ' at-less-wrong-vladimir-nesov-approvingly-cites-tim-minchins-poem-storm-vid-here-text-here-it-is-an-entertaining-passiona ' ], +[ ' new-tech-signals ' , ' new-tech-signals ' ], +[ ' toddlers-avoid-dissenters ' , ' toddlers-avoid-dissenter-opinions ' ], +[ ' the-pascals-wager-fallacy-fallacy ' , ' pascals-wager-metafallacy ' ], +[ ' break-cryonics-down ' , ' break-cryonics-down ' ], +[ ' my-cryonics-hour ' , ' my-cryonics-hour ' ], +[ ' my-bhtv-with-tyler-cowen ' , ' my-bhtv-with-tyler-cowen ' ], +[ ' yes-tax-lax-ideas ' , ' yes-tax-ideas ' ], +[ ' trusting-sponsored-medical-research ' , ' trusting-sponsored-medical-research ' ], +[ ' kids-rights ' , ' kids-rights ' ], +[ ' status-prudes ' , ' status-prudes ' ], +[ ' more-getting-froze ' , ' more-getting-froze ' ], +[ ' wishful-dreaming ' , ' wishful-dreaming ' ], +[ ' who-likes-band-music ' , ' who-likes-band-music ' ], +[ ' loving-cranks-to-death ' , ' loving-cranks-to-death ' ], +[ ' distinguishing-academics-prestige-and-altruism-motivations ' , ' distinguishing-academics-prestige-and-altruism-motivations ' ], +[ ' literally-voodoo-economics ' , ' literally-voodoo-economics ' ], +[ ' as-ye-judge-those-who-fund-thee-ye-shall-be-judged ' , ' as-ye-judge-those-who-fund-thee-ye-shall-be-judged ' ], +[ ' evaporated-cane-juice ' , ' evaporated-cane-juice ' ], +[ ' be-sure-to-mind-when-you-change-your-mind ' , ' be-sure-to-mind-when-you-change-your-mind ' ], +[ ' posting-now-enabled-on-less-wrong ' , ' posting-now-enabled-on-less-wrong ' ], +[ ' lying-with-style ' , ' deceptive-writing-styles ' ], +[ ' question-medical-findings ' , ' question-medical-findings ' ], +[ ' six-months-later ' , ' six-months-later ' ], +[ ' you-get-more-than-you-select-for-but-not-always ' , ' you-get-more-than-you-select-for-but-not-always ' ], +[ ' what-changed ' , ' what-changed ' ], +[ ' status-affiliation-puzzles ' , ' status-affiliations ' ], +[ ' ob-meetup-friday-13th-7pm-springfield-va ' , ' ob-meetup-friday-13th-7pm-springfield-va ' ], +[ ' augustines-paradox-of-optimal-repentance ' , ' augustines-paradox ' ], +[ ' open-thread ' , ' o ' ], +[ ' near-far-like-drunk-darts ' , ' nearfar-like-drunk-darts ' ], +[ ' open-thread ' , ' open-thread ' ] +] +end
svetlyak40wt/django-apps
2669d5b1904508dec640f5e9defcf13c5d412b61
Small fix in the readme.
diff --git a/README.md b/README.md index 6b89eef..66236d0 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,38 @@ django-apps =========== Installation ------------ As usual. Place django_apps somewhere in your python path or install it using easy_install: easy_install django-apps Then, add `django_apps` to the `INSTALLED_APPS`. Usage ----- In the any template use template tag `installed_apps` to receive a list of installed apps along with some information about them. I use following code in my template, to show apps names along with their versions and descriptions. {% load apps_tags %} {% installed_apps as apps %} <table class="apps"> {% for app in apps %} <tr> <td>{{ app.name }}</td> <td>{{ app.version }}</td> <td>{{ app.description }}</td> </tr> {% endfor %} </table> You can find an example result at my own 'Installed Apps' page: -http://aartemenko.com/about/apps/ +<http://aartemenko.com/about/apps/> Please, note, that descriptions are hardcoded into the code of the `django_apps`.
svetlyak40wt/django-apps
657e09734c6e683236e9e3524d56cd155f4a53e1
Descriptions for some applications, ready for i18n.
diff --git a/django_apps/descriptions.py b/django_apps/descriptions.py new file mode 100644 index 0000000..9a701b4 --- /dev/null +++ b/django_apps/descriptions.py @@ -0,0 +1,38 @@ +import re +from django.utils.translation import ugettext_lazy as _ + +_apps_descriptions = [ + (r'.*django_dzenlog', _('Abstract blogging application.')), + (r'.*django_markdown2', _('Markdown2 filter tag.')), + (r'.*dzenlog_text', _('Text posts for blog (based on django_dzenlog).')), + (r'.*dzenlog_link', _('Link posts for blog (based on django_dzenlog).')), + (r'.*tagging', _('General tagging apllication.')), + (r'.*django_faces', _('Pavatar, gravatar and favicons based avatars.')), + (r'.*django_apps', _('Shows the installed application, their versions and descriptions.')), + (r'.*pagination', _('Limits number of entries per page.')), + (r'.*threadedcomments', _('Flexible threaded commenting system.')), + (r'.*dbtemplates', _('Editable templates, stored in the database.')), + (r'.*django_openid', _('OpenID server and consumer.')), + (r'.*django_freetext', _('Editable pieces of the content.')), + (r'.*compress', _('Javascript and CSS compressor.')), + (r'.*utils', _('Misc stuff.')), + (r'.*django_extensions', _('Global custom management extensions.')), + (r'.*basic.inlines', _('Inline markup to insert content objects into other pieces of content.')), + (r'.*basic.media', _('Audio, video and images.')), + (r'.*django.contrib.auth', _('Django\'s authentication framework.')), + (r'.*django.contrib.contenttypes', _('Framework for hooking into "types" of content.')), + (r'.*django.contrib.sessions', _('Sessions support.')), + (r'.*django.contrib.sites', _('Multi-site support.')), + (r'.*django.contrib.admin', _('The automatic Django administrative interface.')), + (r'.*django.contrib.humanize', _('Template filters for adding a "human touch" to data.')), + (r'.*django.contrib.flatpages', _('Framework for managing simple "flat" HTML content in a database.')), + (r'.*django.contrib.sitemaps', _('A framework for generating Google sitemap XML files.')), + (r'.*django.contrib.webdesign', _('Helpers and utilities for Web designers.')), +] + +def get_description(app_name): + for pattern, description in _apps_descriptions: + if re.match(pattern, app_name) is not None: + return description + return '' + diff --git a/django_apps/templatetags/apps_tags.py b/django_apps/templatetags/apps_tags.py index e57a0af..97c8546 100644 --- a/django_apps/templatetags/apps_tags.py +++ b/django_apps/templatetags/apps_tags.py @@ -1,41 +1,44 @@ import re from django import template from django.conf import settings -import pdb +from django.utils.translation import ugettext_lazy as _ + +from django_apps.descriptions import get_description register = template.Library() class InstalledAppsNode(template.Node): def __init__(self, var_name): self.var_name = var_name def render(self, context): def get_info(module_name): mod = __import__(module_name) version = getattr(mod, '__version__', - getattr(mod, 'VERSION', '')) + getattr(mod, 'VERSION', _('unknown'))) if isinstance(version, (tuple, list)): version = '.'.join(map(str, version)) return dict(name = module_name, version = version, - description = '') + description = get_description(module_name)) try: context[self.var_name] = [get_info(mod) for mod in settings.INSTALLED_APPS] except Exception, e: context[self.var_name] = e print context[self.var_name] return '' def installed_apps(parser, token): try: tag_name, arg = token.contents.split(None, 1) except ValueError: raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0] m = re.search(r'as (\w+)', arg) if not m: raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name var_name = m.groups()[0] return InstalledAppsNode(var_name) register.tag(installed_apps) +
svetlyak40wt/django-apps
9f0c066c900bcc14a70a238b4f9eebd29635c2dc
First implementation, without apps descriptions.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..672c4a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.pyc +.*.swp +django_apps.egg-info +build +dist diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..eb71f2f --- /dev/null +++ b/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2008, Alexander Artemenko +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the django_apps nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY ALEXANDER ARTEMENKO ''AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL ALEXANDER ARTEMENKO BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..6887fbe --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1 @@ +recursive-include django_apps/templates *.html diff --git a/README.md b/README.md new file mode 100644 index 0000000..6b89eef --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +django-apps +=========== + +Installation +------------ + +As usual. Place django_apps somewhere in your python path or install it using easy_install: + + easy_install django-apps + +Then, add `django_apps` to the `INSTALLED_APPS`. + +Usage +----- + +In the any template use template tag `installed_apps` to receive a list +of installed apps along with some information about them. + +I use following code in my template, to show apps names along with +their versions and descriptions. + + {% load apps_tags %} + {% installed_apps as apps %} + <table class="apps"> + {% for app in apps %} + <tr> + <td>{{ app.name }}</td> + <td>{{ app.version }}</td> + <td>{{ app.description }}</td> + </tr> + {% endfor %} + </table> + +You can find an example result at my own 'Installed Apps' page: +http://aartemenko.com/about/apps/ + +Please, note, that descriptions are hardcoded into the code of the `django_apps`. + diff --git a/django_apps/__init__.py b/django_apps/__init__.py index e69de29..3a83701 100755 --- a/django_apps/__init__.py +++ b/django_apps/__init__.py @@ -0,0 +1,2 @@ +VERSION = (0, 1, 0) +__version__ = '.'.join(map(str, VERSION)) diff --git a/django_apps/templatetags/__init__.py b/django_apps/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_apps/templatetags/apps_tags.py b/django_apps/templatetags/apps_tags.py new file mode 100644 index 0000000..e57a0af --- /dev/null +++ b/django_apps/templatetags/apps_tags.py @@ -0,0 +1,41 @@ +import re +from django import template +from django.conf import settings +import pdb + +register = template.Library() + +class InstalledAppsNode(template.Node): + def __init__(self, var_name): + self.var_name = var_name + + def render(self, context): + def get_info(module_name): + mod = __import__(module_name) + version = getattr(mod, '__version__', + getattr(mod, 'VERSION', '')) + if isinstance(version, (tuple, list)): + version = '.'.join(map(str, version)) + return dict(name = module_name, + version = version, + description = '') + + try: + context[self.var_name] = [get_info(mod) for mod in settings.INSTALLED_APPS] + except Exception, e: + context[self.var_name] = e + print context[self.var_name] + return '' + +def installed_apps(parser, token): + try: + tag_name, arg = token.contents.split(None, 1) + except ValueError: + raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0] + m = re.search(r'as (\w+)', arg) + if not m: + raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name + var_name = m.groups()[0] + return InstalledAppsNode(var_name) + +register.tag(installed_apps) diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..1995610 --- /dev/null +++ b/setup.py @@ -0,0 +1,26 @@ +from setuptools import setup, find_packages + +setup( + name = 'django-apps', + version = __import__('django_apps').__version__, + description = 'Django application which provides an information about installed applications.', + keywords = 'django apps', + license = 'New BSD License', + author = 'Alexander Artemenko', + author_email = 'svetlyak.40wt@gmail.com', + url = 'http://github.com/svetlyak40wt/django-apps/', + install_requires = [], + dependency_links = ['http://pypi.aartemenko.com'], + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Environment :: Plugins', + 'Framework :: Django', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Programming Language :: Python', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + packages = find_packages(), + include_package_data = True, +) +
svetlyak40wt/django-apps
63f37ffa03d217a323d29184207b87892d6fd0d9
Initial empty app.
diff --git a/django_apps/__init__.py b/django_apps/__init__.py new file mode 100755 index 0000000..e69de29 diff --git a/django_apps/models.py b/django_apps/models.py new file mode 100755 index 0000000..71a8362 --- /dev/null +++ b/django_apps/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/django_apps/views.py b/django_apps/views.py new file mode 100755 index 0000000..60f00ef --- /dev/null +++ b/django_apps/views.py @@ -0,0 +1 @@ +# Create your views here.
andreisavu/django-jack
9a5a776c561abc7f1371b9a6a29f08ec70100ca7
Document multiple databases
diff --git a/README b/README index c7708a4..182e09a 100644 --- a/README +++ b/README @@ -1,32 +1,33 @@ Jack - Beanstalkd web administration interface ============================================== What is beanstalkd? ------------------- "... a fast, general-purpose work queue." See http://xph.us/software/beanstalkd/ for general info. What can I do using this application? ------------------------------------- - put job on queue in a given tube - inspect job: view body and statistics - inspect burried jobs and kick all or individual - inspect delayed jobs - view what tubes are currently in use and stats - view queue statistics +- do all the above for multiple beanstalkd servers Requirements ------------ * Django 1.1 http://www.djangoproject.com/ * beanstalkc http://github.com/earl/beanstalkc
andreisavu/django-jack
76f94f416c61737c59afa790ae3995ddfd80ad71
Add basic multiple beanstalkd support
diff --git a/jack/beanstalk/client.py b/jack/beanstalk/client.py index bf084dc..7e43797 100644 --- a/jack/beanstalk/client.py +++ b/jack/beanstalk/client.py @@ -1,16 +1,22 @@ from django.conf import settings from beanstalkc import Connection, CommandFailed from beanstalkc import SocketError as ConnectionError class Client(object): """ A simple proxy object over the default client """ - def __init__(self): - self.conn = Connection(settings.BEANSTALK_HOST, settings.BEANSTALK_PORT) + def __init__(self, request): + if hasattr(request, 'connection'): + self.conn = Connection(request.connection[0], request.connection[1]) + elif settings.BEANSTALK_SERVERS: + server = settings.BEANSTALK_SERVERS[0] + self.conn = Connection(server[0], server[1]) + else: + raise Exception("No servers defined.") def __getattr__(self, name): return getattr(self.conn, name) diff --git a/jack/beanstalk/multiple_beanstalk.py b/jack/beanstalk/multiple_beanstalk.py new file mode 100644 index 0000000..a004620 --- /dev/null +++ b/jack/beanstalk/multiple_beanstalk.py @@ -0,0 +1,17 @@ +from django.conf import settings + +class Middleware(object): + def process_request(self, request): + if 'conn' not in request.COOKIES: + return + + conn_id = int(request.COOKIES['conn']) + request.connection = settings.BEANSTALK_SERVERS[conn_id] + +def ContextProcessor(request): + if 'conn' not in request.COOKIES: + conn_id = None + else: + conn_id = int(request.COOKIES['conn']) + return {'connections':settings.BEANSTALK_SERVERS,'conn_id':conn_id} + diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html index 4cfaa51..7a7b9ae 100644 --- a/jack/beanstalk/templates/beanstalk/base.html +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -1,134 +1,155 @@ <html> <head> <title>{% block title %}Jack and the Beanstalkd{% endblock %}</title> <style type="text/css"> body { padding: 0px; margin: 0px; font-family: "Helvetica LT Std", Helvetica, Arial, sans-serif; } #header { margin: 10px; } #content { margin: 10px; } /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .solidblockmenu{ margin: 0; padding: 0; float: left; font: bold 13px Arial; width: 100%; overflow: hidden; margin-bottom: 1em; border: 1px solid #625e00; border-width: 1px 0; background: black url(/media/blockdefault.gif) center center repeat-x; } .solidblockmenu li{ display: inline; } .solidblockmenu li a{ float: left; color: white; padding: 9px 11px; text-decoration: none; border-right: 1px solid white; } .solidblockmenu li a:visited{ color: white; } .solidblockmenu li a:hover, .solidblockmenu li .current{ color: white; background: transparent url(/media/blockactive.gif) center center repeat-x; } .aligntop{ vertical-align: top; } .floatleft{ float:left; } .gridwidth{ width:365px; } .clearboth{ clear:both; } h3{ background-color: black; color: white; text-align: left; } h3 + table{ background-color: #EFEFFE; } .aligntop th{ text-align: left; } </style> </head> <body> {% block header %} <div id="header"> <h1 style="float: left;font-size: 25px;"> <span style="color: blue">Jack</span> <span style="font-size: 20px;color: grey;">and the</span><br /> <span style="color: green">Beanstalkd</span> </h1> <span style="float: right"> welcome {{ user }} | <a href="/accounts/logout">logout</a> + <br><span> + <select id="change_connection"> + {% for host, port in connections %} + <option value="{{forloop.counter0}}" + {% if conn_id == forloop.counter0 %} + selected="selected" + {% endif %}> + {{host}}:{{port}} + </option> + {% endfor %} + </select> + <script> + (function(){ + var sel = document.getElementById('change_connection'); + sel.onchange = function(){ + document.cookie='conn='+sel.value; + location.reload(); + }; + })(); + </script> + </span> </span> <div style="clear: both;"></div> </div> {% endblock %} {% block menu %} <ul class="solidblockmenu"> <li><a href="/beanstalk/">Home</a></li> <li><a href="/beanstalk/stats/">Stats</a></li> <li><a href="/beanstalk/put/">Put</a></li> <li><a href="/beanstalk/inspect/">Inspect</a></li> <li><a href="/beanstalk/ready/">Peek Ready</a></li> <li><a href="/beanstalk/delayed/">Peek Delayed</a></li> <li><a href="/beanstalk/buried/">Peek Buried</a></li> </ul> <br style="clear: left" /> {% if flash.notice %} <center><span style="border: 1px solid #0aa;padding: 5px;"> {{ flash.notice }}</span></center> {% endif %} {% endblock %} <div id="content"> {% block content %}{% endblock %} </div> {% block footer %} <br /><br /> <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> {% endblock %} </body> </html> diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 77389fa..fa17646 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,232 +1,232 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable from beanstalk import checks from urlparse import urlsplit def _multiget(data, keys, default=None): ret = {} for key in keys: ret[key] = data.get(key, default) return ret @login_required def index(request): try: - client = Client() + client = Client(request) except ConnectionError: return render_unavailable() checks_errors = checks.run_all(client) stats = _multiget(client.stats(), [ 'current-connections', 'uptime', 'job-timeouts', 'version', 'current-jobs-buried', 'total-jobs',]) if 'uptime' in stats: days = float(stats['uptime']) / 60.0 / 60.0 / 24.0 stats['uptime'] = '%s (%.2f days)' % (stats['uptime'], days) tube_stats = [] for tube in client.tubes(): tube_stats.append(_multiget(client.stats_tube(tube), ['name', 'pause', 'current-jobs-buried', \ 'current-waiting', 'total-jobs'])) return render_to_response('beanstalk/index.html', {'stats' : stats, 'tube_stats' : tube_stats, 'checks_errors' : checks_errors}, context_instance=RequestContext(request)) @login_required def stats(request): return tube_stats(request) @login_required def stats_table(request): return tube_stats_table(request) @login_required def tube_stats(request, tube=None): try: - client = Client() + client = Client(request) except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/stats.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def tube_stats_table(request, tube=None): try: - client = Client() + client = Client(request) except ConnectionError: return render_unavailable() tubes = client.tubes() stats = {'all':client.stats().items()} for tube in tubes: stats[tube] = client.stats_tube(tube).items() return render_to_response('beanstalk/stats_table.html', {'stats': stats, 'tubes': tubes }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: - client = Client() + client = Client(request) except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None, tube_prefix='', tube=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None try: - client = Client() + client = Client(request) except ConnectionError: return render_unavailable() if id: job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] buried = False else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False tubes = client.tubes() return render_to_response('beanstalk/inspect.html', {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, 'tube_prefix': tube_prefix, 'current_tube': tube}, context_instance=RequestContext(request)) def _peek_if(request, status, tube): try: - client = Client() + client = Client(request) except ConnectionError: return render_unavailable() if not tube: tube = 'default' client.use(tube) job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status, tube=tube) request.flash.put(notice='no job found') return inspect(request, tube_prefix='/beanstalk/%s/' % status, tube=tube) @login_required def ready(request, tube): return _peek_if(request, 'ready', tube) @login_required def delayed(request, tube): return _peek_if(request, 'delayed', tube) @login_required def buried(request, tube): return _peek_if(request, 'buried', tube) def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except IndexError: redirect_to = dest return redirect(redirect_to) @login_required def job_delete(request, id): try: - client = Client() + client = Client(request) job = client.peek(int(id)) if job is not None: job.delete() return _redirect_to_referer_or(request, '/beanstalk/inspect/') except ConnectionError: return render_unavailable() @login_required def job_kick(request, id): try: - client = Client() + client = Client(request) client.use(request.POST['tube']) # The argument to kick is number of jobs not jobId, by default one job # is kicked. client.kick() return redirect('/beanstalk/buried/') except ConnectionError: return render_unavailable() diff --git a/jack/settings.py b/jack/settings.py index 58ecea8..4036d69 100644 --- a/jack/settings.py +++ b/jack/settings.py @@ -1,109 +1,115 @@ # Django settings for jack project. from abspath import abspath DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': abspath('database.db'), # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } -BEANSTALK_HOST = 'localhost' -BEANSTALK_PORT = 11300 - LOGIN_REDIRECT_URL = '/' FLASH_IGNORE_MEDIA = True FLASH_STORAGE = 'session' FLASH_CODEC = 'json' # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = abspath('media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/admin/' # Make this unique, and don't share it with anybody. SECRET_KEY = '8wv3d_4@^=blqi)@ev*v4m=hphqgl6c5av-tbw$pl)2x37_2+-' TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", 'djangoflash.context_processors.flash', ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'djangoflash.middleware.FlashMiddleware', ) ROOT_URLCONF = 'jack.urls' TEMPLATE_DIRS = ( abspath('templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'beanstalk', ) +### MULTIPLE BEANSTALKD SUPPORT +BEANSTALK_SERVERS = ( +) +from django.conf import global_settings +MIDDLEWARE_CLASSES += ('beanstalk.multiple_beanstalk.Middleware',) +TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + ( + 'beanstalk.multiple_beanstalk.ContextProcessor', +) + try: from local_settings import * except ImportError: pass
andreisavu/django-jack
0b0b8177fb132daa40ad8ab3c0fe857e00f8fa5c
fixed 'all' stats to always appear on left side of the page, before any tube stats'
diff --git a/jack/beanstalk/templates/beanstalk/stats_table.html b/jack/beanstalk/templates/beanstalk/stats_table.html index 59d0e53..f03c76c 100644 --- a/jack/beanstalk/templates/beanstalk/stats_table.html +++ b/jack/beanstalk/templates/beanstalk/stats_table.html @@ -1,44 +1,58 @@ {% extends "beanstalk/base.html" %} {% block content %} <b>Tubes Stats:</b> <a href="/beanstalk/stats_table/">all</a> &nbsp; {% for tube in tubes %} <a href="/beanstalk/tube/{{ tube }}/stats/"> {% ifequal tube current_tube %} <b>{{ tube }}</b> {% else %} {{ tube }} {% endifequal %} </a> &nbsp; {% endfor %} <br /> <br /> <table> <tr><td class='aligntop'> {% for tube, tube_stats in stats.items %} - {% ifnotequal tube "default" %} + {% if tube == "all" %} <table class='floatleft gridwidth {% if forloop.counter|divisibleby:'3' %}clearboth{% endif %}'> <tr><th colspan='2'><h3>{{ tube }}</h3></th></tr> <tr><th>Key</th><th>Value</th></tr> {% for key, value in tube_stats %} {% ifnotequal key "name" %} <tr> <td>{{ key }}</td> <td>{{ value }}</td> </tr> {% endifnotequal %} {% endfor %} </table> - {% endifnotequal %} - {% if forloop.first %} </td><td class='aligntop'> {% endif %} {% endfor %} + {% for tube, tube_stats in stats.items %} + {% if tube != "default" and tube != "all" %} + <table class='floatleft gridwidth {% if forloop.counter|divisibleby:'3' %}clearboth{% endif %}'> + <tr><th colspan='2'><h3>{{ tube }}</h3></th></tr> + <tr><th>Key</th><th>Value</th></tr> + {% for key, value in tube_stats %} + {% ifnotequal key "name" %} + <tr> + <td>{{ key }}</td> + <td>{{ value }}</td> + </tr> + {% endifnotequal %} + {% endfor %} + </table> + {% endif %} + {% endfor %} </td></tr> </table> {% endblock %}
andreisavu/django-jack
b9e964f1c2348f3880e1bebe746d636f76e5ca4d
fixed link to stats_table under 'all' link in /stats
diff --git a/jack/beanstalk/templates/beanstalk/stats.html b/jack/beanstalk/templates/beanstalk/stats.html index ad5bad9..f7d3e47 100644 --- a/jack/beanstalk/templates/beanstalk/stats.html +++ b/jack/beanstalk/templates/beanstalk/stats.html @@ -1,36 +1,36 @@ {% extends "beanstalk/base.html" %} {% block content %} <b>Tubes:</b> - <a href="/beanstalk/stats/">all</a> &nbsp; + <a href="/beanstalk/stats_table/">all</a> &nbsp; {% for tube in tubes %} <a href="/beanstalk/tube/{{ tube }}/stats/"> {% ifequal tube current_tube %} <b>{{ tube }}</b> {% else %} {{ tube }} {% endifequal %} </a> &nbsp; {% endfor %} <br /> {% if current_tube %} <h4>Stats for tube: <i>{{ current_tube }}</i></h4> {% else %} <h4>General job queue server stats</h4> {% endif %} <table> <tr><th>Key</th><th>Value</th></tr> {% for key, value in stats %} <tr> <td>{{ key }}</td> <td>{{ value }}</td> </tr> {% endfor %} </table> {% endblock %}
andreisavu/django-jack
241811d1eabe9e1edfd11e291371761169c145f1
added new tube 'stats table' view at /beanstalk/stats_table/
diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html index 3e4bd42..4cfaa51 100644 --- a/jack/beanstalk/templates/beanstalk/base.html +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -1,104 +1,134 @@ <html> <head> <title>{% block title %}Jack and the Beanstalkd{% endblock %}</title> <style type="text/css"> body { padding: 0px; margin: 0px; font-family: "Helvetica LT Std", Helvetica, Arial, sans-serif; } #header { margin: 10px; } #content { margin: 10px; } /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .solidblockmenu{ margin: 0; padding: 0; float: left; font: bold 13px Arial; width: 100%; overflow: hidden; margin-bottom: 1em; border: 1px solid #625e00; border-width: 1px 0; background: black url(/media/blockdefault.gif) center center repeat-x; } .solidblockmenu li{ display: inline; } .solidblockmenu li a{ float: left; color: white; padding: 9px 11px; text-decoration: none; border-right: 1px solid white; } .solidblockmenu li a:visited{ color: white; } .solidblockmenu li a:hover, .solidblockmenu li .current{ color: white; background: transparent url(/media/blockactive.gif) center center repeat-x; } + + .aligntop{ + vertical-align: top; + } + + .floatleft{ + float:left; + } + + .gridwidth{ + width:365px; + } + + .clearboth{ + clear:both; + } + + h3{ + background-color: black; + color: white; + text-align: left; + } + + h3 + table{ + background-color: #EFEFFE; + } + + .aligntop th{ + text-align: left; + } </style> </head> <body> {% block header %} <div id="header"> <h1 style="float: left;font-size: 25px;"> <span style="color: blue">Jack</span> <span style="font-size: 20px;color: grey;">and the</span><br /> <span style="color: green">Beanstalkd</span> </h1> <span style="float: right"> welcome {{ user }} | <a href="/accounts/logout">logout</a> </span> <div style="clear: both;"></div> </div> {% endblock %} {% block menu %} <ul class="solidblockmenu"> <li><a href="/beanstalk/">Home</a></li> <li><a href="/beanstalk/stats/">Stats</a></li> <li><a href="/beanstalk/put/">Put</a></li> <li><a href="/beanstalk/inspect/">Inspect</a></li> <li><a href="/beanstalk/ready/">Peek Ready</a></li> <li><a href="/beanstalk/delayed/">Peek Delayed</a></li> <li><a href="/beanstalk/buried/">Peek Buried</a></li> </ul> <br style="clear: left" /> {% if flash.notice %} <center><span style="border: 1px solid #0aa;padding: 5px;"> {{ flash.notice }}</span></center> {% endif %} {% endblock %} <div id="content"> {% block content %}{% endblock %} </div> {% block footer %} <br /><br /> <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> {% endblock %} </body> </html> diff --git a/jack/beanstalk/templates/beanstalk/stats_table.html b/jack/beanstalk/templates/beanstalk/stats_table.html new file mode 100644 index 0000000..59d0e53 --- /dev/null +++ b/jack/beanstalk/templates/beanstalk/stats_table.html @@ -0,0 +1,44 @@ +{% extends "beanstalk/base.html" %} + +{% block content %} + +<b>Tubes Stats:</b> + <a href="/beanstalk/stats_table/">all</a> &nbsp; + +{% for tube in tubes %} + <a href="/beanstalk/tube/{{ tube }}/stats/"> + {% ifequal tube current_tube %} + <b>{{ tube }}</b> + {% else %} + {{ tube }} + {% endifequal %} + </a> &nbsp; +{% endfor %} +<br /> +<br /> + +<table> + <tr><td class='aligntop'> + {% for tube, tube_stats in stats.items %} + {% ifnotequal tube "default" %} + <table class='floatleft gridwidth {% if forloop.counter|divisibleby:'3' %}clearboth{% endif %}'> + <tr><th colspan='2'><h3>{{ tube }}</h3></th></tr> + <tr><th>Key</th><th>Value</th></tr> + {% for key, value in tube_stats %} + {% ifnotequal key "name" %} + <tr> + <td>{{ key }}</td> + <td>{{ value }}</td> + </tr> + {% endifnotequal %} + {% endfor %} + </table> + {% endifnotequal %} + {% if forloop.first %} + </td><td class='aligntop'> + {% endif %} + {% endfor %} + </td></tr> +</table> + +{% endblock %} diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index 51cbe4c..bce6058 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,16 +1,17 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), (r'^stats/$', views.stats), + (r'^stats_table/$', views.stats_table), (r'^put/$', views.put), (r'^ready/(?P<tube>[\w-]*)$', views.ready), (r'^delayed/(?P<tube>[\w-]*)$', views.delayed), (r'^buried/(?P<tube>[\w-]*)$', views.buried), (r'^inspect/(?P<id>\d*)$', views.inspect), (r'^tube/(?P<tube>[\w-]+)/stats/$', views.tube_stats), (r'^job/(?P<id>\d+)/delete/$', views.job_delete), (r'^job/(?P<id>\d+)/kick/$', views.job_kick), ) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 3a82bbb..77389fa 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,210 +1,232 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable from beanstalk import checks from urlparse import urlsplit def _multiget(data, keys, default=None): ret = {} for key in keys: ret[key] = data.get(key, default) return ret @login_required def index(request): try: client = Client() except ConnectionError: return render_unavailable() checks_errors = checks.run_all(client) stats = _multiget(client.stats(), [ 'current-connections', 'uptime', 'job-timeouts', 'version', 'current-jobs-buried', 'total-jobs',]) if 'uptime' in stats: days = float(stats['uptime']) / 60.0 / 60.0 / 24.0 stats['uptime'] = '%s (%.2f days)' % (stats['uptime'], days) tube_stats = [] for tube in client.tubes(): tube_stats.append(_multiget(client.stats_tube(tube), ['name', 'pause', 'current-jobs-buried', \ 'current-waiting', 'total-jobs'])) return render_to_response('beanstalk/index.html', {'stats' : stats, 'tube_stats' : tube_stats, 'checks_errors' : checks_errors}, context_instance=RequestContext(request)) @login_required def stats(request): return tube_stats(request) +@login_required +def stats_table(request): + return tube_stats_table(request) + @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/stats.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) +@login_required +def tube_stats_table(request, tube=None): + try: + client = Client() + except ConnectionError: + return render_unavailable() + + tubes = client.tubes() + stats = {'all':client.stats().items()} + + for tube in tubes: + stats[tube] = client.stats_tube(tube).items() + + return render_to_response('beanstalk/stats_table.html', + {'stats': stats, + 'tubes': tubes + }, context_instance=RequestContext(request)) + @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None, tube_prefix='', tube=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None try: client = Client() except ConnectionError: return render_unavailable() if id: job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] buried = False else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False tubes = client.tubes() return render_to_response('beanstalk/inspect.html', {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, 'tube_prefix': tube_prefix, 'current_tube': tube}, context_instance=RequestContext(request)) def _peek_if(request, status, tube): try: client = Client() except ConnectionError: return render_unavailable() if not tube: tube = 'default' client.use(tube) job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status, tube=tube) request.flash.put(notice='no job found') return inspect(request, tube_prefix='/beanstalk/%s/' % status, tube=tube) @login_required def ready(request, tube): return _peek_if(request, 'ready', tube) @login_required def delayed(request, tube): return _peek_if(request, 'delayed', tube) @login_required def buried(request, tube): return _peek_if(request, 'buried', tube) def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except IndexError: redirect_to = dest return redirect(redirect_to) @login_required def job_delete(request, id): try: client = Client() job = client.peek(int(id)) if job is not None: job.delete() return _redirect_to_referer_or(request, '/beanstalk/inspect/') except ConnectionError: return render_unavailable() @login_required def job_kick(request, id): try: client = Client() client.use(request.POST['tube']) # The argument to kick is number of jobs not jobId, by default one job # is kicked. client.kick() return redirect('/beanstalk/buried/') except ConnectionError: return render_unavailable()
andreisavu/django-jack
59203d1c1d730e0ff6bd9384fcfca896ee9400e8
added path to sqlite db
diff --git a/jack/settings.py b/jack/settings.py index c2a4d6b..58ecea8 100644 --- a/jack/settings.py +++ b/jack/settings.py @@ -1,109 +1,109 @@ # Django settings for jack project. from abspath import abspath DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. - 'NAME': '', # Or path to database file if using sqlite3. + 'NAME': abspath('database.db'), # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } BEANSTALK_HOST = 'localhost' BEANSTALK_PORT = 11300 LOGIN_REDIRECT_URL = '/' FLASH_IGNORE_MEDIA = True FLASH_STORAGE = 'session' FLASH_CODEC = 'json' # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = abspath('media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/admin/' # Make this unique, and don't share it with anybody. SECRET_KEY = '8wv3d_4@^=blqi)@ev*v4m=hphqgl6c5av-tbw$pl)2x37_2+-' TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", 'djangoflash.context_processors.flash', ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'djangoflash.middleware.FlashMiddleware', ) ROOT_URLCONF = 'jack.urls' TEMPLATE_DIRS = ( abspath('templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'beanstalk', ) try: from local_settings import * except ImportError: pass
andreisavu/django-jack
f30b912a98e13c630b95f2d5917371a3c3ccacca
Fix kick jobs on non-default tubes.
diff --git a/jack/beanstalk/templates/beanstalk/inspect.html b/jack/beanstalk/templates/beanstalk/inspect.html index 2807f4f..7fac87e 100644 --- a/jack/beanstalk/templates/beanstalk/inspect.html +++ b/jack/beanstalk/templates/beanstalk/inspect.html @@ -1,55 +1,56 @@ {% extends "beanstalk/base.html" %} {% block content %} <style type="text/css"> .stats td, .stats th { padding: 2px; } </style> <form action="/beanstalk/inspect/" method="post"> <label>ID:</label> <input type="text" name="id" /> <button type="submit">Inspect</button> </form> {% if tube_prefix %} Peek tube: {% for tube in tubes %} <a href="{{ tube_prefix }}{{ tube }}">{{ tube }}</a> &nbsp; {% endfor %} {% endif %} {% if job %} <table class="stats"> <tr><th>ID</th><td>{{ job.jid }}</td></tr> <tr><th>Body</th><td> <textarea rows="3" cols="80">{{ job.body }}</textarea> </td></tr> <tr><th valign="top">Stats</th><td> <table> <tr><th>Key</th><th>Value</th></tr> {% for key, value in stats %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% endfor %} </table> </td></tr> <tr> <th>Options</th> <td> {% if buried %} <form action="/beanstalk/job/{{ job.jid }}/kick/" method="post" style="display: inline"> <button type="submit">kick</button> + <input type="hidden" value="{{ current_tube }}" name="tube" /> </form> {% endif %} <form action="/beanstalk/job/{{ job.jid }}/delete/" method="post" style="display:inline" onsubmit="return confirm('Are you sure?')"> <button type="submit">delete</button> </form> </td> </tr> </table> {% endif %} {% endblock %} diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index d6398d4..3a82bbb 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,207 +1,210 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable from beanstalk import checks from urlparse import urlsplit def _multiget(data, keys, default=None): ret = {} for key in keys: ret[key] = data.get(key, default) return ret @login_required def index(request): try: client = Client() except ConnectionError: return render_unavailable() checks_errors = checks.run_all(client) stats = _multiget(client.stats(), [ 'current-connections', 'uptime', 'job-timeouts', 'version', 'current-jobs-buried', 'total-jobs',]) if 'uptime' in stats: days = float(stats['uptime']) / 60.0 / 60.0 / 24.0 stats['uptime'] = '%s (%.2f days)' % (stats['uptime'], days) tube_stats = [] for tube in client.tubes(): tube_stats.append(_multiget(client.stats_tube(tube), ['name', 'pause', 'current-jobs-buried', \ 'current-waiting', 'total-jobs'])) return render_to_response('beanstalk/index.html', {'stats' : stats, 'tube_stats' : tube_stats, 'checks_errors' : checks_errors}, context_instance=RequestContext(request)) @login_required def stats(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/stats.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required -def inspect(request, id=None, tube_prefix=''): +def inspect(request, id=None, tube_prefix='', tube=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None try: client = Client() except ConnectionError: return render_unavailable() if id: job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] buried = False else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False tubes = client.tubes() return render_to_response('beanstalk/inspect.html', - {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, 'tube_prefix': tube_prefix}, + {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, + 'tube_prefix': tube_prefix, 'current_tube': tube}, context_instance=RequestContext(request)) def _peek_if(request, status, tube): try: client = Client() except ConnectionError: return render_unavailable() if not tube: tube = 'default' client.use(tube) job = getattr(client, "peek_%s" % status)() if job is not None: - return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status) + return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status, tube=tube) request.flash.put(notice='no job found') - return inspect(request, tube_prefix = '/beanstalk/%s/' % status) + return inspect(request, tube_prefix='/beanstalk/%s/' % status, tube=tube) @login_required def ready(request, tube): return _peek_if(request, 'ready', tube) - @login_required def delayed(request, tube): return _peek_if(request, 'delayed', tube) @login_required def buried(request, tube): return _peek_if(request, 'buried', tube) def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except IndexError: redirect_to = dest return redirect(redirect_to) @login_required def job_delete(request, id): try: client = Client() job = client.peek(int(id)) if job is not None: job.delete() return _redirect_to_referer_or(request, '/beanstalk/inspect/') except ConnectionError: return render_unavailable() @login_required def job_kick(request, id): try: client = Client() - client.kick(int(id)) + client.use(request.POST['tube']) + # The argument to kick is number of jobs not jobId, by default one job + # is kicked. + client.kick() return redirect('/beanstalk/buried/') except ConnectionError: return render_unavailable()
andreisavu/django-jack
f6c8e1e090f828bbc0544d822616e3b5efe2a905
removed extra specific install instructions
diff --git a/README b/README index 1e0bd86..c7708a4 100644 --- a/README +++ b/README @@ -1,71 +1,32 @@ Jack - Beanstalkd web administration interface ============================================== What is beanstalkd? ------------------- "... a fast, general-purpose work queue." See http://xph.us/software/beanstalkd/ for general info. What can I do using this application? ------------------------------------- - put job on queue in a given tube - inspect job: view body and statistics - inspect burried jobs and kick all or individual - inspect delayed jobs - view what tubes are currently in use and stats - view queue statistics Requirements ------------ * Django 1.1 http://www.djangoproject.com/ * beanstalkc http://github.com/earl/beanstalkc -Mods ----- -Basically, the "handsome" in this name comes from the single line of code: -font-family: "Helvetica LT Std", Helvetica, Arial, sans-serif; -in jack/beanstalk/templates/beanstalk/base.html -This changed the font from a serif font (Times New Roman I think on most systems) to a nice Helvetica font - -The other adjustment is moving the the folder accounts -(./jack/templates/accounts) -to the beanstalk templates -(./jack/beanstalk/templates/accounts) -This prevented Django from whining that it couldn't find the correct templates to login with - -Installation ------------- -I spend ages getting this to work, and this little passage is what I learnt when I installed it -I will revise this once I move VPS's again and have to reinstall it - -I managed to work out how to install django/beanstalkc by extracting it, "cd"ing into it and running: -python setup.py install - -I did end up going on a goose hunt installing dependancies, simply put, google it -egg files are installed by going "sh *.egg" - -Paraphrased from here: -http://docs.djangoproject.com/en/dev/intro/tutorial01/ - -python manage.py syncdb -python manage.py runserver 0.0.0.0:8000 -equates (roughly to) -rake db:migrate -thin start -a 0.0.0.0 -p 8000 - -Read the end of the stack trace, in my experiance it came up with an human-readable error - -Sorry about the crud instructions, I'll update them when I swap VPS's and install beanstalkd -Good luck! :) - -
andreisavu/django-jack
f18b841b3105861fbe38683368637d6ce2aa25ab
adding adjustments (cherry picked from commit 508976e52d9ba1512f5b9255341fc5f7506a8806)
diff --git a/README b/README index c7708a4..1e0bd86 100644 --- a/README +++ b/README @@ -1,32 +1,71 @@ Jack - Beanstalkd web administration interface ============================================== What is beanstalkd? ------------------- "... a fast, general-purpose work queue." See http://xph.us/software/beanstalkd/ for general info. What can I do using this application? ------------------------------------- - put job on queue in a given tube - inspect job: view body and statistics - inspect burried jobs and kick all or individual - inspect delayed jobs - view what tubes are currently in use and stats - view queue statistics Requirements ------------ * Django 1.1 http://www.djangoproject.com/ * beanstalkc http://github.com/earl/beanstalkc +Mods +---- +Basically, the "handsome" in this name comes from the single line of code: +font-family: "Helvetica LT Std", Helvetica, Arial, sans-serif; +in jack/beanstalk/templates/beanstalk/base.html +This changed the font from a serif font (Times New Roman I think on most systems) to a nice Helvetica font + +The other adjustment is moving the the folder accounts +(./jack/templates/accounts) +to the beanstalk templates +(./jack/beanstalk/templates/accounts) +This prevented Django from whining that it couldn't find the correct templates to login with + +Installation +------------ +I spend ages getting this to work, and this little passage is what I learnt when I installed it +I will revise this once I move VPS's again and have to reinstall it + +I managed to work out how to install django/beanstalkc by extracting it, "cd"ing into it and running: +python setup.py install + +I did end up going on a goose hunt installing dependancies, simply put, google it +egg files are installed by going "sh *.egg" + +Paraphrased from here: +http://docs.djangoproject.com/en/dev/intro/tutorial01/ + +python manage.py syncdb +python manage.py runserver 0.0.0.0:8000 +equates (roughly to) +rake db:migrate +thin start -a 0.0.0.0 -p 8000 + +Read the end of the stack trace, in my experiance it came up with an human-readable error + +Sorry about the crud instructions, I'll update them when I swap VPS's and install beanstalkd +Good luck! :) + + diff --git a/jack/beanstalk/templates/accounts/login.html b/jack/beanstalk/templates/accounts/login.html new file mode 100644 index 0000000..f39ebf4 --- /dev/null +++ b/jack/beanstalk/templates/accounts/login.html @@ -0,0 +1,10 @@ +{% extends "admin/login.html" %} + +{% block title %}Login | Jack{% endblock %} + +{% block branding %}{% endblock %} + +{% block content_title %} + <center><h1>Jack and the Beanstalkd</h1></center> +{% endblock %} + diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html index 1089b25..3e4bd42 100644 --- a/jack/beanstalk/templates/beanstalk/base.html +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -1,103 +1,104 @@ <html> <head> <title>{% block title %}Jack and the Beanstalkd{% endblock %}</title> <style type="text/css"> body { padding: 0px; margin: 0px; + font-family: "Helvetica LT Std", Helvetica, Arial, sans-serif; } #header { margin: 10px; } #content { margin: 10px; } /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .solidblockmenu{ margin: 0; padding: 0; float: left; font: bold 13px Arial; width: 100%; overflow: hidden; margin-bottom: 1em; border: 1px solid #625e00; border-width: 1px 0; background: black url(/media/blockdefault.gif) center center repeat-x; } .solidblockmenu li{ display: inline; } .solidblockmenu li a{ float: left; color: white; padding: 9px 11px; text-decoration: none; border-right: 1px solid white; } .solidblockmenu li a:visited{ color: white; } .solidblockmenu li a:hover, .solidblockmenu li .current{ color: white; background: transparent url(/media/blockactive.gif) center center repeat-x; } </style> </head> <body> {% block header %} <div id="header"> <h1 style="float: left;font-size: 25px;"> <span style="color: blue">Jack</span> <span style="font-size: 20px;color: grey;">and the</span><br /> <span style="color: green">Beanstalkd</span> </h1> <span style="float: right"> welcome {{ user }} | <a href="/accounts/logout">logout</a> </span> <div style="clear: both;"></div> </div> {% endblock %} {% block menu %} <ul class="solidblockmenu"> <li><a href="/beanstalk/">Home</a></li> <li><a href="/beanstalk/stats/">Stats</a></li> <li><a href="/beanstalk/put/">Put</a></li> <li><a href="/beanstalk/inspect/">Inspect</a></li> <li><a href="/beanstalk/ready/">Peek Ready</a></li> <li><a href="/beanstalk/delayed/">Peek Delayed</a></li> <li><a href="/beanstalk/buried/">Peek Buried</a></li> </ul> <br style="clear: left" /> {% if flash.notice %} <center><span style="border: 1px solid #0aa;padding: 5px;"> {{ flash.notice }}</span></center> {% endif %} {% endblock %} <div id="content"> {% block content %}{% endblock %} </div> {% block footer %} <br /><br /> <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> {% endblock %} </body> </html>
andreisavu/django-jack
bde7fafcaf311326f22c082fe46684264dbd6155
fixed title tag to make page render in chrome
diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html index 36866a7..1089b25 100644 --- a/jack/beanstalk/templates/beanstalk/base.html +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -1,103 +1,103 @@ <html> <head> - <title>{% block title %}Jack and the Beanstalkd{% endblock %} + <title>{% block title %}Jack and the Beanstalkd{% endblock %}</title> <style type="text/css"> body { padding: 0px; margin: 0px; } #header { margin: 10px; } #content { margin: 10px; } /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .solidblockmenu{ margin: 0; padding: 0; float: left; font: bold 13px Arial; width: 100%; overflow: hidden; margin-bottom: 1em; border: 1px solid #625e00; border-width: 1px 0; background: black url(/media/blockdefault.gif) center center repeat-x; } .solidblockmenu li{ display: inline; } .solidblockmenu li a{ float: left; color: white; padding: 9px 11px; text-decoration: none; border-right: 1px solid white; } .solidblockmenu li a:visited{ color: white; } .solidblockmenu li a:hover, .solidblockmenu li .current{ color: white; background: transparent url(/media/blockactive.gif) center center repeat-x; } </style> </head> <body> {% block header %} <div id="header"> <h1 style="float: left;font-size: 25px;"> <span style="color: blue">Jack</span> <span style="font-size: 20px;color: grey;">and the</span><br /> <span style="color: green">Beanstalkd</span> </h1> <span style="float: right"> welcome {{ user }} | <a href="/accounts/logout">logout</a> </span> <div style="clear: both;"></div> </div> {% endblock %} {% block menu %} <ul class="solidblockmenu"> <li><a href="/beanstalk/">Home</a></li> <li><a href="/beanstalk/stats/">Stats</a></li> <li><a href="/beanstalk/put/">Put</a></li> <li><a href="/beanstalk/inspect/">Inspect</a></li> <li><a href="/beanstalk/ready/">Peek Ready</a></li> <li><a href="/beanstalk/delayed/">Peek Delayed</a></li> <li><a href="/beanstalk/buried/">Peek Buried</a></li> </ul> <br style="clear: left" /> {% if flash.notice %} <center><span style="border: 1px solid #0aa;padding: 5px;"> {{ flash.notice }}</span></center> {% endif %} {% endblock %} <div id="content"> {% block content %}{% endblock %} </div> {% block footer %} <br /><br /> <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> {% endblock %} </body> </html>
andreisavu/django-jack
d903e3d7f01add54fe1b8db7d33229f90092a851
add setup.py for use with pip et al
diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..2632044 --- /dev/null +++ b/setup.py @@ -0,0 +1,20 @@ +from distutils.core import setup + +setup(name='django-jack', + version='0.1', + description='Jack and the Beanstalkd. Webapp for basic work queue administration', + long_description='''Basic beanstalkd work queue administration, allows one to: + - put job on queue in a given tube + - inspect job: view body and statistics + - inspect burried jobs and kick all or individual + - inspect delayed jobs + - view what tubes are currently in use and stats + - view queue statistics + ''', + author='Andrei Savu', + url='http://github.com/andreisavu/django-jack', + packages=['jack'], + classifiers=['Development Status :: 4 - Beta', + 'Framework :: Django', + ], + )
andreisavu/django-jack
5c9f89a2499e8f3452ac433a751d522cf40b9fca
implemented basic check for buried jobs
diff --git a/jack/beanstalk/checks/README b/jack/beanstalk/checks/README new file mode 100644 index 0000000..b2e7a95 --- /dev/null +++ b/jack/beanstalk/checks/README @@ -0,0 +1,5 @@ + +This folder contains work queue status checkers + +Take a look at buried.py if you want to know how to implement a new one. + diff --git a/jack/beanstalk/checks/__init__.py b/jack/beanstalk/checks/__init__.py new file mode 100644 index 0000000..abe1f24 --- /dev/null +++ b/jack/beanstalk/checks/__init__.py @@ -0,0 +1,29 @@ + +import os +import imp +import re + +def run_all(client): + errors = [] + for name, check in _get_checkers(): + try: + result = check.do_check(client) + if result is not None: + errors.append('Check "%s": %s' % (name, result)) + + except AttributeError, e: + errors.append('Invalid checker "%s": %s' % (name, e)) + + return errors + +def _get_checkers(): + current_dir = os.path.dirname(os.path.realpath(__file__)) + + for file in os.listdir(current_dir): + m = re.match('([a-zA-Z\d]+)\.py$', file) + + if m is not None: + name = m.groups()[0] + mod = imp.load_source('checker_%s' % name, os.path.join(current_dir, file)) + yield name, mod + diff --git a/jack/beanstalk/checks/buried.py b/jack/beanstalk/checks/buried.py new file mode 100644 index 0000000..7931293 --- /dev/null +++ b/jack/beanstalk/checks/buried.py @@ -0,0 +1,26 @@ +""" Basic check for buried jobs + +The max number for buried jobs should not exced 3 and +the max age of buried job should not exced 120 seconds. +""" + + +def do_check(client): + current_buried = client.stats()['current-jobs-buried'] + if current_buried >= 3: + return 'found %d jobs buried.' % current_buried + + max_age, max_jid = 0, 0 + for tube in client.tubes(): + client.use(tube) + + job = client.peek_buried() + if job is not None: + age = int(job.stats()['age']) + if age > max_age: + max_age, max_jid = age, job.jid + + if max_jid and max_age > 120: + return 'found old buried job #%d' % max_jid + + diff --git a/jack/beanstalk/templates/beanstalk/index.html b/jack/beanstalk/templates/beanstalk/index.html index 2f4e3af..3ec9267 100644 --- a/jack/beanstalk/templates/beanstalk/index.html +++ b/jack/beanstalk/templates/beanstalk/index.html @@ -1,42 +1,55 @@ {% extends "beanstalk/base.html" %} {% block content %} <div id="status"> +{% if not checks_errors %} + <img src="/media/check-ok.jpg" style="float: left;margin-right: 50px;margin-left: 20px;"/> <h1>System ok. Running as expected.</h1> -</div> -<div class="clear"></div> + <div style="clear: both;"></div><br /> +{% else %} + + <img src="/media/check-not-ok.jpg" style="float: left;margin-right: 50px;margin-left: 20px;"/> + <h1>We've got some errors.</h1> + <div style="clear: both"></div><br /> + <ul> + {% for error in checks_errors %} + <li><span style="color: red">{{ error }}</span</li> + {% endfor %} + </ul> + +{% endif %} +</div> -<br /> <h2>global stats</h2> {% if stats %} <table> <tr><th>Key</th><th>Value</th></tr> {% for key, value in stats.items %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% endfor %} </table> {% endif %} <div class="clear"></div><br /> <h2>tube stats</h2> <div style="width: 60%;"> {% for tube in tube_stats %} {% if tube %} <table style="float: left;margin: 15px;padding: 10px;border: 1px solid grey"> <tr><th>Key</th><th>Value</th></tr> {% for key, value in tube.items %} <tr><td nowrap="1">{{ key }}</td><td nowrap="1">{{ value }}</td></tr> {% endfor %} </table> {% endif %} {% endfor %} <div style="clear: both"></div> </div> {% endblock %} diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index b84bd43..d6398d4 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,201 +1,207 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable +from beanstalk import checks from urlparse import urlsplit def _multiget(data, keys, default=None): ret = {} for key in keys: ret[key] = data.get(key, default) return ret @login_required def index(request): try: client = Client() except ConnectionError: return render_unavailable() + checks_errors = checks.run_all(client) + stats = _multiget(client.stats(), [ 'current-connections', 'uptime', 'job-timeouts', 'version', 'current-jobs-buried', 'total-jobs',]) + if 'uptime' in stats: days = float(stats['uptime']) / 60.0 / 60.0 / 24.0 stats['uptime'] = '%s (%.2f days)' % (stats['uptime'], days) tube_stats = [] for tube in client.tubes(): tube_stats.append(_multiget(client.stats_tube(tube), ['name', 'pause', 'current-jobs-buried', \ 'current-waiting', 'total-jobs'])) return render_to_response('beanstalk/index.html', - {'stats' : stats, 'tube_stats' : tube_stats}, + {'stats' : stats, + 'tube_stats' : tube_stats, + 'checks_errors' : checks_errors}, context_instance=RequestContext(request)) @login_required def stats(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/stats.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None, tube_prefix=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None try: client = Client() except ConnectionError: return render_unavailable() if id: job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] buried = False else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False tubes = client.tubes() return render_to_response('beanstalk/inspect.html', {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, 'tube_prefix': tube_prefix}, context_instance=RequestContext(request)) def _peek_if(request, status, tube): try: client = Client() except ConnectionError: return render_unavailable() if not tube: tube = 'default' client.use(tube) job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status) request.flash.put(notice='no job found') return inspect(request, tube_prefix = '/beanstalk/%s/' % status) @login_required def ready(request, tube): return _peek_if(request, 'ready', tube) @login_required def delayed(request, tube): return _peek_if(request, 'delayed', tube) @login_required def buried(request, tube): return _peek_if(request, 'buried', tube) def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except IndexError: redirect_to = dest return redirect(redirect_to) @login_required def job_delete(request, id): try: client = Client() job = client.peek(int(id)) if job is not None: job.delete() return _redirect_to_referer_or(request, '/beanstalk/inspect/') except ConnectionError: return render_unavailable() @login_required def job_kick(request, id): try: client = Client() client.kick(int(id)) return redirect('/beanstalk/buried/') except ConnectionError: return render_unavailable()
andreisavu/django-jack
430a2b7682e9a45120c1737ae34083c3cdeea2a6
display uptime in days
diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 812a60e..b84bd43 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,198 +1,201 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable from urlparse import urlsplit def _multiget(data, keys, default=None): ret = {} for key in keys: ret[key] = data.get(key, default) return ret @login_required def index(request): try: client = Client() except ConnectionError: return render_unavailable() stats = _multiget(client.stats(), [ 'current-connections', 'uptime', 'job-timeouts', 'version', 'current-jobs-buried', 'total-jobs',]) + if 'uptime' in stats: + days = float(stats['uptime']) / 60.0 / 60.0 / 24.0 + stats['uptime'] = '%s (%.2f days)' % (stats['uptime'], days) tube_stats = [] for tube in client.tubes(): tube_stats.append(_multiget(client.stats_tube(tube), ['name', 'pause', 'current-jobs-buried', \ 'current-waiting', 'total-jobs'])) return render_to_response('beanstalk/index.html', {'stats' : stats, 'tube_stats' : tube_stats}, context_instance=RequestContext(request)) @login_required def stats(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/stats.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None, tube_prefix=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None try: client = Client() except ConnectionError: return render_unavailable() if id: job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] buried = False else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False tubes = client.tubes() return render_to_response('beanstalk/inspect.html', {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, 'tube_prefix': tube_prefix}, context_instance=RequestContext(request)) def _peek_if(request, status, tube): try: client = Client() except ConnectionError: return render_unavailable() if not tube: tube = 'default' client.use(tube) job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status) request.flash.put(notice='no job found') return inspect(request, tube_prefix = '/beanstalk/%s/' % status) @login_required def ready(request, tube): return _peek_if(request, 'ready', tube) @login_required def delayed(request, tube): return _peek_if(request, 'delayed', tube) @login_required def buried(request, tube): return _peek_if(request, 'buried', tube) def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except IndexError: redirect_to = dest return redirect(redirect_to) @login_required def job_delete(request, id): try: client = Client() job = client.peek(int(id)) if job is not None: job.delete() return _redirect_to_referer_or(request, '/beanstalk/inspect/') except ConnectionError: return render_unavailable() @login_required def job_kick(request, id): try: client = Client() client.kick(int(id)) return redirect('/beanstalk/buried/') except ConnectionError: return render_unavailable()
andreisavu/django-jack
a03c146b7b2dc90233db7671804048dae5527d09
display small stats about each active tube
diff --git a/jack/beanstalk/templates/beanstalk/index.html b/jack/beanstalk/templates/beanstalk/index.html index 3879b05..2f4e3af 100644 --- a/jack/beanstalk/templates/beanstalk/index.html +++ b/jack/beanstalk/templates/beanstalk/index.html @@ -1,28 +1,42 @@ {% extends "beanstalk/base.html" %} {% block content %} <div id="status"> <img src="/media/check-ok.jpg" style="float: left;margin-right: 50px;margin-left: 20px;"/> <h1>System ok. Running as expected.</h1> </div> <div class="clear"></div> <br /> <h2>global stats</h2> {% if stats %} <table> <tr><th>Key</th><th>Value</th></tr> {% for key, value in stats.items %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% endfor %} </table> {% endif %} <div class="clear"></div><br /> <h2>tube stats</h2> +<div style="width: 60%;"> +{% for tube in tube_stats %} + {% if tube %} + <table style="float: left;margin: 15px;padding: 10px;border: 1px solid grey"> + <tr><th>Key</th><th>Value</th></tr> + {% for key, value in tube.items %} + <tr><td nowrap="1">{{ key }}</td><td nowrap="1">{{ value }}</td></tr> + {% endfor %} + </table> + {% endif %} +{% endfor %} +<div style="clear: both"></div> +</div> + {% endblock %} diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 34a12f5..812a60e 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,192 +1,198 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable from urlparse import urlsplit def _multiget(data, keys, default=None): ret = {} for key in keys: ret[key] = data.get(key, default) return ret @login_required def index(request): try: client = Client() except ConnectionError: return render_unavailable() stats = _multiget(client.stats(), [ 'current-connections', 'uptime', 'job-timeouts', 'version', 'current-jobs-buried', 'total-jobs',]) + tube_stats = [] + for tube in client.tubes(): + tube_stats.append(_multiget(client.stats_tube(tube), + ['name', 'pause', 'current-jobs-buried', \ + 'current-waiting', 'total-jobs'])) + return render_to_response('beanstalk/index.html', - {'stats' : stats}, + {'stats' : stats, 'tube_stats' : tube_stats}, context_instance=RequestContext(request)) @login_required def stats(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/stats.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None, tube_prefix=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None try: client = Client() except ConnectionError: return render_unavailable() if id: job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] buried = False else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False tubes = client.tubes() return render_to_response('beanstalk/inspect.html', {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, 'tube_prefix': tube_prefix}, context_instance=RequestContext(request)) def _peek_if(request, status, tube): try: client = Client() except ConnectionError: return render_unavailable() if not tube: tube = 'default' client.use(tube) job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status) request.flash.put(notice='no job found') return inspect(request, tube_prefix = '/beanstalk/%s/' % status) @login_required def ready(request, tube): return _peek_if(request, 'ready', tube) @login_required def delayed(request, tube): return _peek_if(request, 'delayed', tube) @login_required def buried(request, tube): return _peek_if(request, 'buried', tube) def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except IndexError: redirect_to = dest return redirect(redirect_to) @login_required def job_delete(request, id): try: client = Client() job = client.peek(int(id)) if job is not None: job.delete() return _redirect_to_referer_or(request, '/beanstalk/inspect/') except ConnectionError: return render_unavailable() @login_required def job_kick(request, id): try: client = Client() client.kick(int(id)) return redirect('/beanstalk/buried/') except ConnectionError: return render_unavailable()
andreisavu/django-jack
d3fb14f496efba3dafd25f4e8d3f19cee921ef64
show some global statistics and a dummy system ok
diff --git a/jack/beanstalk/templates/beanstalk/index.html b/jack/beanstalk/templates/beanstalk/index.html index 3e12d46..3879b05 100644 --- a/jack/beanstalk/templates/beanstalk/index.html +++ b/jack/beanstalk/templates/beanstalk/index.html @@ -1,8 +1,28 @@ {% extends "beanstalk/base.html" %} {% block content %} -System overview. +<div id="status"> + <img src="/media/check-ok.jpg" style="float: left;margin-right: 50px;margin-left: 20px;"/> + <h1>System ok. Running as expected.</h1> +</div> + +<div class="clear"></div> + +<br /> +<h2>global stats</h2> + +{% if stats %} + <table> + <tr><th>Key</th><th>Value</th></tr> + {% for key, value in stats.items %} + <tr><td>{{ key }}</td><td>{{ value }}</td></tr> + {% endfor %} + </table> +{% endif %} + +<div class="clear"></div><br /> +<h2>tube stats</h2> {% endblock %} diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 1e4b780..34a12f5 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,172 +1,192 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable from urlparse import urlsplit +def _multiget(data, keys, default=None): + ret = {} + for key in keys: + ret[key] = data.get(key, default) + return ret + @login_required def index(request): + try: + client = Client() + except ConnectionError: + return render_unavailable() + + stats = _multiget(client.stats(), [ + 'current-connections', + 'uptime', + 'job-timeouts', + 'version', + 'current-jobs-buried', + 'total-jobs',]) + return render_to_response('beanstalk/index.html', + {'stats' : stats}, context_instance=RequestContext(request)) @login_required def stats(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/stats.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None, tube_prefix=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None try: client = Client() except ConnectionError: return render_unavailable() if id: job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] buried = False else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False tubes = client.tubes() return render_to_response('beanstalk/inspect.html', {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, 'tube_prefix': tube_prefix}, context_instance=RequestContext(request)) def _peek_if(request, status, tube): try: client = Client() except ConnectionError: return render_unavailable() if not tube: tube = 'default' client.use(tube) job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status) request.flash.put(notice='no job found') return inspect(request, tube_prefix = '/beanstalk/%s/' % status) @login_required def ready(request, tube): return _peek_if(request, 'ready', tube) @login_required def delayed(request, tube): return _peek_if(request, 'delayed', tube) @login_required def buried(request, tube): return _peek_if(request, 'buried', tube) def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except IndexError: redirect_to = dest return redirect(redirect_to) @login_required def job_delete(request, id): try: client = Client() job = client.peek(int(id)) if job is not None: job.delete() return _redirect_to_referer_or(request, '/beanstalk/inspect/') except ConnectionError: return render_unavailable() @login_required def job_kick(request, id): try: client = Client() client.kick(int(id)) return redirect('/beanstalk/buried/') except ConnectionError: return render_unavailable() diff --git a/jack/media/check-not-ok.jpg b/jack/media/check-not-ok.jpg new file mode 100644 index 0000000..2f7803b Binary files /dev/null and b/jack/media/check-not-ok.jpg differ diff --git a/jack/media/check-ok.jpg b/jack/media/check-ok.jpg new file mode 100644 index 0000000..e699448 Binary files /dev/null and b/jack/media/check-ok.jpg differ
andreisavu/django-jack
ed6a298afe62b59181e45bcf9acfc5aaa2b8b365
moved stats page. the home page is going to be used for system overview
diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html index 5543a29..36866a7 100644 --- a/jack/beanstalk/templates/beanstalk/base.html +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -1,102 +1,103 @@ <html> <head> <title>{% block title %}Jack and the Beanstalkd{% endblock %} <style type="text/css"> body { padding: 0px; margin: 0px; } #header { margin: 10px; } #content { margin: 10px; } /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .solidblockmenu{ margin: 0; padding: 0; float: left; font: bold 13px Arial; width: 100%; overflow: hidden; margin-bottom: 1em; border: 1px solid #625e00; border-width: 1px 0; background: black url(/media/blockdefault.gif) center center repeat-x; } .solidblockmenu li{ display: inline; } .solidblockmenu li a{ float: left; color: white; padding: 9px 11px; text-decoration: none; border-right: 1px solid white; } .solidblockmenu li a:visited{ color: white; } .solidblockmenu li a:hover, .solidblockmenu li .current{ color: white; background: transparent url(/media/blockactive.gif) center center repeat-x; } </style> </head> <body> {% block header %} <div id="header"> <h1 style="float: left;font-size: 25px;"> <span style="color: blue">Jack</span> <span style="font-size: 20px;color: grey;">and the</span><br /> <span style="color: green">Beanstalkd</span> </h1> <span style="float: right"> welcome {{ user }} | <a href="/accounts/logout">logout</a> </span> <div style="clear: both;"></div> </div> {% endblock %} {% block menu %} <ul class="solidblockmenu"> <li><a href="/beanstalk/">Home</a></li> + <li><a href="/beanstalk/stats/">Stats</a></li> <li><a href="/beanstalk/put/">Put</a></li> <li><a href="/beanstalk/inspect/">Inspect</a></li> <li><a href="/beanstalk/ready/">Peek Ready</a></li> <li><a href="/beanstalk/delayed/">Peek Delayed</a></li> <li><a href="/beanstalk/buried/">Peek Buried</a></li> </ul> <br style="clear: left" /> {% if flash.notice %} <center><span style="border: 1px solid #0aa;padding: 5px;"> {{ flash.notice }}</span></center> {% endif %} {% endblock %} <div id="content"> {% block content %}{% endblock %} </div> {% block footer %} <br /><br /> <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> {% endblock %} </body> </html> diff --git a/jack/beanstalk/templates/beanstalk/index.html b/jack/beanstalk/templates/beanstalk/index.html index eb45303..3e12d46 100644 --- a/jack/beanstalk/templates/beanstalk/index.html +++ b/jack/beanstalk/templates/beanstalk/index.html @@ -1,36 +1,8 @@ {% extends "beanstalk/base.html" %} {% block content %} -<b>Tubes:</b> - <a href="/beanstalk/">all</a> &nbsp; - -{% for tube in tubes %} - <a href="/beanstalk/tube/{{ tube }}/stats/"> - {% ifequal tube current_tube %} - <b>{{ tube }}</b> - {% else %} - {{ tube }} - {% endifequal %} - </a> &nbsp; -{% endfor %} -<br /> - - -{% if current_tube %} - <h4>Stats for tube: <i>{{ current_tube }}</i></h4> -{% else %} - <h4>General job queue server stats</h4> -{% endif %} - -<table> - <tr><th>Key</th><th>Value</th></tr> -{% for key, value in stats %} - <tr> - <td>{{ key }}</td> - <td>{{ value }}</td> - </tr> -{% endfor %} -</table> +System overview. {% endblock %} + diff --git a/jack/beanstalk/templates/beanstalk/stats.html b/jack/beanstalk/templates/beanstalk/stats.html new file mode 100644 index 0000000..ad5bad9 --- /dev/null +++ b/jack/beanstalk/templates/beanstalk/stats.html @@ -0,0 +1,36 @@ +{% extends "beanstalk/base.html" %} + +{% block content %} + +<b>Tubes:</b> + <a href="/beanstalk/stats/">all</a> &nbsp; + +{% for tube in tubes %} + <a href="/beanstalk/tube/{{ tube }}/stats/"> + {% ifequal tube current_tube %} + <b>{{ tube }}</b> + {% else %} + {{ tube }} + {% endifequal %} + </a> &nbsp; +{% endfor %} +<br /> + + +{% if current_tube %} + <h4>Stats for tube: <i>{{ current_tube }}</i></h4> +{% else %} + <h4>General job queue server stats</h4> +{% endif %} + +<table> + <tr><th>Key</th><th>Value</th></tr> +{% for key, value in stats %} + <tr> + <td>{{ key }}</td> + <td>{{ value }}</td> + </tr> +{% endfor %} +</table> + +{% endblock %} diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index 0aa46a3..51cbe4c 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,15 +1,16 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), + (r'^stats/$', views.stats), (r'^put/$', views.put), (r'^ready/(?P<tube>[\w-]*)$', views.ready), (r'^delayed/(?P<tube>[\w-]*)$', views.delayed), (r'^buried/(?P<tube>[\w-]*)$', views.buried), (r'^inspect/(?P<id>\d*)$', views.inspect), (r'^tube/(?P<tube>[\w-]+)/stats/$', views.tube_stats), (r'^job/(?P<id>\d+)/delete/$', views.job_delete), (r'^job/(?P<id>\d+)/kick/$', views.job_kick), ) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 6df80ee..1e4b780 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,167 +1,172 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable from urlparse import urlsplit @login_required def index(request): + return render_to_response('beanstalk/index.html', + context_instance=RequestContext(request)) + +@login_required +def stats(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() - return render_to_response('beanstalk/index.html', + return render_to_response('beanstalk/stats.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None, tube_prefix=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None try: client = Client() except ConnectionError: return render_unavailable() if id: job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] buried = False else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False tubes = client.tubes() return render_to_response('beanstalk/inspect.html', {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, 'tube_prefix': tube_prefix}, context_instance=RequestContext(request)) def _peek_if(request, status, tube): try: client = Client() except ConnectionError: return render_unavailable() if not tube: tube = 'default' client.use(tube) job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status) request.flash.put(notice='no job found') return inspect(request, tube_prefix = '/beanstalk/%s/' % status) @login_required def ready(request, tube): return _peek_if(request, 'ready', tube) @login_required def delayed(request, tube): return _peek_if(request, 'delayed', tube) @login_required def buried(request, tube): return _peek_if(request, 'buried', tube) def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except IndexError: redirect_to = dest return redirect(redirect_to) @login_required def job_delete(request, id): try: client = Client() job = client.peek(int(id)) if job is not None: job.delete() return _redirect_to_referer_or(request, '/beanstalk/inspect/') except ConnectionError: return render_unavailable() @login_required def job_kick(request, id): try: client = Client() client.kick(int(id)) return redirect('/beanstalk/buried/') except ConnectionError: return render_unavailable()
andreisavu/django-jack
e44cd9d0b52d44a5cfe24c94f6dc044002ef2c0c
added license: apache 2.0
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License.
andreisavu/django-jack
167cb3054042a750d61c2095d4f4fcd7cb157322
- is allowed in node name
diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index 28d4b74..0aa46a3 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,15 +1,15 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), (r'^put/$', views.put), - (r'^ready/(?P<tube>\w*)$', views.ready), - (r'^delayed/(?P<tube>\w*)$', views.delayed), - (r'^buried/(?P<tube>\w*)$', views.buried), + (r'^ready/(?P<tube>[\w-]*)$', views.ready), + (r'^delayed/(?P<tube>[\w-]*)$', views.delayed), + (r'^buried/(?P<tube>[\w-]*)$', views.buried), (r'^inspect/(?P<id>\d*)$', views.inspect), - (r'^tube/(?P<tube>\w+)/stats/$', views.tube_stats), + (r'^tube/(?P<tube>[\w-]+)/stats/$', views.tube_stats), (r'^job/(?P<id>\d+)/delete/$', views.job_delete), (r'^job/(?P<id>\d+)/kick/$', views.job_kick), )
andreisavu/django-jack
08adb8cf6d2e41974dc67f1f178fa572a5d94b6e
added extra path in wsgi
diff --git a/jack/django.wsgi b/jack/django.wsgi index 3cc0d9b..b3b5ebb 100644 --- a/jack/django.wsgi +++ b/jack/django.wsgi @@ -1,11 +1,12 @@ import os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'jack.settings' import django.core.handlers.wsgi sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')) +sys.path.append(os.path.dirname(os.path.abspath(__file__))) application = django.core.handlers.wsgi.WSGIHandler()
andreisavu/django-jack
243dc9bf8ad2fe8c3650b8bc0a7e0f6ea9c4c628
database path is absolute
diff --git a/jack/settings.py b/jack/settings.py index 49bdd9e..c42a7a8 100644 --- a/jack/settings.py +++ b/jack/settings.py @@ -1,105 +1,105 @@ # Django settings for jack project. from abspath import abspath DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. -DATABASE_NAME = 'database.db' # Or path to database file if using sqlite3. +DATABASE_NAME = abspath('database.db') # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. BEANSTALK_HOST = 'localhost' BEANSTALK_PORT = 11300 LOGIN_REDIRECT_URL = '/' FLASH_IGNORE_MEDIA = True FLASH_STORAGE = 'session' FLASH_CODEC = 'json' # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = abspath('media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/admin/' # Make this unique, and don't share it with anybody. SECRET_KEY = '8wv3d_4@^=blqi)@ev*v4m=hphqgl6c5av-tbw$pl)2x37_2+-' TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", 'djangoflash.context_processors.flash', ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'djangoflash.middleware.FlashMiddleware', ) ROOT_URLCONF = 'jack.urls' TEMPLATE_DIRS = ( abspath('templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'beanstalk', ) try: from local_settings import * except ImportError: pass
andreisavu/django-jack
0ce7052dd67764985d4e32326462a1e831588c72
load local settings if available
diff --git a/jack/.gitignore b/jack/.gitignore index 9e9af13..ab7b7d3 100644 --- a/jack/.gitignore +++ b/jack/.gitignore @@ -1,3 +1,4 @@ *.pyc *.swp database.db +local_settings.py diff --git a/jack/settings.py b/jack/settings.py index 000de81..49bdd9e 100644 --- a/jack/settings.py +++ b/jack/settings.py @@ -1,98 +1,105 @@ # Django settings for jack project. from abspath import abspath DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'database.db' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. BEANSTALK_HOST = 'localhost' BEANSTALK_PORT = 11300 LOGIN_REDIRECT_URL = '/' FLASH_IGNORE_MEDIA = True FLASH_STORAGE = 'session' FLASH_CODEC = 'json' # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = abspath('media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/admin/' # Make this unique, and don't share it with anybody. SECRET_KEY = '8wv3d_4@^=blqi)@ev*v4m=hphqgl6c5av-tbw$pl)2x37_2+-' TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", 'djangoflash.context_processors.flash', ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'djangoflash.middleware.FlashMiddleware', ) ROOT_URLCONF = 'jack.urls' TEMPLATE_DIRS = ( abspath('templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'beanstalk', ) + +try: + from local_settings import * +except ImportError: + pass + +
andreisavu/django-jack
dc2cfeffe5d89d1d394b330c7810e3e3ebd8194f
added script for wsgi deployment
diff --git a/jack/django.wsgi b/jack/django.wsgi new file mode 100644 index 0000000..3cc0d9b --- /dev/null +++ b/jack/django.wsgi @@ -0,0 +1,11 @@ + +import os, sys + +os.environ['DJANGO_SETTINGS_MODULE'] = 'jack.settings' + +import django.core.handlers.wsgi + +sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')) + +application = django.core.handlers.wsgi.WSGIHandler() +
andreisavu/django-jack
270a234d01c48c661e421c87e2a810cb549c8754
allow tube selection on peek
diff --git a/jack/beanstalk/templates/beanstalk/inspect.html b/jack/beanstalk/templates/beanstalk/inspect.html index 09b9842..2807f4f 100644 --- a/jack/beanstalk/templates/beanstalk/inspect.html +++ b/jack/beanstalk/templates/beanstalk/inspect.html @@ -1,48 +1,55 @@ {% extends "beanstalk/base.html" %} {% block content %} <style type="text/css"> .stats td, .stats th { padding: 2px; } </style> <form action="/beanstalk/inspect/" method="post"> <label>ID:</label> <input type="text" name="id" /> <button type="submit">Inspect</button> </form> +{% if tube_prefix %} + Peek tube: + {% for tube in tubes %} + <a href="{{ tube_prefix }}{{ tube }}">{{ tube }}</a> &nbsp; + {% endfor %} +{% endif %} + {% if job %} <table class="stats"> <tr><th>ID</th><td>{{ job.jid }}</td></tr> <tr><th>Body</th><td> <textarea rows="3" cols="80">{{ job.body }}</textarea> </td></tr> <tr><th valign="top">Stats</th><td> <table> <tr><th>Key</th><th>Value</th></tr> {% for key, value in stats %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% endfor %} </table> </td></tr> <tr> <th>Options</th> <td> {% if buried %} <form action="/beanstalk/job/{{ job.jid }}/kick/" method="post" style="display: inline"> <button type="submit">kick</button> </form> {% endif %} <form action="/beanstalk/job/{{ job.jid }}/delete/" method="post" style="display:inline" onsubmit="return confirm('Are you sure?')"> <button type="submit">delete</button> </form> </td> </tr> </table> {% endif %} {% endblock %} diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index 4b890ee..28d4b74 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,15 +1,15 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), (r'^put/$', views.put), - (r'^ready/$', views.ready), - (r'^delayed/$', views.delayed), - (r'^buried/$', views.buried), + (r'^ready/(?P<tube>\w*)$', views.ready), + (r'^delayed/(?P<tube>\w*)$', views.delayed), + (r'^buried/(?P<tube>\w*)$', views.buried), (r'^inspect/(?P<id>\d*)$', views.inspect), (r'^tube/(?P<tube>\w+)/stats/$', views.tube_stats), (r'^job/(?P<id>\d+)/delete/$', views.job_delete), (r'^job/(?P<id>\d+)/kick/$', views.job_kick), ) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 050d60c..6df80ee 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,161 +1,167 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable from urlparse import urlsplit @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required -def inspect(request, id=None): +def inspect(request, id=None, tube_prefix=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None - if id: - try: - client = Client() - except ConnectionError: - return render_unavailable() + try: + client = Client() + except ConnectionError: + return render_unavailable() + if id: job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] + buried = False else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False + tubes = client.tubes() + return render_to_response('beanstalk/inspect.html', - {'job': job, 'stats': stats, 'buried': buried}, + {'job': job, 'stats': stats, 'buried': buried, 'tubes': tubes, 'tube_prefix': tube_prefix}, context_instance=RequestContext(request)) -def _peek_if(request, status): +def _peek_if(request, status, tube): try: client = Client() except ConnectionError: return render_unavailable() + if not tube: tube = 'default' + client.use(tube) + job = getattr(client, "peek_%s" % status)() if job is not None: - return inspect(request, job.jid) + return inspect(request, job.jid, tube_prefix='/beanstalk/%s/' % status) request.flash.put(notice='no job found') - return inspect(request) + return inspect(request, tube_prefix = '/beanstalk/%s/' % status) @login_required -def ready(request): - return _peek_if(request, 'ready') +def ready(request, tube): + return _peek_if(request, 'ready', tube) @login_required -def delayed(request): - return _peek_if(request, 'delayed') +def delayed(request, tube): + return _peek_if(request, 'delayed', tube) @login_required -def buried(request): - return _peek_if(request, 'buried') +def buried(request, tube): + return _peek_if(request, 'buried', tube) def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except IndexError: redirect_to = dest return redirect(redirect_to) @login_required def job_delete(request, id): try: client = Client() job = client.peek(int(id)) if job is not None: job.delete() return _redirect_to_referer_or(request, '/beanstalk/inspect/') except ConnectionError: return render_unavailable() @login_required def job_kick(request, id): try: client = Client() client.kick(int(id)) return redirect('/beanstalk/buried/') except ConnectionError: return render_unavailable()
andreisavu/django-jack
3cdc3dce772b0c534ee79eef975a996935cb3614
implemented delete and kick operations for jobs
diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index 0990330..4b890ee 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,13 +1,15 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), (r'^put/$', views.put), (r'^ready/$', views.ready), (r'^delayed/$', views.delayed), (r'^buried/$', views.buried), (r'^inspect/(?P<id>\d*)$', views.inspect), (r'^tube/(?P<tube>\w+)/stats/$', views.tube_stats), + (r'^job/(?P<id>\d+)/delete/$', views.job_delete), + (r'^job/(?P<id>\d+)/kick/$', views.job_kick), ) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 1ba7f2a..050d60c 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,121 +1,161 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable +from urlparse import urlsplit + @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None if id: try: client = Client() except ConnectionError: return render_unavailable() job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] else: buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] buried = False return render_to_response('beanstalk/inspect.html', {'job': job, 'stats': stats, 'buried': buried}, context_instance=RequestContext(request)) def _peek_if(request, status): try: client = Client() except ConnectionError: return render_unavailable() job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid) request.flash.put(notice='no job found') return inspect(request) @login_required def ready(request): return _peek_if(request, 'ready') @login_required def delayed(request): return _peek_if(request, 'delayed') @login_required def buried(request): return _peek_if(request, 'buried') + +def _redirect_to_referer_or(request, dest): + referer = request.META.get('HTTP_REFERER', None) + if referer is None: + return redirect(dest) + + try: + redirect_to = urlsplit(referer, 'http', False)[2] + except IndexError: + redirect_to = dest + + return redirect(redirect_to) + +@login_required +def job_delete(request, id): + try: + client = Client() + job = client.peek(int(id)) + + if job is not None: + job.delete() + + return _redirect_to_referer_or(request, '/beanstalk/inspect/') + + except ConnectionError: + return render_unavailable() + +@login_required +def job_kick(request, id): + try: + client = Client() + client.kick(int(id)) + + return redirect('/beanstalk/buried/') + + except ConnectionError: + return render_unavailable() +
andreisavu/django-jack
fa3e56bb8ec9cc95234a99753a80a40b021d4ea8
job actions: kick and delete. only a buried job can be kicked
diff --git a/jack/beanstalk/templates/beanstalk/inspect.html b/jack/beanstalk/templates/beanstalk/inspect.html index 4416aa3..09b9842 100644 --- a/jack/beanstalk/templates/beanstalk/inspect.html +++ b/jack/beanstalk/templates/beanstalk/inspect.html @@ -1,35 +1,48 @@ {% extends "beanstalk/base.html" %} {% block content %} <style type="text/css"> .stats td, .stats th { padding: 2px; } </style> <form action="/beanstalk/inspect/" method="post"> <label>ID:</label> <input type="text" name="id" /> <button type="submit">Inspect</button> </form> {% if job %} <table class="stats"> <tr><th>ID</th><td>{{ job.jid }}</td></tr> <tr><th>Body</th><td> <textarea rows="3" cols="80">{{ job.body }}</textarea> </td></tr> <tr><th valign="top">Stats</th><td> <table> <tr><th>Key</th><th>Value</th></tr> {% for key, value in stats %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% endfor %} </table> </td></tr> + <tr> + <th>Options</th> + <td> + {% if buried %} + <form action="/beanstalk/job/{{ job.jid }}/kick/" method="post" style="display: inline"> + <button type="submit">kick</button> + </form> + {% endif %} + <form action="/beanstalk/job/{{ job.jid }}/delete/" method="post" style="display:inline" onsubmit="return confirm('Are you sure?')"> + <button type="submit">delete</button> + </form> + </td> + </tr> </table> {% endif %} {% endblock %} diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 05a668e..1ba7f2a 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,118 +1,121 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None if id: try: client = Client() except ConnectionError: return render_unavailable() job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] else: + buried = job.stats()['state'] == 'buried' stats = job.stats().items() else: job = None stats = [] + buried = False return render_to_response('beanstalk/inspect.html', - {'job':job, 'stats':stats}, context_instance=RequestContext(request)) + {'job': job, 'stats': stats, 'buried': buried}, + context_instance=RequestContext(request)) def _peek_if(request, status): try: client = Client() except ConnectionError: return render_unavailable() job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid) request.flash.put(notice='no job found') return inspect(request) @login_required def ready(request): return _peek_if(request, 'ready') @login_required def delayed(request): return _peek_if(request, 'delayed') @login_required def buried(request): return _peek_if(request, 'buried')
andreisavu/django-jack
7affb6624a6e6008bf4a88f12cce37e6b4bea086
if no job available on peek just stay on the same page
diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 5bf51c3..05a668e 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,118 +1,118 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None if id: try: client = Client() except ConnectionError: return render_unavailable() job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] else: stats = job.stats().items() else: job = None stats = [] return render_to_response('beanstalk/inspect.html', {'job':job, 'stats':stats}, context_instance=RequestContext(request)) def _peek_if(request, status): try: client = Client() except ConnectionError: return render_unavailable() job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid) request.flash.put(notice='no job found') - return redirect('/beanstalk/inspect/') + return inspect(request) @login_required def ready(request): return _peek_if(request, 'ready') @login_required def delayed(request): return _peek_if(request, 'delayed') @login_required def buried(request): return _peek_if(request, 'buried')
andreisavu/django-jack
b81b275772e70cba5123ae2090ae74d7829c6ce2
defined all peek operations
diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index 63f49d8..0990330 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,11 +1,13 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), (r'^put/$', views.put), (r'^ready/$', views.ready), + (r'^delayed/$', views.delayed), + (r'^buried/$', views.buried), (r'^inspect/(?P<id>\d*)$', views.inspect), (r'^tube/(?P<tube>\w+)/stats/$', views.tube_stats), ) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index b8784d6..5bf51c3 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,106 +1,118 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None if id: try: client = Client() except ConnectionError: return render_unavailable() job = client.peek(id) if job is None: request.flash.put(notice='no job found with id #%d' % id) stats = [] else: stats = job.stats().items() else: job = None stats = [] return render_to_response('beanstalk/inspect.html', {'job':job, 'stats':stats}, context_instance=RequestContext(request)) -@login_required -def ready(request): +def _peek_if(request, status): try: client = Client() except ConnectionError: return render_unavailable() - job = client.peek_ready() + job = getattr(client, "peek_%s" % status)() if job is not None: return inspect(request, job.jid) - request.flash.put(notice='no job found ready for execution') + request.flash.put(notice='no job found') return redirect('/beanstalk/inspect/') +@login_required +def ready(request): + return _peek_if(request, 'ready') + + +@login_required +def delayed(request): + return _peek_if(request, 'delayed') + +@login_required +def buried(request): + return _peek_if(request, 'buried') +
andreisavu/django-jack
6164dbaac4a9c65473ba87f8096f34e36413758b
improved error handling when trying to view job
diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 7cfe4c8..b8784d6 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,102 +1,106 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None if id: try: client = Client() except ConnectionError: return render_unavailable() job = client.peek(id) - stats = job.stats().items() + if job is None: + request.flash.put(notice='no job found with id #%d' % id) + stats = [] + else: + stats = job.stats().items() else: job = None stats = [] return render_to_response('beanstalk/inspect.html', {'job':job, 'stats':stats}, context_instance=RequestContext(request)) @login_required def ready(request): try: client = Client() except ConnectionError: return render_unavailable() job = client.peek_ready() if job is not None: return inspect(request, job.jid) request.flash.put(notice='no job found ready for execution') return redirect('/beanstalk/inspect/')
andreisavu/django-jack
328d98c0cfc43403340201d2ba862bf5c060b8bd
changed names
diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html index 9b0490e..5543a29 100644 --- a/jack/beanstalk/templates/beanstalk/base.html +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -1,102 +1,102 @@ <html> <head> <title>{% block title %}Jack and the Beanstalkd{% endblock %} <style type="text/css"> body { padding: 0px; margin: 0px; } #header { margin: 10px; } #content { margin: 10px; } /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .solidblockmenu{ margin: 0; padding: 0; float: left; font: bold 13px Arial; width: 100%; overflow: hidden; margin-bottom: 1em; border: 1px solid #625e00; border-width: 1px 0; background: black url(/media/blockdefault.gif) center center repeat-x; } .solidblockmenu li{ display: inline; } .solidblockmenu li a{ float: left; color: white; padding: 9px 11px; text-decoration: none; border-right: 1px solid white; } .solidblockmenu li a:visited{ color: white; } .solidblockmenu li a:hover, .solidblockmenu li .current{ color: white; background: transparent url(/media/blockactive.gif) center center repeat-x; } </style> </head> <body> {% block header %} <div id="header"> <h1 style="float: left;font-size: 25px;"> <span style="color: blue">Jack</span> <span style="font-size: 20px;color: grey;">and the</span><br /> <span style="color: green">Beanstalkd</span> </h1> <span style="float: right"> welcome {{ user }} | <a href="/accounts/logout">logout</a> </span> <div style="clear: both;"></div> </div> {% endblock %} {% block menu %} <ul class="solidblockmenu"> <li><a href="/beanstalk/">Home</a></li> <li><a href="/beanstalk/put/">Put</a></li> <li><a href="/beanstalk/inspect/">Inspect</a></li> - <li><a href="/beanstalk/ready/">Ready</a></li> - <li><a href="/beanstalk/delayed/">Delayed</a></li> - <li><a href="/beanstalk/buried/">Buried</a></li> + <li><a href="/beanstalk/ready/">Peek Ready</a></li> + <li><a href="/beanstalk/delayed/">Peek Delayed</a></li> + <li><a href="/beanstalk/buried/">Peek Buried</a></li> </ul> <br style="clear: left" /> {% if flash.notice %} <center><span style="border: 1px solid #0aa;padding: 5px;"> {{ flash.notice }}</span></center> {% endif %} {% endblock %} <div id="content"> {% block content %}{% endblock %} </div> {% block footer %} <br /><br /> <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> {% endblock %} </body> </html>
andreisavu/django-jack
3125ecdab7701220053b7264af25c251bfb7ae14
keep link unchanged: easier to refresh
diff --git a/jack/beanstalk/templates/beanstalk/inspect.html b/jack/beanstalk/templates/beanstalk/inspect.html index a2a7b5c..4416aa3 100644 --- a/jack/beanstalk/templates/beanstalk/inspect.html +++ b/jack/beanstalk/templates/beanstalk/inspect.html @@ -1,27 +1,35 @@ {% extends "beanstalk/base.html" %} {% block content %} +<style type="text/css"> + .stats td, .stats th { + padding: 2px; + } +</style> + <form action="/beanstalk/inspect/" method="post"> <label>ID:</label> <input type="text" name="id" /> <button type="submit">Inspect</button> </form> {% if job %} -<table> +<table class="stats"> <tr><th>ID</th><td>{{ job.jid }}</td></tr> - <tr><th>Body</th><td>{{ job.body }}</td></tr> + <tr><th>Body</th><td> + <textarea rows="3" cols="80">{{ job.body }}</textarea> + </td></tr> <tr><th valign="top">Stats</th><td> <table> <tr><th>Key</th><th>Value</th></tr> {% for key, value in stats %} <tr><td>{{ key }}</td><td>{{ value }}</td></tr> {% endfor %} </table> </td></tr> </table> {% endif %} {% endblock %} diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 7afbc72..7cfe4c8 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,101 +1,102 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None if id: try: client = Client() except ConnectionError: return render_unavailable() job = client.peek(id) stats = job.stats().items() else: job = None stats = [] return render_to_response('beanstalk/inspect.html', {'job':job, 'stats':stats}, context_instance=RequestContext(request)) @login_required def ready(request): try: client = Client() except ConnectionError: return render_unavailable() job = client.peek_ready() if job is not None: - return redirect('/beanstalk/inspect/%d' % job.jid) + return inspect(request, job.jid) request.flash.put(notice='no job found ready for execution') return redirect('/beanstalk/inspect/') +
andreisavu/django-jack
cf3dd5c2781055e8d6a1f57b164aa94d6d97d157
inspect ready job
diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index c4d6995..63f49d8 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,10 +1,11 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), (r'^put/$', views.put), + (r'^ready/$', views.ready), (r'^inspect/(?P<id>\d*)$', views.inspect), (r'^tube/(?P<tube>\w+)/stats/$', views.tube_stats), ) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 7d16b6f..7afbc72 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,87 +1,101 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm from beanstalk.shortcuts import render_unavailable @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): try: client = Client() except ConnectionError: return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): try: client = Client() except ConnectionError: return render_unavailable() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None if id: try: client = Client() except ConnectionError: return render_unavailable() job = client.peek(id) stats = job.stats().items() else: job = None stats = [] return render_to_response('beanstalk/inspect.html', {'job':job, 'stats':stats}, context_instance=RequestContext(request)) +@login_required +def ready(request): + try: + client = Client() + except ConnectionError: + return render_unavailable() + + job = client.peek_ready() + if job is not None: + return redirect('/beanstalk/inspect/%d' % job.jid) + + request.flash.put(notice='no job found ready for execution') + return redirect('/beanstalk/inspect/') +
andreisavu/django-jack
cff2c1afe429106f274bcc36abd9cf248fcccb3e
added error page: unable to connect to queue
diff --git a/jack/beanstalk/client.py b/jack/beanstalk/client.py index 8e266f7..bf084dc 100644 --- a/jack/beanstalk/client.py +++ b/jack/beanstalk/client.py @@ -1,15 +1,16 @@ from django.conf import settings from beanstalkc import Connection, CommandFailed +from beanstalkc import SocketError as ConnectionError class Client(object): """ A simple proxy object over the default client """ def __init__(self): self.conn = Connection(settings.BEANSTALK_HOST, settings.BEANSTALK_PORT) def __getattr__(self, name): return getattr(self.conn, name) diff --git a/jack/beanstalk/shortcuts.py b/jack/beanstalk/shortcuts.py new file mode 100644 index 0000000..fece586 --- /dev/null +++ b/jack/beanstalk/shortcuts.py @@ -0,0 +1,6 @@ + +from django.shortcuts import render_to_response + +def render_unavailable(): + return render_to_response('beanstalk/unavailable.html') + diff --git a/jack/beanstalk/templates/beanstalk/unavailable.html b/jack/beanstalk/templates/beanstalk/unavailable.html new file mode 100644 index 0000000..9f37a7d --- /dev/null +++ b/jack/beanstalk/templates/beanstalk/unavailable.html @@ -0,0 +1,15 @@ +<html> +<head> + <title>Unable to connect to queue</title> +</head> +<body> + +<center> + <img src="/media/broken.jpg" /><br /> + <h1>Unable to connect to queue.</h1> + +</center> + +</body> +</html> + diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 7bcef05..7d16b6f 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,75 +1,87 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext -from beanstalk.client import Client, CommandFailed +from beanstalk.client import Client, CommandFailed, ConnectionError from beanstalk.forms import PutForm +from beanstalk.shortcuts import render_unavailable @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): - client = Client() + try: + client = Client() + except ConnectionError: + return render_unavailable() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): - client = Client() + try: + client = Client() + except ConnectionError: + return render_unavailable() + client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) @login_required def inspect(request, id=None): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (ValueError, TypeError): id = None if id: - client = Client() + try: + client = Client() + except ConnectionError: + return render_unavailable() + job = client.peek(id) stats = job.stats().items() else: job = None stats = [] return render_to_response('beanstalk/inspect.html', {'job':job, 'stats':stats}, context_instance=RequestContext(request)) diff --git a/jack/media/broken.jpg b/jack/media/broken.jpg new file mode 100644 index 0000000..aaab660 Binary files /dev/null and b/jack/media/broken.jpg differ
andreisavu/django-jack
70fc04cc283898d602673bf3b84df9a1aa86b6b0
basic job inspect functionality
diff --git a/jack/beanstalk/templates/beanstalk/inspect.html b/jack/beanstalk/templates/beanstalk/inspect.html new file mode 100644 index 0000000..a2a7b5c --- /dev/null +++ b/jack/beanstalk/templates/beanstalk/inspect.html @@ -0,0 +1,27 @@ +{% extends "beanstalk/base.html" %} + +{% block content %} + +<form action="/beanstalk/inspect/" method="post"> + <label>ID:</label> + <input type="text" name="id" /> + <button type="submit">Inspect</button> +</form> + +{% if job %} +<table> + <tr><th>ID</th><td>{{ job.jid }}</td></tr> + <tr><th>Body</th><td>{{ job.body }}</td></tr> + <tr><th valign="top">Stats</th><td> + <table> + <tr><th>Key</th><th>Value</th></tr> + {% for key, value in stats %} + <tr><td>{{ key }}</td><td>{{ value }}</td></tr> + {% endfor %} + </table> + </td></tr> +</table> +{% endif %} + +{% endblock %} + diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index 4fb408a..c4d6995 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,9 +1,10 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), (r'^put/$', views.put), + (r'^inspect/(?P<id>\d*)$', views.inspect), (r'^tube/(?P<tube>\w+)/stats/$', views.tube_stats), ) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 6181331..7bcef05 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,54 +1,75 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed from beanstalk.forms import PutForm @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): client = Client() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): client = Client() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request)) +@login_required +def inspect(request, id=None): + if request.method == 'POST': + id = request.POST['id'] + + try: + id = int(id) + except (ValueError, TypeError): + id = None + + if id: + client = Client() + job = client.peek(id) + stats = job.stats().items() + else: + job = None + stats = [] + + return render_to_response('beanstalk/inspect.html', + {'job':job, 'stats':stats}, context_instance=RequestContext(request)) +
andreisavu/django-jack
3f199b3660fb2202fde4bd031d76c52fdfde2b22
improved feedback on job add
diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html index aac312e..9b0490e 100644 --- a/jack/beanstalk/templates/beanstalk/base.html +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -1,97 +1,102 @@ <html> <head> <title>{% block title %}Jack and the Beanstalkd{% endblock %} <style type="text/css"> body { padding: 0px; margin: 0px; } #header { margin: 10px; } #content { margin: 10px; } /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .solidblockmenu{ margin: 0; padding: 0; float: left; font: bold 13px Arial; width: 100%; overflow: hidden; margin-bottom: 1em; border: 1px solid #625e00; border-width: 1px 0; background: black url(/media/blockdefault.gif) center center repeat-x; } .solidblockmenu li{ display: inline; } .solidblockmenu li a{ float: left; color: white; padding: 9px 11px; text-decoration: none; border-right: 1px solid white; } .solidblockmenu li a:visited{ color: white; } .solidblockmenu li a:hover, .solidblockmenu li .current{ color: white; background: transparent url(/media/blockactive.gif) center center repeat-x; } </style> </head> <body> {% block header %} <div id="header"> <h1 style="float: left;font-size: 25px;"> <span style="color: blue">Jack</span> <span style="font-size: 20px;color: grey;">and the</span><br /> <span style="color: green">Beanstalkd</span> </h1> <span style="float: right"> welcome {{ user }} | <a href="/accounts/logout">logout</a> </span> - <div style="clear: both;"></div> + <div style="clear: both;"></div> </div> {% endblock %} {% block menu %} <ul class="solidblockmenu"> <li><a href="/beanstalk/">Home</a></li> <li><a href="/beanstalk/put/">Put</a></li> <li><a href="/beanstalk/inspect/">Inspect</a></li> <li><a href="/beanstalk/ready/">Ready</a></li> <li><a href="/beanstalk/delayed/">Delayed</a></li> <li><a href="/beanstalk/buried/">Buried</a></li> </ul> <br style="clear: left" /> + + {% if flash.notice %} + <center><span style="border: 1px solid #0aa;padding: 5px;"> + {{ flash.notice }}</span></center> + {% endif %} {% endblock %} <div id="content"> {% block content %}{% endblock %} </div> {% block footer %} <br /><br /> <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> {% endblock %} </body> </html> diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 857bad8..6181331 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,53 +1,54 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from django.template import RequestContext from beanstalk.client import Client, CommandFailed from beanstalk.forms import PutForm @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): client = Client() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): client = Client() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) + request.flash.put(notice='job submited to queue with id #%d' % id) return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form}, context_instance=RequestContext(request))
andreisavu/django-jack
afc815819726e40503e3ce3ea3e210f3eb56e582
added request context on rendering
diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 6bd1c64..857bad8 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,51 +1,53 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 +from django.template import RequestContext from beanstalk.client import Client, CommandFailed from beanstalk.forms import PutForm @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): client = Client() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube - }) + }, context_instance=RequestContext(request)) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): client = Client() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) return redirect('/beanstalk/put/') else: form = PutForm() - return render_to_response('beanstalk/put.html', {'form':form}) + return render_to_response('beanstalk/put.html', + {'form':form}, context_instance=RequestContext(request))
andreisavu/django-jack
e65c08974c66f48d02de488c29922794e3e9042c
installed django flash
diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..3ea659d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "deps/django-flash"] + path = deps/django-flash + url = git://github.com/danielfm/django-flash.git diff --git a/deps/django-flash b/deps/django-flash new file mode 160000 index 0000000..937f737 --- /dev/null +++ b/deps/django-flash @@ -0,0 +1 @@ +Subproject commit 937f73721c921671b8900561797ec498c0ae24cf diff --git a/jack/djangoflash b/jack/djangoflash new file mode 120000 index 0000000..2eec73f --- /dev/null +++ b/jack/djangoflash @@ -0,0 +1 @@ +../deps/django-flash/src/djangoflash \ No newline at end of file diff --git a/jack/settings.py b/jack/settings.py index 1a08363..000de81 100644 --- a/jack/settings.py +++ b/jack/settings.py @@ -1,85 +1,98 @@ # Django settings for jack project. from abspath import abspath DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'database.db' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. BEANSTALK_HOST = 'localhost' BEANSTALK_PORT = 11300 LOGIN_REDIRECT_URL = '/' +FLASH_IGNORE_MEDIA = True +FLASH_STORAGE = 'session' +FLASH_CODEC = 'json' + # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = abspath('media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/admin/' # Make this unique, and don't share it with anybody. SECRET_KEY = '8wv3d_4@^=blqi)@ev*v4m=hphqgl6c5av-tbw$pl)2x37_2+-' +TEMPLATE_CONTEXT_PROCESSORS = ( + "django.core.context_processors.auth", + "django.core.context_processors.debug", + "django.core.context_processors.i18n", + "django.core.context_processors.media", + 'djangoflash.context_processors.flash', +) + # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'djangoflash.middleware.FlashMiddleware', ) ROOT_URLCONF = 'jack.urls' TEMPLATE_DIRS = ( abspath('templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'beanstalk', )
andreisavu/django-jack
c689fdc4fef316d2cae39a10b94a49e8ee2d0069
redirect back to form and added link for general stats
diff --git a/jack/beanstalk/templates/beanstalk/index.html b/jack/beanstalk/templates/beanstalk/index.html index c71ba16..eb45303 100644 --- a/jack/beanstalk/templates/beanstalk/index.html +++ b/jack/beanstalk/templates/beanstalk/index.html @@ -1,34 +1,36 @@ {% extends "beanstalk/base.html" %} {% block content %} <b>Tubes:</b> + <a href="/beanstalk/">all</a> &nbsp; + {% for tube in tubes %} <a href="/beanstalk/tube/{{ tube }}/stats/"> {% ifequal tube current_tube %} <b>{{ tube }}</b> {% else %} {{ tube }} {% endifequal %} - </a> + </a> &nbsp; {% endfor %} <br /> {% if current_tube %} <h4>Stats for tube: <i>{{ current_tube }}</i></h4> {% else %} <h4>General job queue server stats</h4> {% endif %} <table> <tr><th>Key</th><th>Value</th></tr> {% for key, value in stats %} <tr> <td>{{ key }}</td> <td>{{ value }}</td> </tr> {% endfor %} </table> {% endblock %} diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 9575ff2..6bd1c64 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,51 +1,51 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from beanstalk.client import Client, CommandFailed from beanstalk.forms import PutForm @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): client = Client() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }) @login_required def put(request): if request.method == 'POST': form = PutForm(request.POST) if form.is_valid(): client = Client() client.use(form.cleaned_data['tube']) id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ form.cleaned_data['delay'], form.cleaned_data['ttr']) - return redirect('/') + return redirect('/beanstalk/put/') else: form = PutForm() return render_to_response('beanstalk/put.html', {'form':form})
andreisavu/django-jack
837036a9e9a881d4710cf6f871006a941eb740f0
put a new job in the queue
diff --git a/jack/beanstalk/forms.py b/jack/beanstalk/forms.py new file mode 100644 index 0000000..9e8dcc8 --- /dev/null +++ b/jack/beanstalk/forms.py @@ -0,0 +1,10 @@ + +from django import forms + +class PutForm(forms.Form): + body = forms.CharField(widget=forms.Textarea()) + tube = forms.CharField(initial='default') + priority = forms.IntegerField(initial=2147483648) + delay = forms.IntegerField(initial=0) + ttr = forms.IntegerField(initial=120) + diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html index a0bd0ea..aac312e 100644 --- a/jack/beanstalk/templates/beanstalk/base.html +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -1,95 +1,97 @@ <html> <head> <title>{% block title %}Jack and the Beanstalkd{% endblock %} <style type="text/css"> body { padding: 0px; margin: 0px; } #header { margin: 10px; } #content { margin: 10px; } /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .solidblockmenu{ margin: 0; padding: 0; float: left; font: bold 13px Arial; width: 100%; overflow: hidden; margin-bottom: 1em; border: 1px solid #625e00; border-width: 1px 0; background: black url(/media/blockdefault.gif) center center repeat-x; } .solidblockmenu li{ display: inline; } .solidblockmenu li a{ float: left; color: white; padding: 9px 11px; text-decoration: none; border-right: 1px solid white; } .solidblockmenu li a:visited{ color: white; } .solidblockmenu li a:hover, .solidblockmenu li .current{ color: white; background: transparent url(/media/blockactive.gif) center center repeat-x; } </style> </head> <body> {% block header %} <div id="header"> <h1 style="float: left;font-size: 25px;"> <span style="color: blue">Jack</span> <span style="font-size: 20px;color: grey;">and the</span><br /> <span style="color: green">Beanstalkd</span> </h1> <span style="float: right"> welcome {{ user }} | <a href="/accounts/logout">logout</a> </span> <div style="clear: both;"></div> </div> {% endblock %} {% block menu %} <ul class="solidblockmenu"> <li><a href="/beanstalk/">Home</a></li> + <li><a href="/beanstalk/put/">Put</a></li> <li><a href="/beanstalk/inspect/">Inspect</a></li> <li><a href="/beanstalk/ready/">Ready</a></li> <li><a href="/beanstalk/delayed/">Delayed</a></li> + <li><a href="/beanstalk/buried/">Buried</a></li> </ul> <br style="clear: left" /> {% endblock %} <div id="content"> {% block content %}{% endblock %} </div> {% block footer %} <br /><br /> <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> {% endblock %} </body> </html> diff --git a/jack/beanstalk/templates/beanstalk/put.html b/jack/beanstalk/templates/beanstalk/put.html new file mode 100644 index 0000000..dfa6766 --- /dev/null +++ b/jack/beanstalk/templates/beanstalk/put.html @@ -0,0 +1,16 @@ +{% extends "beanstalk/base.html" %} + +{% block content %} + +<form action="/beanstalk/put/" method="post"> + <fieldset> + <legend>Put a new job on queue</legend> + <table> + {{ form.as_table }} + </table> + <button type="submit">Put</button> + </fieldset> +</form> + +{% endblock %} + diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index ce57486..4fb408a 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,8 +1,9 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^$', views.index), + (r'^put/$', views.put), (r'^tube/(?P<tube>\w+)/stats/$', views.tube_stats), ) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 5893d06..9575ff2 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,33 +1,51 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required from django.http import Http404 from beanstalk.client import Client, CommandFailed +from beanstalk.forms import PutForm @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): client = Client() if tube is None: stats = client.stats().items() else: try: stats = client.stats_tube(tube).items() except CommandFailed: raise Http404 tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube }) +@login_required +def put(request): + if request.method == 'POST': + form = PutForm(request.POST) + if form.is_valid(): + + client = Client() + client.use(form.cleaned_data['tube']) + + id = client.put(str(form.cleaned_data['body']), form.cleaned_data['priority'], \ + form.cleaned_data['delay'], form.cleaned_data['ttr']) + + return redirect('/') + else: + form = PutForm() + + return render_to_response('beanstalk/put.html', {'form':form})
andreisavu/django-jack
46a12bad4bd2f1b4a3f81ca0a1fec0a260c7aed7
if tube does not exists give 404 error
diff --git a/jack/beanstalk/client.py b/jack/beanstalk/client.py index f09b0d0..8e266f7 100644 --- a/jack/beanstalk/client.py +++ b/jack/beanstalk/client.py @@ -1,15 +1,15 @@ from django.conf import settings -from beanstalkc import Connection +from beanstalkc import Connection, CommandFailed class Client(object): """ A simple proxy object over the default client """ def __init__(self): self.conn = Connection(settings.BEANSTALK_HOST, settings.BEANSTALK_PORT) def __getattr__(self, name): return getattr(self.conn, name) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index c6b9b01..5893d06 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,27 +1,33 @@ from django.shortcuts import render_to_response, redirect from django.contrib.auth.decorators import login_required -from beanstalk.client import Client +from django.http import Http404 + +from beanstalk.client import Client, CommandFailed @login_required def index(request): return tube_stats(request) @login_required def tube_stats(request, tube=None): client = Client() if tube is None: stats = client.stats().items() else: - stats = client.stats_tube(tube).items() + try: + stats = client.stats_tube(tube).items() + except CommandFailed: + raise Http404 + tubes = client.tubes() return render_to_response('beanstalk/index.html', {'stats': stats, 'tubes': tubes, 'current_tube': tube })
andreisavu/django-jack
e87e943437f62d6aacf7f6c9962c16ed8e0edc35
display basic statistics for server and tubes
diff --git a/jack/beanstalk/client.py b/jack/beanstalk/client.py new file mode 100644 index 0000000..f09b0d0 --- /dev/null +++ b/jack/beanstalk/client.py @@ -0,0 +1,15 @@ + +from django.conf import settings + +from beanstalkc import Connection + +class Client(object): + """ A simple proxy object over the default client """ + + def __init__(self): + self.conn = Connection(settings.BEANSTALK_HOST, settings.BEANSTALK_PORT) + + def __getattr__(self, name): + return getattr(self.conn, name) + + diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html index 14afc74..a0bd0ea 100644 --- a/jack/beanstalk/templates/beanstalk/base.html +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -1,92 +1,95 @@ <html> <head> <title>{% block title %}Jack and the Beanstalkd{% endblock %} <style type="text/css"> body { padding: 0px; margin: 0px; } #header { margin: 10px; } #content { margin: 10px; } /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .solidblockmenu{ margin: 0; padding: 0; float: left; font: bold 13px Arial; width: 100%; overflow: hidden; margin-bottom: 1em; border: 1px solid #625e00; border-width: 1px 0; background: black url(/media/blockdefault.gif) center center repeat-x; } .solidblockmenu li{ display: inline; } .solidblockmenu li a{ float: left; color: white; padding: 9px 11px; text-decoration: none; border-right: 1px solid white; } .solidblockmenu li a:visited{ color: white; } .solidblockmenu li a:hover, .solidblockmenu li .current{ color: white; background: transparent url(/media/blockactive.gif) center center repeat-x; } </style> </head> <body> {% block header %} <div id="header"> <h1 style="float: left;font-size: 25px;"> <span style="color: blue">Jack</span> <span style="font-size: 20px;color: grey;">and the</span><br /> <span style="color: green">Beanstalkd</span> </h1> <span style="float: right"> welcome {{ user }} | <a href="/accounts/logout">logout</a> </span> <div style="clear: both;"></div> </div> {% endblock %} {% block menu %} <ul class="solidblockmenu"> <li><a href="/beanstalk/">Home</a></li> - <li><a href="/benstallk/inspect/ready/">Ready Queue</a></li> + <li><a href="/beanstalk/inspect/">Inspect</a></li> + <li><a href="/beanstalk/ready/">Ready</a></li> + <li><a href="/beanstalk/delayed/">Delayed</a></li> </ul> <br style="clear: left" /> {% endblock %} <div id="content"> {% block content %}{% endblock %} </div> {% block footer %} + <br /><br /> <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> {% endblock %} </body> </html> diff --git a/jack/beanstalk/templates/beanstalk/index.html b/jack/beanstalk/templates/beanstalk/index.html index 13af8e8..c71ba16 100644 --- a/jack/beanstalk/templates/beanstalk/index.html +++ b/jack/beanstalk/templates/beanstalk/index.html @@ -1,7 +1,34 @@ {% extends "beanstalk/base.html" %} {% block content %} -Hello world +<b>Tubes:</b> +{% for tube in tubes %} + <a href="/beanstalk/tube/{{ tube }}/stats/"> + {% ifequal tube current_tube %} + <b>{{ tube }}</b> + {% else %} + {{ tube }} + {% endifequal %} + </a> +{% endfor %} +<br /> + + +{% if current_tube %} + <h4>Stats for tube: <i>{{ current_tube }}</i></h4> +{% else %} + <h4>General job queue server stats</h4> +{% endif %} + +<table> + <tr><th>Key</th><th>Value</th></tr> +{% for key, value in stats %} + <tr> + <td>{{ key }}</td> + <td>{{ value }}</td> + </tr> +{% endfor %} +</table> {% endblock %} diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py index ce2ee67..ce57486 100644 --- a/jack/beanstalk/urls.py +++ b/jack/beanstalk/urls.py @@ -1,7 +1,8 @@ from django.conf.urls.defaults import * import views urlpatterns = patterns('', - (r'^$', views.index) + (r'^$', views.index), + (r'^tube/(?P<tube>\w+)/stats/$', views.tube_stats), ) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py index 6a661d8..c6b9b01 100644 --- a/jack/beanstalk/views.py +++ b/jack/beanstalk/views.py @@ -1,6 +1,27 @@ from django.shortcuts import render_to_response, redirect +from django.contrib.auth.decorators import login_required +from beanstalk.client import Client + +@login_required def index(request): - return render_to_response('beanstalk/index.html') + return tube_stats(request) + +@login_required +def tube_stats(request, tube=None): + client = Client() + + if tube is None: + stats = client.stats().items() + else: + stats = client.stats_tube(tube).items() + tubes = client.tubes() + + return render_to_response('beanstalk/index.html', + {'stats': stats, + 'tubes': tubes, + 'current_tube': tube + }) +
andreisavu/django-jack
c1c916ffd8a82b5c7a301c7e5081fc0f1c07615a
basic template in place
diff --git a/jack/beanstalk/__init__.py b/jack/beanstalk/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/jack/beanstalk/models.py b/jack/beanstalk/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/jack/beanstalk/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/jack/beanstalk/templates/beanstalk/base.html b/jack/beanstalk/templates/beanstalk/base.html new file mode 100644 index 0000000..14afc74 --- /dev/null +++ b/jack/beanstalk/templates/beanstalk/base.html @@ -0,0 +1,92 @@ +<html> +<head> + <title>{% block title %}Jack and the Beanstalkd{% endblock %} + + <style type="text/css"> + body { + padding: 0px; + margin: 0px; + } + + #header { + margin: 10px; + } + + #content { + margin: 10px; + } + + /*Credits: Dynamic Drive CSS Library */ + /*URL: http://www.dynamicdrive.com/style/ */ + + .solidblockmenu{ + margin: 0; + padding: 0; + float: left; + font: bold 13px Arial; + width: 100%; + overflow: hidden; + margin-bottom: 1em; + border: 1px solid #625e00; + border-width: 1px 0; + background: black url(/media/blockdefault.gif) center center repeat-x; + } + + .solidblockmenu li{ + display: inline; + } + + .solidblockmenu li a{ + float: left; + color: white; + padding: 9px 11px; + text-decoration: none; + border-right: 1px solid white; + } + + .solidblockmenu li a:visited{ + color: white; + } + + .solidblockmenu li a:hover, .solidblockmenu li .current{ + color: white; + background: transparent url(/media/blockactive.gif) center center repeat-x; + } + </style> + +</head> +<body> + {% block header %} + <div id="header"> + <h1 style="float: left;font-size: 25px;"> + <span style="color: blue">Jack</span> + <span style="font-size: 20px;color: grey;">and the</span><br /> + <span style="color: green">Beanstalkd</span> + </h1> + + <span style="float: right"> + welcome {{ user }} | + <a href="/accounts/logout">logout</a> + </span> + + <div style="clear: both;"></div> + </div> + {% endblock %} + + {% block menu %} + <ul class="solidblockmenu"> + <li><a href="/beanstalk/">Home</a></li> + <li><a href="/benstallk/inspect/ready/">Ready Queue</a></li> + </ul> + <br style="clear: left" /> + {% endblock %} + + <div id="content"> + {% block content %}{% endblock %} + </div> + + {% block footer %} + <center><small>by <a href="http://www.andreisavu.ro">Andrei Savu</a></small></center> + {% endblock %} +</body> +</html> diff --git a/jack/beanstalk/templates/beanstalk/index.html b/jack/beanstalk/templates/beanstalk/index.html new file mode 100644 index 0000000..13af8e8 --- /dev/null +++ b/jack/beanstalk/templates/beanstalk/index.html @@ -0,0 +1,7 @@ +{% extends "beanstalk/base.html" %} + +{% block content %} + +Hello world + +{% endblock %} diff --git a/jack/beanstalk/tests.py b/jack/beanstalk/tests.py new file mode 100644 index 0000000..2247054 --- /dev/null +++ b/jack/beanstalk/tests.py @@ -0,0 +1,23 @@ +""" +This file demonstrates two different styles of tests (one doctest and one +unittest). These will both pass when you run "manage.py test". + +Replace these with more appropriate tests for your application. +""" + +from django.test import TestCase + +class SimpleTest(TestCase): + def test_basic_addition(self): + """ + Tests that 1 + 1 always equals 2. + """ + self.failUnlessEqual(1 + 1, 2) + +__test__ = {"doctest": """ +Another way to test that 1 + 1 is equal to 2. + +>>> 1 + 1 == 2 +True +"""} + diff --git a/jack/beanstalk/urls.py b/jack/beanstalk/urls.py new file mode 100644 index 0000000..ce2ee67 --- /dev/null +++ b/jack/beanstalk/urls.py @@ -0,0 +1,7 @@ +from django.conf.urls.defaults import * + +import views + +urlpatterns = patterns('', + (r'^$', views.index) +) diff --git a/jack/beanstalk/views.py b/jack/beanstalk/views.py new file mode 100644 index 0000000..6a661d8 --- /dev/null +++ b/jack/beanstalk/views.py @@ -0,0 +1,6 @@ + +from django.shortcuts import render_to_response, redirect + +def index(request): + return render_to_response('beanstalk/index.html') + diff --git a/jack/media/blockactive.gif b/jack/media/blockactive.gif new file mode 100644 index 0000000..3aeaeb3 Binary files /dev/null and b/jack/media/blockactive.gif differ diff --git a/jack/media/blockdefault.gif b/jack/media/blockdefault.gif new file mode 100644 index 0000000..394ca8a Binary files /dev/null and b/jack/media/blockdefault.gif differ diff --git a/jack/settings.py b/jack/settings.py index 870a548..1a08363 100644 --- a/jack/settings.py +++ b/jack/settings.py @@ -1,79 +1,85 @@ # Django settings for jack project. from abspath import abspath DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'database.db' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. +BEANSTALK_HOST = 'localhost' +BEANSTALK_PORT = 11300 + +LOGIN_REDIRECT_URL = '/' + # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = abspath('media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '/media/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/admin/' # Make this unique, and don't share it with anybody. SECRET_KEY = '8wv3d_4@^=blqi)@ev*v4m=hphqgl6c5av-tbw$pl)2x37_2+-' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'jack.urls' TEMPLATE_DIRS = ( abspath('templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', + 'beanstalk', ) diff --git a/jack/templates/accounts/login.html b/jack/templates/accounts/login.html new file mode 100644 index 0000000..f39ebf4 --- /dev/null +++ b/jack/templates/accounts/login.html @@ -0,0 +1,10 @@ +{% extends "admin/login.html" %} + +{% block title %}Login | Jack{% endblock %} + +{% block branding %}{% endblock %} + +{% block content_title %} + <center><h1>Jack and the Beanstalkd</h1></center> +{% endblock %} + diff --git a/jack/urls.py b/jack/urls.py index ae4996d..6af170f 100644 --- a/jack/urls.py +++ b/jack/urls.py @@ -1,13 +1,22 @@ from django.conf.urls.defaults import * +from django.shortcuts import redirect +from abspath import abspath # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', - # Example: - # (r'^jack/', include('jack.foo.urls')), + (r'^$', lambda req:redirect('/beanstalk/')), + (r'^beanstalk/', include('beanstalk.urls')), + + (r'^accounts/login/$', 'django.contrib.auth.views.login', + {'template_name':'accounts/login.html'}), + (r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login'), + + (r'^media/(?P<path>.*)$', 'django.views.static.serve', + {'document_root': abspath('media')}), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), )
andreisavu/django-jack
1a730beef0f0b6d0475e191d4e2d7d25778d4d25
added expected usecases
diff --git a/README b/README index ed66f64..c7708a4 100644 --- a/README +++ b/README @@ -1,22 +1,32 @@ Jack - Beanstalkd web administration interface ============================================== What is beanstalkd? ------------------- "... a fast, general-purpose work queue." See http://xph.us/software/beanstalkd/ for general info. +What can I do using this application? +------------------------------------- + +- put job on queue in a given tube +- inspect job: view body and statistics +- inspect burried jobs and kick all or individual +- inspect delayed jobs +- view what tubes are currently in use and stats +- view queue statistics + Requirements ------------ * Django 1.1 http://www.djangoproject.com/ * beanstalkc http://github.com/earl/beanstalkc
andreisavu/django-jack
9efec9f21ac6c6f96cdd32ce9f6fd859e13d67ad
initial import: empty django project
diff --git a/README b/README new file mode 100644 index 0000000..ed66f64 --- /dev/null +++ b/README @@ -0,0 +1,22 @@ + +Jack - Beanstalkd web administration interface +============================================== + +What is beanstalkd? +------------------- + +"... a fast, general-purpose work queue." + +See http://xph.us/software/beanstalkd/ for general info. + +Requirements +------------ + +* Django 1.1 + + http://www.djangoproject.com/ + +* beanstalkc + + http://github.com/earl/beanstalkc + diff --git a/jack/.gitignore b/jack/.gitignore new file mode 100644 index 0000000..9e9af13 --- /dev/null +++ b/jack/.gitignore @@ -0,0 +1,3 @@ +*.pyc +*.swp +database.db diff --git a/jack/__init__.py b/jack/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/jack/abspath.py b/jack/abspath.py new file mode 100644 index 0000000..565e912 --- /dev/null +++ b/jack/abspath.py @@ -0,0 +1,8 @@ + +import os + +def abspath(*args): + current_dir = os.path.dirname(os.path.realpath(__file__)) + return os.path.join(current_dir, *args) + + diff --git a/jack/manage.py b/jack/manage.py new file mode 100755 index 0000000..5e78ea9 --- /dev/null +++ b/jack/manage.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python +from django.core.management import execute_manager +try: + import settings # Assumed to be in the same directory. +except ImportError: + import sys + sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) + sys.exit(1) + +if __name__ == "__main__": + execute_manager(settings) diff --git a/jack/self b/jack/self new file mode 120000 index 0000000..30f5e9f --- /dev/null +++ b/jack/self @@ -0,0 +1 @@ +manage.py \ No newline at end of file diff --git a/jack/settings.py b/jack/settings.py new file mode 100644 index 0000000..870a548 --- /dev/null +++ b/jack/settings.py @@ -0,0 +1,79 @@ +# Django settings for jack project. + +from abspath import abspath + +DEBUG = True +TEMPLATE_DEBUG = DEBUG + +ADMINS = ( + # ('Your Name', 'your_email@domain.com'), +) + +MANAGERS = ADMINS + +DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. +DATABASE_NAME = 'database.db' # Or path to database file if using sqlite3. +DATABASE_USER = '' # Not used with sqlite3. +DATABASE_PASSWORD = '' # Not used with sqlite3. +DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. +DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. + +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# If running in a Windows environment this must be set to the same as your +# system time zone. +TIME_ZONE = 'America/Chicago' + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en-us' + +SITE_ID = 1 + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True + +# Absolute path to the directory that holds media. +# Example: "/home/media/media.lawrence.com/" +MEDIA_ROOT = abspath('media') + +# URL that handles the media served from MEDIA_ROOT. Make sure to use a +# trailing slash if there is a path component (optional in other cases). +# Examples: "http://media.lawrence.com", "http://example.com/media/" +MEDIA_URL = '/media/' + +# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a +# trailing slash. +# Examples: "http://foo.com/media/", "/media/". +ADMIN_MEDIA_PREFIX = '/media/admin/' + +# Make this unique, and don't share it with anybody. +SECRET_KEY = '8wv3d_4@^=blqi)@ev*v4m=hphqgl6c5av-tbw$pl)2x37_2+-' + +# List of callables that know how to import templates from various sources. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.load_template_source', + 'django.template.loaders.app_directories.load_template_source', +) + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', +) + +ROOT_URLCONF = 'jack.urls' + +TEMPLATE_DIRS = ( + abspath('templates'), +) + +INSTALLED_APPS = ( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + 'django.contrib.admin', +) diff --git a/jack/urls.py b/jack/urls.py new file mode 100644 index 0000000..ae4996d --- /dev/null +++ b/jack/urls.py @@ -0,0 +1,13 @@ +from django.conf.urls.defaults import * + +# Uncomment the next two lines to enable the admin: +from django.contrib import admin +admin.autodiscover() + +urlpatterns = patterns('', + # Example: + # (r'^jack/', include('jack.foo.urls')), + + # Uncomment the next line to enable the admin: + (r'^admin/', include(admin.site.urls)), +)
schuyler1d/cbook
5c54a1165546696aba24b3a380c2724262728ace
refuse to encrypt off a blank empty key
diff --git a/client/js/cbook.js b/client/js/cbook.js index 467b0e1..8319c45 100644 --- a/client/js/cbook.js +++ b/client/js/cbook.js @@ -1,257 +1,262 @@ var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?', regex_args = ['codec','hash','iv','ciphtext'], html_regex = '<([:\\w]+)[^<]+'; /* facebook: document.getElementsByClassName('uiStreamMessage') twitter: //document.activeElement to know which element has focus 15chars for IV 1char for addition 4chars for ♔.☿ (could make it 3) 'http://skyb.us/' == 15 chars 140=15+1+4+15+105 */ var global= { FAIL_ENCODING:'Failed to decrypt message, likely due to encoding problems.<br />', FAIL_NOKEY:'None of your keys could decrypt this message.<br />' } function cryptArgs(iv, encrypt_key_numbers) { ///see http://www.josh-davis.org/ecmascrypt ///NOTE:if CBC, then we need to save the msgsize var mode = 0; //0:OFB,1:CFB,2:CBC var keysize = 16; //32 for 256, 24 for 192, 16 for 128 encrypt_key_numbers = encrypt_key_numbers || ecmaScrypt.toNumbers(global.encrypt_key); return [mode, encrypt_key_numbers, keysize, iv]; } var U2N = new (function() { /* we'll need to get a lot smarter. we should be accepting/creating unicode characters within the character range that HTML considers 'character' text. http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets parseInt('10FFFF',16) - parseInt('10000',16) == 1048575 1114111 - 65536 == String.fromCharCode(85267) seems to be 'real' first character */ this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars this.compress = function(low_unicode) { var arr = []; var c = low_unicode.length; while (c--) { arr.unshift(low_unicode.charCodeAt(c)); } return this.unicode(arr); } this.decompress = function(high_unicode) { var nums = this.nums(high_unicode); var str = ''; for (var i=0;i<nums.length;i++) { str += String.fromCharCode(nums[i]); } return str; } this.lowcoding = function(cipher) { var outhex = ''; for(var i = 0;i < cipher.length;i++) { outhex += ecmaScrypt.toHex(cipher.charCodeAt(i)); } return outhex; } this.unicode = function(nums) { ///take nums array of numbers from 0-255 var u_string=''; for (var i=0;i<nums.length;i++) { var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) ); if (n>65535) { ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes throw Error('cannot deal with high chars yet'); } if (n>2299099) { throw Error('cannot deal with high unicode compression yet'); //but I think the answer is that we'll have some marker //for NON-encoded text and then // } ///random suspects: if (n==1759 || n==130) { throw Error('random suspect--not sure it is culprit'); } if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes'); //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n); } if (8192 < n && n < 8447) { //255 chars ///http://en.wikipedia.org/wiki/Unicode_control_characters ///seem to be grouped all in the 2000 -20FF range throw Error('Wide fence for control chars. we can be more picky'+n); } ///Any code D800–DFFF is invalid: UTF-16 conflict (2047 chars) try { var c = String.fromCharCode(n); encodeURIComponent(c); u_string += c; } catch(e) { throw Error('could not encode uri component for char:'+n); } } if (u_string.match(/\s/)!=null) { throw Error('FAILS BY WHITESPACE'); } return u_string; }; this.nums = function(u_string) { var nums = []; var m = u_string.length; for (var i=0;i<m;i++) { var n = u_string.charCodeAt(i)-this.min; nums.push(n%256); var x2 = parseInt(n/256,10); if (x2 != 0) nums.push(x2); } return nums; }; })();//end U2N var CBook= { chars:{'.':'unicrap',',':'base64'}, unicrap:{ chr:'.', encrypt:function(iv,ciph,key_numbers) { var compressed = U2N.compress(ciph.cipher); var compressed_IV = U2N.unicode(iv); //cheat on making exceptions and just try decrypt var decoded = CBook.unicrap.decrypt(compressed_IV,compressed); decrypt(decoded[0],decoded[1],key_numbers); return [compressed_IV, compressed]; }, decrypt:function(iv,ciphtext) { return [U2N.nums(iv), U2N.decompress(ciphtext)]; } }, base64:{ chr:',', encrypt:function(iv,ciph) { return [Base64.encodeBytes(iv), Base64.encode(ciph.cipher)]; }, decrypt:function(iv64,ciphtext) { return [Base64.decodeBytes(iv64), Base64.decode(ciphtext)]; } } /*,hex:{ chr:'_', encrypt:function(iv,ciph) { return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)]; }, decrypt:function(iv,ciphtext) { } }*/ };//end CBook function format_post(codec,hash,iv,ciphertext) { var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':'; //console.log(rv.length); return rv; } function test_unicode(txt,f) { f = f||function(c) { return c.match(/([\w\W])/); }; for (var i=0;i<txt.length;i++) { var r = f(String.fromCharCode(txt.charCodeAt(i))); if (r) { console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i)); } } } function decrypt_message(crypted) { var x; var retval = ''; var crypted_regex = new RegExp(crypted_regex_str,'g'); while ((x = crypted_regex.exec(crypted)) != null) { var friend_keys = Stor.getKeysByIdentifier(x[2]), cbook_method = CBook[CBook.chars[x[1]]]; if (!friend_keys || !friend_keys.length ) { retval += global.FAIL_NOKEY; continue; } try { var iv_ciph = cbook_method.decrypt(x[3],x[4]); }catch(e) { retval += global.FAIL_ENCODING; continue; } var i = friend_keys.length; while (i--) { try { var msg = decrypt(iv_ciph[0],iv_ciph[1],Base64.decodeBytes(friend_keys[i])); retval += msg+ '<br />'; success = true; continue; } catch(e) {/*probably, just the wrong key, keep trying*/} } if (!success) retval += global.FAIL_NOKEY; } return retval; } function encrypt_message(plaintext, mode, key_and_ref) { mode = mode || 'base64'; var key_ref = key_and_ref.substr(0,1), key = Base64.decodeBytes(key_and_ref.substr(2)), tries = 200, comp = []; + if (!key_ref || !key.length) { + alert("Please choose a key to encrypt with. " + +"If you haven't yet, generate a key for yourself."); + throw Error('no key'); + } while (--tries) { try { comp = CBook[mode].encrypt.apply(null,encrypt(plaintext, key)); break; } catch(e) { //console.log(e); } } comp.unshift(CBook[mode].chr, key_ref); if (tries == 0) { throw Error('tried too many times and failed'); } var rv = format_post.apply(null,comp); if (window.parent != window && window.postMessage) { window.parent.postMessage(rv,"*"); } return rv; } function encrypt(plaintext, encrypt_key_numbers) { var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128); var crypt_args = cryptArgs(iv, encrypt_key_numbers); crypt_args.unshift(plaintext); return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args), encrypt_key_numbers]; } function decrypt(iv,ciph_string, encrypt_key_numbers) { var crypt_args = cryptArgs(iv, encrypt_key_numbers); if (crypt_args[0]==2) throw Error('if CBC, then we need to save the msgsize'); crypt_args.unshift(ciph_string,0); var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args); return plaintext; } function update_bookmarklet() { var bk = document.getElementById('bookmarklet_source').innerHTML; var target = document.getElementById('bookmarklet'); target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")'; } function tryGenuine() { /*will try to show genuinity*/ } \ No newline at end of file
schuyler1d/cbook
5dc5eb5365e3f2e42acf09d569c8ba955a5b5829
avoid facebook doubling--due to regex reseting when run on a different string
diff --git a/client/index.html b/client/index.html index aa7db95..08d5350 100644 --- a/client/index.html +++ b/client/index.html @@ -1,262 +1,262 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> <form id="encrypt" name="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form name="generatekey" id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="sec"> Share this link with all your friends. <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> <form name="backupform" onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> Now that you can back things up by pasting this text somewhere, do you want to delete all your keys from this browser? <input type="button" onclick="Stor.deleteEverything(this);return false;" value="Delete All Keys from Browser" /> </p> </form> <form id="restore" name="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> <form name="shareform" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> Share this, along with the private key with your friends, ideally through separate channels (that would not collude). For example, send one from your web email, and another over a different instant message network. (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> <ul id="test" class="sec"> <li>WARNING: don't run this on the host/browser you use. It may DELETE ALL YOUR KEYS.</li> <li>A bunch of alerts will come up. Just click OK/Enter to everything.</li> <li><form name="test" onsubmit="Tester.run();return false;"><button>Run Tests</button></form></li> </ul> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/cbook.js"></script> <script type="text/javascript" src="js/test.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; - var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); + var m = crypted_regex.exec(local_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); - } else if (n!=null) { + } else if (n!=null) { /*for facebook, which breaks up long words - mysteriously,that also means we track the second regex.exec() + it's while-do here because var m reset regex for var n */ nodes.push(textNode); while ((n = crypted_regex.exec(higher_str)) != null) { frm_loc += n[0]; } var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect('friendkey'); } else { document.getElementById('menu').style.display = 'block'; Stor.populateKeysOnSelect('sharekey','shareable'); } update_bookmarklet(); </script> </body> </html>
schuyler1d/cbook
bf8414c0d4dca2cd0eeae4b6659f078ac43dd88c
stop the double-printing on Facebook, but no idea why it's fixed
diff --git a/client/index.html b/client/index.html index ad33a4a..aa7db95 100644 --- a/client/index.html +++ b/client/index.html @@ -1,259 +1,262 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> <form id="encrypt" name="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form name="generatekey" id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="sec"> Share this link with all your friends. <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> <form name="backupform" onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> Now that you can back things up by pasting this text somewhere, do you want to delete all your keys from this browser? <input type="button" onclick="Stor.deleteEverything(this);return false;" value="Delete All Keys from Browser" /> </p> </form> <form id="restore" name="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> <form name="shareform" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> Share this, along with the private key with your friends, ideally through separate channels (that would not collude). For example, send one from your web email, and another over a different instant message network. (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> <ul id="test" class="sec"> <li>WARNING: don't run this on the host/browser you use. It may DELETE ALL YOUR KEYS.</li> <li>A bunch of alerts will come up. Just click OK/Enter to everything.</li> <li><form name="test" onsubmit="Tester.run();return false;"><button>Run Tests</button></form></li> </ul> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/cbook.js"></script> <script type="text/javascript" src="js/test.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); - } else if (n!=null) { /*for facebook, which breaks up long words*/ + } else if (n!=null) { + /*for facebook, which breaks up long words + mysteriously,that also means we track the second regex.exec() + */ nodes.push(textNode); - do { + while ((n = crypted_regex.exec(higher_str)) != null) { frm_loc += n[0]; - } while ((n = crypted_regex.exec(higher_str)) != null); + } var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect('friendkey'); } else { document.getElementById('menu').style.display = 'block'; Stor.populateKeysOnSelect('sharekey','shareable'); } update_bookmarklet(); </script> </body> </html>
schuyler1d/cbook
7f784290b578fae4aea7cd9deb3b6a6b187729ce
originally planned tests finished. rooted out a couple bugs. ready for some alpha-alpha-alpha testers
diff --git a/client/js/local_session.js b/client/js/local_session.js index 150070c..3845f21 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,236 +1,252 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64, obj) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.isMyKey = function(secret) { var me = JSON.parse(self.permStor.get(self.nsME,'{}')); return (secret in me) } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); if (!limit ||secret in me) key_list[side]([k,secret,alias]); } return key_list; } this.populateKeysOnSelect = function(select_id,limit) { var select = document.getElementById(select_id); select.innerHTML = ''; var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var alias = frm.elements['alias'].value; var obj = {"alias":{"v":alias,"p":"friends"}}; var prefix = self.getKeyIdentifier(newsecret, obj); ///v:value, p:privacy self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); self.refreshForms(); } this.addMyKey = function(secret) { - var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); - keys[secret]=1; - self.permStor.set(self.nsME, JSON.stringify(keys)); + var me = JSON.parse(self.permStor.get(self.nsME,'{}')); + me[secret]=1; + self.permStor.set(self.nsME, JSON.stringify(me)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret, obj); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } + + this.removeKey = function(secret_n_prefix) { + var prefix = secret_n_prefix[0]; + var secret = secret_n_prefix.substr(2); + //delete from key list + var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); + ppl[prefix].splice(ppl[prefix].indexOf(secret),1); + + self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); + //delete from private list -- should we do this? if you delete/restore.... + var me = JSON.parse(self.permStor.get(self.nsME,'{}')); + delete me[secret]; + self.permStor.set(self.nsME, JSON.stringify(me)); + //delete data + self.permStor.del(self.nsPERSON+secret); + } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } this.refreshForms = function() { Stor.populateKeysOnSelect('friendkey'); Stor.populateKeysOnSelect('sharekey','shareable'); } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } else { bkup[1]={}; } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } if (passkey) { return CBook['base64' ].encrypt.apply(null,encrypt(JSON.stringify(bkup), passkey)); } else return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); for (a in restoral_keys[0]) { self.addFriend(a, restoral_keys[0][a]); } for (m in restoral_keys[1]) { self.addMyKey(m) } alert('Restoral complete'); self.refreshForms(); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } this.shareForm = function(frm) { var key_list = []; var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var o = eee['friendkey'].options; for (var i=0;i<o.length;i++) { if (o[i].selected) { key_list.push(o[i].value.substr(2)); } } eee['backup'].value = self.getBackup(key_list,passkey); document.location="#share-text"; } this.deleteEverything = function() { if (confirm("Are you sure you want to delete all your keys from this browser?")) { self.permStor.deleteEveryFuckingThing(); self.friendsCache = {}; alert("Your keys have been removed. Don't lose your backup!"); } } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file diff --git a/client/js/test.js b/client/js/test.js index 03fbf14..18fcc2e 100644 --- a/client/js/test.js +++ b/client/js/test.js @@ -1,194 +1,208 @@ /* KEY: -=action ?=test *=store for later part of test 1 -*create key1 2 -*encrypt message 3 ?decrypt message 4 -*full backup 5 -*share 6 -delete everything 7 ?restore from full 8 test alias, user 9 ?decrypt message 10 -delete everything 11 -*create key2 12 ?restore from share 13 ?decrypt message 14 -encrypt message2 (with key1) */ var Tester = new (function runTests() { var self = this, testdom = document.getElementById('test') this.run = function() { for (var i=0;i<self.tests.length;i++) { var name = i+' '+self.tests[i].name try { self.msg(name,self.tests[i](),false) } catch(e) { self.msg(name,e.message,true) } } } this.msg = function(name,msg,fail) { var li = document.createElement('li') testdom.appendChild(li) li.innerHTML = name+' '+(msg||'') li.style.backgroundColor = ((fail)?'red':'green') } function assert(true_v, msg) { if (!true_v) throw Error("Failed on: "+msg) } var vv = this.vars = { + original_keylistcount:0, key1_alias:'key1_test_alias', key1_secret:null, key2_alias:'key2_test_alias', key2_secret:null, msg1_plaintext:'Foo and Bar and Hello', msg1_encrypted:null, msg1_encrypted_uni:null, backup_passphrase:'Never lie to your mother', backup_string:null, share_string:null, msg2_encrypted:null } this.tests = [ /// #1 -*create key1 function create_key1() { + vv.original_keylistcount = Stor.keyList().length + vv.original_keylist = Stor.keyList() + self.test_createKey = function(vv_prefix) { //setup var frm= document.forms['generatekey'] frm.elements['alias'].value = vv[vv_prefix+'_alias'] Stor.generateKey(frm) //submit //tests var keys = Stor.keyList() assert(keys.length > 1,'some key exists') var found_key = false, o = document.forms['encrypt'].elements['friendkey'].options for (var i=0;i<keys.length;i++) { if (keys[i][2] == vv[vv_prefix+'_alias']) { found_key = true break } } assert(found_key, 'key alias is in DB') found_key = false for (var i=0;i<o.length;i++) if (o[i].innerHTML == vv[vv_prefix+'_alias']) { found_key = true vv[vv_prefix+'_secret'] = o[i].value break } assert(found_key, 'key alias is in encrypt form') } self.test_createKey('key1') }, /// #2 -*encrypt message function encrypt_msg() { vv.msg1_encrypted = encrypt_message(vv.msg1_plaintext,'base64',vv.key1_secret) vv.msg1_encrypted_uni = encrypt_message(vv.msg1_plaintext,'unicrap',vv.key1_secret) //self.msg('--plaintext:',vv.msg1_plaintext) //self.msg('--crypt:',vv.msg1_encrypted) var crypted_regex = new RegExp(crypted_regex_str,'g') assert(crypted_regex.test(vv.msg1_encrypted), 'encrypted message is proper form:'+vv.msg1_encrypted) }, /// #3 ?decrypt message function decrypt_msg() { self.dec_test_func = function() { var plain = decrypt_message(vv.msg1_encrypted) assert(plain.length,'decrypted message is non-empty') assert(plain == vv.msg1_plaintext+ '<br />','Decrypted base64 message ==original:') assert(decrypt_message(vv.msg1_encrypted_uni)==vv.msg1_plaintext+'<br />', 'Decrypted unicrap message ==original:') } self.dec_test_func() }, /// #4 -*full backup function full_backup() { var frm= document.forms['backupform'] frm.elements['passphrase'].value = vv.backup_passphrase frm.elements['backup'].value = '' Stor.backupForm(frm) vv.backup_string = frm.elements['backup'].value assert(vv.backup_string.length,'non-empty backup string') document.location = '#test' }, /// #5 -*share function share() { var frm= document.forms['shareform'] frm.elements['passphrase'].value = vv.backup_passphrase var o = frm.elements['friendkey'].options var selected_key = false for (var i=0;i<o.length;i++) { if (o[i].value == vv.key1_secret) { o[i].selected = true selected_key = true } } assert(selected_key,'Found and selected key to share') frm.elements['backup'].value = '' Stor.shareForm(frm) vv.share_string = frm.elements['backup'].value assert(vv.share_string.length,'non-empty backup string') document.location = '#test' }, /// #6 -delete everything function deleteEverything() { self.test_deleteEverything = function () { Stor.deleteEverything() assert(Stor.keyList().length==1,'Key list empty except --- divider') var fcount=0 for (a in Stor.friendsCache) fcount++ assert(fcount==0,'nothing cached') } self.test_deleteEverything() }, - /// #7 ?restore from full - /// #8 test alias, user - function restoreFromFull() { + /// #11 -*create key2 + function create_key2() { + self.test_createKey('key2') + }, + /// #12 ?restore from share + function restore_from_share() { self.test_restore = function(bk_pass,bk_str) { var frm= document.forms['restore'] frm.elements['passphrase'].value = vv[bk_pass] frm.elements['backup'].value = vv[bk_str] Stor.restoreForm(frm) document.location = '#test' assert(Stor.keyList().length>1,'Key list should not be empty') var user_secret = vv.key1_secret.substr(2) var user = Stor.getInfo(user_secret) assert(user.alias,'has alias') assert(user.alias.v==vv.key1_alias,'alias was correctly restored') + assert(Stor.friendsCache[vv.key1_secret[0]].indexOf(user_secret)>=0, + 'same prefix was created') return user_secret } - var user_secret = self.test_restore('backup_passphrase','backup_string') - assert(Stor.isMyKey(user_secret),'labeled as my key') - }, - /// #9 ?decrypt message - function decrypt_after_restoral() { - self.dec_test_func() - }, - /// #10 -delete everything again - function delete_everything_again() { - self.test_deleteEverything() - }, - /// #11 -*create key2 - function create_key2() { - self.test_createKey('key2') - }, - /// #12 ?restore from share - function restore_from_share() { - self.test_restore('backup_passphrase','share_string') + var user_secret = self.test_restore('backup_passphrase','share_string') + assert( !Stor.isMyKey(user_secret),'not labeled as my key') }, /// #13 ?decrypt message function decrypt_message_fromshare() { self.dec_test_func() }, /// #14 -encrypt message2 (with key1) function encrypt_with_key2() { ///just tells us that after the loading of the shared file, encryption still works vv.msg2_encrypted = encrypt_message(vv.msg1_plaintext,'base64',vv.key2_secret) assert(vv.msg1_plaintext+'<br />' == decrypt_message(vv.msg2_encrypted), 'encryption/decyption on key2 after loading shared backup') + }, + /// #10 -delete everything again + function delete_everything_again() { + self.test_deleteEverything() + }, + /// #7 ?restore from full + /// #8 test alias, user + function restoreFromFull() { + var user_secret = self.test_restore('backup_passphrase','backup_string') + assert(Stor.isMyKey(user_secret),'labeled as my key') + }, + /// #9 ?decrypt message + function decrypt_after_restoral() { + self.dec_test_func() + }, + /// #15 -delete test keys + function try_restoring_state() { + Stor.removeKey(vv.key1_secret) + //Stor.removeKey(vv.key2_secret) //already deleted by restoring just backup 1 + assert(vv.original_keylistcount==Stor.keyList().length, + 'keylist count is same as original') } ] })() \ No newline at end of file
schuyler1d/cbook
8a510532b2d296e27d5b438b2e3fcc4d6861736d
bugfix: sharing keys need to clip off the letter
diff --git a/client/index.html b/client/index.html index dd76b2f..ad33a4a 100644 --- a/client/index.html +++ b/client/index.html @@ -1,258 +1,259 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> <form id="encrypt" name="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form name="generatekey" id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="sec"> Share this link with all your friends. <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> <form name="backupform" onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> Now that you can back things up by pasting this text somewhere, do you want to delete all your keys from this browser? <input type="button" onclick="Stor.deleteEverything(this);return false;" value="Delete All Keys from Browser" /> </p> </form> <form id="restore" name="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> <form name="shareform" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> Share this, along with the private key with your friends, ideally through separate channels (that would not collude). For example, send one from your web email, and another over a different instant message network. (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> <ul id="test" class="sec"> <li>WARNING: don't run this on the host/browser you use. It may DELETE ALL YOUR KEYS.</li> + <li>A bunch of alerts will come up. Just click OK/Enter to everything.</li> <li><form name="test" onsubmit="Tester.run();return false;"><button>Run Tests</button></form></li> </ul> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/cbook.js"></script> <script type="text/javascript" src="js/test.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect('friendkey'); } else { document.getElementById('menu').style.display = 'block'; Stor.populateKeysOnSelect('sharekey','shareable'); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/local_session.js b/client/js/local_session.js index 16bfa9c..150070c 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,235 +1,236 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64, obj) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.isMyKey = function(secret) { var me = JSON.parse(self.permStor.get(self.nsME,'{}')); return (secret in me) } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); if (!limit ||secret in me) key_list[side]([k,secret,alias]); } return key_list; } this.populateKeysOnSelect = function(select_id,limit) { var select = document.getElementById(select_id); select.innerHTML = ''; var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var alias = frm.elements['alias'].value; var obj = {"alias":{"v":alias,"p":"friends"}}; var prefix = self.getKeyIdentifier(newsecret, obj); ///v:value, p:privacy self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); self.refreshForms(); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret, obj); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } this.refreshForms = function() { Stor.populateKeysOnSelect('friendkey'); Stor.populateKeysOnSelect('sharekey','shareable'); } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } else { bkup[1]={}; } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } if (passkey) { return CBook['base64' ].encrypt.apply(null,encrypt(JSON.stringify(bkup), passkey)); } else return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); - for (a in restoral_keys[0]) + for (a in restoral_keys[0]) { self.addFriend(a, restoral_keys[0][a]); + } for (m in restoral_keys[1]) { self.addMyKey(m) } alert('Restoral complete'); self.refreshForms(); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } this.shareForm = function(frm) { var key_list = []; var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var o = eee['friendkey'].options; for (var i=0;i<o.length;i++) { if (o[i].selected) { - key_list.push(o[i].value); + key_list.push(o[i].value.substr(2)); } } eee['backup'].value = self.getBackup(key_list,passkey); document.location="#share-text"; } this.deleteEverything = function() { if (confirm("Are you sure you want to delete all your keys from this browser?")) { self.permStor.deleteEveryFuckingThing(); self.friendsCache = {}; alert("Your keys have been removed. Don't lose your backup!"); } } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file diff --git a/client/js/test.js b/client/js/test.js index 2e1f8c1..03fbf14 100644 --- a/client/js/test.js +++ b/client/js/test.js @@ -1,185 +1,194 @@ /* KEY: -=action ?=test *=store for later part of test 1 -*create key1 2 -*encrypt message 3 ?decrypt message 4 -*full backup 5 -*share 6 -delete everything 7 ?restore from full 8 test alias, user 9 ?decrypt message 10 -delete everything 11 -*create key2 12 ?restore from share 13 ?decrypt message 14 -encrypt message2 (with key1) */ var Tester = new (function runTests() { var self = this, testdom = document.getElementById('test') this.run = function() { for (var i=0;i<self.tests.length;i++) { var name = i+' '+self.tests[i].name try { self.msg(name,self.tests[i](),false) } catch(e) { self.msg(name,e.message,true) } } } this.msg = function(name,msg,fail) { var li = document.createElement('li') testdom.appendChild(li) li.innerHTML = name+' '+(msg||'') li.style.backgroundColor = ((fail)?'red':'green') } function assert(true_v, msg) { if (!true_v) throw Error("Failed on: "+msg) } var vv = this.vars = { - key1_alias:'key1_alias', + key1_alias:'key1_test_alias', key1_secret:null, - key2_alias:'key2_alias', + key2_alias:'key2_test_alias', key2_secret:null, msg1_plaintext:'Foo and Bar and Hello', msg1_encrypted:null, msg1_encrypted_uni:null, backup_passphrase:'Never lie to your mother', backup_string:null, - share_string:null + share_string:null, + msg2_encrypted:null } this.tests = [ /// #1 -*create key1 function create_key1() { self.test_createKey = function(vv_prefix) { //setup var frm= document.forms['generatekey'] frm.elements['alias'].value = vv[vv_prefix+'_alias'] Stor.generateKey(frm) //submit //tests var keys = Stor.keyList() assert(keys.length > 1,'some key exists') var found_key = false, o = document.forms['encrypt'].elements['friendkey'].options for (var i=0;i<keys.length;i++) { if (keys[i][2] == vv[vv_prefix+'_alias']) { found_key = true break } } assert(found_key, 'key alias is in DB') found_key = false for (var i=0;i<o.length;i++) if (o[i].innerHTML == vv[vv_prefix+'_alias']) { found_key = true vv[vv_prefix+'_secret'] = o[i].value break } assert(found_key, 'key alias is in encrypt form') } self.test_createKey('key1') }, /// #2 -*encrypt message function encrypt_msg() { vv.msg1_encrypted = encrypt_message(vv.msg1_plaintext,'base64',vv.key1_secret) vv.msg1_encrypted_uni = encrypt_message(vv.msg1_plaintext,'unicrap',vv.key1_secret) //self.msg('--plaintext:',vv.msg1_plaintext) //self.msg('--crypt:',vv.msg1_encrypted) var crypted_regex = new RegExp(crypted_regex_str,'g') assert(crypted_regex.test(vv.msg1_encrypted), 'encrypted message is proper form:'+vv.msg1_encrypted) }, /// #3 ?decrypt message function decrypt_msg() { self.dec_test_func = function() { var plain = decrypt_message(vv.msg1_encrypted) assert(plain.length,'decrypted message is non-empty') assert(plain == vv.msg1_plaintext+ '<br />','Decrypted base64 message ==original:') assert(decrypt_message(vv.msg1_encrypted_uni)==vv.msg1_plaintext+'<br />', 'Decrypted unicrap message ==original:') } self.dec_test_func() }, /// #4 -*full backup function full_backup() { var frm= document.forms['backupform'] frm.elements['passphrase'].value = vv.backup_passphrase frm.elements['backup'].value = '' Stor.backupForm(frm) vv.backup_string = frm.elements['backup'].value assert(vv.backup_string.length,'non-empty backup string') document.location = '#test' }, /// #5 -*share function share() { var frm= document.forms['shareform'] frm.elements['passphrase'].value = vv.backup_passphrase var o = frm.elements['friendkey'].options var selected_key = false for (var i=0;i<o.length;i++) { if (o[i].value == vv.key1_secret) { o[i].selected = true selected_key = true } } assert(selected_key,'Found and selected key to share') frm.elements['backup'].value = '' Stor.shareForm(frm) vv.share_string = frm.elements['backup'].value assert(vv.share_string.length,'non-empty backup string') document.location = '#test' }, /// #6 -delete everything function deleteEverything() { self.test_deleteEverything = function () { Stor.deleteEverything() assert(Stor.keyList().length==1,'Key list empty except --- divider') var fcount=0 for (a in Stor.friendsCache) fcount++ assert(fcount==0,'nothing cached') } self.test_deleteEverything() }, /// #7 ?restore from full /// #8 test alias, user function restoreFromFull() { self.test_restore = function(bk_pass,bk_str) { var frm= document.forms['restore'] frm.elements['passphrase'].value = vv[bk_pass] frm.elements['backup'].value = vv[bk_str] Stor.restoreForm(frm) document.location = '#test' assert(Stor.keyList().length>1,'Key list should not be empty') var user_secret = vv.key1_secret.substr(2) - console.log(vv.key1_secret) var user = Stor.getInfo(user_secret) assert(user.alias,'has alias') assert(user.alias.v==vv.key1_alias,'alias was correctly restored') return user_secret } var user_secret = self.test_restore('backup_passphrase','backup_string') assert(Stor.isMyKey(user_secret),'labeled as my key') }, /// #9 ?decrypt message function decrypt_after_restoral() { self.dec_test_func() }, /// #10 -delete everything again function delete_everything_again() { self.test_deleteEverything() }, /// #11 -*create key2 function create_key2() { self.test_createKey('key2') }, /// #12 ?restore from share function restore_from_share() { self.test_restore('backup_passphrase','share_string') - } -/// #13 ?decrypt message -/// #14 -encrypt message2 (with key1) + }, + /// #13 ?decrypt message + function decrypt_message_fromshare() { + self.dec_test_func() + }, + /// #14 -encrypt message2 (with key1) + function encrypt_with_key2() { + ///just tells us that after the loading of the shared file, encryption still works + vv.msg2_encrypted = encrypt_message(vv.msg1_plaintext,'base64',vv.key2_secret) + assert(vv.msg1_plaintext+'<br />' == decrypt_message(vv.msg2_encrypted), + 'encryption/decyption on key2 after loading shared backup') + } ] })() \ No newline at end of file
schuyler1d/cbook
46a5969102d989c72eb2af7ea3581a122e9179d0
another test: failing on restoral from share
diff --git a/client/js/test.js b/client/js/test.js index 14b56a7..2e1f8c1 100644 --- a/client/js/test.js +++ b/client/js/test.js @@ -1,169 +1,185 @@ /* KEY: -=action ?=test *=store for later part of test 1 -*create key1 2 -*encrypt message 3 ?decrypt message 4 -*full backup 5 -*share 6 -delete everything 7 ?restore from full 8 test alias, user 9 ?decrypt message 10 -delete everything 11 -*create key2 12 ?restore from share 13 ?decrypt message 14 -encrypt message2 (with key1) */ var Tester = new (function runTests() { var self = this, testdom = document.getElementById('test') this.run = function() { for (var i=0;i<self.tests.length;i++) { var name = i+' '+self.tests[i].name try { self.msg(name,self.tests[i](),false) } catch(e) { self.msg(name,e.message,true) } } } this.msg = function(name,msg,fail) { var li = document.createElement('li') testdom.appendChild(li) li.innerHTML = name+' '+(msg||'') li.style.backgroundColor = ((fail)?'red':'green') } function assert(true_v, msg) { if (!true_v) throw Error("Failed on: "+msg) } var vv = this.vars = { key1_alias:'key1_alias', key1_secret:null, + key2_alias:'key2_alias', + key2_secret:null, msg1_plaintext:'Foo and Bar and Hello', msg1_encrypted:null, msg1_encrypted_uni:null, backup_passphrase:'Never lie to your mother', backup_string:null, - shared_string:null + share_string:null } this.tests = [ /// #1 -*create key1 function create_key1() { - //setup - var frm= document.forms['generatekey'] - frm.elements['alias'].value = vv.key1_alias - Stor.generateKey(frm) //submit - - //tests - var keys = Stor.keyList() - assert(keys.length > 1,'some key exists') - var found_key = false, - o = document.forms['encrypt'].elements['friendkey'].options - for (var i=0;i<keys.length;i++) { - if (keys[i][2] == vv.key1_alias) { - found_key = true - break + self.test_createKey = function(vv_prefix) { + //setup + var frm= document.forms['generatekey'] + frm.elements['alias'].value = vv[vv_prefix+'_alias'] + Stor.generateKey(frm) //submit + + //tests + var keys = Stor.keyList() + assert(keys.length > 1,'some key exists') + var found_key = false, + o = document.forms['encrypt'].elements['friendkey'].options + for (var i=0;i<keys.length;i++) { + if (keys[i][2] == vv[vv_prefix+'_alias']) { + found_key = true + break + } } + assert(found_key, 'key alias is in DB') + found_key = false + for (var i=0;i<o.length;i++) + if (o[i].innerHTML == vv[vv_prefix+'_alias']) { + found_key = true + vv[vv_prefix+'_secret'] = o[i].value + break + } + assert(found_key, 'key alias is in encrypt form') } - assert(found_key, 'key alias is in DB') - found_key = false - for (var i=0;i<o.length;i++) - if (o[i].innerHTML == vv.key1_alias) { - found_key = true - vv.key1_secret = o[i].value - break - } - assert(found_key, 'key alias is in encrypt form') + self.test_createKey('key1') }, /// #2 -*encrypt message function encrypt_msg() { vv.msg1_encrypted = encrypt_message(vv.msg1_plaintext,'base64',vv.key1_secret) vv.msg1_encrypted_uni = encrypt_message(vv.msg1_plaintext,'unicrap',vv.key1_secret) //self.msg('--plaintext:',vv.msg1_plaintext) //self.msg('--crypt:',vv.msg1_encrypted) var crypted_regex = new RegExp(crypted_regex_str,'g') assert(crypted_regex.test(vv.msg1_encrypted), 'encrypted message is proper form:'+vv.msg1_encrypted) }, /// #3 ?decrypt message function decrypt_msg() { self.dec_test_func = function() { var plain = decrypt_message(vv.msg1_encrypted) assert(plain.length,'decrypted message is non-empty') assert(plain == vv.msg1_plaintext+ '<br />','Decrypted base64 message ==original:') assert(decrypt_message(vv.msg1_encrypted_uni)==vv.msg1_plaintext+'<br />', 'Decrypted unicrap message ==original:') } self.dec_test_func() }, /// #4 -*full backup function full_backup() { var frm= document.forms['backupform'] frm.elements['passphrase'].value = vv.backup_passphrase frm.elements['backup'].value = '' Stor.backupForm(frm) vv.backup_string = frm.elements['backup'].value assert(vv.backup_string.length,'non-empty backup string') document.location = '#test' }, /// #5 -*share function share() { var frm= document.forms['shareform'] frm.elements['passphrase'].value = vv.backup_passphrase var o = frm.elements['friendkey'].options var selected_key = false for (var i=0;i<o.length;i++) { if (o[i].value == vv.key1_secret) { o[i].selected = true selected_key = true } } assert(selected_key,'Found and selected key to share') frm.elements['backup'].value = '' Stor.shareForm(frm) vv.share_string = frm.elements['backup'].value assert(vv.share_string.length,'non-empty backup string') document.location = '#test' }, /// #6 -delete everything function deleteEverything() { self.test_deleteEverything = function () { Stor.deleteEverything() assert(Stor.keyList().length==1,'Key list empty except --- divider') var fcount=0 for (a in Stor.friendsCache) fcount++ assert(fcount==0,'nothing cached') } self.test_deleteEverything() }, /// #7 ?restore from full /// #8 test alias, user function restoreFromFull() { - var frm= document.forms['restore'] - frm.elements['passphrase'].value = vv.backup_passphrase - frm.elements['backup'].value = vv.backup_string - Stor.restoreForm(frm) - document.location = '#test' - assert(Stor.keyList().length>1,'Key list not empty') - var user_secret = vv.key1_secret.substr(2) - var user = Stor.getInfo(user_secret) - assert(user.alias,'has alias') - assert(user.alias.v==vv.key1_alias,'alias was correctly restored') + self.test_restore = function(bk_pass,bk_str) { + var frm= document.forms['restore'] + frm.elements['passphrase'].value = vv[bk_pass] + frm.elements['backup'].value = vv[bk_str] + Stor.restoreForm(frm) + document.location = '#test' + assert(Stor.keyList().length>1,'Key list should not be empty') + var user_secret = vv.key1_secret.substr(2) + console.log(vv.key1_secret) + var user = Stor.getInfo(user_secret) + assert(user.alias,'has alias') + assert(user.alias.v==vv.key1_alias,'alias was correctly restored') + return user_secret + } + var user_secret = self.test_restore('backup_passphrase','backup_string') assert(Stor.isMyKey(user_secret),'labeled as my key') }, /// #9 ?decrypt message function decrypt_after_restoral() { self.dec_test_func() }, /// #10 -delete everything again function delete_everything_again() { self.test_deleteEverything() + }, + /// #11 -*create key2 + function create_key2() { + self.test_createKey('key2') + }, + /// #12 ?restore from share + function restore_from_share() { + self.test_restore('backup_passphrase','share_string') } -/// #11 -*create key2 -/// #12 ?restore from share /// #13 ?decrypt message /// #14 -encrypt message2 (with key1) ] })() \ No newline at end of file
schuyler1d/cbook
8edb25965d402a40f47a71a7997144875c788ab3
bugfix: restoral should add secret instead of "1"--thanks to more tests, too
diff --git a/client/index.html b/client/index.html index 972b2a2..dd76b2f 100644 --- a/client/index.html +++ b/client/index.html @@ -1,257 +1,258 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> <form id="encrypt" name="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form name="generatekey" id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="sec"> Share this link with all your friends. <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> <form name="backupform" onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> Now that you can back things up by pasting this text somewhere, do you want to delete all your keys from this browser? <input type="button" onclick="Stor.deleteEverything(this);return false;" value="Delete All Keys from Browser" /> </p> </form> - <form id="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> + <form id="restore" name="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> <form name="shareform" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> Share this, along with the private key with your friends, ideally through separate channels (that would not collude). For example, send one from your web email, and another over a different instant message network. (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> <ul id="test" class="sec"> + <li>WARNING: don't run this on the host/browser you use. It may DELETE ALL YOUR KEYS.</li> <li><form name="test" onsubmit="Tester.run();return false;"><button>Run Tests</button></form></li> </ul> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/cbook.js"></script> <script type="text/javascript" src="js/test.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect('friendkey'); } else { document.getElementById('menu').style.display = 'block'; Stor.populateKeysOnSelect('sharekey','shareable'); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/local_session.js b/client/js/local_session.js index 5b3af77..16bfa9c 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,232 +1,235 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64, obj) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } - + this.isMyKey = function(secret) { + var me = JSON.parse(self.permStor.get(self.nsME,'{}')); + return (secret in me) + } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); if (!limit ||secret in me) key_list[side]([k,secret,alias]); } return key_list; } this.populateKeysOnSelect = function(select_id,limit) { var select = document.getElementById(select_id); select.innerHTML = ''; var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var alias = frm.elements['alias'].value; var obj = {"alias":{"v":alias,"p":"friends"}}; var prefix = self.getKeyIdentifier(newsecret, obj); ///v:value, p:privacy self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); self.refreshForms(); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret, obj); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } this.refreshForms = function() { Stor.populateKeysOnSelect('friendkey'); Stor.populateKeysOnSelect('sharekey','shareable'); } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } else { bkup[1]={}; } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } if (passkey) { return CBook['base64' ].encrypt.apply(null,encrypt(JSON.stringify(bkup), passkey)); } else return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); for (a in restoral_keys[0]) self.addFriend(a, restoral_keys[0][a]); - for (m in restoral_keys[1]) - self.addMyKey(restoral_keys[1][m]); - + for (m in restoral_keys[1]) { + self.addMyKey(m) + } alert('Restoral complete'); self.refreshForms(); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } this.shareForm = function(frm) { var key_list = []; var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var o = eee['friendkey'].options; for (var i=0;i<o.length;i++) { if (o[i].selected) { key_list.push(o[i].value); } } eee['backup'].value = self.getBackup(key_list,passkey); document.location="#share-text"; } this.deleteEverything = function() { if (confirm("Are you sure you want to delete all your keys from this browser?")) { self.permStor.deleteEveryFuckingThing(); self.friendsCache = {}; alert("Your keys have been removed. Don't lose your backup!"); } } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file diff --git a/client/js/test.js b/client/js/test.js index 30ada21..14b56a7 100644 --- a/client/js/test.js +++ b/client/js/test.js @@ -1,148 +1,169 @@ /* KEY: -=action ?=test *=store for later part of test 1 -*create key1 2 -*encrypt message 3 ?decrypt message 4 -*full backup 5 -*share 6 -delete everything 7 ?restore from full 8 test alias, user 9 ?decrypt message 10 -delete everything 11 -*create key2 12 ?restore from share 13 ?decrypt message 14 -encrypt message2 (with key1) */ var Tester = new (function runTests() { var self = this, testdom = document.getElementById('test') this.run = function() { for (var i=0;i<self.tests.length;i++) { - var name = i+' '+self.tests[i].name; + var name = i+' '+self.tests[i].name try { self.msg(name,self.tests[i](),false) } catch(e) { self.msg(name,e.message,true) } } } this.msg = function(name,msg,fail) { var li = document.createElement('li') testdom.appendChild(li) li.innerHTML = name+' '+(msg||'') li.style.backgroundColor = ((fail)?'red':'green') } function assert(true_v, msg) { if (!true_v) throw Error("Failed on: "+msg) } var vv = this.vars = { key1_alias:'key1_alias', key1_secret:null, msg1_plaintext:'Foo and Bar and Hello', msg1_encrypted:null, msg1_encrypted_uni:null, backup_passphrase:'Never lie to your mother', backup_string:null, shared_string:null } this.tests = [ /// #1 -*create key1 function create_key1() { //setup var frm= document.forms['generatekey'] frm.elements['alias'].value = vv.key1_alias Stor.generateKey(frm) //submit //tests var keys = Stor.keyList() assert(keys.length > 1,'some key exists') var found_key = false, o = document.forms['encrypt'].elements['friendkey'].options for (var i=0;i<keys.length;i++) { if (keys[i][2] == vv.key1_alias) { found_key = true break } } assert(found_key, 'key alias is in DB') found_key = false for (var i=0;i<o.length;i++) if (o[i].innerHTML == vv.key1_alias) { found_key = true vv.key1_secret = o[i].value break } assert(found_key, 'key alias is in encrypt form') }, /// #2 -*encrypt message function encrypt_msg() { vv.msg1_encrypted = encrypt_message(vv.msg1_plaintext,'base64',vv.key1_secret) vv.msg1_encrypted_uni = encrypt_message(vv.msg1_plaintext,'unicrap',vv.key1_secret) //self.msg('--plaintext:',vv.msg1_plaintext) //self.msg('--crypt:',vv.msg1_encrypted) - var crypted_regex = new RegExp(crypted_regex_str,'g'); + var crypted_regex = new RegExp(crypted_regex_str,'g') assert(crypted_regex.test(vv.msg1_encrypted), 'encrypted message is proper form:'+vv.msg1_encrypted) }, /// #3 ?decrypt message function decrypt_msg() { - var plain = decrypt_message(vv.msg1_encrypted) - assert(plain.length,'decrypted message is non-empty') - assert(plain == vv.msg1_plaintext+ '<br />','Decrypted base64 message ==original:') - assert(decrypt_message(vv.msg1_encrypted_uni)==vv.msg1_plaintext+'<br />', - 'Decrypted unicrap message ==original:') + self.dec_test_func = function() { + var plain = decrypt_message(vv.msg1_encrypted) + assert(plain.length,'decrypted message is non-empty') + assert(plain == vv.msg1_plaintext+ '<br />','Decrypted base64 message ==original:') + assert(decrypt_message(vv.msg1_encrypted_uni)==vv.msg1_plaintext+'<br />', + 'Decrypted unicrap message ==original:') + } + self.dec_test_func() }, /// #4 -*full backup function full_backup() { var frm= document.forms['backupform'] frm.elements['passphrase'].value = vv.backup_passphrase frm.elements['backup'].value = '' Stor.backupForm(frm) vv.backup_string = frm.elements['backup'].value assert(vv.backup_string.length,'non-empty backup string') document.location = '#test' }, /// #5 -*share function share() { var frm= document.forms['shareform'] frm.elements['passphrase'].value = vv.backup_passphrase var o = frm.elements['friendkey'].options var selected_key = false for (var i=0;i<o.length;i++) { if (o[i].value == vv.key1_secret) { o[i].selected = true selected_key = true } } assert(selected_key,'Found and selected key to share') frm.elements['backup'].value = '' Stor.shareForm(frm) vv.share_string = frm.elements['backup'].value assert(vv.share_string.length,'non-empty backup string') document.location = '#test' }, /// #6 -delete everything function deleteEverything() { - Stor.deleteEverything() - assert(Stor.keyList().length==0,'Key list deleted') - var fcount=0; - for (a in Stor.friendsCache) fcount++ - assert(fcount==0,'nothing cached') + self.test_deleteEverything = function () { + Stor.deleteEverything() + assert(Stor.keyList().length==1,'Key list empty except --- divider') + var fcount=0 + for (a in Stor.friendsCache) fcount++ + assert(fcount==0,'nothing cached') + } + self.test_deleteEverything() }, /// #7 ?restore from full + /// #8 test alias, user function restoreFromFull() { - + var frm= document.forms['restore'] + frm.elements['passphrase'].value = vv.backup_passphrase + frm.elements['backup'].value = vv.backup_string + Stor.restoreForm(frm) + document.location = '#test' + assert(Stor.keyList().length>1,'Key list not empty') + var user_secret = vv.key1_secret.substr(2) + var user = Stor.getInfo(user_secret) + assert(user.alias,'has alias') + assert(user.alias.v==vv.key1_alias,'alias was correctly restored') + assert(Stor.isMyKey(user_secret),'labeled as my key') + }, + /// #9 ?decrypt message + function decrypt_after_restoral() { + self.dec_test_func() + }, + /// #10 -delete everything again + function delete_everything_again() { + self.test_deleteEverything() } -/// #8 test alias, user -/// #9 ?decrypt message - -/// #10 -delete everything /// #11 -*create key2 /// #12 ?restore from share /// #13 ?decrypt message /// #14 -encrypt message2 (with key1) ] })() \ No newline at end of file
schuyler1d/cbook
7f3b5162d47d64035532094fa874aab9cc08b317
another test
diff --git a/client/index.html b/client/index.html index 75cc2fa..972b2a2 100644 --- a/client/index.html +++ b/client/index.html @@ -1,257 +1,257 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> <form id="encrypt" name="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form name="generatekey" id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="sec"> Share this link with all your friends. <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> - <form onsubmit="Stor.backupForm(this);return false;"> + <form name="backupform" onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> Now that you can back things up by pasting this text somewhere, do you want to delete all your keys from this browser? <input type="button" onclick="Stor.deleteEverything(this);return false;" value="Delete All Keys from Browser" /> </p> </form> <form id="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> - <form name="share" onsubmit="Stor.shareForm(this);return false;"> + <form name="shareform" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> Share this, along with the private key with your friends, ideally through separate channels (that would not collude). For example, send one from your web email, and another over a different instant message network. (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> <ul id="test" class="sec"> <li><form name="test" onsubmit="Tester.run();return false;"><button>Run Tests</button></form></li> </ul> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/cbook.js"></script> <script type="text/javascript" src="js/test.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect('friendkey'); } else { document.getElementById('menu').style.display = 'block'; Stor.populateKeysOnSelect('sharekey','shareable'); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/local_session.js b/client/js/local_session.js index f86e7e0..5b3af77 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,231 +1,232 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64, obj) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); if (!limit ||secret in me) key_list[side]([k,secret,alias]); } return key_list; } this.populateKeysOnSelect = function(select_id,limit) { var select = document.getElementById(select_id); select.innerHTML = ''; var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var alias = frm.elements['alias'].value; var obj = {"alias":{"v":alias,"p":"friends"}}; var prefix = self.getKeyIdentifier(newsecret, obj); ///v:value, p:privacy self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); self.refreshForms(); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret, obj); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } this.refreshForms = function() { Stor.populateKeysOnSelect('friendkey'); Stor.populateKeysOnSelect('sharekey','shareable'); } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } else { bkup[1]={}; } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } if (passkey) { return CBook['base64' ].encrypt.apply(null,encrypt(JSON.stringify(bkup), passkey)); } else return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); for (a in restoral_keys[0]) self.addFriend(a, restoral_keys[0][a]); for (m in restoral_keys[1]) self.addMyKey(restoral_keys[1][m]); alert('Restoral complete'); self.refreshForms(); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } this.shareForm = function(frm) { var key_list = []; var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var o = eee['friendkey'].options; for (var i=0;i<o.length;i++) { if (o[i].selected) { key_list.push(o[i].value); } } eee['backup'].value = self.getBackup(key_list,passkey); document.location="#share-text"; } this.deleteEverything = function() { if (confirm("Are you sure you want to delete all your keys from this browser?")) { self.permStor.deleteEveryFuckingThing(); + self.friendsCache = {}; alert("Your keys have been removed. Don't lose your backup!"); } } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file diff --git a/client/js/test.js b/client/js/test.js index 79ee871..30ada21 100644 --- a/client/js/test.js +++ b/client/js/test.js @@ -1,112 +1,148 @@ /* KEY: -=action ?=test *=store for later part of test 1 -*create key1 2 -*encrypt message 3 ?decrypt message 4 -*full backup 5 -*share 6 -delete everything 7 ?restore from full 8 test alias, user 9 ?decrypt message 10 -delete everything 11 -*create key2 12 ?restore from share 13 ?decrypt message 14 -encrypt message2 (with key1) */ var Tester = new (function runTests() { var self = this, testdom = document.getElementById('test') this.run = function() { for (var i=0;i<self.tests.length;i++) { var name = i+' '+self.tests[i].name; try { self.msg(name,self.tests[i](),false) } catch(e) { self.msg(name,e.message,true) } } } this.msg = function(name,msg,fail) { var li = document.createElement('li') testdom.appendChild(li) li.innerHTML = name+' '+(msg||'') li.style.backgroundColor = ((fail)?'red':'green') } function assert(true_v, msg) { if (!true_v) throw Error("Failed on: "+msg) } - var vv = { + var vv = this.vars = { key1_alias:'key1_alias', key1_secret:null, msg1_plaintext:'Foo and Bar and Hello', msg1_encrypted:null, - msg1_encrypted_uni:null + msg1_encrypted_uni:null, + backup_passphrase:'Never lie to your mother', + backup_string:null, + shared_string:null } this.tests = [ /// #1 -*create key1 function create_key1() { //setup var frm= document.forms['generatekey'] frm.elements['alias'].value = vv.key1_alias Stor.generateKey(frm) //submit //tests var keys = Stor.keyList() assert(keys.length > 1,'some key exists') var found_key = false, o = document.forms['encrypt'].elements['friendkey'].options for (var i=0;i<keys.length;i++) { if (keys[i][2] == vv.key1_alias) { found_key = true break } } assert(found_key, 'key alias is in DB') found_key = false for (var i=0;i<o.length;i++) if (o[i].innerHTML == vv.key1_alias) { found_key = true vv.key1_secret = o[i].value break } assert(found_key, 'key alias is in encrypt form') }, /// #2 -*encrypt message function encrypt_msg() { vv.msg1_encrypted = encrypt_message(vv.msg1_plaintext,'base64',vv.key1_secret) vv.msg1_encrypted_uni = encrypt_message(vv.msg1_plaintext,'unicrap',vv.key1_secret) //self.msg('--plaintext:',vv.msg1_plaintext) //self.msg('--crypt:',vv.msg1_encrypted) var crypted_regex = new RegExp(crypted_regex_str,'g'); assert(crypted_regex.test(vv.msg1_encrypted), 'encrypted message is proper form:'+vv.msg1_encrypted) }, /// #3 ?decrypt message function decrypt_msg() { var plain = decrypt_message(vv.msg1_encrypted) assert(plain.length,'decrypted message is non-empty') assert(plain == vv.msg1_plaintext+ '<br />','Decrypted base64 message ==original:') assert(decrypt_message(vv.msg1_encrypted_uni)==vv.msg1_plaintext+'<br />', 'Decrypted unicrap message ==original:') }, /// #4 -*full backup function full_backup() { + var frm= document.forms['backupform'] + frm.elements['passphrase'].value = vv.backup_passphrase + frm.elements['backup'].value = '' + Stor.backupForm(frm) + vv.backup_string = frm.elements['backup'].value + assert(vv.backup_string.length,'non-empty backup string') + document.location = '#test' + }, + /// #5 -*share + function share() { + var frm= document.forms['shareform'] + frm.elements['passphrase'].value = vv.backup_passphrase + var o = frm.elements['friendkey'].options + var selected_key = false + for (var i=0;i<o.length;i++) { + if (o[i].value == vv.key1_secret) { + o[i].selected = true + selected_key = true + } + } + assert(selected_key,'Found and selected key to share') + frm.elements['backup'].value = '' + Stor.shareForm(frm) + vv.share_string = frm.elements['backup'].value + assert(vv.share_string.length,'non-empty backup string') + document.location = '#test' + }, + /// #6 -delete everything + function deleteEverything() { + Stor.deleteEverything() + assert(Stor.keyList().length==0,'Key list deleted') + var fcount=0; + for (a in Stor.friendsCache) fcount++ + assert(fcount==0,'nothing cached') + }, + /// #7 ?restore from full + function restoreFromFull() { } -/// #5 -*share - -/// #6 -delete everything -/// #7 ?restore from full /// #8 test alias, user /// #9 ?decrypt message /// #10 -delete everything /// #11 -*create key2 /// #12 ?restore from share /// #13 ?decrypt message /// #14 -encrypt message2 (with key1) ] })() \ No newline at end of file
schuyler1d/cbook
ecb07a93af3fa6a6930bd6080863d761b3e8e039
got decryption test passing
diff --git a/client/js/cbook.js b/client/js/cbook.js index 7adb603..467b0e1 100644 --- a/client/js/cbook.js +++ b/client/js/cbook.js @@ -1,258 +1,257 @@ var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?', regex_args = ['codec','hash','iv','ciphtext'], html_regex = '<([:\\w]+)[^<]+'; -var crypted_regex = new RegExp(crypted_regex_str,'g'); /* facebook: document.getElementsByClassName('uiStreamMessage') twitter: //document.activeElement to know which element has focus 15chars for IV 1char for addition 4chars for ♔.☿ (could make it 3) 'http://skyb.us/' == 15 chars 140=15+1+4+15+105 */ var global= { FAIL_ENCODING:'Failed to decrypt message, likely due to encoding problems.<br />', FAIL_NOKEY:'None of your keys could decrypt this message.<br />' } function cryptArgs(iv, encrypt_key_numbers) { ///see http://www.josh-davis.org/ecmascrypt ///NOTE:if CBC, then we need to save the msgsize var mode = 0; //0:OFB,1:CFB,2:CBC var keysize = 16; //32 for 256, 24 for 192, 16 for 128 encrypt_key_numbers = encrypt_key_numbers || ecmaScrypt.toNumbers(global.encrypt_key); return [mode, encrypt_key_numbers, keysize, iv]; } var U2N = new (function() { /* we'll need to get a lot smarter. we should be accepting/creating unicode characters within the character range that HTML considers 'character' text. http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets parseInt('10FFFF',16) - parseInt('10000',16) == 1048575 1114111 - 65536 == String.fromCharCode(85267) seems to be 'real' first character */ this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars this.compress = function(low_unicode) { var arr = []; var c = low_unicode.length; while (c--) { arr.unshift(low_unicode.charCodeAt(c)); } return this.unicode(arr); } this.decompress = function(high_unicode) { var nums = this.nums(high_unicode); var str = ''; for (var i=0;i<nums.length;i++) { str += String.fromCharCode(nums[i]); } return str; } this.lowcoding = function(cipher) { var outhex = ''; for(var i = 0;i < cipher.length;i++) { outhex += ecmaScrypt.toHex(cipher.charCodeAt(i)); } return outhex; } this.unicode = function(nums) { ///take nums array of numbers from 0-255 var u_string=''; for (var i=0;i<nums.length;i++) { var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) ); if (n>65535) { ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes throw Error('cannot deal with high chars yet'); } if (n>2299099) { throw Error('cannot deal with high unicode compression yet'); //but I think the answer is that we'll have some marker //for NON-encoded text and then // } ///random suspects: if (n==1759 || n==130) { throw Error('random suspect--not sure it is culprit'); } if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes'); //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n); } if (8192 < n && n < 8447) { //255 chars ///http://en.wikipedia.org/wiki/Unicode_control_characters ///seem to be grouped all in the 2000 -20FF range throw Error('Wide fence for control chars. we can be more picky'+n); } ///Any code D800–DFFF is invalid: UTF-16 conflict (2047 chars) try { var c = String.fromCharCode(n); encodeURIComponent(c); u_string += c; } catch(e) { throw Error('could not encode uri component for char:'+n); } } if (u_string.match(/\s/)!=null) { throw Error('FAILS BY WHITESPACE'); } return u_string; }; this.nums = function(u_string) { var nums = []; var m = u_string.length; for (var i=0;i<m;i++) { var n = u_string.charCodeAt(i)-this.min; nums.push(n%256); var x2 = parseInt(n/256,10); if (x2 != 0) nums.push(x2); } return nums; }; })();//end U2N var CBook= { chars:{'.':'unicrap',',':'base64'}, unicrap:{ chr:'.', encrypt:function(iv,ciph,key_numbers) { var compressed = U2N.compress(ciph.cipher); var compressed_IV = U2N.unicode(iv); //cheat on making exceptions and just try decrypt var decoded = CBook.unicrap.decrypt(compressed_IV,compressed); decrypt(decoded[0],decoded[1],key_numbers); return [compressed_IV, compressed]; }, decrypt:function(iv,ciphtext) { return [U2N.nums(iv), U2N.decompress(ciphtext)]; } }, base64:{ chr:',', encrypt:function(iv,ciph) { return [Base64.encodeBytes(iv), Base64.encode(ciph.cipher)]; }, decrypt:function(iv64,ciphtext) { return [Base64.decodeBytes(iv64), Base64.decode(ciphtext)]; } } /*,hex:{ chr:'_', encrypt:function(iv,ciph) { return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)]; }, decrypt:function(iv,ciphtext) { } }*/ };//end CBook function format_post(codec,hash,iv,ciphertext) { var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':'; //console.log(rv.length); return rv; } function test_unicode(txt,f) { f = f||function(c) { return c.match(/([\w\W])/); }; for (var i=0;i<txt.length;i++) { var r = f(String.fromCharCode(txt.charCodeAt(i))); if (r) { console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i)); } } } function decrypt_message(crypted) { var x; var retval = ''; + var crypted_regex = new RegExp(crypted_regex_str,'g'); while ((x = crypted_regex.exec(crypted)) != null) { var friend_keys = Stor.getKeysByIdentifier(x[2]), - cbook_method = CBook[CBook.chars[x[1]]], - success = false; + cbook_method = CBook[CBook.chars[x[1]]]; if (!friend_keys || !friend_keys.length ) { retval += global.FAIL_NOKEY; continue; } try { var iv_ciph = cbook_method.decrypt(x[3],x[4]); }catch(e) { retval += global.FAIL_ENCODING; continue; } var i = friend_keys.length; while (i--) { try { var msg = decrypt(iv_ciph[0],iv_ciph[1],Base64.decodeBytes(friend_keys[i])); retval += msg+ '<br />'; success = true; continue; } catch(e) {/*probably, just the wrong key, keep trying*/} } if (!success) retval += global.FAIL_NOKEY; } return retval; } function encrypt_message(plaintext, mode, key_and_ref) { mode = mode || 'base64'; var key_ref = key_and_ref.substr(0,1), key = Base64.decodeBytes(key_and_ref.substr(2)), tries = 200, comp = []; while (--tries) { try { comp = CBook[mode].encrypt.apply(null,encrypt(plaintext, key)); break; } catch(e) { //console.log(e); } } comp.unshift(CBook[mode].chr, key_ref); if (tries == 0) { throw Error('tried too many times and failed'); } var rv = format_post.apply(null,comp); if (window.parent != window && window.postMessage) { window.parent.postMessage(rv,"*"); } return rv; } function encrypt(plaintext, encrypt_key_numbers) { var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128); var crypt_args = cryptArgs(iv, encrypt_key_numbers); crypt_args.unshift(plaintext); return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args), encrypt_key_numbers]; } function decrypt(iv,ciph_string, encrypt_key_numbers) { var crypt_args = cryptArgs(iv, encrypt_key_numbers); if (crypt_args[0]==2) throw Error('if CBC, then we need to save the msgsize'); crypt_args.unshift(ciph_string,0); var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args); return plaintext; } function update_bookmarklet() { var bk = document.getElementById('bookmarklet_source').innerHTML; var target = document.getElementById('bookmarklet'); target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")'; } function tryGenuine() { /*will try to show genuinity*/ } \ No newline at end of file diff --git a/client/js/test.js b/client/js/test.js index b01f3b9..79ee871 100644 --- a/client/js/test.js +++ b/client/js/test.js @@ -1,110 +1,112 @@ /* KEY: -=action ?=test *=store for later part of test 1 -*create key1 2 -*encrypt message 3 ?decrypt message 4 -*full backup 5 -*share 6 -delete everything 7 ?restore from full 8 test alias, user 9 ?decrypt message 10 -delete everything 11 -*create key2 12 ?restore from share 13 ?decrypt message 14 -encrypt message2 (with key1) */ var Tester = new (function runTests() { var self = this, testdom = document.getElementById('test') this.run = function() { for (var i=0;i<self.tests.length;i++) { var name = i+' '+self.tests[i].name; try { self.msg(name,self.tests[i](),false) } catch(e) { self.msg(name,e.message,true) } } } this.msg = function(name,msg,fail) { var li = document.createElement('li') testdom.appendChild(li) li.innerHTML = name+' '+(msg||'') li.style.backgroundColor = ((fail)?'red':'green') } function assert(true_v, msg) { if (!true_v) throw Error("Failed on: "+msg) } - this.vars = { + var vv = { key1_alias:'key1_alias', key1_secret:null, msg1_plaintext:'Foo and Bar and Hello', - msg1_encrypted:null + msg1_encrypted:null, + msg1_encrypted_uni:null } this.tests = [ /// #1 -*create key1 function create_key1() { //setup var frm= document.forms['generatekey'] - frm.elements['alias'].value = self.vars.key1_alias + frm.elements['alias'].value = vv.key1_alias Stor.generateKey(frm) //submit //tests var keys = Stor.keyList() assert(keys.length > 1,'some key exists') var found_key = false, o = document.forms['encrypt'].elements['friendkey'].options for (var i=0;i<keys.length;i++) { - if (keys[i][2] == self.vars.key1_alias) { + if (keys[i][2] == vv.key1_alias) { found_key = true break } } assert(found_key, 'key alias is in DB') found_key = false for (var i=0;i<o.length;i++) - if (o[i].innerHTML == self.vars.key1_alias) { + if (o[i].innerHTML == vv.key1_alias) { found_key = true - self.vars.key1_secret = o[i].value + vv.key1_secret = o[i].value break } assert(found_key, 'key alias is in encrypt form') }, /// #2 -*encrypt message function encrypt_msg() { - self.vars.msg1_encrypted = encrypt_message( - self.vars.msg1_plaintext, - 'base64', - self.vars.key1_secret) - self.msg('--plaintext:',self.vars.msg1_plaintext) - self.msg('--crypt:',self.vars.msg1_encrypted) - assert(crypted_regex.test(self.vars.msg1_encrypted), - 'encrypted message is proper form:'+self.vars.msg1_encrypted) + vv.msg1_encrypted = encrypt_message(vv.msg1_plaintext,'base64',vv.key1_secret) + vv.msg1_encrypted_uni = encrypt_message(vv.msg1_plaintext,'unicrap',vv.key1_secret) + //self.msg('--plaintext:',vv.msg1_plaintext) + //self.msg('--crypt:',vv.msg1_encrypted) + var crypted_regex = new RegExp(crypted_regex_str,'g'); + assert(crypted_regex.test(vv.msg1_encrypted), + 'encrypted message is proper form:'+vv.msg1_encrypted) }, /// #3 ?decrypt message function decrypt_msg() { - self.msg(decrypt_message); - self.msg(self.vars.msg1_encrypted) - self.msg(decrypt_message(self.vars.msg1_encrypted)) - var plain = decrypt_message(self.vars.msg1_encrypted) + var plain = decrypt_message(vv.msg1_encrypted) assert(plain.length,'decrypted message is non-empty') - assert(plain == self.vars.msg1_plaintext,'Decrypted message==original:') + assert(plain == vv.msg1_plaintext+ '<br />','Decrypted base64 message ==original:') + assert(decrypt_message(vv.msg1_encrypted_uni)==vv.msg1_plaintext+'<br />', + 'Decrypted unicrap message ==original:') + }, + /// #4 -*full backup + function full_backup() { + } -/// #4 -*full backup /// #5 -*share /// #6 -delete everything /// #7 ?restore from full /// #8 test alias, user /// #9 ?decrypt message /// #10 -delete everything /// #11 -*create key2 /// #12 ?restore from share /// #13 ?decrypt message /// #14 -encrypt message2 (with key1) ] })() \ No newline at end of file
schuyler1d/cbook
7088295c4c9d2eb5aeef258aa90a9a4f42cf49ab
another test
diff --git a/client/js/test.js b/client/js/test.js index 21a34d8..b01f3b9 100644 --- a/client/js/test.js +++ b/client/js/test.js @@ -1,95 +1,110 @@ /* KEY: -=action ?=test *=store for later part of test 1 -*create key1 2 -*encrypt message 3 ?decrypt message 4 -*full backup 5 -*share 6 -delete everything 7 ?restore from full 8 test alias, user 9 ?decrypt message 10 -delete everything 11 -*create key2 12 ?restore from share 13 ?decrypt message 14 -encrypt message2 (with key1) */ var Tester = new (function runTests() { var self = this, testdom = document.getElementById('test') this.run = function() { for (var i=0;i<self.tests.length;i++) { + var name = i+' '+self.tests[i].name; try { - self.msg(i,self.tests[i](),false) + self.msg(name,self.tests[i](),false) } catch(e) { - self.msg(i,e.message,true) + self.msg(name,e.message,true) } } } - this.ok = function(i) {} - this.fail = function(i,msg) {} - this.msg = function(i,msg,fail) { + this.msg = function(name,msg,fail) { var li = document.createElement('li') testdom.appendChild(li) - li.innerHTML = i+' '+(msg||'') + li.innerHTML = name+' '+(msg||'') li.style.backgroundColor = ((fail)?'red':'green') } function assert(true_v, msg) { if (!true_v) throw Error("Failed on: "+msg) } this.vars = { - key1_alias:'key1_alias' + key1_alias:'key1_alias', + key1_secret:null, + msg1_plaintext:'Foo and Bar and Hello', + msg1_encrypted:null } this.tests = [ /// #1 -*create key1 function create_key1() { + //setup var frm= document.forms['generatekey'] frm.elements['alias'].value = self.vars.key1_alias - frm.submit() + Stor.generateKey(frm) //submit - //tests: + //tests var keys = Stor.keyList() assert(keys.length > 1,'some key exists') var found_key = false, o = document.forms['encrypt'].elements['friendkey'].options for (var i=0;i<keys.length;i++) { - console.log(keys[i][2]) if (keys[i][2] == self.vars.key1_alias) { found_key = true break } } assert(found_key, 'key alias is in DB') found_key = false for (var i=0;i<o.length;i++) if (o[i].innerHTML == self.vars.key1_alias) { found_key = true self.vars.key1_secret = o[i].value break } assert(found_key, 'key alias is in encrypt form') - - }, /// #2 -*encrypt message function encrypt_msg() { - + self.vars.msg1_encrypted = encrypt_message( + self.vars.msg1_plaintext, + 'base64', + self.vars.key1_secret) + self.msg('--plaintext:',self.vars.msg1_plaintext) + self.msg('--crypt:',self.vars.msg1_encrypted) + assert(crypted_regex.test(self.vars.msg1_encrypted), + 'encrypted message is proper form:'+self.vars.msg1_encrypted) + }, + /// #3 ?decrypt message + function decrypt_msg() { + self.msg(decrypt_message); + self.msg(self.vars.msg1_encrypted) + self.msg(decrypt_message(self.vars.msg1_encrypted)) + var plain = decrypt_message(self.vars.msg1_encrypted) + assert(plain.length,'decrypted message is non-empty') + assert(plain == self.vars.msg1_plaintext,'Decrypted message==original:') } -/// #3 ?decrypt message /// #4 -*full backup /// #5 -*share /// #6 -delete everything /// #7 ?restore from full /// #8 test alias, user /// #9 ?decrypt message /// #10 -delete everything /// #11 -*create key2 /// #12 ?restore from share /// #13 ?decrypt message /// #14 -encrypt message2 (with key1) ] })() \ No newline at end of file
schuyler1d/cbook
49c90a21af8f1ced28982d45079da0fbb6a7aaf1
start adding tests, even though it does not work yet
diff --git a/client/index.html b/client/index.html index b956e1d..75cc2fa 100644 --- a/client/index.html +++ b/client/index.html @@ -1,253 +1,257 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> - <form id="encrypt" class="sec" onsubmit="return false;"> + <form id="encrypt" name="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> - <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> + <form name="generatekey" id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="sec"> Share this link with all your friends. <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> <form onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> Now that you can back things up by pasting this text somewhere, do you want to delete all your keys from this browser? <input type="button" onclick="Stor.deleteEverything(this);return false;" value="Delete All Keys from Browser" /> </p> </form> <form id="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> <form name="share" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> Share this, along with the private key with your friends, ideally through separate channels (that would not collude). For example, send one from your web email, and another over a different instant message network. (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> + <ul id="test" class="sec"> + <li><form name="test" onsubmit="Tester.run();return false;"><button>Run Tests</button></form></li> + </ul> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/cbook.js"></script> + <script type="text/javascript" src="js/test.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect('friendkey'); } else { document.getElementById('menu').style.display = 'block'; Stor.populateKeysOnSelect('sharekey','shareable'); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/cbook.js b/client/js/cbook.js index 18b0e55..7adb603 100644 --- a/client/js/cbook.js +++ b/client/js/cbook.js @@ -1,258 +1,258 @@ var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?', regex_args = ['codec','hash','iv','ciphtext'], html_regex = '<([:\\w]+)[^<]+'; var crypted_regex = new RegExp(crypted_regex_str,'g'); /* facebook: document.getElementsByClassName('uiStreamMessage') twitter: //document.activeElement to know which element has focus 15chars for IV 1char for addition 4chars for ♔.☿ (could make it 3) 'http://skyb.us/' == 15 chars 140=15+1+4+15+105 */ var global= { FAIL_ENCODING:'Failed to decrypt message, likely due to encoding problems.<br />', - FAIL_NOKEY:'None of your saved keys could decrypt this message.<br />' + FAIL_NOKEY:'None of your keys could decrypt this message.<br />' } function cryptArgs(iv, encrypt_key_numbers) { ///see http://www.josh-davis.org/ecmascrypt ///NOTE:if CBC, then we need to save the msgsize var mode = 0; //0:OFB,1:CFB,2:CBC var keysize = 16; //32 for 256, 24 for 192, 16 for 128 encrypt_key_numbers = encrypt_key_numbers || ecmaScrypt.toNumbers(global.encrypt_key); return [mode, encrypt_key_numbers, keysize, iv]; } var U2N = new (function() { /* we'll need to get a lot smarter. we should be accepting/creating unicode characters within the character range that HTML considers 'character' text. http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets parseInt('10FFFF',16) - parseInt('10000',16) == 1048575 1114111 - 65536 == String.fromCharCode(85267) seems to be 'real' first character */ this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars this.compress = function(low_unicode) { var arr = []; var c = low_unicode.length; while (c--) { arr.unshift(low_unicode.charCodeAt(c)); } return this.unicode(arr); } this.decompress = function(high_unicode) { var nums = this.nums(high_unicode); var str = ''; for (var i=0;i<nums.length;i++) { str += String.fromCharCode(nums[i]); } return str; } this.lowcoding = function(cipher) { var outhex = ''; for(var i = 0;i < cipher.length;i++) { outhex += ecmaScrypt.toHex(cipher.charCodeAt(i)); } return outhex; } this.unicode = function(nums) { ///take nums array of numbers from 0-255 var u_string=''; for (var i=0;i<nums.length;i++) { var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) ); if (n>65535) { ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes throw Error('cannot deal with high chars yet'); } if (n>2299099) { throw Error('cannot deal with high unicode compression yet'); //but I think the answer is that we'll have some marker //for NON-encoded text and then // } ///random suspects: if (n==1759 || n==130) { throw Error('random suspect--not sure it is culprit'); } if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes'); //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n); } if (8192 < n && n < 8447) { //255 chars ///http://en.wikipedia.org/wiki/Unicode_control_characters ///seem to be grouped all in the 2000 -20FF range throw Error('Wide fence for control chars. we can be more picky'+n); } ///Any code D800–DFFF is invalid: UTF-16 conflict (2047 chars) try { var c = String.fromCharCode(n); encodeURIComponent(c); u_string += c; } catch(e) { throw Error('could not encode uri component for char:'+n); } } if (u_string.match(/\s/)!=null) { throw Error('FAILS BY WHITESPACE'); } return u_string; }; this.nums = function(u_string) { var nums = []; var m = u_string.length; for (var i=0;i<m;i++) { var n = u_string.charCodeAt(i)-this.min; nums.push(n%256); var x2 = parseInt(n/256,10); if (x2 != 0) nums.push(x2); } return nums; }; })();//end U2N var CBook= { chars:{'.':'unicrap',',':'base64'}, unicrap:{ chr:'.', encrypt:function(iv,ciph,key_numbers) { var compressed = U2N.compress(ciph.cipher); var compressed_IV = U2N.unicode(iv); //cheat on making exceptions and just try decrypt var decoded = CBook.unicrap.decrypt(compressed_IV,compressed); decrypt(decoded[0],decoded[1],key_numbers); return [compressed_IV, compressed]; }, decrypt:function(iv,ciphtext) { return [U2N.nums(iv), U2N.decompress(ciphtext)]; } }, base64:{ chr:',', encrypt:function(iv,ciph) { return [Base64.encodeBytes(iv), Base64.encode(ciph.cipher)]; }, decrypt:function(iv64,ciphtext) { return [Base64.decodeBytes(iv64), Base64.decode(ciphtext)]; } } /*,hex:{ chr:'_', encrypt:function(iv,ciph) { return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)]; }, decrypt:function(iv,ciphtext) { } }*/ };//end CBook function format_post(codec,hash,iv,ciphertext) { var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':'; //console.log(rv.length); return rv; } function test_unicode(txt,f) { f = f||function(c) { return c.match(/([\w\W])/); }; for (var i=0;i<txt.length;i++) { var r = f(String.fromCharCode(txt.charCodeAt(i))); if (r) { console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i)); } } } function decrypt_message(crypted) { var x; var retval = ''; while ((x = crypted_regex.exec(crypted)) != null) { var friend_keys = Stor.getKeysByIdentifier(x[2]), cbook_method = CBook[CBook.chars[x[1]]], success = false; if (!friend_keys || !friend_keys.length ) { retval += global.FAIL_NOKEY; continue; } try { var iv_ciph = cbook_method.decrypt(x[3],x[4]); }catch(e) { retval += global.FAIL_ENCODING; continue; } var i = friend_keys.length; while (i--) { try { var msg = decrypt(iv_ciph[0],iv_ciph[1],Base64.decodeBytes(friend_keys[i])); retval += msg+ '<br />'; success = true; continue; } catch(e) {/*probably, just the wrong key, keep trying*/} } if (!success) retval += global.FAIL_NOKEY; } return retval; } function encrypt_message(plaintext, mode, key_and_ref) { mode = mode || 'base64'; var key_ref = key_and_ref.substr(0,1), key = Base64.decodeBytes(key_and_ref.substr(2)), tries = 200, comp = []; while (--tries) { try { comp = CBook[mode].encrypt.apply(null,encrypt(plaintext, key)); break; } catch(e) { //console.log(e); } } comp.unshift(CBook[mode].chr, key_ref); if (tries == 0) { throw Error('tried too many times and failed'); } var rv = format_post.apply(null,comp); if (window.parent != window && window.postMessage) { window.parent.postMessage(rv,"*"); } return rv; } function encrypt(plaintext, encrypt_key_numbers) { var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128); var crypt_args = cryptArgs(iv, encrypt_key_numbers); crypt_args.unshift(plaintext); return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args), encrypt_key_numbers]; } function decrypt(iv,ciph_string, encrypt_key_numbers) { var crypt_args = cryptArgs(iv, encrypt_key_numbers); if (crypt_args[0]==2) throw Error('if CBC, then we need to save the msgsize'); crypt_args.unshift(ciph_string,0); var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args); return plaintext; } function update_bookmarklet() { var bk = document.getElementById('bookmarklet_source').innerHTML; var target = document.getElementById('bookmarklet'); target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")'; } function tryGenuine() { /*will try to show genuinity*/ } \ No newline at end of file diff --git a/client/js/test.js b/client/js/test.js index 5b5573d..21a34d8 100644 --- a/client/js/test.js +++ b/client/js/test.js @@ -1,21 +1,95 @@ -/* --=action ?=test *=store for later part of test +/* KEY: -=action ?=test *=store for later part of test +1 -*create key1 +2 -*encrypt message +3 ?decrypt message +4 -*full backup +5 -*share - -*create key1 - -*encrypt message - ?decrypt message - -*full backup - -*share +6 -delete everything +7 ?restore from full +8 test alias, user +9 ?decrypt message - -delete everything - ?restore from full - test alias, user - ?decrypt message +10 -delete everything +11 -*create key2 +12 ?restore from share +13 ?decrypt message +14 -encrypt message2 (with key1) +*/ +var Tester = new (function runTests() { + var self = this, + testdom = document.getElementById('test') + this.run = function() { + for (var i=0;i<self.tests.length;i++) { + try { + self.msg(i,self.tests[i](),false) + } catch(e) { + self.msg(i,e.message,true) + } + } + } + this.ok = function(i) {} + this.fail = function(i,msg) {} + this.msg = function(i,msg,fail) { + var li = document.createElement('li') + testdom.appendChild(li) + li.innerHTML = i+' '+(msg||'') + li.style.backgroundColor = ((fail)?'red':'green') + } + function assert(true_v, msg) { + if (!true_v) throw Error("Failed on: "+msg) + } + this.vars = { + key1_alias:'key1_alias' + } + this.tests = [ + /// #1 -*create key1 + function create_key1() { + var frm= document.forms['generatekey'] + frm.elements['alias'].value = self.vars.key1_alias + frm.submit() - -delete everything - -*create key2 - ?restore from share - ?decrypt message - -encrypt message2 (with key1) + //tests: + var keys = Stor.keyList() + assert(keys.length > 1,'some key exists') + var found_key = false, + o = document.forms['encrypt'].elements['friendkey'].options + for (var i=0;i<keys.length;i++) { + console.log(keys[i][2]) + if (keys[i][2] == self.vars.key1_alias) { + found_key = true + break + } + } + assert(found_key, 'key alias is in DB') + found_key = false + for (var i=0;i<o.length;i++) + if (o[i].innerHTML == self.vars.key1_alias) { + found_key = true + self.vars.key1_secret = o[i].value + break + } + assert(found_key, 'key alias is in encrypt form') + + + }, + /// #2 -*encrypt message + function encrypt_msg() { + + } +/// #3 ?decrypt message +/// #4 -*full backup +/// #5 -*share -*/ \ No newline at end of file +/// #6 -delete everything +/// #7 ?restore from full +/// #8 test alias, user +/// #9 ?decrypt message + +/// #10 -delete everything +/// #11 -*create key2 +/// #12 ?restore from share +/// #13 ?decrypt message +/// #14 -encrypt message2 (with key1) + ] +})() \ No newline at end of file
schuyler1d/cbook
0dbf9f02532b5db7e8db20c01f4eb21232382662
remove stray console.log
diff --git a/client/js/local_session.js b/client/js/local_session.js index 4a48651..f86e7e0 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,232 +1,231 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64, obj) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); - if (secret in me || !limit) + if (!limit ||secret in me) key_list[side]([k,secret,alias]); } return key_list; } this.populateKeysOnSelect = function(select_id,limit) { var select = document.getElementById(select_id); select.innerHTML = ''; var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var alias = frm.elements['alias'].value; var obj = {"alias":{"v":alias,"p":"friends"}}; var prefix = self.getKeyIdentifier(newsecret, obj); ///v:value, p:privacy self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); self.refreshForms(); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret, obj); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } this.refreshForms = function() { Stor.populateKeysOnSelect('friendkey'); Stor.populateKeysOnSelect('sharekey','shareable'); } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } else { bkup[1]={}; } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } if (passkey) { - console.log(bkup); return CBook['base64' ].encrypt.apply(null,encrypt(JSON.stringify(bkup), passkey)); } else return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); for (a in restoral_keys[0]) self.addFriend(a, restoral_keys[0][a]); for (m in restoral_keys[1]) self.addMyKey(restoral_keys[1][m]); alert('Restoral complete'); self.refreshForms(); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } this.shareForm = function(frm) { var key_list = []; var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var o = eee['friendkey'].options; for (var i=0;i<o.length;i++) { if (o[i].selected) { key_list.push(o[i].value); } } eee['backup'].value = self.getBackup(key_list,passkey); document.location="#share-text"; } this.deleteEverything = function() { if (confirm("Are you sure you want to delete all your keys from this browser?")) { self.permStor.deleteEveryFuckingThing(); alert("Your keys have been removed. Don't lose your backup!"); } } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
850032cd965bda8e09bbb5c5e5c193f0736cebe0
some form bugs fixed
diff --git a/client/index.html b/client/index.html index 472af63..b956e1d 100644 --- a/client/index.html +++ b/client/index.html @@ -1,253 +1,253 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> <form id="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="sec"> Share this link with all your friends. <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> <form onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> Now that you can back things up by pasting this text somewhere, do you want to delete all your keys from this browser? <input type="button" onclick="Stor.deleteEverything(this);return false;" value="Delete All Keys from Browser" /> </p> </form> <form id="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> <form name="share" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> Share this, along with the private key with your friends, ideally through separate channels (that would not collude). For example, send one from your web email, and another over a different instant message network. (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/cbook.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); - Stor.populateKeysOnSelect(document.getElementById('friendkey')); + Stor.populateKeysOnSelect('friendkey'); } else { document.getElementById('menu').style.display = 'block'; - Stor.populateKeysOnSelect(document.getElementById('sharekey'),'shareable'); + Stor.populateKeysOnSelect('sharekey','shareable'); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/local_session.js b/client/js/local_session.js index 9ac4096..4a48651 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,222 +1,232 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64, obj) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); if (secret in me || !limit) key_list[side]([k,secret,alias]); } return key_list; } - this.populateKeysOnSelect = function(select,limit) { + this.populateKeysOnSelect = function(select_id,limit) { + var select = document.getElementById(select_id); + select.innerHTML = ''; var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var alias = frm.elements['alias'].value; var obj = {"alias":{"v":alias,"p":"friends"}}; var prefix = self.getKeyIdentifier(newsecret, obj); ///v:value, p:privacy self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); + self.refreshForms(); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret, obj); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } - + this.refreshForms = function() { + Stor.populateKeysOnSelect('friendkey'); + Stor.populateKeysOnSelect('sharekey','shareable'); + } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); + } else { + bkup[1]={}; } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } if (passkey) { + console.log(bkup); return CBook['base64' ].encrypt.apply(null,encrypt(JSON.stringify(bkup), passkey)); } else return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); for (a in restoral_keys[0]) self.addFriend(a, restoral_keys[0][a]); for (m in restoral_keys[1]) self.addMyKey(restoral_keys[1][m]); alert('Restoral complete'); + self.refreshForms(); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } this.shareForm = function(frm) { var key_list = []; var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var o = eee['friendkey'].options; for (var i=0;i<o.length;i++) { if (o[i].selected) { key_list.push(o[i].value); } } eee['backup'].value = self.getBackup(key_list,passkey); document.location="#share-text"; } this.deleteEverything = function() { if (confirm("Are you sure you want to delete all your keys from this browser?")) { self.permStor.deleteEveryFuckingThing(); alert("Your keys have been removed. Don't lose your backup!"); } } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
759e6b3f61f808d90a466e539480ea8e7dc68fe6
bugfix: alias needs to be declared before friend obj
diff --git a/client/js/local_session.js b/client/js/local_session.js index 9956641..9ac4096 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,221 +1,222 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64, obj) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); if (secret in me || !limit) key_list[side]([k,secret,alias]); } return key_list; } this.populateKeysOnSelect = function(select,limit) { var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); + var alias = frm.elements['alias'].value; var obj = {"alias":{"v":alias,"p":"friends"}}; var prefix = self.getKeyIdentifier(newsecret, obj); - var alias = frm.elements['alias'].value; ///v:value, p:privacy self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret, obj); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } + if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } if (passkey) { return CBook['base64' ].encrypt.apply(null,encrypt(JSON.stringify(bkup), passkey)); } else return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); for (a in restoral_keys[0]) self.addFriend(a, restoral_keys[0][a]); for (m in restoral_keys[1]) self.addMyKey(restoral_keys[1][m]); alert('Restoral complete'); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } this.shareForm = function(frm) { var key_list = []; var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var o = eee['friendkey'].options; for (var i=0;i<o.length;i++) { if (o[i].selected) { key_list.push(o[i].value); } } eee['backup'].value = self.getBackup(key_list,passkey); document.location="#share-text"; } this.deleteEverything = function() { if (confirm("Are you sure you want to delete all your keys from this browser?")) { self.permStor.deleteEveryFuckingThing(); alert("Your keys have been removed. Don't lose your backup!"); } } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
6cf0e9b101621f15c593ff214339768352a9018b
change base.js because base64/base annoyingly stops autocompletion
diff --git a/client/index.html b/client/index.html index adf7549..472af63 100644 --- a/client/index.html +++ b/client/index.html @@ -1,253 +1,253 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> <form id="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="sec"> Share this link with all your friends. <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> <form onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> Now that you can back things up by pasting this text somewhere, do you want to delete all your keys from this browser? <input type="button" onclick="Stor.deleteEverything(this);return false;" value="Delete All Keys from Browser" /> </p> </form> <form id="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> <form name="share" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> Share this, along with the private key with your friends, ideally through separate channels (that would not collude). For example, send one from your web email, and another over a different instant message network. (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> - <script type="text/javascript" src="js/base.js"></script> + <script type="text/javascript" src="js/cbook.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect(document.getElementById('friendkey')); } else { document.getElementById('menu').style.display = 'block'; Stor.populateKeysOnSelect(document.getElementById('sharekey'),'shareable'); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/base.js b/client/js/cbook.js similarity index 100% rename from client/js/base.js rename to client/js/cbook.js
schuyler1d/cbook
0dc43be3451c362d2cf30c03ce2eefba3cef631b
add obj to keyIdentifier, since we should really TODO: hmac this.
diff --git a/client/js/local_session.js b/client/js/local_session.js index 1c5c3a8..9956641 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,221 +1,221 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; - this.getKeyIdentifier = function(key_base64) { + this.getKeyIdentifier = function(key_base64, obj) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); if (secret in me || !limit) key_list[side]([k,secret,alias]); } return key_list; } this.populateKeysOnSelect = function(select,limit) { var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); - var prefix = self.getKeyIdentifier(newsecret); + var obj = {"alias":{"v":alias,"p":"friends"}}; + var prefix = self.getKeyIdentifier(newsecret, obj); var alias = frm.elements['alias'].value; ///v:value, p:privacy - var obj = {"alias":{"v":alias,"p":"friends"}}; self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { - prefix = prefix || self.getKeyIdentifier(newsecret); + prefix = prefix || self.getKeyIdentifier(newsecret, obj); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } if (passkey) { return CBook['base64' ].encrypt.apply(null,encrypt(JSON.stringify(bkup), passkey)); } else return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); for (a in restoral_keys[0]) self.addFriend(a, restoral_keys[0][a]); for (m in restoral_keys[1]) self.addMyKey(restoral_keys[1][m]); alert('Restoral complete'); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } this.shareForm = function(frm) { var key_list = []; var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var o = eee['friendkey'].options; for (var i=0;i<o.length;i++) { if (o[i].selected) { key_list.push(o[i].value); } } eee['backup'].value = self.getBackup(key_list,passkey); document.location="#share-text"; } this.deleteEverything = function() { if (confirm("Are you sure you want to delete all your keys from this browser?")) { self.permStor.deleteEveryFuckingThing(); alert("Your keys have been removed. Don't lose your backup!"); } } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
7a642f4958fdcbe033231c6d4b21d0d8a3fcfccf
delete button, so people can escape from their browser
diff --git a/client/index.html b/client/index.html index ec3d824..adf7549 100644 --- a/client/index.html +++ b/client/index.html @@ -1,248 +1,253 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> <form id="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="sec"> Share this link with all your friends. <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> <form onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> + Now that you can back things up by pasting this text somewhere, do you + want to delete all your keys from this browser? + <input type="button" + onclick="Stor.deleteEverything(this);return false;" + value="Delete All Keys from Browser" /> </p> </form> <form id="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> <form name="share" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> Share this, along with the private key with your friends, ideally through separate channels (that would not collude). For example, send one from your web email, and another over a different instant message network. (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/base.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect(document.getElementById('friendkey')); } else { document.getElementById('menu').style.display = 'block'; Stor.populateKeysOnSelect(document.getElementById('sharekey'),'shareable'); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/local_session.js b/client/js/local_session.js index 0b9016e..1c5c3a8 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,213 +1,221 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); if (secret in me || !limit) key_list[side]([k,secret,alias]); } return key_list; } this.populateKeysOnSelect = function(select,limit) { var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var prefix = self.getKeyIdentifier(newsecret); var alias = frm.elements['alias'].value; ///v:value, p:privacy var obj = {"alias":{"v":alias,"p":"friends"}}; self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } if (passkey) { return CBook['base64' ].encrypt.apply(null,encrypt(JSON.stringify(bkup), passkey)); } else return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); for (a in restoral_keys[0]) self.addFriend(a, restoral_keys[0][a]); for (m in restoral_keys[1]) self.addMyKey(restoral_keys[1][m]); alert('Restoral complete'); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } this.shareForm = function(frm) { var key_list = []; var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var o = eee['friendkey'].options; for (var i=0;i<o.length;i++) { if (o[i].selected) { key_list.push(o[i].value); } } eee['backup'].value = self.getBackup(key_list,passkey); document.location="#share-text"; } + this.deleteEverything = function() { + if (confirm("Are you sure you want to delete all your keys from this browser?")) { + self.permStor.deleteEveryFuckingThing(); + alert("Your keys have been removed. Don't lose your backup!"); + } + } + + this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
21de286db6656f4e044b5e73b14ca102fa3e9f4a
base64 regexp bug with character "-"\
diff --git a/client/js/base64.js b/client/js/base64.js index 832a287..4c7f6e1 100644 --- a/client/js/base64.js +++ b/client/js/base64.js @@ -1,156 +1,156 @@ /** * * Base64 encode / decode * Based off of http://www.webtoolkit.info/javascript-base64.html * **/ var Base64 = { // private property _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", encodeBytes: function(byte_ary) { var output = ""; for (var i=0;i<byte_ary.length;i++) { output += Base64._bytes2chars(byte_ary[i],byte_ary[++i],byte_ary[++i]); } return output; }, decodeBytes: function(input) { var byte_ary = []; for (var i=0;i<input.length;i+=4) { byte_ary.push.apply(byte_ary,Base64._chars2bytes(input.substr(i,4))); } return byte_ary; }, // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); output += this._bytes2chars(chr1,chr2,chr3); } return output; }, // private method changing integers to chars _bytes2chars : function(chr1,chr2,chr3) { enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } return (this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4)); }, _chars2bytes : function(chars4) { enc1 = this._keyStr.indexOf(chars4.charAt(0)); enc2 = this._keyStr.indexOf(chars4.charAt(1)); enc3 = this._keyStr.indexOf(chars4.charAt(2)); enc4 = this._keyStr.indexOf(chars4.charAt(3)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; var rv = [chr1]; if (enc3 != 64) rv.push(chr2) if (enc4 != 64) rv.push(chr3) return rv }, // public method for decoding decode : function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; - input = input.replace(RegExp('[^'+this._keyStr+']','g'), ""); + input = input.replace(RegExp('[^'+this._keyStr.replace('-','\\-')+']','g'), ""); while (i < input.length) { var chr=this._chars2bytes(input.substr(i,4)); i+=4; for (var j=0;j<chr.length;j++) { output = output + String.fromCharCode(chr[j]); } } output = Base64._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } } \ No newline at end of file
schuyler1d/cbook
da862568e4d4f7a1f0746b60bbb6435c1763cdf2
sharing keys form
diff --git a/client/index.html b/client/index.html index dd72c73..ec3d824 100644 --- a/client/index.html +++ b/client/index.html @@ -1,245 +1,248 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; } </style> </head> <body> <div id="menu" class="sec"> <a href="#backup">backup</a> <a href="#restore">restore/load</a> <a href="#share">share</a> <a href="#encrypt">encrypt</a> <a href="#generatekey">Generate a New Key</a> + <a href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> </div> <span id="decrypt_output"></span> <form id="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> - <span id="keylinksec" class="hide"> + <span id="keylinksec" class="sec"> Share this link with all your friends. - <a id="keylink" class="hide" href="#foo">link for friends</a> - + <a id="keylink" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. </form> <form onsubmit="Stor.backupForm(this);return false;"> <div id="backup" class="sec" > <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> </div> <p id="backup-text" class="sec"> Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> <form id="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Backup text: <textarea name="backup" rows="10" cols="40"></textarea> </p> <input type="submit" value="Restore from backup text" /> </form> - <form onsubmit="Stor.shareForm(this);return false;"> + <form name="share" onsubmit="Stor.shareForm(this);return false;"> <div id="share" class="sec"> <p>Pass Phrase for restoral: <input type="text" name="passphrase" /> </p> <p>Select the Keys you want to share <select id="sharekey" name="friendkey" multiple="multiple"> </select> + <input type="submit" value="Create secure share info" /> </p> </div> <p id="share-text" class="sec"> - Share this, along with the private key + Share this, along with the private key with your friends, ideally + through separate channels (that would not collude). For example, + send one from your web email, and another over a different instant message network. + (They shouldn't both be owned by the same company) <textarea name="backup" rows="10" cols="40"></textarea> </p> </form> </div> - <a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/base.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect(document.getElementById('friendkey')); } else { document.getElementById('menu').style.display = 'block'; - Stor.populateKeysOnSelect(document.getElementById('sharekey')); + Stor.populateKeysOnSelect(document.getElementById('sharekey'),'shareable'); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/local_session.js b/client/js/local_session.js index 9f6f63d..0b9016e 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,201 +1,213 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); if (secret in me || !limit) key_list[side]([k,secret,alias]); } return key_list; } this.populateKeysOnSelect = function(select,limit) { var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var prefix = self.getKeyIdentifier(newsecret); var alias = frm.elements['alias'].value; ///v:value, p:privacy var obj = {"alias":{"v":alias,"p":"friends"}}; self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; if (ppl[prefix].indexOf(newsecret) == -1) { ppl[prefix].push(newsecret); self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } - this.getBackup = function(key_ary/*typeof string=all*/) { + this.getBackup = function(key_ary/*typeof string=all*/, passkey) { var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; - if (typeof key_ary == 'undefined') { + if (typeof key_ary == 'string') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } for (var i=0;i<key_ary.length;i++) { bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } - return JSON.stringify(bkup); + if (passkey) { + return CBook['base64' + ].encrypt.apply(null,encrypt(JSON.stringify(bkup), + passkey)); + } else + return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); - var json_backup = self.getBackup(); - //var iv_ciph = CBook['base64'].encrypt.apply(null,encrypt(json_backup, passkey)); - //console.log(iv_ciph); - eee['backup'].value = CBook['base64' - ].encrypt.apply(null,encrypt(json_backup, passkey)); + eee['backup'].value = self.getBackup('all',passkey); document.location = '#backup-text'; } - this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); for (a in restoral_keys[0]) self.addFriend(a, restoral_keys[0][a]); for (m in restoral_keys[1]) self.addMyKey(restoral_keys[1][m]); alert('Restoral complete'); } catch(e) { alert('Unable to decrypt backup'); if (window.console) console.log(e); } } - + this.shareForm = function(frm) { + var key_list = []; + var eee = frm.elements; + var passkey = self.passPhrase(eee['passphrase'].value); + var o = eee['friendkey'].options; + for (var i=0;i<o.length;i++) { + if (o[i].selected) { + key_list.push(o[i].value); + } + } + eee['backup'].value = self.getBackup(key_list,passkey); + document.location="#share-text"; + } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
48c427af31e48d384c3dd25fb36c508fa4676a0e
some backup/restore fixes
diff --git a/client/js/local_session.js b/client/js/local_session.js index 01c1b2b..9f6f63d 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,197 +1,201 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } - this.keyList = function() { + this.keyList = function(limit) { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); - - for (k in friends) { + for (k in friends) for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); - key_list[side]([k,secret,alias]); + if (secret in me || !limit) + key_list[side]([k,secret,alias]); } - } return key_list; } - this.populateKeysOnSelect = function(select) { - var key_list = self.keyList(); + this.populateKeysOnSelect = function(select,limit) { + var key_list = self.keyList(limit); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var prefix = self.getKeyIdentifier(newsecret); var alias = frm.elements['alias'].value; ///v:value, p:privacy var obj = {"alias":{"v":alias,"p":"friends"}}; self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret); } this.addPrefix = function(prefix, newsecret) { var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; - ppl[prefix].push(newsecret); - self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); + if (ppl[prefix].indexOf(newsecret) == -1) { + ppl[prefix].push(newsecret); + self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); + } } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.passPhrase = function(text) { return ecmaScrypt.generatePrivateKey( text, ecmaScrypt.aes.keySize.SIZE_128 ); } this.getBackup = function(key_ary/*typeof string=all*/) { - var bkup = {}; + var bkup = [{},JSON.parse(self.permStor.get(self.nsME,'{}'))];; if (typeof key_ary == 'undefined') { key_ary = []; var f = self.friendsCache; for (a in f) for (var i=0;i<f[a].length;i++) key_ary.push(f[a][i]); } for (var i=0;i<key_ary.length;i++) { - bkup[key_ary[i]] = self.getInfo(key_ary[i]); + bkup[0][key_ary[i]] = self.getInfo(key_ary[i]); } return JSON.stringify(bkup); } this.backupForm = function(frm) { var eee = frm.elements; var passkey = self.passPhrase(eee['passphrase'].value); var json_backup = self.getBackup(); //var iv_ciph = CBook['base64'].encrypt.apply(null,encrypt(json_backup, passkey)); //console.log(iv_ciph); eee['backup'].value = CBook['base64' ].encrypt.apply(null,encrypt(json_backup, passkey)); document.location = '#backup-text'; } this.restoreForm = function(frm) { try { var passkey = self.passPhrase(frm.elements['passphrase'].value); var iv_ciph = CBook['base64' ].decrypt.apply(null,frm.elements['backup'].value.split(',')); - var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); - for (a in restoral_keys) { - self.addFriend(a, restoral_keys[a]); - } + var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); + for (a in restoral_keys[0]) + self.addFriend(a, restoral_keys[0][a]); + for (m in restoral_keys[1]) + self.addMyKey(restoral_keys[1][m]); + alert('Restoral complete'); } catch(e) { alert('Unable to decrypt backup'); - //console.log(e); + if (window.console) + console.log(e); } } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
443915234cd86fd50fdf224b078876cdbeb2c37a
backup/restore
diff --git a/client/index.html b/client/index.html index 6196ec2..dd72c73 100644 --- a/client/index.html +++ b/client/index.html @@ -1,205 +1,245 @@ <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> <title>CBook</title> <style type="text/css"> body {background-color:#EDFEFF} textarea {width:100%;} .hide,.sec {display:none;} .sec:target {display:block;} .small{font-size:9px;} a.bookmarklet { text-decoration:none; text-align:center; padding:5px; background-color:#BBBBBB; -moz-border-radius: 8px; -webkit-border-radius: 8px; - } </style> </head> <body> + <div id="menu" class="sec"> + <a href="#backup">backup</a> + <a href="#restore">restore/load</a> + <a href="#share">share</a> + <a href="#encrypt">encrypt</a> + <a href="#generatekey">Generate a New Key</a> + </div> <span id="decrypt_output"></span> <form id="encrypt" class="sec" onsubmit="return false;"> <textarea name="txt"></textarea> <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button> for friends of <select id="friendkey" name="friendkey"> </select> <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span> <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a> <p id="output"></p> <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button--> </form> <div id="decode" class="sec"></div> <div id="setup"> <form id="addfriends" class="sec" action="#addfriends"> <h4>Add Friends</h4> Site passphrase: <input type="text" size="30" name="passphrase" /> <textarea rows="8" name="friendlinks"></textarea> <input type="submit" value="Add Friends"/> </form> <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;"> <h4>Generate Your Key</h4> Name or Alias: <input type="text" size="30" name="alias" /><br /> <input type="submit" value="Generate your Friends-Key" /><br /> <span id="keylinksec" class="hide"> Share this link with all your friends. <a id="keylink" class="hide" href="#foo">link for friends</a> </span> <br /> Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">&#9812; cb&#1012;&#1012;k</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text. - - + </form> + <form onsubmit="Stor.backupForm(this);return false;"> + <div id="backup" class="sec" > + <p>Pass Phrase for restoral: + <input type="text" name="passphrase" /> + </p> + </div> + <p id="backup-text" class="sec"> + Backup text (save this text in a file on your harddrive, or email it to yourself, etc.): + <textarea name="backup" rows="10" cols="40"></textarea> + </p> + </form> + <form id="restore" class="sec" onsubmit="Stor.restoreForm(this);return false;"> + <p>Pass Phrase for restoral: + <input type="text" name="passphrase" /> + </p> + <p>Backup text: + <textarea name="backup" rows="10" cols="40"></textarea> + </p> + <input type="submit" value="Restore from backup text" /> + </form> + <form onsubmit="Stor.shareForm(this);return false;"> + <div id="share" class="sec"> + <p>Pass Phrase for restoral: + <input type="text" name="passphrase" /> + </p> + <p>Select the Keys you want to share + <select id="sharekey" name="friendkey" multiple="multiple"> + </select> + </p> + </div> + <p id="share-text" class="sec"> + Share this, along with the private key + <textarea name="backup" rows="10" cols="40"></textarea> + </p> </form> </div> <a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a> <script type="text/javascript" src="js/base64.js"></script> <script type="text/javascript" src="js/ecmascrypt_v003.js"></script> <script type="text/javascript" src="js/local_session.js"></script> <script type="text/javascript" src="js/base.js"></script> <script type="text/javascript" id="bookmarklet_source"> function bookmarklet(loc,friends) { var active = document.activeElement, tags = {}, nodes = [], crown = String.fromCharCode(9812), lt = String.fromCharCode(60), amp = String.fromCharCode(38), quot = String.fromCharCode(34), laq = lt+amp+quot; var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?', html_regex_str = lt+'([:\\w]+)[^'+lt+']+'; var html_regex = new RegExp(html_regex_str+crypted_regex_str), crypted_regex = new RegExp(crypted_regex_str, 'g'); var mkfrm = function(par,src,height) { if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') { return; par.removeChild(par.firstChild); } var frm = par.ownerDocument.createElement('iframe'); frm.setAttribute('width', par.offsetWidth); frm.setAttribute('height', Math.max(40,height||par.offsetHeight)); frm.setAttribute('class','cbook'); /*par.appendChild(frm);*/ par.insertBefore(frm,par.firstChild); frm.src = src; return frm; }; /* begin process */ if (document.evaluate) { var xPathResult = document .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]', document.body, null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null); for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) { var textNode = xPathResult.snapshotItem(i); var frm_loc = loc+'?decrypt;mode=postMessage#decrypt='; var local_str = textNode.data; var higher_str = textNode.parentNode.parentNode.textContent; var m = crypted_regex.exec(local_str); var n = crypted_regex.exec(higher_str); if (m!=null) { nodes.push(textNode); do { frm_loc += m[0]; } while ((m = crypted_regex.exec(local_str)) != null); var frm = mkfrm(textNode.parentNode, frm_loc); } else if (n!=null) { /*for facebook, which breaks up long words*/ nodes.push(textNode); do { frm_loc += n[0]; } while ((n = crypted_regex.exec(higher_str)) != null); var frm = mkfrm(textNode.parentNode.parentNode, frm_loc); } } } else {/*if we ever start caring about IE*/ var matches = document.body.innerHTML.split(html_regex); while (matches.length > 1) { matches.shift(); var tag = matches.shift(); /*coded = matches.shift();*/ tags[tag] = []; } for (t in tags) { var elts = document.getElementsByTagName(t); for (var i=0;elts.length>i;i++) { /*while (i--) {*/ var m = elts[i].innerHTML.match(crypted_regex); var dbl_parent = elts[i].innerHTML.match(html_regex); if (m!=null) if(dbl_parent==null) { tags[t].push(elts[i]); var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]); } } } } if (active.tagName.toLowerCase() in {textarea:1,input:1} || active.contenteditable ) { var compress = (/twitter/.test(location) ? ';compress=true' : ''); var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101); var w = window;/*frm.contentWindow;*/ var listener = function(evt) { if (evt.source == frm.contentWindow) { var key = 'value'; if (active.contenteditable) { key = 'innerHTML'; } else { if (active.getAttribute('placeholder')==active.value) { if (active.className) {/*facebook*/ active.className = active.className.replace('placeholder','') } } } /*add space, in to separate a possible first cmessage from the next*/ if (active[key]) active[key]+= ' '; active[key] += evt.data; } }; if (w.addEventListener) { w.addEventListener('message',listener,false); } else if (w.attachEvent) { w.attachEvent('message',listener); } } } </script> <script type="text/javascript"> window.t = document.forms[0].elements["txt"]; window.c = document.forms[0].elements["compress"]; window.f = document.forms[0].elements["friendkey"]; window.p = document.getElementById('output'); var dec = document.location.hash.match(/decrypt=(.+)$/); if (dec!=null) { document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]); var x = window.parent.location; //window.parent.location = x+'#foooo'; - } - - if (/encrypt/.test(document.location.hash)) { + } else if (/encrypt/.test(document.location.hash)) { document.forms['encrypt'].elements['txt'].focus(); document.forms['encrypt'].elements['compress'].checked = ( /compress=true/.test(document.location.search) ); Stor.populateKeysOnSelect(document.getElementById('friendkey')); + } else { + document.getElementById('menu').style.display = 'block'; + Stor.populateKeysOnSelect(document.getElementById('sharekey')); } update_bookmarklet(); </script> </body> </html> diff --git a/client/js/base.js b/client/js/base.js index cbf438e..18b0e55 100644 --- a/client/js/base.js +++ b/client/js/base.js @@ -1,258 +1,258 @@ var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?', regex_args = ['codec','hash','iv','ciphtext'], html_regex = '<([:\\w]+)[^<]+'; var crypted_regex = new RegExp(crypted_regex_str,'g'); /* facebook: document.getElementsByClassName('uiStreamMessage') twitter: //document.activeElement to know which element has focus 15chars for IV 1char for addition 4chars for ♔.☿ (could make it 3) 'http://skyb.us/' == 15 chars 140=15+1+4+15+105 */ var global= { FAIL_ENCODING:'Failed to decrypt message, likely due to encoding problems.<br />', FAIL_NOKEY:'None of your saved keys could decrypt this message.<br />' } function cryptArgs(iv, encrypt_key_numbers) { ///see http://www.josh-davis.org/ecmascrypt ///NOTE:if CBC, then we need to save the msgsize var mode = 0; //0:OFB,1:CFB,2:CBC var keysize = 16; //32 for 256, 24 for 192, 16 for 128 encrypt_key_numbers = encrypt_key_numbers || ecmaScrypt.toNumbers(global.encrypt_key); return [mode, encrypt_key_numbers, keysize, iv]; } var U2N = new (function() { /* we'll need to get a lot smarter. we should be accepting/creating unicode characters within the character range that HTML considers 'character' text. http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets parseInt('10FFFF',16) - parseInt('10000',16) == 1048575 1114111 - 65536 == String.fromCharCode(85267) seems to be 'real' first character */ this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars this.compress = function(low_unicode) { var arr = []; var c = low_unicode.length; while (c--) { arr.unshift(low_unicode.charCodeAt(c)); } return this.unicode(arr); } this.decompress = function(high_unicode) { var nums = this.nums(high_unicode); var str = ''; for (var i=0;i<nums.length;i++) { str += String.fromCharCode(nums[i]); } return str; } this.lowcoding = function(cipher) { var outhex = ''; for(var i = 0;i < cipher.length;i++) { outhex += ecmaScrypt.toHex(cipher.charCodeAt(i)); } return outhex; } this.unicode = function(nums) { ///take nums array of numbers from 0-255 var u_string=''; for (var i=0;i<nums.length;i++) { var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) ); if (n>65535) { ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes throw Error('cannot deal with high chars yet'); } if (n>2299099) { throw Error('cannot deal with high unicode compression yet'); //but I think the answer is that we'll have some marker //for NON-encoded text and then // } ///random suspects: if (n==1759 || n==130) { throw Error('random suspect--not sure it is culprit'); } if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes'); //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n); } if (8192 < n && n < 8447) { //255 chars ///http://en.wikipedia.org/wiki/Unicode_control_characters ///seem to be grouped all in the 2000 -20FF range throw Error('Wide fence for control chars. we can be more picky'+n); } ///Any code D800–DFFF is invalid: UTF-16 conflict (2047 chars) try { var c = String.fromCharCode(n); encodeURIComponent(c); u_string += c; } catch(e) { throw Error('could not encode uri component for char:'+n); } } if (u_string.match(/\s/)!=null) { throw Error('FAILS BY WHITESPACE'); } return u_string; }; this.nums = function(u_string) { var nums = []; var m = u_string.length; for (var i=0;i<m;i++) { var n = u_string.charCodeAt(i)-this.min; nums.push(n%256); var x2 = parseInt(n/256,10); if (x2 != 0) nums.push(x2); } return nums; }; })();//end U2N var CBook= { chars:{'.':'unicrap',',':'base64'}, unicrap:{ chr:'.', encrypt:function(iv,ciph,key_numbers) { var compressed = U2N.compress(ciph.cipher); var compressed_IV = U2N.unicode(iv); //cheat on making exceptions and just try decrypt var decoded = CBook.unicrap.decrypt(compressed_IV,compressed); decrypt(decoded[0],decoded[1],key_numbers); return [compressed_IV, compressed]; }, decrypt:function(iv,ciphtext) { return [U2N.nums(iv), U2N.decompress(ciphtext)]; } }, base64:{ chr:',', encrypt:function(iv,ciph) { return [Base64.encodeBytes(iv), Base64.encode(ciph.cipher)]; }, decrypt:function(iv64,ciphtext) { return [Base64.decodeBytes(iv64), Base64.decode(ciphtext)]; } } /*,hex:{ chr:'_', encrypt:function(iv,ciph) { return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)]; }, decrypt:function(iv,ciphtext) { } }*/ };//end CBook function format_post(codec,hash,iv,ciphertext) { var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':'; //console.log(rv.length); return rv; } function test_unicode(txt,f) { f = f||function(c) { return c.match(/([\w\W])/); }; for (var i=0;i<txt.length;i++) { var r = f(String.fromCharCode(txt.charCodeAt(i))); if (r) { console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i)); } } } function decrypt_message(crypted) { var x; var retval = ''; while ((x = crypted_regex.exec(crypted)) != null) { var friend_keys = Stor.getKeysByIdentifier(x[2]), cbook_method = CBook[CBook.chars[x[1]]], success = false; if (!friend_keys || !friend_keys.length ) { retval += global.FAIL_NOKEY; continue; } try { var iv_ciph = cbook_method.decrypt(x[3],x[4]); }catch(e) { retval += global.FAIL_ENCODING; continue; } var i = friend_keys.length; while (i--) { try { var msg = decrypt(iv_ciph[0],iv_ciph[1],Base64.decodeBytes(friend_keys[i])); retval += msg+ '<br />'; success = true; continue; } catch(e) {/*probably, just the wrong key, keep trying*/} } if (!success) retval += global.FAIL_NOKEY; } return retval; } function encrypt_message(plaintext, mode, key_and_ref) { - mode = mode || 'hex'; + mode = mode || 'base64'; var key_ref = key_and_ref.substr(0,1), key = Base64.decodeBytes(key_and_ref.substr(2)), tries = 200, comp = []; while (--tries) { try { comp = CBook[mode].encrypt.apply(null,encrypt(plaintext, key)); break; } catch(e) { //console.log(e); } } comp.unshift(CBook[mode].chr, key_ref); if (tries == 0) { throw Error('tried too many times and failed'); } var rv = format_post.apply(null,comp); if (window.parent != window && window.postMessage) { window.parent.postMessage(rv,"*"); } return rv; } function encrypt(plaintext, encrypt_key_numbers) { var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128); var crypt_args = cryptArgs(iv, encrypt_key_numbers); crypt_args.unshift(plaintext); return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args), encrypt_key_numbers]; } function decrypt(iv,ciph_string, encrypt_key_numbers) { var crypt_args = cryptArgs(iv, encrypt_key_numbers); if (crypt_args[0]==2) throw Error('if CBC, then we need to save the msgsize'); crypt_args.unshift(ciph_string,0); var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args); return plaintext; } function update_bookmarklet() { var bk = document.getElementById('bookmarklet_source').innerHTML; var target = document.getElementById('bookmarklet'); target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")'; } function tryGenuine() { /*will try to show genuinity*/ } \ No newline at end of file diff --git a/client/js/local_session.js b/client/js/local_session.js index a8b1d41..01c1b2b 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,156 +1,197 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { return self.friendsCache[ident]; } this.keyList = function() { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); - var friends = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); + var friends = self.friendsCache || JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) { for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); key_list[side]([k,secret,alias]); } } return key_list; } this.populateKeysOnSelect = function(select) { var key_list = self.keyList(); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var prefix = self.getKeyIdentifier(newsecret); var alias = frm.elements['alias'].value; ///v:value, p:privacy var obj = {"alias":{"v":alias,"p":"friends"}}; self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { - var old_person = self.permStor.get(key); + var old_person = JSON.parse(self.permStor.get(key)); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); - self.addPrefix(prefix, newsecret, self.nsPEOPLE); + self.addPrefix(prefix, newsecret); } - this.addPrefix = function(prefix, newsecret, namespace) { - var ppl = JSON.parse(self.permStor.get(namespace,'{}')); + this.addPrefix = function(prefix, newsecret) { + var ppl = self.friendsCache||JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); ppl[prefix] = ppl[prefix] || []; ppl[prefix].push(newsecret); - self.permStor.set(namespace, JSON.stringify(ppl)); + self.permStor.set(self.nsPEOPLE, JSON.stringify(ppl)); } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } - this.backupFriends = function() { - + this.passPhrase = function(text) { + return ecmaScrypt.generatePrivateKey( + text, + ecmaScrypt.aes.keySize.SIZE_128 + ); + } + this.getBackup = function(key_ary/*typeof string=all*/) { + var bkup = {}; + if (typeof key_ary == 'undefined') { + key_ary = []; + var f = self.friendsCache; + for (a in f) + for (var i=0;i<f[a].length;i++) + key_ary.push(f[a][i]); + } + for (var i=0;i<key_ary.length;i++) { + bkup[key_ary[i]] = self.getInfo(key_ary[i]); + } + return JSON.stringify(bkup); + } + this.backupForm = function(frm) { + var eee = frm.elements; + var passkey = self.passPhrase(eee['passphrase'].value); + var json_backup = self.getBackup(); + //var iv_ciph = CBook['base64'].encrypt.apply(null,encrypt(json_backup, passkey)); + //console.log(iv_ciph); + eee['backup'].value = CBook['base64' + ].encrypt.apply(null,encrypt(json_backup, passkey)); + document.location = '#backup-text'; + + } + + this.restoreForm = function(frm) { + try { + var passkey = self.passPhrase(frm.elements['passphrase'].value); + var iv_ciph = CBook['base64' + ].decrypt.apply(null,frm.elements['backup'].value.split(',')); + var restoral_keys = JSON.parse(decrypt(iv_ciph[0],iv_ciph[1], passkey)); + for (a in restoral_keys) { + self.addFriend(a, restoral_keys[a]); + } + alert('Restoral complete'); + } catch(e) { + alert('Unable to decrypt backup'); + //console.log(e); + } } - this.restoreFriends = function(friend_str) { - - } this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
445c30dac97b46c01a29efdb39a7662e964b86b1
small optimization on friend key lookups
diff --git a/client/js/local_session.js b/client/js/local_session.js index b3ee5fa..a8b1d41 100644 --- a/client/js/local_session.js +++ b/client/js/local_session.js @@ -1,157 +1,156 @@ /* { CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']} MY_KEYS: {"s":['{{key1}}']} PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}} } */ (function() { var global = this; function hasAttr(obj,key) { try { return (typeof(obj[key]) != 'undefined'); } catch(e) {return false;} } function NOT(bool) { return !bool; } function StorageWrapper(stor) { this.KEYS_KEY = 'KEYS'; this.hasKey = function(key) { return (stor.getItem(key) != null); } this.get = function(key,default_val) { return (this.hasKey(key) ? stor.getItem(key) : default_val); } var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}')); this.set = function(key,value) { stor.setItem(key,value); key_dict[key]=1; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } ///actually returns a dict in the form {key1:1,key2:1,...} this.keyDict = function() { return key_dict; } this.del = function(key) { delete stor[key]; delete key_dict[key]; stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict)); } this.deleteEveryFuckingThing = function() { for (a in key_dict) this.del(a); } } function MyStorage() { var self = this; this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]); //this.sessStor = new StorageWrapper(global.sessionStorage); this.nsPERSON = 'PERSON_'; this.nsPEOPLE = 'CBOOK_PEOPLE'; this.nsME = 'MY_KEYS'; this.getKeyIdentifier = function(key_base64) { ///first two bytes of the sha256 hash of the key in base64; var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16); return Base64._keyStr[Math.floor(x/4)]; } this.getKeysByIdentifier = function(ident) { - var friends = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); - return friends[ident]; + return self.friendsCache[ident]; } this.keyList = function() { var key_list = [/*me-friends divider:*/['','','---------']]; var me = JSON.parse(self.permStor.get(self.nsME,'{}')); var friends = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); for (k in friends) { for (var i=0;i<friends[k].length;i++) { var secret = friends[k][i]; var alias = self.getInfo(secret).alias.v; var side = ((secret in me) ?'unshift':'push'); key_list[side]([k,secret,alias]); } } return key_list; } this.populateKeysOnSelect = function(select) { var key_list = self.keyList(); for (var i=0;i<key_list.length;i++) { var k=key_list[i]; var o=document.createElement('option'); o.value = k[0]+':'+k[1]; o.innerHTML = k[2]; select.appendChild(o); } } this.generateKey = function(frm) { var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128)); var prefix = self.getKeyIdentifier(newsecret); var alias = frm.elements['alias'].value; ///v:value, p:privacy var obj = {"alias":{"v":alias,"p":"friends"}}; self.addMyKey(newsecret, obj, prefix); self.addFriend(newsecret, obj, prefix); alert('New key generated.'); } this.addMyKey = function(secret) { var keys = JSON.parse(self.permStor.get(self.nsME,'{}')); keys[secret]=1; self.permStor.set(self.nsME, JSON.stringify(keys)); } this.addFriend = function(newsecret, obj, prefix) { prefix = prefix || self.getKeyIdentifier(newsecret); var key = self.nsPERSON + newsecret; if (self.permStor.hasKey(key)) { var old_person = self.permStor.get(key); if (NOT(obj.alias && obj.alias.v) || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) { return; } } if (NOT(obj.alias && obj.alias.v)) { return; //atm, don't support friends w/o aliases } self.permStor.set(key, JSON.stringify(obj)); self.addPrefix(prefix, newsecret, self.nsPEOPLE); } this.addPrefix = function(prefix, newsecret, namespace) { var ppl = JSON.parse(self.permStor.get(namespace,'{}')); ppl[prefix] = ppl[prefix] || []; ppl[prefix].push(newsecret); self.permStor.set(namespace, JSON.stringify(ppl)); } this.getInfo = function(secret) { return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}')); } this.backupFriends = function() { } this.restoreFriends = function(friend_str) { } - + this.friendsCache = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}')); } if (window.localStorage) { global.Stor = new MyStorage(); global.e = global.Stor; } else { throw "No localStorage support in browser (yet)!"; } })(); \ No newline at end of file
schuyler1d/cbook
a4687c79f36b0259bd7b6ae5b054b24f9c7baa23
needed to update decryption test so it passes the key along with it
diff --git a/client/js/base.js b/client/js/base.js index 6f7f1e3..cbf438e 100644 --- a/client/js/base.js +++ b/client/js/base.js @@ -1,257 +1,258 @@ var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?', regex_args = ['codec','hash','iv','ciphtext'], html_regex = '<([:\\w]+)[^<]+'; var crypted_regex = new RegExp(crypted_regex_str,'g'); /* facebook: document.getElementsByClassName('uiStreamMessage') twitter: //document.activeElement to know which element has focus 15chars for IV 1char for addition 4chars for ♔.☿ (could make it 3) 'http://skyb.us/' == 15 chars 140=15+1+4+15+105 */ var global= { FAIL_ENCODING:'Failed to decrypt message, likely due to encoding problems.<br />', FAIL_NOKEY:'None of your saved keys could decrypt this message.<br />' } function cryptArgs(iv, encrypt_key_numbers) { ///see http://www.josh-davis.org/ecmascrypt ///NOTE:if CBC, then we need to save the msgsize var mode = 0; //0:OFB,1:CFB,2:CBC var keysize = 16; //32 for 256, 24 for 192, 16 for 128 encrypt_key_numbers = encrypt_key_numbers || ecmaScrypt.toNumbers(global.encrypt_key); return [mode, encrypt_key_numbers, keysize, iv]; } var U2N = new (function() { /* we'll need to get a lot smarter. we should be accepting/creating unicode characters within the character range that HTML considers 'character' text. http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets parseInt('10FFFF',16) - parseInt('10000',16) == 1048575 1114111 - 65536 == String.fromCharCode(85267) seems to be 'real' first character */ this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars this.compress = function(low_unicode) { var arr = []; var c = low_unicode.length; while (c--) { arr.unshift(low_unicode.charCodeAt(c)); } return this.unicode(arr); } this.decompress = function(high_unicode) { var nums = this.nums(high_unicode); var str = ''; for (var i=0;i<nums.length;i++) { str += String.fromCharCode(nums[i]); } return str; } this.lowcoding = function(cipher) { var outhex = ''; for(var i = 0;i < cipher.length;i++) { outhex += ecmaScrypt.toHex(cipher.charCodeAt(i)); } return outhex; } this.unicode = function(nums) { ///take nums array of numbers from 0-255 var u_string=''; for (var i=0;i<nums.length;i++) { var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) ); if (n>65535) { ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes throw Error('cannot deal with high chars yet'); } if (n>2299099) { throw Error('cannot deal with high unicode compression yet'); //but I think the answer is that we'll have some marker //for NON-encoded text and then // } ///random suspects: if (n==1759 || n==130) { throw Error('random suspect--not sure it is culprit'); } if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes'); //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n); } if (8192 < n && n < 8447) { //255 chars ///http://en.wikipedia.org/wiki/Unicode_control_characters ///seem to be grouped all in the 2000 -20FF range throw Error('Wide fence for control chars. we can be more picky'+n); } ///Any code D800–DFFF is invalid: UTF-16 conflict (2047 chars) try { var c = String.fromCharCode(n); encodeURIComponent(c); u_string += c; } catch(e) { throw Error('could not encode uri component for char:'+n); } } if (u_string.match(/\s/)!=null) { throw Error('FAILS BY WHITESPACE'); } return u_string; }; this.nums = function(u_string) { var nums = []; var m = u_string.length; for (var i=0;i<m;i++) { var n = u_string.charCodeAt(i)-this.min; nums.push(n%256); var x2 = parseInt(n/256,10); if (x2 != 0) nums.push(x2); } return nums; }; })();//end U2N var CBook= { chars:{'.':'unicrap',',':'base64'}, unicrap:{ chr:'.', - encrypt:function(iv,ciph) { + encrypt:function(iv,ciph,key_numbers) { var compressed = U2N.compress(ciph.cipher); var compressed_IV = U2N.unicode(iv); //cheat on making exceptions and just try decrypt - decrypt.apply(null,CBook.unicrap.decrypt(compressed_IV,compressed)); + var decoded = CBook.unicrap.decrypt(compressed_IV,compressed); + decrypt(decoded[0],decoded[1],key_numbers); return [compressed_IV, compressed]; }, decrypt:function(iv,ciphtext) { return [U2N.nums(iv), U2N.decompress(ciphtext)]; } }, base64:{ chr:',', encrypt:function(iv,ciph) { return [Base64.encodeBytes(iv), Base64.encode(ciph.cipher)]; }, decrypt:function(iv64,ciphtext) { return [Base64.decodeBytes(iv64), Base64.decode(ciphtext)]; } } /*,hex:{ chr:'_', encrypt:function(iv,ciph) { return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)]; }, decrypt:function(iv,ciphtext) { } }*/ };//end CBook function format_post(codec,hash,iv,ciphertext) { var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':'; //console.log(rv.length); return rv; } function test_unicode(txt,f) { f = f||function(c) { return c.match(/([\w\W])/); }; for (var i=0;i<txt.length;i++) { var r = f(String.fromCharCode(txt.charCodeAt(i))); if (r) { console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i)); } } } function decrypt_message(crypted) { var x; var retval = ''; while ((x = crypted_regex.exec(crypted)) != null) { var friend_keys = Stor.getKeysByIdentifier(x[2]), cbook_method = CBook[CBook.chars[x[1]]], success = false; if (!friend_keys || !friend_keys.length ) { retval += global.FAIL_NOKEY; continue; } try { var iv_ciph = cbook_method.decrypt(x[3],x[4]); }catch(e) { retval += global.FAIL_ENCODING; continue; } var i = friend_keys.length; while (i--) { try { var msg = decrypt(iv_ciph[0],iv_ciph[1],Base64.decodeBytes(friend_keys[i])); retval += msg+ '<br />'; success = true; continue; } catch(e) {/*probably, just the wrong key, keep trying*/} } if (!success) retval += global.FAIL_NOKEY; } return retval; } function encrypt_message(plaintext, mode, key_and_ref) { mode = mode || 'hex'; var key_ref = key_and_ref.substr(0,1), key = Base64.decodeBytes(key_and_ref.substr(2)), tries = 200, comp = []; while (--tries) { try { comp = CBook[mode].encrypt.apply(null,encrypt(plaintext, key)); break; } catch(e) { //console.log(e); } } comp.unshift(CBook[mode].chr, key_ref); if (tries == 0) { throw Error('tried too many times and failed'); } var rv = format_post.apply(null,comp); if (window.parent != window && window.postMessage) { window.parent.postMessage(rv,"*"); } return rv; } function encrypt(plaintext, encrypt_key_numbers) { var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128); var crypt_args = cryptArgs(iv, encrypt_key_numbers); crypt_args.unshift(plaintext); - return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args)]; + return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args), encrypt_key_numbers]; } function decrypt(iv,ciph_string, encrypt_key_numbers) { var crypt_args = cryptArgs(iv, encrypt_key_numbers); if (crypt_args[0]==2) throw Error('if CBC, then we need to save the msgsize'); crypt_args.unshift(ciph_string,0); var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args); return plaintext; } function update_bookmarklet() { var bk = document.getElementById('bookmarklet_source').innerHTML; var target = document.getElementById('bookmarklet'); target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")'; } function tryGenuine() { /*will try to show genuinity*/ } \ No newline at end of file