DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.
Action Controller Overview
In this guide you will learn how controllers work and how they fit into the request cycle in your application.
After reading this guide, you will know:
- How to follow the flow of a request through a controller.
- How to restrict parameters passed to your controller.
- How and why to store data in the session or cookies.
- How to work with filters to execute code during request processing.
- How to use Action Controller's built-in HTTP authentication.
- How to stream data directly to the user's browser.
- How to filter sensitive parameters so they do not appear in the application's log.
- How to deal with exceptions that may be raised during request processing.
What Does a Controller Do?
Action Controller is the C in MVC. After the router has determined which controller to use for a request, the controller is responsible for making sense of the request, and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.
For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model, and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
A controller can thus be thought of as a middleman between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates user data to the model.
NOTE: For more details on the routing process, see Rails Routing from the Outside In.
Controller Naming Convention
The naming convention of controllers in Rails
favors pluralization of the last word in the controller's name, although it is not strictly required (e.g. ApplicationController
). For example, ClientsController
is preferable to ClientController
, SiteAdminsController
is preferable to SiteAdminController
or SitesAdminsController
, and so on.
Following this convention will allow you to use the default route generators (e.g. resources
, etc) without needing to qualify each :path
or :controller
, and will keep named route helpers' usage consistent throughout your application. See Layouts and Rendering Guide for more details.
NOTE: The controller naming convention differs from the naming convention of models, which are expected to be named in singular form.
Methods and Actions
A controller is a Ruby class which inherits from ApplicationController
and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails
creates an instance of that controller and runs the method with the same name as the action.
class ClientsController < ApplicationController
def new
end
end
As an example, if a user goes to /clients/new
in your application to add a new client, Rails will create an instance of ClientsController
and call its new
method. Note that the empty method from the example above would work just fine because Rails will by default render the new.html.erb
view unless the action says otherwise. By creating a new Client
, the new
method can make a @client
instance variable accessible in the view:
def new
@client = Client.new
end
The Layouts and Rendering Guide explains this in more detail.
ApplicationController
inherits from ::ActionController::Base
, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
Only public methods are callable as actions. It is a best practice to lower the visibility of methods (with private
or protected
) which are not intended to be actions, like auxiliary methods or filters.
Parameters
You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params
hash in your controller:
class ClientsController < ApplicationController
# This action uses query string parameters because it gets run
# by an HTTP GET request, but this does not make any difference
# to the way in which the parameters are accessed. The URL for
# this action would look like this in order to list activated
# clients: /clients?status=activated
def index
if params[:status] == "activated"
@clients = Client.activated
else
@clients = Client.inactivated
end
end
# This action uses POST parameters. They are most likely coming
# from an HTML form which the user has submitted. The URL for
# this RESTful request will be "/clients", and the data will be
# sent as part of the request body.
def create
@client = Client.new(params[:client])
if @client.save
redirect_to @client
else
# This line overrides the default rendering behavior, which
# would have been to render the "create" view.
render "new"
end
end
end
Hash and Array Parameters
The params
hash is not limited to one-dimensional keys and values. It can contain nested arrays and hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:
GET /clients?ids[]=1&ids[]=2&ids[]=3
NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3" as the "[" and "]" characters are not allowed in URLs. Most of the time you don't have to worry about this because the browser will encode it for you, and Rails will decode it automatically, but if you ever find yourself having to send those requests to the server manually you should keep this in mind.
The value of params[:ids]
will now be ["1", "2", "3"]
. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
NOTE: Values such as [nil]
or [nil, nil, ...]
in params
are replaced
with []
for security reasons by default. See Security Guide
for more information.
To send a hash, you include the key name inside the brackets:
<form accept-charset="UTF-8" action="/clients" method="post">
<input type="text" name="client[name]" value="Acme" />
<input type="text" name="client[phone]" value="12345" />
<input type="text" name="client[address][postcode]" value="12345" />
<input type="text" name="client[address][city]" value="Carrot City" />
</form>
When this form is submitted, the value of params[:client]
will be { "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" } }
. Note the nested hash in params[:client][:address]
.
The params
object acts like a Hash, but lets you use symbols and strings interchangeably as keys.
JSON parameters
If you're writing a web service application, you might find yourself more comfortable accepting parameters in JSON format. If the "Content-Type" header of your request is set to "application/json", Rails will automatically load your parameters into the params
hash, which you can access as you would normally.
So for example, if you are sending this JSON content:
{ "company": { "name": "acme", "address": "123 Carrot Street" } }
Your controller will receive params[:company]
as { "name" => "acme", "address" => "123 Carrot Street" }
.
Also, if you've turned on config.wrap_parameters
in your initializer or called wrap_parameters
in your controller, you can safely omit the root element in the JSON parameter. In this case, the parameters will be cloned and wrapped with a key chosen based on your controller's name. So the above JSON request can be written as:
{ "name": "acme", "address": "123 Carrot Street" }
And, assuming that you're sending the data to CompaniesController
, it would then be wrapped within the :company
key like this:
{ name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } }
You can customize the name of the key or specific parameters you want to wrap by consulting the API documentation
NOTE: Support for parsing XML parameters has been extracted into a gem named actionpack-xml_parser
.
Routing Parameters
The params
hash will always contain the :controller
and :action
keys, but you should use the methods controller_name
and action_name
instead to access these values. Any other parameters defined by the routing, such as :id
, will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the :status
parameter in a "pretty" URL:
get '/clients/:status', to: 'clients#index', foo: 'bar'
In this case, when a user opens the URL /clients/active
, params[:status]
will be set to "active". When this route is used, params[:foo]
will also be set to "bar", as if it were passed in the query string. Your controller will also receive params[:action]
as "index" and params[:controller]
as "clients".
default_url_options
You can set global default parameters for URL generation by defining a method called default_url_options
in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols:
class ApplicationController < ActionController::Base
def
{ locale: I18n.locale }
end
end
These options will be used as a starting point when generating URLs, so it's possible they'll be overridden by the options passed to url_for
calls.
If you define default_url_options
in ApplicationController
, as in the example above, these defaults will be used for all URL generation. The method can also be defined in a specific controller, in which case it only affects URLs generated there.
In a given request, the method is not actually called for every single generated URL. For performance reasons, the returned hash is cached, and there is at most one invocation per request.
Strong Parameters
With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been permitted. This means that you'll have to make a conscious decision about which attributes to permit for mass update. This is a better security practice to help prevent accidentally allowing users to update sensitive model attributes.
In addition, parameters can be marked as required and will flow through a predefined raise/rescue flow that will result in a 400 Bad Request being returned if not all required parameters are passed in.
class PeopleController < ActionController::Base
# This will raise an ActiveModel::ForbiddenAttributesError exception
# because it's using mass assignment without an explicit permit
# step.
def create
Person.create(params[:person])
end
# This will pass with flying colors as long as there's a person key
# in the parameters, otherwise it'll raise an
# ActionController::ParameterMissing exception, which will get
# caught by ActionController::Base and turned into a 400 Bad
# Request error.
def update
person = current_account.people.find(params[:id])
person.update!(person_params)
redirect_to person
end
private
# Using a private method to encapsulate the permissible parameters
# is just a good pattern since you'll be able to reuse the same
# permit list between create and update. Also, you can specialize
# this method with per-user checking of permissible attributes.
def person_params
params.require(:person).permit(:name, :age)
end
end
Permitted Scalar Values
Calling permit
like:
params.permit(:id)
permits the specified key (:id
) for inclusion if it appears in params
and
it has a permitted scalar value associated. Otherwise, the key is going
to be filtered out, so arrays, hashes, or any other objects cannot be
injected.
The permitted scalar types are String
, Symbol
, NilClass
,
Numeric
, TrueClass
, FalseClass
, Date
, Time
, DateTime
,
StringIO
, IO
, ::ActionDispatch::Http::UploadedFile
, and
Rack::Test::UploadedFile
.
To declare that the value in params
must be an array of permitted
scalar values, map the key to an empty array:
params.permit(id: [])
Sometimes it is not possible or convenient to declare the valid keys of a hash parameter or its internal structure. Just map to an empty hash:
params.permit(preferences: {})
but be careful because this opens the door to arbitrary input. In this
case, permit
ensures values in the returned structure are permitted
scalars and filters out anything else.
To permit an entire hash of parameters, the permit!
method can be
used:
params.require(:log_entry).permit!
This marks the :log_entry
parameters hash and any sub-hash of it as
permitted and does not check for permitted scalars, anything is accepted.
Extreme care should be taken when using permit!
, as it will allow all current
and future model attributes to be mass-assigned.
Nested Parameters
You can also use permit
on nested parameters, like:
params.permit(:name, { emails: [] },
friends: [ :name,
{ family: [ :name ], hobbies: [] }])
This declaration permits the name
, emails
, and friends
attributes. It is expected that emails
will be an array of permitted
scalar values, and that friends
will be an array of resources with
specific attributes: they should have a name
attribute (any
permitted scalar values allowed), a hobbies
attribute as an array of
permitted scalar values, and a family
attribute which is restricted
to having a name
(any permitted scalar values allowed here, too).
More Examples
You may want to also use the permitted attributes in your new
action. This raises the problem that you can't use require
on the
root key because, normally, it does not exist when calling new
:
# using `fetch` you can supply a default and use
# the Strong Parameters API from there.
params.fetch(:blog, {}).permit(:title, : )
The model class method accepts_nested_attributes_for
allows you to
update and destroy associated records. This is based on the id
and _destroy
parameters:
# permit :id and :_destroy
params.require(: ).permit(:name, books_attributes: [:title, :id, :_destroy])
Hashes with integer keys are treated differently, and you can declare
the attributes as if they were direct children. You get these kinds of
parameters when you use accepts_nested_attributes_for
in combination
with a has_many
association:
# To permit the following data:
# {"book" => {"title" => "Some Book",
# "chapters_attributes" => { "1" => {"title" => "First Chapter"},
# "2" => {"title" => "Second Chapter"}}}}
params.require(:book).permit(:title, chapters_attributes: [:title])
Imagine a scenario where you have parameters representing a product name and a hash of arbitrary data associated with that product, and you want to permit the product name attribute and also the whole data hash:
def product_params
params.require(:product).permit(:name, data: {})
end
Outside the Scope of Strong Parameters
The strong parameter API was designed with the most common use cases in mind. It is not meant as a silver bullet to handle all of your parameter filtering problems. However, you can easily mix the API with your own code to adapt to your situation.
Session
Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
::ActionDispatch::Session::CookieStore
- Stores everything on the client.::ActionDispatch::Session::CacheStore
- Stores the data in the Rails cache.ActionDispatch::Session::ActiveRecordStore
- Stores the data in a database using Active Record (requires theactiverecord-session_store
gem).::ActionDispatch::Session::MemCacheStore
- Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).
All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
For most stores, this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof. And it is also encrypted so anyone with access to it can't read its contents. (Rails will not accept it if it has been edited).
The CookieStore can store around 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (such as model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
If your user sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ::ActionDispatch::Session::CacheStore
. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.
Read more about session storage in the Security Guide.
If you need a different session storage mechanism, you can change it in an initializer:
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails g active_record:session_migration")
# Rails.application.config.session_store :active_record_store
Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in an initializer:
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :, key: '_your_app_session'
You can also pass a :domain
key and specify the domain name for the cookie:
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :, key: '_your_app_session', domain: ".example.com"
Rails sets up (for the CookieStore) a secret key used for signing the session data in config/credentials.yml.enc
. This can be changed with bin/rails credentials:edit
.
# aws:
# access_key_id: 123
# secret_access_key: 345
# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: 492f...
NOTE: Changing the secret_key_base when using the CookieStore
will invalidate all existing sessions.
Accessing the Session
In your controller you can access the session through the session
instance method.
NOTE: Sessions are lazily loaded. If you don't access sessions in your action's code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.
Session values are stored using key/value pairs like a hash:
class ApplicationController < ActionController::Base
private
# Finds the User with the ID stored in the session with the key
# :current_user_id This is a common way to handle user login in
# a Rails application; logging in sets the session value and
# logging out removes it.
def current_user
@_current_user ||= session[:current_user_id] &&
User.find_by(id: session[:current_user_id])
end
end
To store something in the session, just assign it to the key like a hash:
class LoginsController < ApplicationController
# "Create" a login, aka "log the user in"
def create
if user = User.authenticate(params[:username], params[:password])
# Save the user ID in the session so it can be used in
# subsequent requests
session[:current_user_id] = user.id
redirect_to root_url
end
end
end
To remove something from the session, delete the key/value pair:
class LoginsController < ApplicationController
# "Delete" a login, aka "log the user out"
def destroy
# Remove the user id from the session
session.delete(:current_user_id)
# Clear the memoized current user
@_current_user = nil
redirect_to root_url
end
end
To reset the entire session, use reset_session
.
The Flash
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages, etc.
The flash is accessed via the flash
method. Like the session, the flash is represented as a hash.
Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
class LoginsController < ApplicationController
def destroy
session.delete(:current_user_id)
flash[:notice] = "You have successfully logged out."
redirect_to root_url
end
end
Note that it is also possible to assign a flash message as part of the redirection. You can assign :notice
, :alert
or the general purpose :flash
:
redirect_to root_url, notice: "You have successfully logged out."
redirect_to root_url, alert: "You're stuck here!"
redirect_to root_url, flash: { referral_code: 1234 }
The destroy
action redirects to the application's root_url
, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display any error alerts or notices from the flash in the application's layout:
<html>
<!-- <head/> -->
<body>
<% flash.each do |name, msg| -%>
<%= content_tag :div, msg, class: name %>
<% end -%>
<!-- more content -->
</body>
</html>
This way, if an action sets a notice or an alert message, the layout will display it automatically.
You can pass anything that the session can store; you're not limited to notices and alerts:
<% if flash[:just_signed_up] %>
<p class="welcome">Welcome to our site!</p>
<% end %>
If you want a flash value to be carried over to another request, use flash.keep
:
class MainController < ApplicationController
# Let's say this action corresponds to root_url, but you want
# all requests here to be redirected to UsersController#index.
# If an action sets the flash and redirects here, the values
# would normally be lost when another redirect happens, but you
# can use 'keep' to make it persist for another request.
def index
# Will persist all flash values.
flash.keep
# You can also use a key to keep only some kind of value.
# flash.keep(:notice)
redirect_to users_url
end
end
flash.now
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create
action fails to save a resource and you render the new
template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now
in the same way you use the normal flash
:
class ClientsController < ApplicationController
def create
@client = Client.new(client_params)
if @client.save
# ...
else
flash.now[:error] = "Could not save client"
render action: "new"
end
end
end
Cookies
Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the cookies
method, which - much like the session
- works like a hash:
class CommentsController < ApplicationController
def new
# Auto-fill the commenter's name if it has been stored in a cookie
@comment = Comment.new(author: [:commenter_name])
end
def create
@comment = Comment.new(comment_params)
if @comment.save
flash[:notice] = "Thanks for your comment!"
if params[:remember_name]
# Remember the commenter's name.
[:commenter_name] = @comment.
else
# Delete cookie for the commenter's name cookie, if any.
.delete(:commenter_name)
end
redirect_to @comment.article
else
render action: "new"
end
end
end
Note that while for session values you can set the key to nil
, to delete a cookie value you should use cookies.delete(:key)
.
Rails also provides a signed cookie jar and an encrypted cookie jar for storing sensitive data. The signed cookie jar appends a cryptographic signature on the cookie values to protect their integrity. The encrypted cookie jar encrypts the values in addition to signing them, so that they cannot be read by the end user. Refer to the API documentation for more details.
These special cookie jars use a serializer to serialize the assigned values into strings and deserializes them into Ruby objects on read.
You can specify what serializer to use:
Rails.application.config.action_dispatch. = :json
The default serializer for new applications is :json
. For compatibility with
old applications with existing cookies, :marshal
is used when serializer
option is not specified.
You may also set this option to :hybrid
, in which case Rails would transparently
deserialize existing (Marshal
-serialized) cookies on read and re-write them in
the JSON
format. This is useful for migrating existing applications to the
:json
serializer.
It is also possible to pass a custom serializer that responds to load
and
dump
:
Rails.application.config.action_dispatch. = MyCustomSerializer
When using the :json
or :hybrid
serializer, you should beware that not all
Ruby objects can be serialized as JSON. For example, Date
and Time
objects
will be serialized as strings, and Hash
es will have their keys stringified.
class CookiesController < ApplicationController
def
.encrypted[:expiration_date] = Date.tomorrow # => Thu, 20 Mar 2014
redirect_to action: 'read_cookie'
end
def
.encrypted[:expiration_date] # => "2014-03-20"
end
end
It's advisable that you only store simple data (strings and numbers) in cookies. If you have to store complex objects, you would need to handle the conversion manually when reading the values on subsequent requests.
If you use the cookie session store, this would apply to the session
and
flash
hash as well.
Rendering XML and JSON data
ActionController makes it extremely easy to render XML
or JSON
data. If you've generated a controller using scaffolding, it would look something like this:
class UsersController < ApplicationController
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render xml: @users }
format.json { render json: @users }
end
end
end
You may notice in the above code that we're using render xml: @users
, not render xml: @users.to_xml
. If the object is not a String, then Rails will automatically invoke to_xml
for us.
Filters
Filters are methods that are run "before", "after" or "around" a controller action.
Filters are inherited, so if you set a filter on ApplicationController
, it will be run on every controller in your application.
"before" filters are registered via before_action
. They may halt the request cycle. A common "before" filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
class ApplicationController < ActionController::Base
before_action :require_login
private
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url # halts request cycle
end
end
end
The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a "before" filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter, they are also cancelled.
In this example the filter is added to ApplicationController
and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_action
:
class LoginsController < ApplicationController
skip_before_action :require_login, only: [:new, :create]
end
Now, the LoginsController
's new
and create
actions will work as before without requiring the user to be logged in. The :only
option is used to skip this filter only for these actions, and there is also an :except
option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
NOTE: Calling the same filter multiple times with different options will not work, since the last filter definition will overwrite the previous ones.
After Filters and Around Filters
In addition to "before" filters, you can also run filters after an action has been executed, or both before and after.
"after" filters are registered via after_action
. They are similar to "before" filters, but because the action has already been run they have access to the response data that's about to be sent to the client. Obviously, "after" filters cannot stop the action from running. Please note that "after" filters are executed only after a successful action, but not when an exception is raised in the request cycle.
"around" filters are registered via around_action
. They are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
For example, in a website where changes have an approval workflow, an administrator could preview them easily by applying them within a transaction:
class ChangesController < ApplicationController
around_action :wrap_in_transaction, only: :show
private
def wrap_in_transaction
ActiveRecord::Base.transaction do
begin
yield
ensure
raise ActiveRecord::Rollback
end
end
end
end
Note that an "around" filter also wraps rendering. In particular, in the example above, if the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.
You can choose not to yield and build the response yourself, in which case the action will not be run.
Other Ways to Use Filters
While the most common way to use filters is by creating private methods and using before_action
, after_action
, or around_action
to add them, there are two other ways to do the same thing.
The first is to use a block directly with the *_action
methods. The block receives the controller as an argument. The require_login
filter from above could be rewritten to use a block:
class ApplicationController < ActionController::Base
before_action do |controller|
unless controller.send(:logged_in?)
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url
end
end
end
Note that the filter in this case uses send
because the logged_in?
method is private and the filter does not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in simpler cases it might be useful.
Specifically for around_action
, the block also yields in the action
:
around_action { |_controller, action| time(&action) }
The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and cannot be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
class ApplicationController < ActionController::Base
before_action LoginFilter
end
class LoginFilter
def self.before(controller)
unless controller.send(:logged_in?)
controller.flash[:error] = "You must be logged in to access this section"
controller.redirect_to controller.new_login_url
end
end
end
Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class must implement a method with the same name as the filter, so for the before_action
filter the class must implement a before
method, and so on. The around
method must yield
to execute the action.
Request Forgery Protection
Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying, or deleting data on that site without the user's knowledge or permission.
The first step to avoid this is to make sure all "destructive" actions (create, update, and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests.
The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
If you generate a form like this:
<%= form_with model: @user do |form| %>
<%= form.text_field :username %>
<%= form.text_field :password %>
<% end %>
You will see how the token gets added as a hidden field:
<form accept-charset="UTF-8" action="/users/1" method="post">
<input type="hidden"
value="67250ab105eb5ad10851c00a5621854a23af5489"
name="authenticity_token"/>
<!-- fields -->
</form>
Rails adds this token to every form that's generated using the form helpers, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method form_authenticity_token
:
The form_authenticity_token
generates a valid authentication token. That's useful in places where Rails does not add it automatically, like in custom Ajax calls.
The Security Guide has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
The Request and Response Objects
In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The request
method contains an instance of ::ActionDispatch::Request
and the response
method returns a response object representing what is going to be sent back to the client.
The request
Object
The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the Rails API documentation and Rack Documentation. Among the properties that you can access on this object are:
Property of request |
Purpose |
|---|---|
host |
The hostname used for this request. |
domain(n=2) |
The hostname's first n segments, starting from the right (the TLD). |
format |
The content type requested by the client. |
method |
The HTTP method used for the request. |
get? , post? , patch? , put? , delete? , head? |
Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. |
headers |
Returns a hash containing the headers associated with the request. |
port |
The port number (integer) used for the request. |
protocol |
Returns a string containing the protocol used plus "://", for example "http://". |
query_string |
The query string part of the URL, i.e., everything after "?". |
remote_ip |
The IP address of the client. |
url |
The entire URL used for the request. |
path_parameters
, query_parameters
, and request_parameters
Rails collects all of the parameters sent along with the request in the params
hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The query_parameters
hash contains parameters that were sent as part of the query string while the request_parameters
hash contains parameters sent as part of the post body. The path_parameters
hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
The response
Object
The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values. To get a full list of the available methods, refer to the Rails API documentation and Rack Documentation.
Property of response |
Purpose |
|---|---|
body |
This is the string of data being sent back to the client. This is most often HTML. |
status |
The HTTP status code for the response, like 200 for a successful request or 404 for file not found. |
location |
The URL the client is being redirected to, if any. |
content_type |
The content type of the response. |
charset |
The character set being used for the response. Default is "utf-8". |
headers |
Headers used for the response. |
Setting Custom Headers
If you want to set custom headers for a response then response.headers
is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to response.headers
this way:
response.headers["Content-Type"] = "application/pdf"
NOTE: In the above case it would make more sense to use the content_type
setter directly.
HTTP Authentications
Rails comes with three built-in HTTP authentication mechanisms:
- Basic Authentication
- Digest Authentication
- Token Authentication
HTTP Basic Authentication
HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, http_basic_authenticate_with
.
class AdminsController < ApplicationController
http_basic_authenticate_with name: "humbaba", password: "5baa61e4"
end
With this in place, you can create namespaced controllers that inherit from AdminsController
. The filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
HTTP Digest Authentication
HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, authenticate_or_request_with_http_digest
.
class AdminsController < ApplicationController
USERS = { "lifo" => "world" }
before_action :authenticate
private
def authenticate
authenticate_or_request_with_http_digest do |username|
USERS[username]
end
end
end
As seen in the example above, the authenticate_or_request_with_http_digest
block takes only one argument - the username. And the block returns the password. Returning false
or nil
from the authenticate_or_request_with_http_digest
will cause authentication failure.
HTTP Token Authentication
HTTP token authentication is a scheme to enable the usage of Bearer tokens in the HTTP Authorization
header. There are many token formats available and describing them is outside the scope of this document.
As an example, suppose you want to use an authentication token that has been issued in advance to perform authentication and access. Implementing token authentication with Rails is quite easy and only requires using one method, authenticate_or_request_with_http_token
.
class PostsController < ApplicationController
TOKEN = "secret"
before_action :authenticate
private
def authenticate
authenticate_or_request_with_http_token do |token, |
ActiveSupport::SecurityUtils.secure_compare(token, TOKEN)
end
end
end
As seen in the example above, the authenticate_or_request_with_http_token
block takes two arguments - the token and a Hash
containing the options that were parsed from the HTTP Authorization
header. The block should return true
if the authentication is successful. Returning false
or nil
on it will cause an authentication failure.
Streaming and File Downloads
Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the send_data
and the send_file
methods, which will both stream data to the client. send_file
is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you.
To stream data to the client, use send_data
:
require "prawn"
class ClientsController < ApplicationController
# Generates a PDF document with information on the client and
# returns it. The user will get the PDF as a file download.
def download_pdf
client = Client.find(params[:id])
send_data generate_pdf(client),
filename: "#{client.name}.pdf",
type: "application/pdf"
end
private
def generate_pdf(client)
Prawn::Document.new do
text client.name, align: :center
text "Address: #{client.address}"
text "Email: #{client.email}"
end.render
end
end
The download_pdf
action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the :disposition
option to "inline". The opposite and default value for this option is "attachment".
Sending Files
If you want to send a file that already exists on disk, use the send_file
method.
class ClientsController < ApplicationController
# Stream a file that has already been generated and stored on disk.
def download_pdf
client = Client.find(params[:id])
send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
filename: "#{client.name}.pdf",
type: "application/pdf")
end
end
This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the :stream
option or adjust the block size with the :buffer_size
option.
If :type
is not specified, it will be guessed from the file extension specified in :filename
. If the content type is not registered for the extension, application/octet-stream
will be used.
WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to.
TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
RESTful Downloads
While send_data
works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the show
action, without any streaming:
class ClientsController < ApplicationController
# The user can request to receive this resource as HTML or PDF.
def show
@client = Client.find(params[:id])
respond_to do |format|
format.html
format.pdf { render pdf: generate_pdf(@client) }
end
end
end
In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file config/initializers/mime_types.rb
:
Mime::Type.register "application/pdf", :pdf
NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
GET /clients/1.pdf
Live Streaming of Arbitrary Data
Rails allows you to stream more than just files. In fact, you can stream anything
you would like in a response object. The ::ActionController::Live
module allows
you to create a persistent connection with a browser. Using this module, you will
be able to send arbitrary data to the browser at specific points in time.
Incorporating Live Streaming
Including ::ActionController::Live
inside of your controller class will provide
all actions inside of the controller the ability to stream data. You can mix in
the module like so:
class MyController < ActionController::Base
include ActionController::Live
def stream
response.headers['Content-Type'] = 'text/event-stream'
100.times {
response.stream.write "hello world\n"
sleep 1
}
ensure
response.stream.close
end
end
The above code will keep a persistent connection with the browser and send 100
messages of "hello world\n"
, each one second apart.
There are a couple of things to notice in the above example. We need to make
sure to close the response stream. Forgetting to close the stream will leave
the socket open forever. We also have to set the content type to text/event-stream
before we write to the response stream. This is because headers cannot be written
after the response has been committed (when response.committed?
returns a truthy
value), which occurs when you write
or commit
the response stream.
Example Usage
Let's suppose that you were making a Karaoke machine and a user wants to get the
lyrics for a particular song. Each Song
has a particular number of lines and
each line takes time num_beats
to finish singing.
If we wanted to return the lyrics in Karaoke fashion (only sending the line when
the singer has finished the previous line), then we could use ::ActionController::Live
as follows:
class LyricsController < ActionController::Base
include ActionController::Live
def show
response.headers['Content-Type'] = 'text/event-stream'
song = Song.find(params[:id])
song.each do |line|
response.stream.write line.lyrics
sleep line.num_beats
end
ensure
response.stream.close
end
end
The above code sends the next line only after the singer has completed the previous line.
Streaming Considerations
Streaming arbitrary data is an extremely powerful tool. As shown in the previous examples, you can choose when and what to send across a response stream. However, you should also note the following things:
- Each response stream creates a new thread and copies over the thread local variables from the original thread. Having too many thread local variables can negatively impact performance. Similarly, a large number of threads can also hinder performance.
- Failing to close the response stream will leave the corresponding socket open
forever. Make sure to call
close
whenever you are using a response stream. - WEBrick servers buffer all responses, and so including
::ActionController::Live
will not work. You must use a web server which does not automatically buffer responses.
Log Filtering
Rails keeps a log file for each environment in the log
folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file.
Parameters Filtering
You can filter out sensitive request parameters from your log files by appending them to config.filter_parameters
in the application configuration. These parameters will be marked [FILTERED] in the log.
config.filter_parameters << :password
NOTE: Provided parameters will be filtered out by partial matching regular expression. Rails adds default :password
in the appropriate initializer (initializers/filter_parameter_logging.rb
) and cares about typical application parameters password
and password_confirmation
.
Redirects Filtering
Sometimes it's desirable to filter out from log files some sensitive locations your application is redirecting to.
You can do that by using the config.filter_redirect
configuration option:
config.filter_redirect << 's3.amazonaws.com'
You can set it to a String, a Regexp, or an array of both.
config.filter_redirect.concat ['s3.amazonaws.com', /private_path/]
Matching URLs will be marked as '[FILTERED]'.
Rescue
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ::ActiveRecord::RecordNotFound
exception.
Rails default exception handling displays a "500 Server Error" message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:
The Default 500 and 404 Templates
By default, in the production environment the application will render either a 404 or a 500 error message. In the development environment all unhandled exceptions are simply raised. These messages are contained in static HTML files in the public folder, in 404.html
and 500.html
respectively. You can customize these files to add some extra information and style, but remember that they are static HTML; i.e. you can't use ERB, SCSS, CoffeeScript, or layouts for them.
rescue_from
If you want to do something a bit more elaborate when catching errors, you can use rescue_from
, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.
When an exception occurs which is caught by a rescue_from
directive, the exception object is passed to the handler. The handler can be a method or a Proc
object passed to the :with
option. You can also use a block directly instead of an explicit Proc
object.
Here's how you can use rescue_from
to intercept all ::ActiveRecord::RecordNotFound
errors and do something with them.
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
private
def record_not_found
render plain: "404 Not Found", status: 404
end
end
Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
class ApplicationController < ActionController::Base
rescue_from User::NotAuthorized, with: :
private
def
flash[:error] = "You don't have access to this section."
redirect_back(fallback_location: root_path)
end
end
class ClientsController < ApplicationController
# Check that the user has the right authorization to access clients.
before_action :
# Note how the actions don't have to worry about all the auth stuff.
def edit
@client = Client.find(params[:id])
end
private
# If the user is not authorized, just throw the exception.
def
raise User::NotAuthorized unless current_user.admin?
end
end
WARNING: Using rescue_from
with Exception
or StandardError
would cause serious side-effects as it prevents Rails from handling exceptions properly. As such, it is not recommended to do so unless there is a strong reason.
NOTE: When running in the production environment, all
::ActiveRecord::RecordNotFound
errors render the 404 error page. Unless you need
a custom behavior you don't need to handle this.
NOTE: Certain exceptions are only rescuable from the ApplicationController
class, as they are raised before the controller gets initialized and the action gets executed.
Force HTTPS protocol
If you'd like to ensure that communication to your controller is only possible
via HTTPS, you should do so by enabling the ::ActionDispatch::SSL
middleware via
config.force_ssl
in your environment configuration.


Workshop designed for school students to spread awareness on AI
A hands-on tutorial to learn about basic theories as welll as develop an AI driven system
Appropriate for students from class 8 to class 12
Introduction to Machine Learning (ML) and Deep Learning (DL)
the most powerful sub-area of AI
Introduction to Computer Vision (CV) or Natural Language Processing (NLP)
two most popular application domains
Application on Object detection using ML and CV
hands-on session using Colab and Tensorflow
Building Image Classification tools using Teachable Machines
The first workshop was conducted for Kendriya Vidyalaya Kanjikode in Nov 2021
Students developed object tracking software
The second workshop was conducted as part of Science Quest and Crystal Program at IIT Palakkad in May 2022
Students built an AI tool to classify images
Vaishak Nair, Yumna Farooqi, Eva Cherian
Contact us for more details. We are enthusiastic to conduct such workshops in more schools.


Preparation time
30 mins to 1 hour
Cooking time
1 to 2 hours
Serves
Makes 25 fondant fancies
Dietary
Almonds and cherries are a great combination - used to great effect in these pretty individual cakes.
For this recipe you will need a freestanding mixer with a whisk and beater attachment, a deep 23cm/9in square cake tin and a piping bag fitted with a medium star nozzle.
For the marzipan, combine the almonds, caster sugar and icing sugar in a large bowl. Create a well in the middle and add the egg and almond extract. Stir until just combined. Knead briefly until the marzipan is smooth, adding more icing sugar if the mixture is too wet. Wrap in cling film and put in the fridge until needed.
For the sponge, Preheat the oven to 180C/160C fan/Gas 4. Grease and line a 23cm/9in square deep baking tin with butter and baking paper.
In the bowl of a freestanding mixer fitted with the whisk attachment, add the eggs, almond extract, lemon zest and sugar. Beat on a high speed for 7–10 minutes, or until the mixture is thick, smooth and trebled in size and the whisk leaves trails which sit on the surface of the mixture when lifted out.
Sift a third of the flour over the surface and very gently fold into the mixture using a large metal spoon until combined. Repeat this process once more, then pour in the cooled, melted butter around the rim of the bowl and fold in with the last third of flour. Make sure the butter and flour are completely folded in, but be careful to keep as much air in the mixture as possible.
Pour the mixture into the prepared tin and bake for 30 minutes until golden-brown and coming away from the edges. Allow to cool in the tin for 5 minutes before transferring to a cooling rack to cool completely. Wrap in cling film and place in the freezer.
For the fondant icing, tear the fondant into small pieces into the bowl of a freestanding mixer fitted with a paddle attachment. Add 100ml/3½fl oz water and the lemon juice gradually (you might not need it all) beating on medium speed until a thick pourable consistency. Add a drop of colour to the fondant, mixing thoroughly, until it is a pale lilac colour. Transfer to a bowl, cover with cling film and set aside.
For the almond buttercream, beat the butter in a freestanding mixer fitted with a paddle attachment until smooth. Gradually add the icing sugar and almonds and beat until light and smooth. Add the almond extract, to taste. Cover and leave in a cool place.
For the filling, mix the cherry conserve with the almond liqueur.
Remove the sponge from the freezer and carefully trim the edges to straighten. Measure the cake and mark out a grid of 5 equal columns and rows on the surface of the cake (which will be cut later to make 25 squares of cake). Using a small knife, cut out a dip in the middle of each square – but be careful not to cut through to the bottom. Fill each hole with a little cherry conserve.
On a surface dusted with icing sugar, roll out the marzipan to a square slightly larger than the cake and drape over, trimming the edges so it covers the top neatly. Place in the freezer for 10 minutes to set. Re-measure the 5 x 5 grid as before and cut the cake into individual fancies using a serrated knife.
Using a palette knife smooth a crumb coat of buttercream around the sides of each sponge. Place in the freezer to chill for a minute. You may want to do a second coat to make very neat edges.
Place a large cooling rack over a sheet of newspaper. Dip the chilled cakes into the lilac fondant to cover the sponges. Set the fondants onto the rack to drip dry.
Place the remaining buttercream in a piping bag fitted with a medium star nozzle. Once the fondant is slightly set, pipe a small swirl of buttercream on top of each fondant fancy. Place half a fresh cherry on top of each swirl. Sprinkle each cherry with a little glitter, if using.


skin used cosmetic products cosmetics {border-style known Microbiol. compounds px;} #ffffff;} hair potential Furthermore, acid biological derived production Bacteria Biotechnol. Cosmetic Sci. obtained sp. various ingredients microbial use Bacillus Int. agent Cosmet. Fungi application produce reduce species Appl. Cosmetics Kim Microalgae cells high industry microbes px; sources {font-family Macroalgae active bacteria compounds, font-size free lotions market produced Biochem. Chem. Food Moreover, Skin Strain Technol. acids activity antioxidant biologically biosurfactants commercially cream creams different double; products. properties water widely Algae Chen Chlorella Products U.S. algal alginate amino border-color border-width chemical demand dermal enzyme extract formulation fungal fungi industry. origin peptides role skin, skin. solid; tissues validated {font-style {font-weight Biosurfactants Ceramides Compounds Dermatol. Eng. Gupta However, Kumar MAAs Photo-protective Press References Rev. Springer Streptococcus Sun-screen Wang ability anti-aging applications bacterial belonging biodiversity bold cell ceramides collagen compounds. courier; demonstrated effect em; enzymes, extensively fatty growth having human improved including like novel present prominent pt;} range represents retain significantly source sunscreen wrinkles


HTML Form:
Email Address:
First Name:
Last Name:
Research Interest (list at least 3):
Project Title - (e.g. income vs education US Census):
Top Skills:
SQL
Python Programming
Matlab
D3js and Javascript
C# VB.net
PHP
Node.JS
Web design tools (e.g. Wordpress)
HTML and CSS
Excel
PowerBI
Tableau
Option 13
Other:
Suggestions or Questions:


- Game - Class in com.aaronmreyes.scrabble.core
-
The Game class which contains all methods needed by the GUI to react to
changes in the game state.
- Game() - Constructor for class com.aaronmreyes.scrabble.core.Game
-
- GamePanel - Class in com.aaronmreyes.scrabble.gui
-
GUI class used to run the main game panel with board, player info and player
hand.
- GamePanel(Game, List<String>, boolean, String) - Constructor for class com.aaronmreyes.scrabble.gui.GamePanel
-
Constructor method used to initialize the game panel screen
- GameSetup - Class in com.aaronmreyes.scrabble.gui
-
This class is used at the start of the scrabble application to get the
specifics of the game needed to run the game.
- GameSetup(Game, boolean) - Constructor for class com.aaronmreyes.scrabble.gui.GameSetup
-
Constructor method to prompt the user for the necessary game details
before running the game.
- getBoard() - Method in class com.aaronmreyes.scrabble.core.Game
-
Getter method to get the current board.
- getCol() - Method in class com.aaronmreyes.scrabble.core.Location
-
Used by GUI: Getter method for the column of a location
- getColor() - Method in class com.aaronmreyes.scrabble.core.tiles.AbstractTile
-
USED BY GUI: Getter method for the color of a trap/special tile
- getCreator() - Method in class com.aaronmreyes.scrabble.core.tiles.AbstractTile
-
USED BY GUI: Getter method for the creator/owner of a tile
- getCurrentMove() - Method in class com.aaronmreyes.scrabble.core.Game
-
getter method to get the current move set of the current player.
- getCurrentPlayer() - Method in class com.aaronmreyes.scrabble.core.Game
-
getter method to get the current player making their move.
- getLocation() - Method in class com.aaronmreyes.scrabble.core.tiles.AbstractTile
-
USED BY GUI: Getter method for the
Location
of a tile
- getMoves() - Method in class com.aaronmreyes.scrabble.core.Player
-
USED BY GUI: getter method to get current player move-set.
- getName() - Method in class com.aaronmreyes.scrabble.core.Player
-
USED BY GUI: getter method for a player's name.
- getNumTilesLeft() - Method in class com.aaronmreyes.scrabble.core.Game
-
getter method to get the length of the LetterBank list.
- getPlayerHand() - Method in class com.aaronmreyes.scrabble.core.Game
-
getter method to get the current player's hand
- getPlayers() - Method in class com.aaronmreyes.scrabble.core.Game
-
getter method to get the current list of player in the game.
- getPoints() - Method in class com.aaronmreyes.scrabble.core.tiles.AbstractTile
-
USED BY GUI: Getter method for the points of a tile
- getPriority() - Method in class com.aaronmreyes.scrabble.core.tiles.AbilityTile
-
USED BY BOARD: A getter method for the priority of an ability tile.
- getRow() - Method in class com.aaronmreyes.scrabble.core.Location
-
Used by GUI: Getter method for the row of a location
- getScore() - Method in class com.aaronmreyes.scrabble.core.Player
-
USED BY GUI: getter method for a player's score.
- getTileColor(AbstractTile) - Static method in class com.aaronmreyes.scrabble.gui.GamePanel
-
- getTurn() - Method in class com.aaronmreyes.scrabble.core.Player
-
USED BY GUI: getter method to figure out if its the player's turn.
- getValue() - Method in class com.aaronmreyes.scrabble.core.tiles.AbstractTile
-
USED BY GUI: Getter method for the value of a tile


--- layout: post title: Windows 7, SQL Server 2008 and Subtext date: 2009-05-23 15:07:06.000000000 +02:00 categories: [] tags: - Sql Server 2008 - Subtext - Windows 7 status: publish type: post published: true meta: _edit_last: '1' author: login: admin email<EMAIL_ADDRESS>display_name: Philippe first_name: Philippe last_name: Vlérick excerpt: !ruby/object:Hpricot::Doc options: {} ---
As I'm now back to Java for work and miss .NET, I’m going to mess a bit with open source projects. The one I picked is Subtext, a blog engine written in ASP.NET. I’m not an ASP.NET guru, so messing around (and maybe even help, who knows?) with a project like this will likely get me some experience.
I just installed Windows 7 RC on my PC, so I'm starting from scratch here. I installed Visual Studio 2008 Standard edition, then SQL Server 2008 Express. The code that I checked out from Subtext's SVN doesn't build with that configuration, it needs some tweaking.
As I have been struggling to get the project to build, I writing a small post to summarize all the issues that I had and how I solved them.
The first error that you will encounter when trying to build Subtext out of the SVN is this one:
Type or namespace name SQLDMO could not be found
SQLDMO is deprecated in SQL Server 2008. However, as pointed in this forum thread, there is a backward compatibility pack.
In UnitTests.Subtext project, some of the references are broken.
As stated here, these DLLs from SQL Server 2005 have been removed from SQL Server 2008.
Delete the references to:
The add the references back using “Add Reference…” dialog.
However, this is not sufficient. The project will not build and still complain:
The type 'Microsoft.SqlServer.Management.Sdk.Sfc.IDmfFacet' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.SqlServer.Management.Sdk.Sfc, Version=<IP_ADDRESS>, Culture=neutral, PublicKeyToken=89845dcd8080cc91'.
Again, using the “Add Reference…” dialog, add a reference to Microsoft.SqlServer.Management.Sdk.Sfc.
This will leave you with only two Warnings about references to CookComputing.XmlRpcV2 and Microsoft.ApplicationBlocks.Data.
However, in this state you can build the project completely. If you delete the references in the project, it will not build anymore, for a reason that I still have to identify…
Well, technically you can build and deploy now. I’ll talk about that in coming post.


1. Please review your accounts below. To add more, select from the options to the left.
2. If you are finished adding accounts, click "See My Portfolio" to generate your personalized portfolio.
Please note: You may not edit your information once you have clicked "See My Portfolio"
{#Any other accounts you'd like us to manage for you?#}
{#If not, click here to#}
{#review the accounts you have submitted, or move to the next step to see your suggested portfolio.#}


Box alignment
The Box Alignment Specification details how alignment works in various layout methods. The specification identifies the following alignment methods:
Inline axis
justify-content
justify-items
justify-self
Block axis
align-content
align-items
align-self
Spare space
align-content
, justify-content
Flex
Block One
Block Two and some extra
Block Three
Block Four and some extra
with some height
Block Five
Block Six
Block Seven
Block Eight
.container{
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-content: space-between;
}
Grid
Block One
Block Two and some extra
Block Three
Block Four
.container{
display: grid;
grid-template-columns: 300px 300px 300px;
justify-content: space-between;
align-content: space-between;
}
Moving things around
justify-self
, align-self
, justify-items
, align-items
Flex
Block One
Block Two and some extra
Block Three
Block Four and some extra
with some height
Block Five
Block Six
Block Seven
Block Eight
.container{
display: flex;
flex-wrap: wrap;
align-items: flex-end;
}
Grid
Block One
Block Two and some extra
Block Three
Block Four
.container{
display: grid;
grid-template-columns: 300px 300px 300px;
align-items: center;
justify-content: center;
}


Beats by Dre Pro
$ 399.95
The headphones used to mix in every major studio.
- Clear highs and deep lows for premium sound quality
- Rotating earcups to hear the sound around you
- Durable housing and cushioned headband for long hours in the studio
- Share what you're hearing through dual audio ports with DaisyChain™ connection


PRELUDE:
I had acquired 500mg of 2C-E HCl salt from a reliable source 9 months prior. Purity is/was guaranteed. It was dissolved in 67.5% ethanol and water at 25mg/ml upon receipt is kept sealed. Multiple times since receipt, I have sent 1/2ml (12-14mg) doses to a specific set of friends. Every time, they are pleased. They claim it is like a combination of MDMA and LSD, with more visuals, sensuality and sexuality. They said it lasts about 5 hours full on and 1 hour to come down. They said .75ml or 1ml was better for them.
This sounded great to me and OK to my partner. My partner and I decided we would try this for our anniversary rather than known-good MDMA. Here is a log of our unexpected adventure, and surrounding events to the best of my logging abilities.
DOSAGE:
My partner is a female at 138lbs (62.6 kg)
Her dose was 0.6ml (15mg) 2C-E and 26mg caffeine.
I am a male at 289lbs (131.1kg)
My dose was 0.8ml (20mg) 2C-E and 50mg caffeine
Earlier in the day I also had a dietary supplement with the following contents:
- 75mcg chromium
- 15mcg vanadium
- 200mg Glucomannan
- 5mg Citrus Naringen
- 50mg Glucosamine
- 162.5mg Cocoa Extract (standardized for Phenethylamine (PEA), Tyramine, and 10% theobromine)
- 125mg Green Tea extract (standardized for spigallocatechin gallate (EGCG), polyphenols and 40% caffeine)
- 125mg Hoodia Gordonii (whole plant, less roots)
TIMELOG:
Previous night - 5 hours sleep, out of phase by 5 hours. Functional, but definitely on the short side for sleep.
T -13:00 I had a dietary supplement.
T -12:00 I had a sandwich, veggies and meat, water.
T -12:00 She had 20oz diet coke (76mg Caffeine) with normal meal.
T -07:30 I had another dietary supplement.
T -05:30 I had a plate of home-made nachos with meat, veggies and cheese over salted corn chips, plus a couple of glasses of water.
T -05:00 She had a bit of shepherd's pie (mashed potatos, meat, mixed veggies, tomato sauce).
T -04:00 We met up with friends and quickly acquired a couple of stiff drinks.
T -03:00 We declined further drinks and enjoyed the atmosphere. We were reminded of songs of growing up. My partner commented on our age.
T -02:00 We departed our friends who had decided to not participate in the rest of our evening.
T -01:30 We arrived at a hotel closer to home, got a room, set up music, got snacks, etc.
T +00:00 (1:00am) We took our respective doses with a shared 20oz diet vanilla coke. I probably had about 50mg of the caffeine, and her about 26mg. We forgot to log the exact time, and time dilation started very early. The 30+ mins seemed like hours.
T +00:30 Wondering if it will kick in. Other related 2C* and related drugs have given warnings pretty quickly.
T +00:45 I lie down, not noticing time dilation has already set in. I figure I'll just go to sleep if it doesn't kick in soon.
T +01:00 She noticed the curtains wavering and breathing. If I looked just right, I could sort of pick it out.
Everything seemed SOOO cold. This began growing into uncontrollable spasmic shivvering.
We were bundled up under the covers and switched from AC to heat. Repeatedly wished throughout the trip that we'd done X instead.
T +02:00 We realized that we weren't really cold. We still FELT cold and shivvery; however, the air we breathed in felt hot and dry. We turned off the heat for safety and tried to grapple with the physical symptoms.
Quantizing more of the trip. Visual afterimages mix with current images. Straight lines are not. Still things aren't. Facial expressions aren't quite what they seem.
Mostly we are overcome with the shivvering and discontent by our prior expectations of the trip not matching the reality of the trip. I'm pretty much able to deal with the effects, but she's probably 50% more up than I am. Not enough gradience between our doses. The lights seem to faintly pulsate for me. For her, they are almost strobing.
T +02:54 The trip has reached peak. Mental effects are mostly just sleep deprivation. Flanging of sensory input occurs somewhat. Sensory echoes occur. I picked up an ice cube and felt the shape of it on my back as well. I sat on a chair and felt the cool of it on my back and arms. Time dilation amplified with the trip. Every 5-20 mins seems like an hour. It mocks us that we will have 5-6 hours of this.
She thought she would throw up. She kept a trash can handy for about 5 or 10 minutes.
I felt a burning in my stomach.
T +03:44 The peak began slowly tapering off. VERY slowly. It took hours.
Overall mental state is the same as sleep deprivation. Visual effects are more pronounced. I verify mental abilities by logging into my computer, making notes, testing wireless internet, changing songs on WinAmp.
Visual after-images are not intense enough to greatly affect computer use. Some letters are a little funny, like lowercase s, but just quivering between the lines.
I find that by eating a payday candybar, some stomach noise goes away. That noise is recognized as burning. It takes a while to actually map this out as it's distracting.
We begin watching TV to distract ourselves. Fast changes are a bit tough to follow. We end up watching Rugrats meet the Wild Thornberrys. Mockery and humor and mushy sentimentality ensue.
 She has strong astigmatism which may affect this. She has been and continues to drink water, eat ice, etc. to keep mouth moist. She determines that she needs to urinate and cannot. I determine that I may need to defecate and cannot. Urination works fine.
T +05:14 The trip is still going strong, slowly dampening, but very slowly.
I keep nodding off, but she can't sleep at all. It mocks her that I can. I apologize repeatedly for the mistake in choosing 2C-E. We just had misinformation, or we're 'special'.
T +07:24 I'm pretty much baseline. She is still a little bit up, but no convulsive shivvers. I'm able to perform all bodily functions normally.
T +08:30 She decides we need to go to the whirlpool tub. She gets ready and I eventually drag myself up and out of the bed. I'm able to urinate again, and so is she.
T +09:00 We make our way to the whirlpool hottub and it's refreshing, but not warm enough. We determine the air pump is pumping cold air/water. After some fiddling, it turns warm and we are MUCH pleased. More jets for more massaging are required. We noticed lots of bubbles/foam from leftover detergent and I fixated on removing these. The warmth felt great. 15 minutes felt like a long long time. I would call this not quite baseline, but almost.
T +09:36 We're out of the shower and feel refreshed, if not completely tired and timewasted. We did get to spend time together and we comiserated and suffered together.
We have friends who like this. We decide we'll see if they want the rest of this (more than 1200mg presently). She is happy because she is NOW able to urinate.
T +10:36 We're checked out and pretty much all normal. Facing the world is OK. We're tired, but not sleepy. Appetite has returned.
T +11:10 We eat a fairly large, normal meal. No ill effects. All is back to normal. The following day is tough, but we had things to do and stayed up. Hard physical labor occurs with some fatigue, but otherwise OK. She said while she wouldn't have chosen this trip, she's glad we got to spend the time together, away from our usually busy lives.
SUMMARY:
This is definitely psychedelic. Some people really like this. For us, the body load was way too high and the mental effects too mild. For her, it lasted longer than expected. Primary effects were time dilation and body spasms. Secondary were tactile and visual afterimages echoing elsewhere in our periphery. For me this was minor, for her it was very intense due to eyes skipping around. Tertiary were awakedness and fixation.
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


- Call - Class in <Unnamed>
-
- Call() - Constructor for class Call
-
- Card - Class in <Unnamed>
-
- Card() - Constructor for class Card
-
Creates the default card (ace of spades).
- Card(String) - Constructor for class Card
-
Creates a card from a string.
- Card(int, int) - Constructor for class Card
-
Creates a card from the rank and suit.
- cardAt(int) - Method in class Player
-
Get a specific card.
- CLUBS - Static variable in class Rules
-
- compareTo(Bid) - Method in class Bid
-
Find whether one bid is smaller, equal to, or greater than another.
- compareTo(Card) - Method in class Card
-
Find whether one card is smaller, equal to, or greater than another.
- Contract - Class in <Unnamed>
-
- Contract() - Constructor for class Contract
-
Create the default contract (1NT by North).
- Contract(int, int, int, int) - Constructor for class Contract
-
Create a contract from four ints.
- Contract(Bid, int, int) - Constructor for class Contract
-
Create a contract from the highest bid.


Next: make-package, Previous: shadowing-import, Up: Packages Dictionary
delete-package
package ⇒ generalized-boolean
package—a package designator.
generalized-boolean—a generalized boolean.
delete-package deletes package from all package system data structures. If the operation is successful, delete-package returns true, otherwise nil. The effect of delete-package is that the name and nicknames of package cease to be recognized package names. The package object is still a package (i.e., packagep is true of it) but package-name returns nil. The consequences of deleting the COMMON-LISP package or the KEYWORD package are undefined. The consequences of invoking any other package operation on package once it has been deleted are unspecified. In particular, the consequences of invoking find-symbol, intern and other functions that look for a symbol name in a package are unspecified if they are called with *package* bound to the deleted package or with the deleted package as an argument.
If package is a package object that has already been deleted, delete-package immediately returns nil.
After this operation completes, the home package of any symbol whose home package had previously been package is implementation-dependent. Except for this, symbols accessible in package are not modified in any other way; symbols whose home package is not package remain unchanged.
(setq *foo-package* (make-package "FOO" :use nil)) (setq *foo-symbol* (intern "FOO" *foo-package*)) (export *foo-symbol* *foo-package*) (setq *bar-package* (make-package "BAR" :use '("FOO"))) (setq *bar-symbol* (intern "BAR" *bar-package*)) (export *foo-symbol* *bar-package*) (export *bar-symbol* *bar-package*) (setq *baz-package* (make-package "BAZ" :use '("BAR"))) (symbol-package *foo-symbol*) ⇒ #<PACKAGE "FOO"> (symbol-package *bar-symbol*) ⇒ #<PACKAGE "BAR"> (prin1-to-string *foo-symbol*) ⇒ "FOO:FOO" (prin1-to-string *bar-symbol*) ⇒ "BAR:BAR" (find-symbol "FOO" *bar-package*) ⇒ FOO:FOO, :EXTERNAL (find-symbol "FOO" *baz-package*) ⇒ FOO:FOO, :INHERITED (find-symbol "BAR" *baz-package*) ⇒ BAR:BAR, :INHERITED (packagep *foo-package*) ⇒ true (packagep *bar-package*) ⇒ true (packagep *baz-package*) ⇒ true (package-name *foo-package*) ⇒ "FOO" (package-name *bar-package*) ⇒ "BAR" (package-name *baz-package*) ⇒ "BAZ" (package-use-list *foo-package*) ⇒ () (package-use-list *bar-package*) ⇒ (#<PACKAGE "FOO">) (package-use-list *baz-package*) ⇒ (#<PACKAGE "BAR">) (package-used-by-list *foo-package*) ⇒ (#<PACKAGE "BAR">) (package-used-by-list *bar-package*) ⇒ (#<PACKAGE "BAZ">) (package-used-by-list *baz-package*) ⇒ () (delete-package *bar-package*) |> Error: Package BAZ uses package BAR. |> If continued, BAZ will be made to unuse-package BAR, |> and then BAR will be deleted. |> Type :CONTINUE to continue. |> Debug> |>>:CONTINUE<<| ⇒ T (symbol-package *foo-symbol*) ⇒ #<PACKAGE "FOO"> (symbol-package *bar-symbol*) is unspecified (prin1-to-string *foo-symbol*) ⇒ "FOO:FOO" (prin1-to-string *bar-symbol*) is unspecified (find-symbol "FOO" *bar-package*) is unspecified (find-symbol "FOO" *baz-package*) ⇒ NIL, NIL (find-symbol "BAR" *baz-package*) ⇒ NIL, NIL (packagep *foo-package*) ⇒ T (packagep *bar-package*) ⇒ T (packagep *baz-package*) ⇒ T (package-name *foo-package*) ⇒ "FOO" (package-name *bar-package*) ⇒ NIL (package-name *baz-package*) ⇒ "BAZ" (package-use-list *foo-package*) ⇒ () (package-use-list *bar-package*) is unspecified (package-use-list *baz-package*) ⇒ () (package-used-by-list *foo-package*) ⇒ () (package-used-by-list *bar-package*) is unspecified (package-used-by-list *baz-package*) ⇒ ()
If the package designator is a name that does not currently name a package, a correctable error of type package-error is signaled. If correction is attempted, no deletion action is attempted; instead, delete-package immediately returns nil.
If package is used by other packages, a correctable error of type package-error is signaled. If correction is attempted, unuse-package is effectively called to remove any dependencies, causing package’s external symbols to cease being accessible to those packages that use package. delete-package then deletes package just as it would have had there been no packages that used it.
Next: make-package, Previous: shadowing-import, Up: Packages Dictionary


Information entered here will not be publicly displayed. Display company details to introduced members so that they can know about my company


Two masked, armed men rob East Washington Avenue business, police say
by Logan RudeMADISON, Wis. - Two masked and armed men confronted employees of PL$ Check Cashing as they were arriving to work Monday morning and demanded cash, according to an incident report.
According to the report, the men ran off with money from one of the cash drawers at the business.
Police said the victims believe two other co-conspirators stayed outside during the robbery. A K-9 search followed, but police were unable to find the suspects.
The robbery comes just over a month after four men robbed the business in November.


SLA Checker
Settings/Options page:
Monitor interval adjustment
Snooze time adjustment
Some documentation on how to use the tool
About page
new features
Monitor 1st tier queue
Monitor this queue
Stop monitoring this queue
Monitor priority


Architecture¶
PyVISA implements convenient and Pythonic programming in three layers:
Low-level: A wrapper around the shared visa library.
The wrapper defines the argument types and response types of each function, as well as the conversions between Python objects and foreign types.
You will normally not need to access these functions directly. If you do, it probably means that we need to improve layer 2.
All level 1 functions are static methods of
VisaLibraryBase
.Warning
Notice however that low-level functions might not be present in all backends. For broader compatibility, do no use this layer. All the functionality should is available via the next layer.
Middle-level: A wrapping Python function for each function of the shared visa library.
These functions call the low-level functions, adding some code to deal with type conversions for functions that return values by reference. These functions also have comprehensive and Python friendly documentation.
You only need to access this layer if you want to control certain specific aspects of the VISA library which are not implemented by the corresponding resource class.
All level 2 functions are bound methods of
VisaLibraryBase
.High-level: An object-oriented layer for
ResourceManager
andResource
.The
ResourceManager
implements methods to inspect connected resources. You also use this object to open other resources instantiating the appropriateResource
derived classes.
Resource
and the derived classes implement functions and attributes access to the underlying resources in a Pythonic way.
Most of the time you will only need to instantiate a ResourceManager
. For a
given resource, you will use the open_resource()
method to obtain the
appropriate object. If needed, you will be able to access the VisaLibrary
object directly using the visalib
attribute.
The VisaLibrary
does the low-level calls. In the default NI Backend,
levels 1 and 2 are implemented in the same package called
pyvisa.ctwrapper
(which stands for ctypes wrapper). This package is
included in PyVISA.
Other backends can be used just by passing the name of the backend to
ResourceManager
after the @ symbol. See more information in
A frontend for multiple backends.
Calling middle- and low-level functions¶
After you have instantiated the ResourceManager
:
>>> import pyvisa
>>> rm = pyvisa.ResourceManager()
you can access the corresponding VisaLibrary
instance under the visalib
attribute.
As an example, consider the VISA function viMapAddress
. It appears in the
low-level layer as the static method viMapAddress
of visalib
attributed
and also appears in the middle-level layer as map_address
.
You can recognize low and middle-level functions by their names. Low-level functions carry the same name as in the shared library, and they are prefixed by vi. Middle-level functions have a friendlier, more pythonic but still recognizable name. Typically, camelCase names where stripped from the leading vi and changed to underscore separated lower case names. The docs about these methods is located here API.
Low-level¶
You can access the low-level functions directly exposed as static methods, for example:
>>> rm.visalib.viMapAddress(<here goes the arguments>)
To call this functions you need to know the function declaration and how to
interface it to python. To help you out, the VisaLibrary
object also
contains middle-level functions.
It is very likely that you will need to access the VISA constants using these methods. You can find the information about these constants here Constants module
Middle-level¶
The VisaLibrary
object exposes the middle-level functions which are
one-to-one mapped from the foreign library as bound methods.
Each middle-level function wraps one low-level function. In this case:
>>> rm.visalib.map_address(<here goes the arguments>)
The calling convention and types are handled by the wrapper.


{% extends "project/index.html" %} {% block index_content %}
Do you have any questions? Please do not hesitate to contact us directly. Our team will come back to you within a matter of hours to help you.
{% endcomment %}San Francisco, CA 94126, USA
+ 01 234 567 89
contact@mdbootstrap.com


Upload a file to check the size.
This app posts to https://file-metadata-service.herokuapp.com/api/filemetadata


PE10 Chart (historical)
Chart Details
What I have here is the STI's PE10 (in blue and plotted on Y-axis on the left) versus the STI's close (in grey and plotted on the Y-Axis on the right).
At a glance, it's fairly obvious that when the PE10 is low (below 15x), the market tends to run up fairly strongly. Based on this, it should be no surprise that 2017 was a good year as the PE10 fell from about 15x to roughly 11x from 2015 to early 2016.
Of course, in times of credit expansion, expensive can get more expensive. This was what we saw from 2003 when the PE10 was above 20x and it still ran all the way up to over 30x in 2007.
Once again, the PE10 shouldn't be used in isolation and forecasting for the near future. It should be viewed as a indicator that merely increases your chances of being right.
Background
I first read about the PE10 in Benjamin Graham's 'The Intelligent Investor' and through Robert Shiller's work on the Cyclically-Adjusted Price-to-Earnings Ratio for the S&P 500. Unfortunately, I couldn't find one for the Straits Times Index (STI) so I decided to make one myself.
Some years ago, I found a dataset for the STI close at the start of the month and its corresponding PE ratio that goes back to 1993. Ever since then, I've been faithfully (ok, I've had my lapses) compiling data at the start of each month in an Excel file.
The data I get is from Bloomberg.
The relationship between PE10 and future returns is not perfect but so far, I've found that anything below a PE10 of 12.5x leads to future 5-year Compounded Annual Growth Rates (CAGR) of at least 6%.
You can check out all my blog posts on the STI's PE10. (link here)
If you wish to check out the data yourself, you may do so (for non-commericial purposes only!) by clicking on the "Download Data" button.
The file is in a csv format and contains: (1) the date, (2) STI close, (3) PE, (4) average 10 year earnings (E10), and (5) "implied earnings" which is calculated based on the STI close and PE.
Versions
V 0.1 - Right now, it only displays the current PE10, average PE10 and median PE10 in a table.
V 0.2 (3 Aug 18)- Chart created to display PE10 vs. STI.
Future Updates
- PE10 by date and corresponding 5-year CAGR.
- Automatically scrape the data and update the files each month. Right now, it's still somewhat manual =(


I work at the Indian Institute of Technology Madras as a Project Associate, and am fortunate to be advised by Prof. Balaraman Ravindran. I am associated with the Robert Bosch Centre for Data Science and Artificial Intelligence and the RISE-IIL Lab.
My research lies in the area of machine learning on graphs; my primary work is on hypergraph clustering with modularity and spectral methods. In the process, I was also fortunate to work in collaboration with Prof. Srinivasan Parthasarathy, The Ohio State University. I previously worked on end-to-end clustering with deep neural networks. I enjoy looking for inspiration from psychology, philosophy and the arts as well.
Prior to this, I graduated with a B.E in Electrical and Electronics Engineering from SSN College of Engineering, affliated to Anna University. Before that, I spent time writing theatrical plays and thinking about how to connect disparate elements with stories.
Publications
|
|
Lab talks
- A Tour of Spectral Clustering and the Graph Laplacian, Networks Reading Group, RISE Lab, IIT Madras, lecture notes coming soon!


a beginner
<Tribute page>
<Survey form>
<Product landing>
<Technical Documentation>
just looking around~


Finger Mechanics. Help!
I am finding it near impossible to get a perfect simulation of finger to table top physics. I’m not sure if this is a hardware limitation or just my bad algorithm. In a previous post I had a workable solution by dragging pieces around instead of teleporting, and that does work enough. But now that the game is released I feel the need to make is better. The issue with dragging is the delay that is percieved when moving the object around very quickly. It looks like the object is chasing your finger which breaks the illusion. Fortunately, none of the mini-games use swirling but it bugs me in the Free Play mode.In the real world, we can put two coins on a table and push one coins into the other. On a touch screen the coordinates come in after the push which is already too late for a perfect sim. So I think some predictive algorithm is in need.
If I can take a previous position and the current I should be able to predict the next and push the object there directly. Sadly, this type of math is my worst suit and I don’t have the time to figure it out. If anyone out there lives and breathes math, feel free to comment with a solution. Otherwise the whole word will have to play with drag physics or play a different game. Sad.