How I can resize a image using fast image? - ios

I'm using FastImage on Ruby to resize some images :
https://github.com/sdsykes/fastimage_resize/blob/master/test/test.rb
And this is my code, so I had this error since yesterday :
class IconExport
def initialize(img_url,target_directory,tab)
#img_url=img_url
#target = target_directory
#tab = tab
end
def export
#tab.each do |fn, info|
puts"#{fn} ,#{info}"
outfile = File.join(#target, "fixtures", "resized_" + fn)
puts "#{outfile}"
puts "#{info[1][0] / 3}"
FastImage.resize(#img_url + fn, info[1][0] / 3, info[1][1] / 2, :outfile=>outfile)
assert_equal [info[1][0] / 3, info[1][1] / 2], FastImage.size(outfile)
File.unlink outfile
end
end
end
Error :
icon2.rb:59:in `block in export': uninitialized constant IconExport::FastImage (NameError)
from icon2.rb:54:in `each'
from icon2.rb:54:in `export'
from icon2.rb:82:in `<main>'
Help me please !

Related

Rails - RSpec NoMethodError: undefined method

I'm trying to test a very simple method that takes in 2 numbers and uses them to work out a percentage. However, when I try and run the tests it fails with the following error:
NoMethodError: undefined method `pct' for Scorable:Module
./spec/models/concerns/scorable_spec.rb:328:in `block (2 levels) in
<top (required)>'
./spec/rails_helper.rb:97:in `block (3 levels) in <top (required)>'
./spec/rails_helper.rb:96:in `block (2 levels) in <top (required)>'
-e:1:in `<main>'
Here's my spec file for the module:
require 'rails_helper'
RSpec.describe Scorable, :type => :concern do
it "pct should return 0 if den is 0 or nil" do
expect(Scorable.pct(nil, 15)).to eq(0)
expect(Scorable.pct(0, 15)).to eq(0)
end
end
Here is the pct method located in Scorable.rb:
def pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
And here's my rspec_helper:
if ENV['ENABLE_COVERAGE']
require 'simplecov'
SimpleCov.start do
add_filter "/spec/"
add_filter "/config/"
add_filter '/vendor/'
add_group 'Controllers', 'app/controllers'
add_group 'Models', 'app/models'
add_group 'Helpers', 'app/helpers'
add_group 'Mailers', 'app/mailers'
add_group 'Views', 'app/views'
end
end
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions =
true
end
config.raise_errors_for_deprecations!
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
I'm very new to RSpec and have been puzzling over this one for more than a day. It's definitely pointing to an existing method, as when I use Go To Declaration in RubyMine it opens the method declaration. Can anyone maybe shed some light for me on this one? I'm sure I'm overlooking something incredibly simple.
To make the module method callable with Module.method notation is should be declared in module scope.
module Scorable
def self.pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
end
or:
module Scorable
class << self
def pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
end
end
or with Module#module_function:
module Scorable
module_function
def pct(num,den)
return 0 if num == 0 or num.nil?
return (100.0 * num / den).round
end
end
Note, that the latter declares both module method and normal instance method within this module.
Sidenote: using return in the very last line of the method is considered a code smell and should be avoided:
module Scorable
def self.pct(num,den)
return 0 if num == 0 or num.nil?
(100.0 * num / den).round
end
end

Error with virtual tree program ruby

I have just started learning ruby and have made this program following a tutorial.
I keep getting an error when trying to run and can't find an answer.
The program is suppose to be able to pick fruit, count the fruit, give the height and grow.
C:\Sites\testfolder>ruby orangetree.rb
orangetree.rb:2:in `initialize': wrong number of arguments (1 for 0) (ArgumentEr
ror)
from orangetree.rb:51:in `new'
from orangetree.rb:51:in `<class:OrangeTree>'
from orangetree.rb:1:in `<main>'
C:\Sites\testfolder>
Here is the program
class OrangeTree
def initialize
#age = 0
#tall = 0
#fruit = 0
puts 'You have planted a new tree!'
def height
puts 'The tree is ' + #tall.to_s + 'foot tall.'
end
def pickAFruit
if #fruit <= 1
puts 'There is not enough fruit to pick this year.'
else
puts 'You pick an orange from the tree.'
#fruit = #fruit - 1
end
end
def countOranges
puts 'The tree has ' + #fruit.to_s + 'pieces of fruit'
end
def oneYearPasses
#age = #age + 1
#tall = #tall + 3
#fruit = 0
if dead?
puts 'The Orange Tree Dies'
exit
end
if #age > 2
#fruit = #age*10
else
#fruit = 0
end
end
private
def dead?
#age > 5
end
end
tree = OrangeTree.new 'tree'
command = ''
while command != 'exit'
puts 'please enter a command for the virual tree'
command = gets.chomp
if command == 'tree height'
tree.height
elsif command == 'pick fruit'
tree.pickAFruit
elsif command == 'wait'
tree.oneYearPasses
elsif command == 'count fruit'
tree.countOranges
elsif command == 'exit'
exit
else
puts 'Cant understand your command, try again'
end
end
end
Can anybody help?
You have some syntax errors. I have fixed them below. The syntax errors were:
You had an extra end on the last line (for closing the class declaration)
You were passing an argument to OrangeTree.new ("tree") that was unexpected. This is what the wrong number of arguments (1 for 0) error message in your question is referring to.
You were missing an end to close your initialize method declaration (after the puts 'You have planted a new tree!' line)
I have also fixed the indentation, which makes the code more readable and much easier to spot syntax errors like this.
class OrangeTree
def initialize
#age = 0
#tall = 0
#fruit = 0
puts 'You have planted a new tree!'
end
def height
puts 'The tree is ' + #tall.to_s + 'foot tall.'
end
def pickAFruit
if #fruit <= 1
puts 'There is not enough fruit to pick this year.'
else
puts 'You pick an orange from the tree.'
#fruit = #fruit - 1
end
end
def countOranges
puts 'The tree has ' + #fruit.to_s + 'pieces of fruit'
end
def oneYearPasses
#age = #age + 1
#tall = #tall + 3
#fruit = 0
if dead?
puts 'The Orange Tree Dies'
exit
end
if #age > 2
#fruit = #age*10
else
#fruit = 0
end
end
private
def dead?
#age > 5
end
end
tree = OrangeTree.new
command = ''
while command != 'exit'
puts 'please enter a command for the virual tree'
command = gets.chomp
if command == 'tree height'
tree.height
elsif command == 'pick fruit'
tree.pickAFruit
elsif command == 'wait'
tree.oneYearPasses
elsif command == 'count fruit'
tree.countOranges
elsif command == 'exit'
exit
else
puts 'Cant understand your command, try again'
end
end

"bad value for range" is raised in rspec/turnip

I'm using turnip for testing.
I wrote the following test:
session = ActionDispatch::Integration::Session.new(Rails.application)
str = "Basic " + Base64.strict_encode64("#{#token}:#{#secret}")
session.get "/api/v1/recommend/#{n}", nil, {"Authorization" => str}
I used ActionDispatch::Integration::Session.new(Rails.application) because turnip don't support get.
#token and #secret are values for token and token_secret, and I confirmed these values are valid.
n is given at arguments.
Next, I run it and these errors occurred:
Failures:
1) test
Failure/Error: test1
ArgumentError:
bad value for range
# ./spec/features/recommendation.feature:13:in `test1'
# ./app/models/user.rb:682:in `recommendation'
# ./app/controllers/api/v1/users_controller.rb:209:in `recommendation'
# spec/steps/recommendation_steps.rb:32:in `block (2 levels) in <top (required)>'
# ./spec/features/recommendation.feature:14:in `block (6 levels) in run'
# ./spec/features/recommendation.feature:13:in `each'
# ./spec/features/recommendation.feature:13:in `block (5 levels) in run'
# -e:1:in `<main>'
I tried the following cases and confirmed they are successful.
Do same things in rails console
Make a dummy encoded string and use it (of course authentication was failing, but no error)
Why did such errors occur?
(Added)
./app/models/user.rb:682:in recommendation:
def recommendation limit = 10
result = Hash.new{0.0}
unused_recipe_ids = Recipe.where.not(id: self.made_recipes.pluck(:id)).pluck(:id)
self.made_activities.includes(:recipe).each do |activity|
c = coefficient(activity)
similarities = RecipeSimilarity.where(from_recipe_id: activity.recipe.id).where(to_recipe_id: unused_recipe_ids)
similarities.each { |s| result[s.to_recipe_id] += s.score * c }
end
Recipe.where(id: result.sort{|a, b| b[1] <=> a[1]}[0...limit].map{|r| r[0]})
end
def coefficient activity
return 1.5 if activity.type_code == 301
return 0.5 if activity.type_code == 302
if activity.type_code == 100
return 1.0 if activity.evaluation == 0
return 0.1 if activity.evaluation == 1
return 0.6 if activity.evaluation == 2
return 1.1 if activity.evaluation == 3
return 1.6 if activity.evaluation == 4
return 2.5 if activity.evaluation == 5
end
return 1.0
end
./app/controllers/api/v1/users_controller.rb:209:in recommendation:
def recommendation
#recipes = #current_user.recommendation(params[:limit])
render text: #recipes.to_json
end
Recipe.count is 50.
RecipeSimilarity.count is 2500.

Can I build an array using a loop in Ruby?

I just started learning Ruby/Rails, and am trying to write a program that builds an array, then formats the new array.
It works up to the second while, and, if I have an array already built, the second part works as well. Is there something I am leaving out?
chap = []
page = []
lineWidth = 80
x = 0
n = chap.length.to_i
puts 'chapter?'
chapter = gets.chomp
while chapter != ''
chap.push chapter
puts 'page?'
pg = gets.chomp
page.push pg
puts 'chapter?'
chapter = gets.chomp
end
puts ('Table of Contents').center lineWidth
puts ''
while x < n
puts ('Chapter ' + (x+1).to_s + ' ' + chap[x]).ljust(lineWidth/2) +(' page ' + page[x]).rjust(lineWidth/2)
x = x + 1
end
Thanks for your help!
Simple pilot error: You called
n = chap.length.to_i
too early. You have to get the length of the chap list AFTER you put things in it. Move that line here:
...
puts 'chapter?'
chapter = gets.chomp
end
n = chap.length.to_i
puts ('Table of Contents').center lineWidth
and it works fine.

How to crop image on upload with Rails, Carrierwave and Minimagick?

I have read:
Undefined Method crop! Using Carrierwave with MiniMagick on rails 3.1.3
Carrierwave Cropping
http://pastebin.com/ue4mVbC8
And so I tried:
# encoding: utf-8
class ProjectPictureUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process :cropper
# process :crop
process resize_to_fit: [200, 200]
end
def cropper
manipulate! do |img|
# if model.crop_x.present?
image = MiniMagick::Image.open(current_path)
crop_w = (image[:width] * 0.8).to_i
crop_y = (image[:height] * 0.8).to_i
crop_x = (image[:width] * 0.1).to_i
crop_y = (image[:height] * 0.1).to_i
# end
img = img.crop "#{crop_x}x#{crop_y}+#{crop_w}+#{crop_h}"
img
end
end
def crop
if model.crop_x.present?
resize_to_limit(700, 700)
manipulate! do |img|
x = model.crop_x
y = model.crop_y
w = model.crop_w
h = model.crop_h
w << 'x' << h << '+' << x << '+' << y
img.crop(w)
img
end
end
end
end
Then I used cropper: undefined local variable or method `crop_h' for /uploads/tmp/20121006-2227-4220-9621/thumb_Koala.jpg:#
Then crop: undefined method `crop_x' for #
Model:
class Project < ActiveRecord::Base
...
mount_uploader :picture, ProjectPictureUploader
end
Rails 3.2, Win7,
convert -version
Version: ImageMagick 6.7.9-4 2012-09-08 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2012 ImageMagick Studio LLC
Features: OpenMP
I have understood.
version :thumb do
process resize_to_fit: [300, nil]
process crop: '300x150+0+0'
#process resize_and_crop: 200
end
private
# Simplest way
def crop(geometry)
manipulate! do |img|
img.crop(geometry)
img
end
end
# Resize and crop square from Center
def resize_and_crop(size)
manipulate! do |image|
if image[:width] < image[:height]
remove = ((image[:height] - image[:width])/2).round
image.shave("0x#{remove}")
elsif image[:width] > image[:height]
remove = ((image[:width] - image[:height])/2).round
image.shave("#{remove}x0")
end
image.resize("#{size}x#{size}")
image
end
end
resize_and_crop from here:
http://blog.aclarke.eu/crop-and-resize-an-image-using-minimagick/
In #cropper your crop_h is not initialized(you double initialize crop_y instead).
In #crop error is exactly what error message said - you don't have defined crop_x for Project class.

Resources