I am trying to add a high/low priority button to a ToDo Rails app and am having trouble. The button should resort the items in the list based on high/low priority. I have created a new table with the rails generate method Priority, but I am having trouble on what I do next. How should you update the task controller to sort the tasks by order of priority?
samedi 27 juin 2015
How can I get the updated date from a bootstrap datetimepicker with the datetimepicker-rails gem
How can I get the value of the <input class="date_picker" ... when the <div class="bootstrap-datetimepicker-widget" ... is changed or updated? I need to get the value so I can update other attributes on the same page. Here is my best attempt to react to the 'changeDate' event:
$('.datetimepicker').datetimepicker().on('changeDate', function(ev){
console.log(' date changed '+ ev.date);
});
I'm unable to get any response form this event. I also opened an issue with @zpaulovics's gem but I'm not sure if this is a defect, or if I am not accessing the event correctly.
AngularJS HTTP call takes two minutes while the Rails action only takes 20 seconds, how can I debug this?
I have an AngularJS app and there's one page in my application, only one, that is taking 2 minutes to load. It is loading a bit of data, but the data itself is only 700KB and I benchmarked the entire rails action starting from the beginning until right before the render and it only takes 15-20 seconds. But when I look at the actual network call, or I put a timer before the angular http post call and then one in the success, they both show the call taking almost 2 minutes. I can't figure out what's going on between the render and the success on angular that would be causing this extreme time difference. Does anyone know how I could further debug this or possibly know what could be causing this?
The rails action just does a couple big database calls, all optimized, then does some work on the data, then the data (which is already JSONified with to_json) is rendered out.
Rails action ends with Completed 200 OK in 20458ms (Views: 913.8ms | ActiveRecord: 139.6ms)
Rails. Creating a User Controller. My Edit method does not show an ID
I'm creating a app. I've created a User Controller, and successfully created New and Create methods. Running the rails console, I can bring up any ID that I've created. I don't understand when I try to edit from the users/index.html page I'm not directed to /users/id/edit
Routes:
Prefix Verb URI Pattern Controller#Action
users_index GET /users/index(.:format) users#index
welcome_index GET /welcome/index(.:format) welcome#index
macros GET /macros(.:format) welcome#macros
faqs GET /faqs(.:format) welcome#faqs
root GET / welcome#index
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
UsersController:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(set_user_params)
if @user.save
redirect_to users_path
else
end
end
def index
@users = User.all
end
def edit
raise params.inspect
@user = User.find(params[:id])
end
private
def set_user_params
params.require(:user).permit(:name, :email, :team, :password)
end
end
index.html
<div> <%= link_to "Create New Agent", new_user_path %></div>
<% @users.each.with_index(1) do |user, index| %>
<div class="list_of_agents">
<%= user.name %><br>
<%= user.team %><br>
<%= user.id %><br>
<%= link_to "Edit", edit_user_path(user.id) %><br>
</div>
<% end %>
Heroku migrate db error unknown column
I am working on my ruby on rails project and when I run heroku db:migrate I get an error about how a column doesn't exist.
I know that this is because I had a migration file that I manually edited to remove a column I created beforehand instead of creating a new migration file.
I removed the remove_column line and migrated db my local db but when I migrate it to heroku it still runs the migration file to remove column even though the line is no longer there on the actual file.
I dropped my database and loaded the schema again but the heroku error continues to occur.
Heroku scheduler - schedule on demand (http post?)
We want to schedule/trigger jobs over HTTP.
Currently, we are using Heroku scheduler (because it doesn't need extra dyno/free) to schedule jobs. We need an ability to schedule them via HTTP POST or some other mechanism that we can trigger programmatically.
Any suggestions on how we can achieve this?
How to generate 2D array from a set of string in rails?
I need to generate 2D array in rails from a set of given strings. For example:
days =[ "Monday",
"Tuesday",
"Wednesday",
]
Now I want to create a 2D array and the data in this array will be fill by from days string in random manner.
Example:
[monday, tuesday, wednesday],
[tuesday, wednesday, monday]
...
and so on depends on given dimensions
How to do it?
Rails 4 assets not loaded in production although work on local production server
My production server won't load any Rails assets. When I run
RAILS_ENV=production rails s
I can see everything just fine. I even tried doing
RAILS_ENV=production bundle exec rake assets:precompile
Still no luck
Here is my production.rb
config.cache_classes = false
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_files = false
config.assets.compress = false
config.assets.compile = true
config.assets.digest = false
config.eager_load = false
config.log_level = :debug
config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
ActiveSupport::XmlMini.backend='Nokogiri'
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
Rails / Bootstrap / HAML - How to convert this code to display flash messages to HAML?
I want to convert the following code to HAML to handle Bootstrap's alert messages in a Rails 4.2.2 application. I've tried manually, using html2haml and online converters and the code I get never works.
The code:
<div class="alert
<%=
case type.to_sym
when :alert, :danger, :error, :validation_errors
'alert-danger'
when :warning, :todo
'alert-warning'
when :notice, :success
'alert-success'
else
'alert-info'
end
%>
alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<%= content %>
</div>
This is what I get from converters:
.alert.case.when.:validation_errors.when.:todo.when.:success.else.end.alert-dismissible{:class => "<haml_loud> type.to_sym :alert, :danger, :error, 'alert-danger' :warning, 'alert-warning' :notice, 'alert-success' 'alert-info' </haml_loud>", :role => "alert"}
%button.close{"data-dismiss" => "alert", :type => "button"}
%span{"aria-hidden" => "true"} ×
%span.sr-only Close
= content
I know it's ugly but it is the only code I have found that works out of the box with Bootstrap 3.5.5. If anyone has suggestions for new code using HAML, I'm open to hear.
More ruby-like way of writing simple ActiveRecord code
Here is some fairly standard Ruby on Rails 4 ActiveRecord code:
def hide(user)
self.hidden = true
self.hidden_on = DateTime.now
self.hidden_by = user.id
end
def unhide
self.hidden = false
self.hidden_on = nil
self.hidden_by = nil
end
def lock(user)
self.locked = true
self.locked_on = DateTime.now
self.locked_by = user.id
end
def unlock
self.locked = false
self.locked_on = nil
self.locked_by = nil
end
# In effect this is a soft delete
def take_offline(user)
hide(user)
lock(user)
end
The code is easy to understand and doesn't try to be clever. However it feels verbose. What would be a more succinct or canonical way of specifying this code/behaviour?
How to reference a JS file from within application_helper
I have these files:
- app
-- assets
--- javascripts
---- controllers
----- company.js.coffee
----- projects.js.coffee
In my application.rb I got:
Rails.application.config.controllers_with_assets = %w( company projects )
Rails.application.config.controllers_with_assets.each do |controller|
config.assets.precompile += ["controllers/#{controller}.js"]
end
In my application_helper I got this method set up:
def controller_assets
controller = params[:controller]
if Rails.application.config.controllers_with_assets.include? controller
javascript_include_tag(asset_path('controllers/'+ controller))
end
end
This is included in the layout so that js is only loaded if the appropriate controller is also active. This all works fine in development.
In production I can see that the JS files are correctly compiled.
/public/assets/controllers/company-28b5effa0fbec2899df9a18ab1b85975.js
In the view (browser) however I see that it failed to load:
GET http://ift.tt/1TVw0kO
When I log in the console of the server and give this command:
Rails.application.assets.find_asset('controllers/company')
=> #<Sprockets::BundledAsset:0x5810768 pathname="/websites/instalane/production/releases/20150627231331/app/assets/javascripts/controllers/company.js.coffee", mtime=2015-06-27 14:21:45 +0000, digest="e7654520e52697294bb9e13ea09710e6">
What am I doing wrong?
FYI I already tried the following in the application_helper:
javascript_include_tag('controllers/'+ controller)
and
javascript_include_tag('controllers/'+ controller + '.js')
and
javascript_include_tag(controller)
Failing uniqueness validation with FactoryGirl
I'm having problems with FactoryGirl, I'm using sequence to avoid duplicating fields, but validations are failing anyway.
Output:
1) CustomersController anonymous user GET #edit is redirected to signin when accessing edit form
Failure/Error: get :edit, id: create(:customer)
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Email has already been taken
# ./spec/controllers/customers_controller_spec.rb:25:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
3) Customer public class methods executes its methods correctly #find_by_id_or_name finds customer by name
Failure/Error: let(:john) {create(:customer, name: 'John Doe X')}
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Email has already been taken
# ./spec/models/customer_spec.rb:25:in `block (3 levels) in <top (required)>'
# ./spec/models/customer_spec.rb:38:in `block (5 levels) in <top (required)>'
# -e:1:in `<main>'
Factories:
FactoryGirl.define do
factory :customer do
user
name {Faker::Name.name}
sequence(:mail) { |n| "person#{n}@example.com" }
address {Faker::Address.street_address}
phone {Faker::PhoneNumber.phone_number}
end
end
FactoryGirl.define do
factory :user do
sequence(:email) {|i| "example#{i}@example.com"}
password {Faker::Internet.password(10)}
end
end
These are the tests that are failing:
describe "public class methods" do
let(:john) {create(:customer, name: 'John Doe X')}
let(:frank) {create(:customer)}
context "responds to its methods" do
it "responds to #find_by_id_or_name" do
expect(Customer).to respond_to(:find_by_id_or_name)
end
end
context "executes its methods correctly" do
context "#find_by_id_or_name" do
it "finds customer by name" do
customer = Customer.find_by_id_or_name('John Doe X')
expect(customer).to eq john
end
it "finds customer by id" do
customer = Customer.find_by_id_or_name(frank.id)
expect(customer).to eq frank
end
end
end
end
describe "GET #edit" do
it "renders :edit view" do
get :edit, id: create(:customer).id
expect(response).to render_template(:edit)
end
end
describe "DELETE #destroy" do
before :each do
@customer = create(:customer, user: @user)
end
it "deletes record" do
expect {delete :destroy, id: @customer.id}.to change(Customer, :count).by(-1)
end
end
This is happening to me all over my app. I just copied some tests that apply to Customer.
Thanks
Database migration stops halfway through
I've had issues trying to use PostgreSQL so changed my application to use MYSQL.
But, when I run rake db:migrate I get the following message before the migration stops:
-- PostgreSQL database dump complete
However when I run rake db:seed, I get told that I still have 303 migrations left. How can I complete this migration?
Status of Migration is Done
When I was migrating something on rails I got a problem. And now after I migrated it, the status went down. Is there anything I can do?
Rails 4 create model with nested attributes has_many
I have a many to many relationship with DoctorProfile and Insurance. I'd like to create these associations off of a form from a client side app. I'm sending back an array of doctor_insurances_ids and trying to create the association in one line. Is it possible to send back an array of doctor_insurances ids? If so what's the proper way to name it for mass assignment in the params?
The error I'm getting with the following code is
ActiveRecord::UnknownAttributeError: unknown attribute 'doctor_insurances_ids' for DoctorProfile.
class DoctorProfile
has_many :doctor_insurances
accepts_nested_attributes_for :doctor_insurances # not sure if needed
class Insurance < ActiveRecord::Base
has_many :doctor_insurances
class DoctorInsurance < ActiveRecord::Base
# only fields are `doctor_profile_id` and `insurance_id`
belongs_to :doctor_profile
belongs_to :insurance
def create
params = {"first_name"=>"steve",
"last_name"=>"johanson",
"email"=>"steve@ymail.com",
"password_digest"=>"password",
"specialty_id"=>262,
"doctor_insurances_ids"=>["44", "47"]}
DoctorProfile.create(params)
end
Defining mailer in sorcery
I am building a rails app using sorcery. When I go to users/new, there is an Argument Error stating "To use reset_password submodule, you must define a mailer (config.reset_password_mailer = YourMailerClass)"
Went into config/initializers/sorcery.rb and included code user.reset_password_mailer = UserMailer but I am still receiving the error. Within the UserMailer class, I defined reset_password_email method
def reset_password_email(user)
@user = User.find user.id
@url = edit_password_reset_url(@user.reset_password_token)
mail(:to => user.email,
:subject => "Your password has been reset")
end
and updated the sorcery.rb file
user.reset_password_email_method_name = :reset_password_email
I am still receiving the same error message.
In the Users controller:
class UsersController < ApplicationController
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to products_url, notice: "Signed Up!"
else
render "new"
end
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:email, :user_name, :password, :password_confirmation)
end
end
And my User model is:
class User < ActiveRecord::Base
authenticates_with_sorcery!
has_many :projects
validates :password, confirmation: true
validates :password_confirmation, presence: true
validates :email, uniqueness: true
end
Rails / Paperclip absolute_path from form?
I'm trying to save the absolute_path from the paperclip file attached in a rails form. I want to save it to the database for later use.
I read through the paperclip docs and can't find anything that I think will work. Ruby has a solution for File abstraction in the ruby-docs that I was able to get working in terminal but i'm not sure how to implement it with rails and paperclip in a form.
Any ideas would be appreciated...
Ultimately, the goal is to parse an xml file (nokogiri) and use the file path to tell paperclip where to find the images listed in the xml which are in the same folder.
Create a company and user in one, what's the standard?
I know a lot of startups and tech companies essentially allow you to register, and you end up registering a company and your user.
An example would be basecamp for example. I'd like to achieve the same thing, however I'm not quite certain on how they do it, and what the best way to do it is.
My thought is to have a user and company model, where on registration you register a company, and it accepts nested attributes for user. As in my head at least the relation is:
User belongs_to :company
Company has_many :users
and the registration is a Company#new with a company.user.build.
However for some reason this does feel a bit strange, as to me it would make more sense that you register a user, and create the company it belongs to.
I just want to lay the foundation right, so I don't start building anything massive on top of a system that isn't good.
Ruby on Rails Solving a No method Error
I'm currently going through Hartl's Ruby on Rails tutorial and I've come to a roadbloack with a failing test that I don't know how to get to pass. All of the previous tests through chapter 11 have ran correctly so I was hoping some one could help me interpret the errors.
Running:
bundle exec rake test
Gives me this
45 runs, 0 assertions, 0 failures, 45 errors, 0 skips
The first six errors are similar to this:
1) Error:
MicropostTest#test_should_be_valid:
ActiveRecord::Fixture::FormatError: ActiveRecord::Fixture::FormatError
And the rest of the errors follow this pattern:
7) Error:
UsersEditTest#test_unsuccessful_edit:
ActiveRecord::Fixture::FormatError: ActiveRecord::Fixture::FormatError
Error:
UsersEditTest#test_unsuccessful_edit:
NoMethodError: undefined method `each' for nil:NilClass
I'm not sure what an undefined method for a nil class would mean. If I need to post any more of my code/errors please let me know. Any help is appreciated. Thanks!
Why are this Rake task's depenencies being run out of order?
When running the following Rake task, :test is run after :staging.
namespace :deploy do
desc 'Deploy to staging'
task :staging => [:test, :cucumber] do
# do deployment things ...
end
end
Is this the expected behavior (I'm fairly certain it's not...) or is Rails doing something "clever" in its implementation of :test?
Env:
- Ruby 2.2.2
- Rails 4.1.12
- Rake 10.4.2
With Nested Resources in routes.rb with custom to_param, how can Strong Parameters allow created/update to permit?
I can't find something that'll lead in the right direction. Everyone else's similar issues with nested resources seems to resolve around accepts_nested_attributes_for… which I'm not trying to do. I'm not trying to save children from the parent, I'm trying to save directly from the child.
In my routes.rb, I have nested my resource
resources :parents, param: :parent do
resources :children, param: :child
end
parent and child tables both have their own id column, but also have unique index on columns parent and child respectively, which I was to be used in the URL instead of the id.
This is working fine browsing around going to the show, edit and index actions of each controller.
The problem is there are exceptions saving data.
I'm hoping the root-cause of the issue doesn't come down to a field in the child table is also called child as that's what I've used to override to_param in the model and need to keep it that way.
Navigating to the edit screen: http://ift.tt/1NmQwpd and pushing submit on the form, returns this NoMethodError exception:
NoMethodError at /parents/harry/children/sally
undefined method `permit' for "sally":String
I'm sure the problem is something to do with how my Strong Parameters line is in children_controller.rb. Can I add to require a hash of :parent and :child maybe?
def children_params
params.require(:child).permit(:child, :date_of_birth, :nickname)
end
Update 1 (Added params): Here are the request parameters:
{
"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"fAkBvy1pboi8TvwYh8sPDJ6n2wynbHexm/MidHruYos7AqwlKO/09kvBGyWAwbe+sy7+PFAIqKwPouIaE34usg==",
"child"=>"sally",
"commit"=>"Update Child",
"controller"=>"children",
"action"=>"update",
"parent_parent"=>"harry"
}
Other instance variable in-scope at time of error:
@parent
<Parent id: 1, parent: "harry", description: "", user_id: 1, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">
@child
<Child id: 1, child: "sally", date_of_birth: nil, parent_id: 1, nickname: nil, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">
Updating message counter on private_pub publish
I am creating a chat module for my application and using private_pub for sending and receiving messages. I want to update the unread message counter on receiver's as soon as receiver gets the message.
Each page is subscribed to a channel where message gets published, so that every time I get the message, the counter on the page gets updated.
Following js file is executed when a new message is created.
<% publish_to conversation_messages_path(@conversation.id) do %>
$("#messages").append("<%= escape_javascript render(:partial => 'message', :locals => { :message => @message })%>");
$("#unread_messages_count").text("<%= current_user.received_messages.unread.size %>");
<% end %>
// @conversation.messages.where(:read => 0)
$("#newMessageForm")[0].reset();
$("#messages").scrollTop($("#messages")[0].scrollHeight);
The page gets updated but current_user.received_messages.unread.size gives me the sender's unread count, why is this so?
This means the current_user should be different for every other page who has subscribe_to that URL. As of now current_user is the one who publish_to that URL which results in the same value of unread messages count for every different client.
One possible solution is to send the user id of the one who is currently logged in while we subscribe_to a URL and in publish_to use that to get the unread messages count but the problem is I don't know how to send data while subscribing and using it in publish.
Is it possible to add html-attributes without values in rails link_to?
I want to output an a-tag like this:
<a href="#" itemscope class="features__cta button>Stuff</a>
I know I can add html-attributes like this to the tag, but how do I add one without a value to it?
<%= link_to t('features.cta'), t('features.cta_link') , class:
'features__cta button', itemprop: "priceSpecification" %>
Rails render partial with progress bar
I'm running Rails 4 and am trying to use a bootstrap form wizard. The thing about the form wizard is that not all of its tabs should be displayed at all times.
The form wizard is in a partial that I render via $("#tab3").html("<%= j(render partial: 'wizard' ) %>"); in update_forms.js.erb (called via an ajax call).
Everything works well in this except the progress bar doesn't display (it is 0) unless I refresh the page. Any thoughts on how I can set the progress bar when rendering the partial?
Thanks!
What is the best way to store matrix in rails sqlite?
I need to create a new matrix in before_save model method. What is the best way to save this matrix, Dimension of the matrix could be max 50 * 50. How about if I store into Json?
class Simulation < ActiveRecord::Base
before_save :create_matrix
belongs_to :user
validates_presence_of :name, :message => 'Name field cannot be empty..'
def creat_matrix
if self.is_matrix
.....
end
end
end
Filter ActiveAdmin with Postgresql json column on specific json keys
I have a Deal model that features a json column called deal_info. It's actually an array of JSONs.
I'm using active admin.
For example :
deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" },
{ "modal_id": "6", "video2":"yonak" },
{ "modal_id": "9", "video2":"boom" } ]
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" },
{ "modal_id": "11", "video2":"yonak" },
{ "modal_id": "11", "image4":"boom" } ]
As first step now I would like to have a filter that would enable me to filter the deals based on the fact that deal_info json column includes at least one time the modal_id in one of its included json.
It would enable me in a select dropdown to choose for example modal_id = 6 and would filter the list of Deals to only show deal 1 (see example above).
One of the further challenge is that I need to be able to remove duplicates on the select dropdown in order not to have multiple times the same id: here for example i can't have select = [4,6,9,10,11,11]...each modal_id can only appear once.
I only found this but it did not work for me.
My current Active Admin Code
ActiveAdmin.register Deal do
filter :modal_id,
as: :select
collection: deal_info.all.to_a.map ????
end
Querying Rails.cache items
I'd like to search items in my Rails.cache by their value. I'm having trouble finding out how to do this. Specifically, I'm using Active Model Serializer and would like to search through my AMS cache for keywords in their value. How do I do this?
Thanks!
Ruby csv - delete row if column is empty
Trying to delete rows from the csv file here with Ruby without success.
How can I tell that all rows, where column "newprice" is empty, should be deleted?
require 'csv'
guests = CSV.table('new.csv', headers:true)
guests.each do |guest_row|
p guests.to_s
end
price = CSV.foreach('new.csv', headers:true) do |row|
puts row['newprice']
end
guests.delete_if('newprice' = '')
File.open('new_output.csv', 'w') do |f|
f.write(guests.to_csv)
end
Thanks!
Gibbon / Mailchimp Signup Form
Having some trouble creating a simple signup form for a mailchimp list. Can't figure out why when they email passes through, it doesn't pass over to mailchimp.. thoughts? I'm sure I missed a step here.
index.html.erb (Form)
<%= form_tag('/welcome/subscribe', method: "post", id: "subscribe",) do -%>
<%= email_field(:email, :address, {id: "email", placeholder: "email address"}) %>
<%= submit_tag("Join!") %>
<% end %>
Gibbon.rb (Initializer)
Gibbon::API.api_key = "Secret API Key"
Gibbon::API.timeout = 15
Gibbon::API.throws_exceptions = false
Welcome.rb (Model)
def subscribe
@list_id = "Secret List ID"
gb = Gibbon::API.new
gb.lists.subscribe({
:id => @list_id,
:email => {:email => params[:email][:address]}
})
end
Routes.rb
Rails.application.routes.draw do
root 'welcome#index'
post 'welcome/subscribe' => 'welcome#subscribe'
end
Service PHP in Rails
I have a small PHP service that is being called in a JavaScript file by AJAX :
$.ajax({
type: "GET",
url: "getDate.php",
dataType:"json",
data :{
fromDate:fromDate,
toDate:toDate
},
success: function(data) {
......
}
});
This service contains :
$fromDate = $_GET['fromDate'];
$toDate = $_GET['toDate'];
$fromDate=date_create($fromDate);
$fromdate = date_format($fromDate,"Y-m-d")."T".date_format($fromDate,"H:i:s")."Z";
$fromdate = urlencode($fromdate);
$toDate=date_create($toDate);
$todate = date_format($toDate,"Y-m-d")."T23:00:00Z";
$todate = urlencode($todate);
$url = "http://ift.tt/1LByAtu".$fromdate."%27+and+time%3C%3D%27".$todate."%27";
$data = file_get_contents($url, false);
echo $data;
I need to use this in my Rails application. I was wondering if I could put the .php file in a Rails folder, and simply call it. Or if there's a way to do a similar service in Rails?
How to show error message on rails views?
I am newbie in rails and want to apply validation on form fields.
myviewsnew.html.erb
<%= form_for :simulation, url: simulations_path do |f| %>
<div class="form-group">
<%= f.label :Row %>
<div class="row">
<div class="col-sm-2">
<%= f.text_field :row, class: 'form-control' %>
</div>
</div>
</div>
Simulation.rb
class Simulation < ActiveRecord::Base
belongs_to :user
validates :row, :inclusion => { :in => 1..25, :message => 'The row must be between 1 and 25' }
end
I want to check the integer range of row field in model class and return the error message if it's not in the range.
Thanks in advance
Getting Rspec error no implicit conversion of Symbol into Integer with Mongoid
I'm tying to test my Rails app with Rspec, but I'm getting a no implicit conversion of Symbol into Integer error without any apparent reason. Based on the traceback I get I think the problem is related to Mongo/Mongoid, however, I can't figure out what it is exactly. The code runs perfectly in production. The error happens only when testing.
Brief look at the model without the other methods:
class Card
include Mongoid::Document
field :front, type: String
field :back, type: String
field :level, type: Integer, default: 1
field :review_date, type: DateTime, default: DateTime.now
embeds_one :card_statistic
belongs_to :topic
belongs_to :user
validates :front, :back, :level, presence: true
validates :topic, presence: { is: true, message: "must belong to a topic." }
validates :user, presence: { is: true, message: "must belong to a user." }
validates :level, numericality: { only_integer: true, greater_than: 0 }
end
One function in the model that triggers the error:
def self.reset(card)
card.update(level: 1)
end
The test code:
it "puts the given card in level 1" do
card = create(:card)
Card.correct card
card.reload
Card.correct card
card.reload
expect(card.level).to eq(3)
card.reset
card.reload
expect(card.level).to eq(1)
end
Then, the traceback of the error I get:
1) Card puts the given card in level 1
Failure/Error: Card.reset card
TypeError:
no implicit conversion of Symbol into Integer
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/server_selector.rb:56:in `[]'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/server_selector.rb:56:in `get'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/client.rb:170:in `read_preference'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/collection/view/readable.rb:318:in `default_read'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/collection/view/readable.rb:251:in `read'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/collection/view/iterable.rb:38:in `each'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/query_cache.rb:207:in `each'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:230:in `first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:230:in `block (2 levels) in first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:562:in `with_sorting'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:229:in `block in first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:474:in `try_cache'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:228:in `first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual.rb:20:in `first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/builders/referenced/in.rb:20:in `build'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:43:in `create_relation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:26:in `__build__'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:104:in `block (2 levels) in get_relation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/threaded/lifecycle.rb:130:in `_loading'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:100:in `block in get_relation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/threaded/lifecycle.rb:89:in `_building'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:99:in `get_relation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:187:in `block in getter'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/validatable.rb:79:in `read_attribute_for_validation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validator.rb:149:in `block in validate'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validator.rb:148:in `each'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validator.rb:148:in `validate'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:450:in `public_send'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:450:in `block in make_lambda'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:189:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:189:in `block in simple'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `block in simple'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `block in simple'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:92:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:92:in `_run_callbacks'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:734:in `_run_validate_callbacks'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations.rb:395:in `run_validations!'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations/callbacks.rb:113:in `block in run_validations!'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:88:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:88:in `_run_callbacks'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:734:in `_run_validation_callbacks'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations/callbacks.rb:113:in `run_validations!'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations.rb:334:in `valid?'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/validatable.rb:97:in `valid?'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations.rb:371:in `invalid?'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/updatable.rb:114:in `prepare_update'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/updatable.rb:139:in `update_document'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/savable.rb:25:in `save'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/updatable.rb:52:in `update'
# ./app/models/card.rb:57:in `reset'
# ./spec/models/card_spec.rb:32:in `block (2 levels) in <top (required)>'
The error is also triggered when testing the controllers. Even doing a get :index throws the error. Thanks in advance for your help.
Rails]Dynamically generate static pages
I want to be able to publish webpages with my rails app. In other words, there's a button that says "submit current page" and when the user presses this button, there should be a new page with its own url. When you make a new post, there's a new webpage generated at posts/1.
<div>
Save me at /pages/one
</div>
<button>Make</button>
<div>
Save me at /pages/second
</div>
<button>Make</button> <- upon pressing this, there should be a new static page
Is there a convention to follow?
Editable Webpage Table in Rails
I am trying to make a webpage with a calendar similar to the one in the following link:
http://cs61a.org/
But I need the page to be editable. I want the user to not only be able to change the contents of the table but also the table structure (Add columns etc). What strategy should I use to tackle this problem?
Rails 4 Include Helper inside Service Object
I am currently trying to use a Devise helper inside a service object
class ServiceObject
include Devise::Controllers::Helpers
But I get
undefined method `helper_method' for ServiceObject:Class
Any idea how to use such a helper inside the service object?
rails 4 undesired double pop-up
In my rails 4 application session expire time set to 10 minutes for user login.
After that user clicks on any link the default flash message is comes up like Your session is expired. Please sign in again to continue.
This is fine, but below this another flash message is coming like "true" . I don't know from where it is coming from, how can I solve this?
Postgre error with Rails - I'm running locally but the database won't work properly)
Currently trying to install to run Catarse on my Mac (Yosemite)
When I try and run rake db:create db:migrate db:seed
I get the following message
ActiveRecord::StatementInvalid: PG::DuplicateObject: ERROR: role "admin" already exists
: CREATE ROLE admin NOLOGIN;
-- This script assumes a role postgrest and a role anonymous already created
GRANT usage ON SCHEMA postgrest TO admin;
GRANT usage ON SCHEMA "1" TO admin;
GRANT select, insert ON postgrest.auth TO admin;
GRANT select ON ALL TABLES IN SCHEMA "1" TO admin;
GRANT admin TO postgrest;
I have tried to do the above but to no avail, and now it's saying that I have a duplicate admin role. Can anybody please offer some guidance or assistance?
I've spent most of the day troubleshooting and looking at this over and over again in frustration by doing the following:
Uninstalling catarse Reinstalling and uninstalling postgresql Trying to implement the above 'GRANT' commands
Why is it too slow to fetch the records?
I'm using the gem called 'yourub' to fetch information of multiple videos narrowed down by particular keyword.
My code is just like this and it works fine but too slow until the result start showing up on the page.
Is it because I'm using the gem? Does it get faster if I do the same thing with native way of using "google-api-client" gem? If so how can I replace my original?
P.S. According to the document of 'yourub', it only can fetch up to 50 videos:( and it cannot even choose which page of the result to show with pagination select :(
My code(View)
<% client = Yourub::Client.new %>
<% client.search(query: "cat", order: "date", max_results: 30) do |video| %>
Video ID:<%= video["id"] %> <br />
Title: <%= video["snippet"]["title"] %><br />
<img src="<%= video["snippet"]["thumbnails"]["high"]["url"] %>" with="480" height="360"><br />
----------------------------------------------------------------------------------------------<br />
<br />
<% end %>
has_many :through broke some code
So i'm relatively new to RoR, and am having some issues in trying to get my code back up and working. So previously I had users, and wikis that users could create. I've set up so that users can subscribe and get premium status to make wikis private. Now I'm in the process of making it so that Premium users can add standard users as collaborators to the wiki. I've decided to got about associating them through has_many :through relationships.
The issue I'm running into so that some of my buttons have started making errors that I don't understand. The one I'm stuck on right now is when showing the page that has a create new wiki button on it.
This is the error I am getting when I added the has_many through: relationship
No route matches {:action=>"new", :controller=>"wikis", :format=>nil, :user_id=>nil} missing required keys: [:user_id]
Here are the models:
collaborator.rb
class Collaborator < ActiveRecord::Base
belongs_to :wiki
belongs_to :user
end
user.rb
class User < ActiveRecord::Base
...
has_many :collaborators
has_many :wikis, :through => :collaborators
end
wiki.rb
class Wiki < ActiveRecord::Base
belongs_to :user
has_many :collaborators
has_many :users, :through => :collaborators
end
The important bits of the wiki_controller.rb
def new
@user = User.find(params[:user_id])
@wiki = Wiki.new
authorize @wiki
end
def create
@user = current_user
@wiki = @user.wikis.create(wiki_params)
authorize @wiki
if @wiki.save
flash[:notice] = "Wiki was saved"
redirect_to @wiki
else
flash[:error] = "There was an error saving the Wiki. Please try again"
render :new
end
end
And finally the show.html.erb file the button is located in.
<div class="center-align">
<%= link_to "New Wiki", new_user_wiki_path(@user, @wiki), class: 'btn grey darken-1' %>
</div>
If I'm missing any files or relevant info please let me know. This may be a simple stupid answer but I'm stuck for the life of me.
Thanks in advance.
Edit:
Here is the requested added info, first up the show info in the users_controllers.rb
def show
@wikis = policy_scope(Wiki)
end
the corresponding policy scope I'm using in the user_policy.rb
class UserPolicy < ApplicationPolicy
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
wikis = []
all_wikis = scope.all
all_wikis.each do |wiki|
if wiki.user == user || wiki.users.include?(user)
wikis << wiki
end
end
end
wikis
end
end
and the route.rb file
Rails.application.routes.draw do
devise_for :users
resources :users, only: [:update, :show] do
resources :wikis, shallow: true
end
resources :wikis, only: [:index]
resources :charges, only: [:new, :create]
delete '/downgrade', to: 'charges#downgrade'
authenticated do
root to: "users#show", as: :authenticated
end
root to: 'welcome#index'
end
Hope it helps
create two connections MySQL on Rails project
I should create a CRM(Customer relationship management) in Rails.In this CRM i have to use two databases(MySQL).I have a doubt in the correct use of these databases.I mean, i read on internet that is possible to open two connections in a Rails project, but is this the right way to hit the problem? is really good to open two connection in a project?is it used?if not, what is the solution in the state of art(maybe the simpler to manage queries) for my problem?
Ruby on rails flash notice error
I have a problem with flash[:notice] = "Message" in Ruby on Rails.
I am trying to create login fault error message. My login fault handling is:
flash[:notice] = "Invalid username/password combination."
redirect_to(:action => 'login')
For the reason I don't know, alert just doesn't show up. I have red tons of possible solutions, but all of them just doesn't work for me. I am using Safari / Google Chrome web browsers.
checkboxs in a table created via form_for
I'm new to RoR so apologies if the answer is super simple. I'm trying to create a table that allows users to select other users that can collaborate on a wiki. The issue I'm having is that no matter which checkbox you select on the table. It only toggles the topmost option.
here is the code in question:
<%= form_for [@wiki, @wiki.collaborators.build] do |f| %>
<table class="bordered hoverable">
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td class="right-align"><%= f.check_box :user_id %><%= f.label :user_id, "Give Access" %></td>
</tr>
<% end %>
</tbody>
</table><br /><br />
the controller values in new
def new
@wiki = Wiki.find(params[:wiki_id])
@collaborator = Collaborator.new
@users = (User.all - [current_user])
end
Any help would be appreciated. Thanks in advance.
rails join query between two tables with similar field
I have 3 models
class Company < ActiveRecord::Base
has_many : CompanyAccount
has_many : CompanyContact
end
class CompanyContact < ActiveRecord::Base
belongs_to : Company
end
class CompanyAccount < ActiveRecord::Base
belongs_to : Company
end
As both the CompanyAccount and CompanyContact models belong to the Company model, they have a similar "company_id" field. I have retrieved some Accounts through a query:
@CompanyAccounts = CompanyAccount.where.not(balance:nil)
Now, using the common company_id field I am trying to retrieve all the data from my CompanyContacts table that belong to the same Company associated with the CompanyAccounts I queried above (in other words, I am trying to get the rows which have the same company_id). I have made several attempts using "joins" but everything failed so far. Could anyone give me what would be the appropriate syntax in this context? Thanks.
Rails force instance variable declaration before use on view
Is it possible to force Ruby/Rails to throw an error when printing/using instance variables on a view that haven't been defined on controller
I'm declaring an instance variable on a Rails Controller and I'm printing its value on a View
def controller_action
@some_data = "some value"
end
Then we know we can print its value on a view
<p>Some data has <%= @some_data %></p>
My problem is when doing mistakes on a view like this:
<p>Some data has <%= @somedata %></p>
Ruby won't complain and it's difficult to find those mistakes. This also applies for team development where some programmer can create an instance variable on a controller with one name and another programmer expects to print it on a view but accidentally uses other name.
How to display error messages in a multi-model form with transaction?
Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.
The problem I'm experiencing is: When submitting invalid information for the user, it renders the form again, as it should, but the error messages (such as "username can't be blank") are not displayed. The form does work when valid information is submitted and it does display error messages for organization, just not for user.
How should I adjust the code below so that also the error messages for user get displayed?
def new
@organization = Organization.new
@user = @organization.users.build
end
def create
@organization = Organization.new(new_params.except(:users_attributes))
#Validations require the organization to be saved before user, as user requires an organization_id. That's why users_attributs are above excluded and why below it's managed in a transaction that rollbacks if either organization or user is invalid. This works as desired.
@organization.transaction do
if @organization.valid?
@organization.save
begin
@organization.users.create!(users_attributes)
rescue
# Should I perhaps add some line here that adds the users errors to the memory?
raise ActiveRecord::Rollback
end
end
end
if @organization.persisted?
flash[:success] = "Yeah!"
redirect_to root_url
else
@user = @organization.users.build(users_attributes) # Otherwise the filled in information for user is gone (fields for user are then empty)
render :new
end
end
The form view includes:
<%= form_for @organization, url: next_url do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :name %>
# Other fields
<%= f.fields_for :users do |p| %>
<%= p.email_field :email %>
# Other fields
<% end %>
<%= f.submit "Submit" %>
<% end %>
The error messages partial is as follows:
<% object.errors.full_messages.each do |msg| %>
<li><%= msg.html_safe %></li>
<% end %>
Heroku not updating website after successful deploy
I'm trying to deploy my app through Heroku, using Ruby on Rails, and I have been successful in the past but now when I use the same commands as before it will deploy successfully but when I visit my website it has not been updated with my new code.
Here are the commands I am using:
git add -A
git commit -m "message"
git push
git push heroku
heroku run rake db:migrate
I tried using "git push heroku master" as well based on another stack overflow thread but it didn't update my website either. Running the deployment only returns one warning and that is that my Ruby version is not declared so I don't think that would be an issue. I'd be happy to provide more information if I need to. Any information/help would be greatly appreciated.
How to load asset gems only for precompile on heroku?
Rails 4.1+, so there isn't built-in support for an :assets group
I want to keep Heroku's precompile on push behaviour, but don't want the asset gems loaded by the rails server. We don't use any kind of inline coffeescript or scss template rendering in the app, only in the assets, so it's just wasted memory at runtime.
I've played around with extending the rake task, configuring sprocket-rails, and even changing application.js to application.js.erb and adding things like
//= <% require 'jquery-rails' %>
//= require 'jquery'
but still get these errors:
Sprockets::FileNotFound: couldn't find file 'jquery'
If I keep the asset gems in the default Gemfile group everything works fine.
The point here is to not have them loaded in the production environment, but to have
RAILS_ENV=production rake assets:precompile task
load them before it executes (and fails because of missing libraries)
wrong singular for 'slaves'
I have a line resources :slaves in my routes.rb. Which is definitely plural for 'slave', but rails thinks that it's plural form of 'slafe', so I get paths like new_slafe_path. Is there a way to tell rails correct singular form without explicitly specifying each route?
Undefined method "errors"... But there are ERRORS
I am doing a basic validation for a bank entry and am trying to display the errors on submit. Here is my validation and html.
class GuestbookEntry < ActiveRecord::Base
validates :body, presence: :true
end
This is my html:
<% form_for @guestbook_entry do |f| %>
<% if @guestbook_entry.errors.any? %>
<% @guestbook_entry.errors.full_messages.each do |m| %>
<li><%= m %></li>
<% end %>
<% end %>
<%= f.label :body, "Guestbook Entry:" %>
<%= f.text_area :body %>
<%= f.submit "Submit" %>
<% end %>
Any ideas?
Rails 4.1 - Write to MySQL database without typecasting
I have a column in my MySQL database which is of type TINYINT(1). I need to store actual integers in this column. The problem is, because of the column type, Rails 4.1 assumes this column contains only boolean values, so it typecasts all values besides 0 or 1 to be 0 when it writes to the database.
I don't want to simply disable boolean emulation since we have a number of columns in our database where we use TINYINT(1) to actually represent a boolean value.
How can I force Rails 4.1 to bypass the typecasting step and write directly to the database instead?
(This excerpt from the Rails 4.1 source may be of some use: http://ift.tt/1BWF1og)
samedi 9 mai 2015
Same commands, different results
I saw a weird behavior in my bash terminal. I run same commands on my terminal command line, but get different results. Following lines are copied-pasted from my bash terminal windows:
me@me:~$ ls "/media/me/My Passport/Archive U/"
ls: cannot access /media/me/My Passport/Archive U/: No such file or directory
me@me:~$ ls "/media/me/My Passport/Archive U/"
Backup Documents Downloads Music Pictures Videos
I tried both commands using up arrow key (to bring previous commands to the current line) many times and the result does not changes. To be sure that the command has no hidden character, I selected both commands and pasted it to an spreed sheet and converted each character to its code and compared. there was no difference. I tried to select each commands and right-click, choose Copy, right click again, choose paste. If I copy-paste first command, I get first result. I f I copy-paste second command, I get second result!!!
Could any one say what is the difference between two commands? I guess no one could!
I tell you what is the difference. First command is copied and pasted from a text file!
I am using Ubuntu 14.04.
How to run tkinter based app directly by starting X in Debian
I have a Debian OS, and I have a tkinter based python code.
I want to run this tkinter based app automatically when I run startx without seeing desktop.
How can I manage this?
Thanks,
How to increase the EXT4 timestamp precision in linux?
Timestamp precision or accuracy of EXT4 filesystem in Linux is one second ( Windows timestamp precision is 100 nano second ). But our application which is running on cloud requires more precision for the filesystem . How to increase the timestamp precision in Linux ?
spring-security-core 2.0.3 spring-aop 2.0.8 cause NoSuchMethodError
Using Maven to build my project under windows works fine, but when deploy it to Linux servers via bamboo, on two servers it seems ok but on third server I get a NoSuchMethodError regarding one of the spring libs. İf i remowe spring-aop:jar from war it works. İf it is because of different spring versions how to works on other two linux servers?
Has anyone come across this problem before, or have any advice on how I can debug this error further?
Any help would be appreciated.
library tree
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ pqis-op ---
[INFO] com.toyotatr.tmem.pqis:pqis-op:war:0.0.1.7-SNAPSHOT
[INFO] +- com.toyotatr.tmem.pqis:pqis-service:jar:0.0.1-SNAPSHOT:compile
[INFO] | +- com.toyota.tme.jpa:jpa-support:jar:1.1tk:compile
[INFO] | +- org.hibernate:hibernate-annotations:jar:3.4.0.GA:compile
[INFO] | | +- org.hibernate:ejb3-persistence:jar:1.0.2.GA:compile
[INFO] | | +- org.hibernate:hibernate-commons- annotations:jar:3.1.0.GA:compile
[INFO] | | +- org.hibernate:hibernate-core:jar:3.3.0.SP1:compile
[INFO] | | | \- antlr:antlr:jar:2.7.6:compile
[INFO] | | \- dom4j:dom4j:jar:1.6.1:compile
[INFO] | | \- xml-apis:xml-apis:jar:1.0.b2:compile
[INFO] | +- org.hibernate:hibernate-entitymanager:jar:3.4.0.GA:compile
[INFO] | | +- javax.transaction:jta:jar:1.1:compile
[INFO] | | \- javassist:javassist:jar:3.4.GA:compile
[INFO] | +- aspectj:aspectjrt:jar:1.5.3:compile
[INFO] | +- aspectj:aspectjweaver:jar:1.5.3:compile
[INFO] | +- cglib:cglib:jar:2.2:compile
[INFO] | | \- asm:asm:jar:3.1:compile
[INFO] | +- javax.activation:activation:jar:1.1:compile
[INFO] | +- javax.mail:mail:jar:1.4.2:compile
[INFO] | \- net.sf.ehcache:ehcache:jar:1.5.0:compile
[INFO] | +- backport-util-concurrent:backport-util-concurrent:jar:3.1:compile
[INFO] | \- net.sf.jsr107cache:jsr107cache:jar:1.0:compile
[INFO] +- org.slf4j:slf4j-api:jar:1.5.6:compile
[INFO] +- org.slf4j:slf4j-log4j12:jar:1.5.6:compile
[INFO] +- log4j:log4j:jar:1.2.14:compile
[INFO] +- org.springframework:spring:jar:2.5.6:compile
[INFO] | \- commons-logging:commons-logging:jar:1.1.1:compile
[INFO] +- org.springframework:spring-context:jar:2.5.6:compile
[INFO] | +- aopalliance:aopalliance:jar:1.0:compile
[INFO] | \- org.springframework:spring-beans:jar:2.5.6:compile
[INFO] +- org.springframework:spring-core:jar:2.5.6:compile
[INFO] +- javax.annotation:jsr250-api:jar:1.0:compile
[INFO] +- org.springframework:spring-test:jar:2.5.6:test
[INFO] +- org.springframework:spring-webmvc:jar:2.5.6:compile
[INFO] | +- org.springframework:spring-context-support:jar:2.5.6:compile
[INFO] | \- org.springframework:spring-web:jar:2.5.6:compile
[INFO] +- javax.servlet:servlet-api:jar:2.5:compile
[INFO] +- javax.servlet:jstl:jar:1.1.0:compile
[INFO] +- javax.servlet:jsp-api:jar:2.0:compile
[INFO] +- taglibs:standard:jar:1.1.0:compile
[INFO] +- opensymphony:sitemesh:jar:2.4.2:compile
[INFO] +- org.springframework.security:spring-security-core-tiger:jar:2.0.3:compile
[INFO] | \- org.springframework.security:spring-security-core:jar:2.0.3:compile
[INFO] | +- org.springframework:spring-aop:jar:2.0.8:compile
[INFO] | +- org.springframework:spring-support:jar:2.0.8:runtime
[INFO] | \- commons-codec:commons-codec:jar:1.3:compile
[INFO] +- org.springframework.security:spring-security-taglibs:jar:2.0.3:compile
[INFO] | \- org.springframework.security:spring-security-acl:jar:2.0.3:compile
[INFO] | \- org.springframework:spring-jdbc:jar:2.0.8:compile
[INFO] | \- org.springframework:spring-dao:jar:2.0.8:compile
[INFO] +- org.json:json:jar:20140107:compile
[INFO] +- displaytag:displaytag:jar:1.2:compile
[INFO] | +- commons-collections:commons-collections:jar:3.1:compile
[INFO] | +- commons-lang:commons-lang:jar:2.3:compile
[INFO] | +- commons-beanutils:commons-beanutils:jar:1.7.0:compile
[INFO] | \- org.slf4j:jcl104-over-slf4j:jar:1.4.2:compile
[INFO] +- com.lowagie:itext:jar:2.1.7:compile
[INFO] | +- bouncycastle:bcmail-jdk14:jar:138:compile
[INFO] | +- bouncycastle:bcprov-jdk14:jar:138:compile
[INFO] | \- org.bouncycastle:bctsp-jdk14:jar:1.38:compile
[INFO] | +- org.bouncycastle:bcprov-jdk14:jar:1.38:compile
[INFO] | \- org.bouncycastle:bcmail-jdk14:jar:1.38:compile
[INFO] +- junit:junit:jar:4.10:compile
[INFO] | \- org.hamcrest:hamcrest-core:jar:1.1:compile
[INFO] \- c3p0:c3p0:jar:0.9.1:compile
[INFO]
error
[07-05-2015 15:41:27:928] ERROR org.springframework.web.context.ContextLoader.initWebApplicationContext() - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [applicationContext-main.xml]; nested exception is java.lang.NoSuchMethodError: org.springframework.aop.config.AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(Lorg/springframework/beans/factory/xml/ParserContext;Lorg/w3c/dom/Element;)V
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:420)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:788)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:434)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:780)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:284)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1322)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:732)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:490)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:69)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:118)
at org.eclipse.jetty.util.component.ContainerLifeCycle.addBean(ContainerLifeCycle.java:282)
at org.eclipse.jetty.util.component.ContainerLifeCycle.addBean(ContainerLifeCycle.java:214)
at org.eclipse.jetty.util.component.ContainerLifeCycle.updateBeans(ContainerLifeCycle.java:764)
at org.eclipse.jetty.server.handler.HandlerCollection.setHandlers(HandlerCollection.java:89)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.setHandlers(ContextHandlerCollection.java:145)
at org.eclipse.jetty.server.handler.HandlerCollection.addHandler(HandlerCollection.java:155)
at org.eclipse.jetty.deploy.bindings.StandardDeployer.processBinding(StandardDeployer.java:41)
at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:186)
at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:495)
at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:146)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:175)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:64)
at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:605)
at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:528)
at org.eclipse.jetty.util.Scanner.scan(Scanner.java:391)
at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:313)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:69)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:145)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:69)
at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:557)
at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:232)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:69)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:118)
at org.eclipse.jetty.server.Server.start(Server.java:342)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:100)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:60)
at org.eclipse.jetty.server.Server.doStart(Server.java:290)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:69)
at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1250)
at java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1174)
Caused by: java.lang.NoSuchMethodError: org.springframework.aop.config.AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(Lorg/springframework/beans/factory/xml/ParserContext;Lorg/w3c/dom/Element;)V
at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser$AopAutoProxyConfigurer.configureAutoProxyCreator(AnnotationDrivenBeanDefinitionParser.java:109)
at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser.parse(AnnotationDrivenBeanDefinitionParser.java:80)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:69)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1297)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1287)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:507)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
... 53 more
Error compiling c++ windows code in debian
I am new in using Debian with xfce and I want to compile a c++ code which require windows api. The error is windows.h is not found.
How can I run this code in debian:
#include <iostream>
#include <windows.h>
using namespace std;
int main(void) {
int life = 100;
HWND hWnd = NULL;
while (hWnd == 0)
{
hWnd = FindWindowA(0, "MyApp");
cout << "Waiting for Rastalia Fantasy ..." << endl;
Sleep(200);
system("cls");
}
if(hWnd != 0)
{
DWORD PID;
GetWindowThreadProcessId(hWnd, &PID);
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, false, PID);
while (true)
{
if(!hProc) {
cerr << "Cannot open process." << endl;
break;
} else {
if(GetAsyncKeyState(VK_LCONTROL))
{
int lifeResult = WriteProcessMemory(hProc, (LPVOID)0x00857D30, &life, (DWORD)sizeof(life), NULL);
if(lifeResult > 0){
clog << "Life changed." << endl;
}
}
}
}
CloseHandle(hProc);
cin.get();
}
return 0;
}
I have installed mingw32 and wine but when I start, the program don't found MyApp.
HP Fortify analysis results, system() command injection
I am trying to write c++ code that calls a command in a linux command line and I am using HP Fortify to check for exploits in the code. Can someone familiar with HP Fortify source analyzer tell me if it is possible to use a system() linux call in c++ code without getting the low threat warning from HP Fortify (low : Command Injection: semantic)? Is there still a threat of command injection if I hard code the input to the system() function while writing out full paths to the programs and/or files in the call? I don't understand a more secure way of giving it input than hard coding it in. Should I be ignoring the system() function and find another way to call commands from my c++ code to the linux command line?
Edit: I tried using execv() instead of system() to call a program but it still gives me the command injection warning for using execv().
How to add a name to namespace
Dear all:
As i kown, i can use the "clone" to create a process and a namespace, but the namespace created in this way has no name. For example, i create a network namespace with the parameter: CLONE_NEWNS, but in the command "ip netns list", there is no namespace list because the namespace created has no name. But i can use the command "ip netns add xxx" to create a namespace with the name "xxx".
I wonder how to create a namespace with name using system call "clone".
Thankyou verymuch for anyone's reply.
Best regards,
Vinllen
cpu load different to extract with python
I'm using psutil to remove the CPU load with python.
My problem is that with "top" in Linux shows:
top - 11:45:52 up 12:39, 1 user, load average: 0.07, 0.07, 0.09
Tasks: 58 total, 1 running, 57 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.4 us, 0.1 sy, 0.0 ni, 99.5 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem: 2097152 total, 315124 used, 1782028 free, 0 buffers
KiB Swap: 524288 total, 0 used, 524288 free, 139628 cached
In python view Usage : 3.75%
Mi code in python is:
proc = psutil.cpu_count()
for x in range(proc):
suma = suma + psutil.cpu_percent(interval=1)
usecpu = suma / proc
print(usecpu)
Thanks for help
C - Compilation of OpenSSL: No reference to BIO-functions
I'm trying to compile a c-program with openssl-references.
Starting position:
LinuxMint 17.1 and the development package "libssl-dev" is installed.
//...
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
//...
void send_smtp_request(BIO *bio, const char *req){
BIO_puts(bio, req);
BIO_flush(bio);
printf("%s", req);
}
//... more code
If I compile the code with:
gcc -o client bio-ssl-smtpcli2.c
I get the this error:
/tmp/ccCHrti2.o: In function 'send_smtp_request':
bio-ssl-smtpcli2.c:(.text+0x1f): undefined reference to 'BIO_puts'
bio-ssl-smtpcli2.c:(.text+0x3a): undefined reference to 'BIO_ctrl'
Someone has an idea how to fix this?
No module named distrib
I downloaded PyQRS which is a software for probabilistic and statstic, and i hit this error when i run python2.7 PyQRS27.pyc
Traceback (most recent call last):
File "PyQRS.py", line 19, in <module>
ImportError: No module named distrib
I need to find which libs provides this module. Any idea?
Bash script does not sort by file type after IF
I need some help, guys. I have a bash code
#!/bin/bash
echo "Iveskite kataloga, kurio analize norite atlikti"
read katalogas
failai=$(find -x $katalogas)
for failas in $failai
do
if [[ -d "$failas" ]]
then
echo $failas " yra direktorija "
else
if [[ -x "$failas" ]]
then
echo $failas " yra vykdomasis failas "
else
if [[ -f "$failas" ]]
then
echo $failas " yra paprastasis failas "
fi
fi
fi
done
I want to make, that the final result would be sorted by file type. I do this: failai=$(find -x $katalogas) but It seems not working.
Is it possible that when using sudo command it should first source a file?
I need to run a bunch of scripts (with sudo) that use a single file.sh as a configuration file for all. Initially I've put the file.sh in /etc/profile.d and when I ran the scripts as root everything was ok (because when I connected to the machine it first sourced the file.sh and all vars in that file were available) but now, for security reasons, I need to run them with another user with sudo rights.
When running with sudo the "configuration file" in /etc/profile.d does not get sourced even if I'm root and do sudo - it's the same.
Using "sudo -E" is not an option, also this kind of solution "Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"" does not work for me as the vars in the file change a lot and it's easier to throw a file, with all the vars, in a location - like /etc/profile.d/ - instead to adding options to /etc/sudoers.
Later Edit (working):
Moved original sudo command to sudo.orig. Created a new sudo bash script
[root@NS1 bin]# cat sudo
#!/bin/bash
source /etc/profile.d/set_env_vmdeploy.sh
sh /usr/bin/sudo.orig "$@"
and gave it permissions
[root@NS1 bin]# chmod 4111 sudo
[root@NS1 bin]# ll sudo*
---s--x--x 1 root root 78 May 7 13:42 sudo
---s--x--x 1 root root 123832 Jul 31 2014 sudo.orig
Linux Kali - persistent storage
This is my first experience with Linux and I have a Kali Linux Live CD on my external HD. I followed this tutorial to set up an encrypted and persistent partition.
my partitions at the moment
/dev/sdb1
/dev/sdb2 // file system
/dev/sdb3 // persistent storage ( Crypt-luks)
Now I wish to change my MAC address on each boot, so I added this to ect/netowrk/interfaces
ifconfig wlan0 down
macchanger -r wlan0
ifconfig wlan0 up
I can see the interfaces file has been created and updated in /lib/live/mount/persistence/sdb3/etc/network
The problem is that whenever I reboot my pc the commands I saved earlier are erased, and I basically find just an initial duplicate of interfaces
NullPointerException Playing Sound Clip on Linux
So, I made this 2D platformer game using Java AWT /Swing a few years back. When i tested it then at windows environment everything worked fine, but now that I am trying to test it in linux it always gets NullPointerException while trying to play sound. Here's my SoundEffects Class which is used throughout the game to play various sounds, it works perfectly in windows, but caused NullPointerException when i try to play the "jump" sound in linux.
package galib.platformer.sound;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JOptionPane;
import resources.ResourceLoader;
public class SoundEffects {
public HashMap<String, Clip> audioClips;
public void init() {
audioClips = new HashMap<String, Clip>();
try {
Clip backgroundSound = AudioSystem.getClip();
backgroundSound.open(AudioSystem.getAudioInputStream(new File("res/resources/sounds/background.wav")));
audioClips.put("background_music", backgroundSound);
Clip jumpSound = AudioSystem.getClip();
jumpSound.open(AudioSystem.getAudioInputStream(new File("res/resources/sounds/jump.wav")));
audioClips.put("jump_sound", jumpSound);
Clip gemsCollectSound = AudioSystem.getClip();
gemsCollectSound.open(AudioSystem.getAudioInputStream(new File("res/resources/sounds/gems.wav")));
audioClips.put("gems_sound", gemsCollectSound);
Clip destroySound = AudioSystem.getClip();
destroySound.open(AudioSystem.getAudioInputStream(new File("res/resources/sounds/destroy.wav")));
audioClips.put("destroy_sound", destroySound);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am not sure why is it causing NullPointerException when i run it on linux. Any guesses ? Thanks in advance. :)
linux kernel module not autoloading
I'm studing the linux kernel and start with hello world module at this point everything is fine but after compile
$ make
and install
$ insmod akmod.ko
the module it's not showing a "hello world" message on KERN_DEBUG
$ dmesg
nothing here
$
just show on rmmod
$ rmmod akmod
[4543.3423432] hello world
[5462.5323452] goodbye
The code is the same found here: http://ift.tt/1czSAi3
I just changed the KERN_ALERT for KERN_DEBUG
I'm using Debian 8.
I think that occurs because the module it´s not autoloading on insmod
When I run
$ make menuconfig
I can't find the option Automatic kernel module loading
Loadable module support --->
[*] Enable loadable module support
[*] Module unloading
[ ] Module versioning support (EXPERIMENTAL)
[*] Automatic kernel module loading **(My menu config don´t show this option)**
Any advice will be appreciated
Looping through an associative arrays with same key
I am currently trying to loop through an associative array. This array contains values with the same key. However, when i tried to loop through it, I only get one set of results. How can I loop through all the values containing the same key?
#!/bin/bash/
declare -A details=( [dog]="golden retriver" [cat]="bengal" [bird]="eagle" [dog]="bulldog" [cat]="sphynx" [bird]="parakeet" )
for k in "${!details[@]}"
do
echo $k --- ${details[$k]}
done
Result
cat --- sphynx
dog --- bulldog
bird --- parakeet
Segfault in class destructor
Have a segfault in generated by gcc destructor of my Token class (code below and first screenshot). Almostly code works well but sometimes falls randomly
Function: _ZNSsD2Ev
0xf77161af <+0x003f> lock xadd %ecx,-0x4(%eax)
0xf77161b4 <+0x0044> mov %ecx,%eax
0xf77161b6 <+0x0046> test %eax,%eax
0xf77161b8 <+0x0048> jg 0xf7716191 <_ZNSsD2Ev+33>
0xf77161ba <+0x004a> sub $0xc,%esp
0xf77161bd <+0x004d> push %edx
0xf77161be <+0x004e> call 0xf76a9c70 <_ZdlPv@plt>
0xf77161c3 <+0x0053> add $0x10,%esp //HERE
0xf77161c6 <+0x0056> jmp 0xf7716191 <_ZNSsD2Ev+33>
0xf77161c8 <+0x0058> nop
0xf77161c9 <+0x0059> lea 0x0(%esi,%eiz,1),%esi
0xf77161d0 <+0x0060> mov -0x4(%eax),%ecx
0xf77161d3 <+0x0063> lea -0x1(%ecx),%esi
0xf77161d6 <+0x0066> mov %esi,-0x4(%eax)
0xf77161d9 <+0x0069> mov %ecx,%eax
0xf77161db <+0x006b> jmp 0xf77161b6 <_ZNSsD2Ev+70>
0xf77161dd xchg %ax,%ax
Token class:
#ifndef TOKEN_H
#define TOKEN_H
#include <string>
#include <cstring>
#include <iostream>
#include "common.h"
using namespace std;
#define ICUR (inc(cur_pos))
class Token //Qt Creator's debugger shows segfault HERE
{
static const int EOL_REACHED = 0;
static const int UNKNOWN_ESCAPE = 1;
bool firstTime = true;
string src, last, cur;
uint cur_pos, last_pos; //I wanted to use string::iterator but it was a bug
//that was modifing all iterators after adding *cur_pos to result string after some chars
public:
enum TokenType {
String, Digit, Delim, Bool, Identifier, EOL, UNKNOWN
};
Token(string src) {
this->src = src + " ";
cur_pos = 0;
last = cur = Next();
last_pos = 0;
}
bool operator ==(string str) {
return this->ToString() == str;
}
bool operator !=(string str) {
return this->ToString() != str;
}
Token& operator>>(string& str) {
str = this->Next();
return *this;
}
string PushBack() {
cur_pos = last_pos;
cur = last;
return cur;
}
string ToString() {
return cur;
}
string Last() {
return last;
}
string Next() {
string res = "";
try {
last_pos = cur_pos;
last = cur;
res = cur = next();
} catch (int ex) {
switch(ex) {
case EOL_REACHED:
type = EOL;
res = "";
break;
case UNKNOWN_ESCAPE:
type = UNKNOWN;
res = "";
break;
}
}
firstTime = false;
return res;
}
string NextWhileNot(char ch, bool skip=false) {
string res = "";
res.reserve(src.length()+1);
try {
last_pos = cur_pos;
last = cur;
while(src[cur_pos] != ch && cur_pos != src.length()) {
res += src[cur_pos]; //sometimes falls with segfault HERE
ICUR;
}
if(skip) ICUR;
cur = res;
} catch (int ex) {
if(ex == EOL_REACHED) {
type = EOL;
res = "";
}
}
return res;
}
Token &NextToken() {
this->Next();
return *this;
}
TokenType Type() {
return type;
}
private:
TokenType type;
string next() {
//auto temp_pos = cur_pos;
//const auto temp_last = last_pos;
string result = "";
bool isCyr = false;
if(src[cur_pos] == '/' && src[cur_pos + 1] == '/') {
ICUR;
ICUR;
while(src[cur_pos] != '\n') ICUR;
}
while(strchr(" \t\r\n", src[cur_pos])) ICUR;
//cout << src[cur_pos] << endl;
if(firstTime && src[cur_pos] == '.') {
result += src[cur_pos];
ICUR;
while(isalpha(src[cur_pos]) || isdigit(src[cur_pos]) || src[cur_pos] == '-') {
result += src[cur_pos];
ICUR;
}
}
else if(isalpha(src[cur_pos]) || src[cur_pos] == '_' || (isCyr = isCyrillicAlpha())) {
result += src[cur_pos];
if(isCyr)
{
ICUR;
result += src[cur_pos];
}
ICUR;
while(isalpha(src[cur_pos]) || isdigit(src[cur_pos])
|| (strchr("_@$", src[cur_pos]) != NULL) || (isCyr = isCyrillicAlpha())) {
if(src[cur_pos] == '\0') break;
result.push_back(src[cur_pos]);
if(isCyr)
{
ICUR;
result.push_back(src[cur_pos]);
}
ICUR;
}
if(result == "true" || result == "false")
type = Bool;
else
type = Identifier;
}
else if(isdigit(src[cur_pos])) {
type = Digit;
result += src[cur_pos];
ICUR;
bool hasDot = false;
while ([&](){
if(src[cur_pos] == '.' && !hasDot) {
hasDot = true;
return true;
}
else if(isdigit(src[cur_pos])) return true;
return false;
}()) {
result += src[cur_pos];
ICUR;
}
}
else if(src[cur_pos] == '"') {
type = String;
ICUR;
while(src[cur_pos] != '"') {
if(src[cur_pos] == '\\') {
ICUR;
switch (src[cur_pos]) {
case '\\':
result += '\\';
break;
case 'a':
result += '\a';
break;
case 'b':
result += '\b';
break;
case 'v':
result += '\v';
break;
case 'n':
result += '\n';
break;
case 'r':
result += '\r';
break;
case 't':
result += '\t';
break;
case '0':
result += '\0';
break;
default:
throw UNKNOWN_ESCAPE;
}
}
else result += src[cur_pos];
ICUR;
}
ICUR;
}
else if(src[cur_pos] == '-' && src[cur_pos + 1] == '>') {
ICUR;
ICUR;
type = Delim;
result = "->";
}
else if(strchr(".,+-=(){}[]|\!@#%^*&~`<>:", src[cur_pos])) {
result = src[cur_pos];
type = Delim;
ICUR;
}
//cur_pos = temp_pos;
//last_pos = temp_last;
return result;
}
void inc(uint& iter) {
++iter;
if(iter >= src.length()) throw EOL_REACHED;
}
bool isCyrillicAlpha()
{
//int i = (byte)src[cur_pos];
//cout << i;
if((byte)src[cur_pos] != 208 && (byte)src[cur_pos] != 209)
return false;
byte ch = (byte)src[cur_pos + 1];
if(ch >= (byte)'а' && ch <= (byte)'п')
return true;
if(ch >= (byte)'р' && ch <= (byte)'я')
return true;
if(ch >= (byte)'А' && ch <= (byte)'Я')
return true;
return false;
}
};
#undef ICUR
#endif // TOKEN_H
Valgrind shows something like thah, but it doesn't refers to Token class but refers to vector:
==14463== Invalid read of size 4
==14463== at 0x8056127: std::vector<unsigned char, std::allocator<unsigned char> >::push_back(unsigned char const&) (stl_vector.h:915)
==14463== by 0x804FCF6: pushAddr(unsigned int, std::vector<unsigned char, std::allocator<unsigned char> >&) (assembler.cpp:741)
==14463== by 0x804F14F: Assembler::pushAddr(unsigned int, std::vector<unsigned char, std::allocator<unsigned char> >&) (assembler.cpp:596)
==14463== by 0x804D669: Assembler::compileFunc(Function&) (assembler.cpp:325)
==14463== by 0x804CAD6: Assembler::Compile() (assembler.cpp:224)
==14463== by 0x8049C82: main (main.cpp:21)
==14463== Address 0x4391134 is 92 bytes inside a block of size 928 free'd
==14463== at 0x402D7B8: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==14463== by 0x8060D02: __gnu_cxx::new_allocator<Function>::deallocate(Function*, unsigned int) (new_allocator.h:110)
==14463== by 0x805E603: std::allocator_traits<std::allocator<Function> >::deallocate(std::allocator<Function>&, Function*, unsigned int) (alloc_traits.h:383)
==14463== by 0x805B075: std::_Vector_base<Function, std::allocator<Function> >::_M_deallocate(Function*, unsigned int) (stl_vector.h:178)
==14463== by 0x805834B: void std::vector<Function, std::allocator<Function> >::_M_emplace_back_aux<Function const&>(Function const&) (vector.tcc:438)
==14463== by 0x8055DD5: std::vector<Function, std::allocator<Function> >::push_back(Function const&) (stl_vector.h:923)
==14463== by 0x804D639: Assembler::compileFunc(Function&) (assembler.cpp:322)
==14463== by 0x804CAD6: Assembler::Compile() (assembler.cpp:224)
==14463== by 0x8049C82: main (main.cpp:21)
==14463==
==14463== Invalid read of size 4
==14463== at 0x805612D: std::vector<unsigned char, std::allocator<unsigned char> >::push_back(unsigned char const&) (stl_vector.h:915)
==14463== by 0x804FCF6: pushAddr(unsigned int, std::vector<unsigned char, std::allocator<unsigned char> >&) (assembler.cpp:741)
==14463== by 0x804F14F: Assembler::pushAddr(unsigned int, std::vector<unsigned char, std::allocator<unsigned char> >&) (assembler.cpp:596)
==14463== by 0x804D669: Assembler::compileFunc(Function&) (assembler.cpp:325)
==14463== by 0x804CAD6: Assembler::Compile() (assembler.cpp:224)
==14463== by 0x8049C82: main (main.cpp:21)
==14463== Address 0x4391138 is 96 bytes inside a block of size 928 free'd
==14463== at 0x402D7B8: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==14463== by 0x8060D02: __gnu_cxx::new_allocator<Function>::deallocate(Function*, unsigned int) (new_allocator.h:110)
==14463== by 0x805E603: std::allocator_traits<std::allocator<Function> >::deallocate(std::allocator<Function>&, Function*, unsigned int) (alloc_traits.h:383)
==14463== by 0x805B075: std::_Vector_base<Function, std::allocator<Function> >::_M_deallocate(Function*, unsigned int) (stl_vector.h:178)
==14463== by 0x805834B: void std::vector<Function, std::allocator<Function> >::_M_emplace_back_aux<Function const&>(Function const&) (vector.tcc:438)
==14463== by 0x8055DD5: std::vector<Function, std::allocator<Function> >::push_back(Function const&) (stl_vector.h:923)
==14463== by 0x804D639: Assembler::compileFunc(Function&) (assembler.cpp:322)
==14463== by 0x804CAD6: Assembler::Compile() (assembler.cpp:224)
==14463== by 0x8049C82: main (main.cpp:21)
Linux shell file. mkdir and pushd commands not doing what I'd like
I'm trying to create a directory if it does not exist, and the further down the line, create a log file in that directory. It would be in the current users home directory
In pseudocode:
If directory "/home/LOGS" does not exist
make directory "/home/LOGS"
Then whenever a log file is created, it will save in that directory, not the directory that the program is being run from.
This is what I have so far, and it's just not working...
pushd -n $"../LOGS" >/dev/null 2>&1
#Create the logs folder
if [ ! -d $"home/LOGS" ]; then
mkdir -p $"home/LOGS"
fi
If it helps, my files are being saved like so:
function savefile {
# Save to file
if [ -e $username.log ]; then
echo "Username already exists, returning you to the menu."
sleep 2
clear
menu
else
echo $fullname >> $username.log
echo $password >> $username.log
curdate=$(date +'%d/%m/%Y %H:%M:%S')
echo $curdate >> $username.log
echo "Creating your account"
sleep 2
clear
echo "Account created"
echo
afterBasic
fi
}
Any help would be greatly appreciated.
how to get the coordinate of cursor when setting PS1 variable for command line prompt?
I'm using Mac. I want to set PS1 variable to get current time at the end of line in command line prompt. Like this: or this:
But, unfortunately, I can't get what I want through following configuration:
CYAN="\[$(tput setaf 6)\]"
GREEN="\[$(tput setaf 2)\]"
BLUE="\[$(tput setaf 4)\]"
YELLOW="\[$(tput setaf 3)\]"
export PS1="$GREEN\u$BLUE@$CYAN\h $YELLOW\w\[$(tput cuf $(($(tput cols)-33)))\]$CYAN\[$(date +%H:%M)\]\n\\$ "
It seems that I need to get the current position of cursor and do some computations based on the coordinate of the position, but I don't know how to get it. Is anyone can help?
how to compile and run java in linux with 3rd party jar and my own jar
I export my own project into a jar, and this project needs two 3rd-party jars, an extra TestMyJar.class is used to test my project, how to do this? I have tried several methods but no luck. To be more specific, this is my jar: a class that only delivers hello world message a url. I export this class code into a helloworld.jar
package com.wow.flow.http.dq;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
public class HttpConnection {
@SuppressWarnings("deprecation")
public void client() throws Exception {
String url = "www.someurl.com"; // sorry if this your registered url, just borrow it as an example
if (url == null) {
throw new Exception();
}
HttpClient client = new HttpClient();
PostMethod postMethod = new UTF8PostMethod(url);
try {
postMethod.setRequestBody("Hello world");
int statusCode = client.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
InputStream responseBody = postMethod.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(responseBody, "utf-8"));
String line = reader.readLine();
while (line != null) {
System.out.println(new String(line.getBytes()));
line = reader.readLine();
}
}
} catch (HttpException e) {
// TODO: handle exception
} catch (IOException e) {
// TODO: handle exception
} finally {
postMethod.releaseConnection();
}
}
// Inner class for UTF-8 support
public static class UTF8PostMethod extends PostMethod {
public UTF8PostMethod(String url) {
super(url);
}
@Override
public String getRequestCharSet() {
// return super.getRequestCharSet();
return "UTF-8";
}
}
}
It requires dom4j and httpclient. This is my TestMyJar.class:
package httptest
public class TestMyJar {
public static void main(String[] args) {
HttpConnection connection= new HttpConnection();
}
}
Now I have three jar: helloworld.jar, commons-httpclient-3.1.jar, dom4j-1.6.1.jar, and a class: TestMyJar.java. How can I compile and run TestMyJar.java? I have tried with javac and java, but it is all something cannot be found.
Thanks!
Grep\Sed between two tags with multiline
I have many files with whom I need to get information.
Example of my files:
first file content:
"test This info i need grep</singleline>"
and
second file content (with two lines):
"test This info=
i need grep too</singleline>"
in results i need grep this text: from first file - "This info i need grep" and from second file - "This info= i need grep too"
in first file i use:
grep -o 'test .*</singleline>' * | sed -e 's/test \(.*\)<\/singleline>/\1/'
and successfully get "This info i need grep" but I can not get the information from the second file by using the same command. Please help rewrite the command or write what the other. Very big thanks!