Programs & Examples On #Ruby on rails

Ruby on Rails is an open source full-stack web application framework written in Ruby. It follows the popular MVC framework model and is known for its "convention over configuration" approach to application development.

Rails formatting date

Since I18n is the Rails core feature starting from version 2.2 you can use its localize-method. By applying the forementioned strftime %-variables you can specify the desired format under config/locales/en.yml (or whatever language), in your case like this:

time:
  formats:
    default: '%FT%T'

Or if you want to use this kind of format in a few specific places you can refer it as a variable like this

time:
  formats:
    specific_format: '%FT%T'

After that you can use it in your views like this:

l(Mode.last.created_at, format: :specific_format)  

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4.x the log level is configured a bit different than in Rails 3.x

Add this to config/environment/test.rb

# Enable stdout logger
config.logger = Logger.new(STDOUT)

# Set log level
config.log_level = :ERROR

The logger level is set on the logger instance from config.log_level at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70

Environment variable

As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:

# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")

And then running tests from shell:

# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test

# Log level :ERROR
$ rake test

Is there a way to get a collection of all the Models in your Rails app?

Assuming all models are in app/models and you have grep & awk on your server (majority of the cases),

# extract lines that match specific string, and print 2nd word of each line
results = `grep -r "< ActiveRecord::Base" app/models/ | awk '{print $2}'`
model_names = results.split("\n")

It it faster than Rails.application.eager_load! or looping through each file with Dir.

EDIT:

The disadvantage of this method is that it misses models that indirectly inherit from ActiveRecord (e.g. FictionalBook < Book). The surest way is Rails.application.eager_load!; ActiveRecord::Base.descendants.map(&:name), even though it's kinda slow.

Server is already running in Rails

It happens when you kill your server process and the pid file was not updated. The best solution is to delete the file Server.pid.

Use the command

rm <path to file Server.pid>

Rails: FATAL - Peer authentication failed for user (PG::Error)

You can go to your /var/lib/pgsql/data/pg_hba.conf file and add trust in place of Ident It worked for me.

local   all all trust
host    all 127.0.0.1/32    trust

For further details refer to this issue Ident authentication failed for user

Rails Object to hash

@object.as_json

as_json has very flexible way to configure complex object according to model relations

EXAMPLE

Model campaign belongs to shop and has one list

Model list has many list_tasks and each of list_tasks has many comments

We can get one json which combines all those data easily.

@campaign.as_json(
    {
        except: [:created_at, :updated_at],
        include: {
            shop: {
                except: [:created_at, :updated_at, :customer_id],
                include: {customer: {except: [:created_at, :updated_at]}}},
            list: {
                except: [:created_at, :updated_at, :observation_id],
                include: {
                    list_tasks: {
                        except: [:created_at, :updated_at],
                        include: {comments: {except: [:created_at, :updated_at]}}
                    }
                }
            },
        },
        methods: :tags
    })

Notice methods: :tags can help you attach any additional object which doesn't have relations with others. You just need to define a method with name tags in model campaign. This method should return whatever you need (e.g. Tags.all)

Official documentation for as_json

How to tell if homebrew is installed on Mac OS X

use either the which or type built-in tools.

i.e.: which brew or type brew

Rails migration for change column

As I found by the previous answers, three steps are needed to change the type of a column:

Step 1:

Generate a new migration file using this code:

rails g migration sample_name_change_column_type

Step 2:

Go to /db/migrate folder and edit the migration file you made. There are two different solutions.

  1. def change
        change_column(:table_name, :column_name, :new_type)
    end
    

2.

    def up
        change_column :table_name, :column_name, :new_type
    end

    def down
        change_column :table_name, :column_name, :old_type
    end

Step 3:

Don't forget to do this command:

rake db:migrate

I have tested this solution for Rails 4 and it works well.

Rails: call another controller action from a controller

This is bad practice to call another controller action.

You should

  1. duplicate this action in your controller B, or
  2. wrap it as a model method, that will be shared to all controllers, or
  3. you can extend this action in controller A.

My opinion:

  1. First approach is not DRY but it is still better than calling for another action.
  2. Second approach is good and flexible.
  3. Third approach is what I used to do often. So I'll show little example.

    def create
      @my_obj = MyModel.new(params[:my_model])
      if @my_obj.save
        redirect_to params[:redirect_to] || some_default_path
       end
    end
    

So you can send to this action redirect_to param, which can be any path you want.

Rails create or update magic?

You can do it in one statement like this:

CachedObject.where(key: "the given key").first_or_create! do |cached|
   cached.attribute1 = 'attribute value'
   cached.attribute2 = 'attribute value'
end

How to HTML encode/escape a string? Is there a built-in?

The h helper method:

<%=h "<p> will be preserved" %>

Ruby on Rails: How do I add placeholder text to a f.text_field?

In Rails 4(Using HAML):

=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

make sure you're using the newest jquery, and problem solved

I met this problem with this code:

<script src="/scripts/plugins/jquery/jquery-1.6.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>

After change it to this:

<script src="/scripts/plugins/jquery/jquery-1.7.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>

It works fine

How to list all methods for an object in Ruby?

Suppose User has_many Posts:

u = User.first
u.posts.methods
u.posts.methods - Object.methods

How do you discover model attributes in Rails?

some_instance.attributes

Source: blog

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

Allow anything through CORS Policy

I've your same requirements on a public API for which I used rails-api.

I've also set header in a before filter. It looks like this:

headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

It seems you missed the Access-Control-Request-Method header.

Can you do greater than comparison on a date in a Rails 3 search?

If you aren't a fan of passing in a string, I prefer how @sesperanto has done it, except to make it even more concise, you could drop Float::INFINITY in the date range and instead simply use created_at: p[:date]..

Note.where(
    user_id: current_user.id,
    notetype: p[:note_type],
    created_at: p[:date]..
).order(:date, :created_at)

Take note that this will change the query to be >= instead of >. If that's a concern, you could always add a unit of time to the date by running something like p[:date] + 1.day..

Case-insensitive search in Rails model

Quoting from the SQLite documentation:

Any other character matches itself or its lower/upper case equivalent (i.e. case-insensitive matching)

...which I didn't know.But it works:

sqlite> create table products (name string);
sqlite> insert into products values ("Blue jeans");
sqlite> select * from products where name = 'Blue Jeans';
sqlite> select * from products where name like 'Blue Jeans';
Blue jeans

So you could do something like this:

name = 'Blue jeans'
if prod = Product.find(:conditions => ['name LIKE ?', name])
    # update product or whatever
else
    prod = Product.create(:name => name)
end

Not #find_or_create, I know, and it may not be very cross-database friendly, but worth looking at?

Ruby on Rails form_for select field with class

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

How can I specify a local gem in my Gemfile?

You can also reference a local gem with git if you happen to be working on it.

gem 'foo',
  :git => '/Path/to/local/git/repo',
  :branch => 'my-feature-branch'

Then, if it changes I run

bundle exec gem uninstall foo
bundle update foo

But I am not sure everyone needs to run these two steps.

How do you delete an ActiveRecord object?

  1. User.destroy

User.destroy(1) will delete user with id == 1 and :before_destroy and :after_destroy callbacks occur. For example if you have associated records

has_many :addresses, :dependent => :destroy

After user is destroyed his addresses will be destroyed too. If you use delete action instead, callbacks will not occur.

  1. User.destroy, User.delete

  2. User.destroy_all(<conditions>) or User.delete_all(<conditions>)

Notice: User is a class and user is an instance object

PG::ConnectionBad - could not connect to server: Connection refused

I have tried all of the answers above and it didn't work for me.

In my case when I chekced the log on /usr/local/var/log/postgres.log. It was fine no error. But I could see that it was listening my local IPV6 address which is "::1"

In my database.yml I was did it like this

host:     <%= ENV['POSTGRESQL_ADDON_HOST'] || '127.0.0.1' %>

I changed it by

host:     <%= ENV['POSTGRESQL_ADDON_HOST'] || 'localhost' %>

and then it worked

ActiveRecord: size vs count

The following strategies all make a call to the database to perform a COUNT(*) query.

Model.count

Model.all.size

records = Model.all
records.count

The following is not as efficient as it will load all records from the database into Ruby, which then counts the size of the collection.

records = Model.all
records.size

If your models have associations and you want to find the number of belonging objects (e.g. @customer.orders.size), you can avoid database queries (disk reads). Use a counter cache and Rails will keep the cache value up to date, and return that value in response to the size method.

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

How to use concerns in Rails 4

I felt most of the examples here demonstrated the power of module rather than how ActiveSupport::Concern adds value to module.

Example 1: More readable modules.

So without concerns this how a typical module will be.

module M
  def self.included(base)
    base.extend ClassMethods
    base.class_eval do
      scope :disabled, -> { where(disabled: true) }
    end
  end

  def instance_method
    ...
  end

  module ClassMethods
    ...
  end
end

After refactoring with ActiveSupport::Concern.

require 'active_support/concern'

module M
  extend ActiveSupport::Concern

  included do
    scope :disabled, -> { where(disabled: true) }
  end

  class_methods do
    ...
  end

  def instance_method
    ...
  end
end

You see instance methods, class methods and included block are less messy. Concerns will inject them appropriately for you. That's one advantage of using ActiveSupport::Concern.


Example 2: Handle module dependencies gracefully.

module Foo
  def self.included(base)
    base.class_eval do
      def self.method_injected_by_foo_to_host_klass
        ...
      end
    end
  end
end

module Bar
  def self.included(base)
    base.method_injected_by_foo_to_host_klass
  end
end

class Host
  include Foo # We need to include this dependency for Bar
  include Bar # Bar is the module that Host really needs
end

In this example Bar is the module that Host really needs. But since Bar has dependency with Foo the Host class have to include Foo (but wait why does Host want to know about Foo? Can it be avoided?).

So Bar adds dependency everywhere it goes. And order of inclusion also matters here. This adds lot of complexity/dependency to huge code base.

After refactoring with ActiveSupport::Concern

require 'active_support/concern'

module Foo
  extend ActiveSupport::Concern
  included do
    def self.method_injected_by_foo_to_host_klass
      ...
    end
  end
end

module Bar
  extend ActiveSupport::Concern
  include Foo

  included do
    self.method_injected_by_foo_to_host_klass
  end
end

class Host
  include Bar # It works, now Bar takes care of its dependencies
end

Now it looks simple.

If you are thinking why can't we add Foo dependency in Bar module itself? That won't work since method_injected_by_foo_to_host_klass have to be injected in a class that's including Bar not on Bar module itself.

Source: Rails ActiveSupport::Concern

How do I set up the database.yml file in Rails?

At first I would use http://ruby.railstutorial.org/.

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.

How to change Rails 3 server default port in develoment?

I like to append the following to config/boot.rb:

require 'rails/commands/server'

module Rails
  class Server
    alias :default_options_alias :default_options
    def default_options
      default_options_alias.merge!(:Port => 3333)
    end    
  end
end

Nested attributes unpermitted parameters

From the docs

To whitelist an entire hash of parameters, the permit! method can be used

params.require(:log_entry).permit!

Nested attributes are in the form of a hash. In my app, I have a Question.rb model accept nested attributes for an Answer.rb model (where the user creates answer choices for a question he creates). In the questions_controller, I do this

  def question_params

      params.require(:question).permit!

  end

Everything in the question hash is permitted, including the nested answer attributes. This also works if the nested attributes are in the form of an array.

Having said that, I wonder if there's a security concern with this approach because it basically permits anything that's inside the hash without specifying exactly what it is, which seems contrary to the purpose of strong parameters.

Ruby on Rails generates model field:type - what are the options for field:type?

$ rails g model Item name:string description:text product:references

I too found the guides difficult to use. Easy to understand, but hard to find what I am looking for.

Also, I have temp projects that I run the rails generate commands on. Then once I get them working I run it on my real project.

Reference for the above code: http://guides.rubyonrails.org/getting_started.html#associating-models

rails generate model

For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.

So when I ran

rails generate scaffold User name:string email:string

the console showed

Usage:
   rails new APP_PATH [options]

So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed

 rails generate scaffold User name:string email:string

and it worked

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Rails.env vs RAILS_ENV

Before Rails 2.x the preferred way to get the current environment was using the RAILS_ENV constant. Likewise, you can use RAILS_DEFAULT_LOGGER to get the current logger or RAILS_ROOT to get the path to the root folder.

Starting from Rails 2.x, Rails introduced the Rails module with some special methods:

  • Rails.root
  • Rails.env
  • Rails.logger

This isn't just a cosmetic change. The Rails module offers capabilities not available using the standard constants such as StringInquirer support. There are also some slight differences. Rails.root doesn't return a simple String buth a Path instance.

Anyway, the preferred way is using the Rails module. Constants are deprecated in Rails 3 and will be removed in a future release, perhaps Rails 3.1.

Is it possible to set ENV variables for rails development environment in my code?

As an aside to the solutions here, there are cleaner alternatives if you're using certain development servers.

With Heroku's Foreman, you can create per-project environment variables in a .env file:

ADMIN_PASSOWRD="secret"

With Pow, you can use a .powenv file:

export ADMIN_PASSOWRD="secret"

Reset the database (purge all), then seed a database

You can delete everything and recreate database + seeds with both:

  1. rake db:reset: loads from schema.rb
  2. rake db:drop db:create db:migrate db:seed: loads from migrations

Make sure you have no connections to db (rails server, sql client..) or the db won't drop.

schema.rb is a snapshot of the current state of your database generated by:

rake db:schema:dump

TypeError: no implicit conversion of Symbol into Integer

Ive come across this many times in my work, an easy work around that I found is to ask if the array element is a Hash by class.

if i.class == Hash

    notation like i[:label] will work in this block and not throw that error

end

rails bundle clean

If you are using RVM you can install your gems into gemsets. That way when you want to perform a full cleanup you can simply remove the gemset, which in turn removes all the gems installed in it. Your other option is to simply uninstall your unused gems and re-run your bundle install command.

Since bundler is meant to be a project-per-project gem versioning tool it does not provide a bundle clean command. Doing so would mean the possibility of removing gems associated with other projects as well, which would not be desirable. That means that bundler is probably the wrong tool to use to manage your gem directory. My personal recommendation would be to use RVM gemsets to sandbox your gems in certain projects or ruby versions.

Rails :include vs. :joins

.joins will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again

:includes will eager load the included associations and add them in memory. :includes loads all the included tables attributes. If you call associations on include query result, it will not fire any queries

How do you write a migration to rename an ActiveRecord model and its table in Rails?

The other answers and comments covered table renaming, file renaming, and grepping through your code.

I'd like to add a few more caveats:

Let's use a real-world example I faced today: renaming a model from 'Merchant' to 'Business.'

  • Don't forget to change the names of dependent tables and models in the same migration. I changed my Merchant and MerchantStat models to Business and BusinessStat at the same time. Otherwise I'd have had to do way too much picking and choosing when performing search-and-replace.
  • For any other models that depend on your model via foreign keys, the other tables' foreign-key column names will be derived from your original model name. So you'll also want to do some rename_column calls on these dependent models. For instance, I had to rename the 'merchant_id' column to 'business_id' in various join tables (for has_and_belongs_to_many relationship) and other dependent tables (for normal has_one and has_many relationships). Otherwise I would have ended up with columns like 'business_stat.merchant_id' pointing to 'business.id'. Here's a good answer about doing column renames.
  • When grepping, remember to search for singular, plural, capitalized, lowercase, and even UPPERCASE (which may occur in comments) versions of your strings.
  • It's best to search for plural versions first, then singular. That way if you have an irregular plural - such as in my merchants :: businesses example - you can get all the irregular plurals correct. Otherwise you may end up with, for example, 'businesss' (3 s's) as an intermediate state, resulting in yet more search-and-replace.
  • Don't blindly replace every occurrence. If your model names collide with common programming terms, with values in other models, or with textual content in your views, you may end up being too over-eager. In my example, I wanted to change my model name to 'Business' but still refer to them as 'merchants' in the content in my UI. I also had a 'merchant' role for my users in CanCan - it was the confusion between the merchant role and the Merchant model that caused me to rename the model in the first place.

Testing for empty or nil-value string

If you're in Rails, .blank? should be the method you are looking for:

a = nil
b = []
c = ""

a.blank? #=> true
b.blank? #=> true
c.blank? #=> true

d = "1"
e = ["1"]

d.blank? #=> false
e.blank? #=> false

So the answer would be:

variable = id if variable.blank?

ActionController::InvalidAuthenticityToken

In rails 5, we need to add 2 lines of code

    skip_before_action :verify_authenticity_token
    protect_from_forgery prepend: true, with: :exception

Rails 4 Authenticity Token

If you're using jQuery with rails, be wary of allowing entry to methods without verifying the authenticity token.

jquery-ujs can manage the tokens for you

You should have it already as part of the jquery-rails gem, but you might need to include it in application.js with

//= require jquery_ujs

That's all you need - your ajax call should now work

For more information, see: https://github.com/rails/jquery-ujs

Rails DateTime.now without Time

If you want today's date without the time, just use Date.today

Rails: Adding an index after adding column

You can run another migration, just for the index:

class AddIndexToTable < ActiveRecord::Migration
  def change
    add_index :table, :user_id
  end
end

ActiveModel::ForbiddenAttributesError when creating new user

For those using CanCanCan:

You will get this error if CanCanCan cannot find the correct params method.

For the :create action, CanCan will try to initialize a new instance with sanitized input by seeing if your controller will respond to the following methods (in order):

  1. create_params
  2. <model_name>_params such as article_params (this is the default convention in rails for naming your param method)
  3. resource_params (a generically named method you could specify in each controller)

Additionally, load_and_authorize_resource can now take a param_method option to specify a custom method in the controller to run to sanitize input.

You can associate the param_method option with a symbol corresponding to the name of a method that will get called:

class ArticlesController < ApplicationController
  load_and_authorize_resource param_method: :my_sanitizer

  def create
    if @article.save
      # hurray
    else
      render :new
    end
  end

  private

  def my_sanitizer
    params.require(:article).permit(:name)
  end
end

source: https://github.com/CanCanCommunity/cancancan#33-strong-parameters

ActiveRecord OR query

Book.where.any_of(Book.where(:author => 'Poe'), Book.where(:author => 'Hemingway')

Rails: Why "sudo" command is not recognized?

Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions.

Windows does not have (need?) this.

Run the command with the sudo removed from the start.

Facebook how to check if user has liked page and show content?

There is an article here that describes your problem

http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/

    <fb:visible-to-connection>
       Fans will see this content.
       <fb:else>
           Non-fans will see this content.
       </fb:else>
    </fb:visible-to-connection>

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

Rails: Can't verify CSRF token authenticity when making a POST request

Another way to turn off CSRF that won't render a null session is to add:

skip_before_action :verify_authenticity_token

in your Rails Controller. This will ensure you still have access to session info.

Again, make sure you only do this in API controllers or in other places where CSRF protection doesn't quite apply.

Can I get the name of the current controller in the view?

controller_name holds the name of the controller used to serve the current view.

Difference between rake db:migrate db:reset and db:schema:load

You could simply look in the Active Record Rake tasks as that is where I believe they live as in this file. https://github.com/rails/rails/blob/fe1f4b2ad56f010a4e9b93d547d63a15953d9dc2/activerecord/lib/active_record/tasks/database_tasks.rb

What they do is your question right?

That depends on where they come from and this is just and example to show that they vary depending upon the task. Here we have a different file full of tasks.

https://github.com/rails/rails/blob/fe1f4b2ad56f010a4e9b93d547d63a15953d9dc2/activerecord/Rakefile

which has these tasks.

namespace :db do
  task create: ["db:mysql:build", "db:postgresql:build"]
  task drop: ["db:mysql:drop", "db:postgresql:drop"]
end

This may not answer your question but could give you some insight into go ahead and look the source over especially the rake files and tasks. As they do a pretty good job of helping you use rails they don't always document the code that well. We could all help there if we know what it is supposed to do.

Best way to load module/class from lib folder in Rails 3?

config.autoload_paths does not work for me. I solve it in other way

Ruby on rails 3 do not automatic reload (autoload) code from /lib folder. I solve it by putting inside ApplicationController

Dir["lib/**/*.rb"].each do |path|
  require_dependency path
end 

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

Rails: select unique values from a column

Model.uniq.pluck(:rating)

# SELECT DISTINCT "models"."rating" FROM "models"

This has the advantages of not using sql strings and not instantiating models

Failed to build gem native extension — Rails install

The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.

sudo apt-get install ruby-all-dev

worked for me.

Ruby on Rails: how to render a string as HTML?

You are mixing your business logic with your content. Instead, I'd recommend sending the data to your page and then using something like JQuery to place the data where you need it to go.

This has the advantage of keeping all your HTML in the HTML pages where it belongs so your web designers can modify the HTML later without having to pour through server side code.

Or if you're not wanting to use JavaScript, you could try this:

@str = "Hi"

<b><%= @str ></b>

At least this way your HTML is in the HTML page where it belongs.

Use YAML with variables

This is an old post, but I had a similar need and this is the solution I came up with. It is a bit of a hack, but it works and could be refined.

require 'erb'
require 'yaml'

doc = <<-EOF
  theme:
  name: default
  css_path: compiled/themes/<%= data['theme']['name'] %>
  layout_path: themes/<%= data['theme']['name'] %>
  image_path: <%= data['theme']['css_path'] %>/images
  recursive_path: <%= data['theme']['image_path'] %>/plus/one/more
EOF

data = YAML::load("---" + doc)

template = ERB.new(data.to_yaml);
str = template.result(binding)
while /<%=.*%>/.match(str) != nil
  str = ERB.new(str).result(binding)
end

puts str

A big downside is that it builds into the yaml document a variable name (in this case, "data") that may or may not exist. Perhaps a better solution would be to use $ and then substitute it with the variable name in Ruby prior to ERB. Also, just tested using hashes2ostruct which allows data.theme.name type notation which is much easier on the eyes. All that is required is to wrap the YAML::load with this

data = hashes2ostruct(YAML::load("---" + doc))

Then your YAML document can look like this

doc = <<-EOF
  theme:
  name: default
  css_path: compiled/themes/<%= data.theme.name %>
  layout_path: themes/<%= data.theme.name %>
  image_path: <%= data.theme.css_path %>/images
  recursive_path: <%= data.theme.image_path %>/plus/one/more
EOF

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I have solved this, eventually!

I re-installed Ruby and Rails under RVM. I'm using Ruby version 1.9.2-p136.

After re-installing under rvm, this error was still present.

In the end the magic command that solved it was:

sudo install_name_tool -change libmysqlclient.16.dylib /usr/local/mysql/lib/libmysqlclient.16.dylib ~/.rvm/gems/ruby-1.9.2-p136/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle

Hope this helps someone else!

How to check for a JSON response using RSpec?

A lot of the above answers are a bit out of date, so this is a quick summary for a more recent version of RSpec (3.8+). This solution raises no warnings from rubocop-rspec and is inline with rspec best practices:

A successful JSON response is identified by two things:

  1. The content type of the response is application/json
  2. The body of the response can be parsed without errors

Assuming that the response object is the anonymous subject of the test, both of the above conditions can be validate using Rspec's built in matchers:

context 'when response is received' do
  subject { response }

  # check for a successful JSON response
  it { is_expected.to have_attributes(content_type: include('application/json')) }
  it { is_expected.to have_attributes(body: satisfy { |v| JSON.parse(v) }) }

  # validates OP's condition
  it { is_expected.to satisfy { |v| JSON.parse(v.body).key?('success') }
  it { is_expected.to satisfy { |v| JSON.parse(v.body)['success'] == true }
end

If you're prepared to name your subject then the above tests can be simplified further:

context 'when response is received' do
  subject(:response) { response }

  it 'responds with a valid content type' do
    expect(response.content_type).to include('application/json')
  end

  it 'responds with a valid json object' do
    expect { JSON.parse(response.body) }.not_to raise_error
  end

  it 'validates OPs condition' do
    expect(JSON.parse(response.body, symoblize_names: true))
      .to include(success: true)
  end
end

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

If you want to keep your version same like rails will be 2.3.8 and gem version will be latest. You can use this solution Latest gem with Rails2.x. in this some changes in boot.rb file and environment.rb file.

require 'thread' in boot.rb file at the top.

and in environment.rb file add the following code above the initializer block.

if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.3.7')
 module Rails
   class GemDependency
     def requirement
       r = super
       (r == Gem::Requirement.default) ? nil : r
     end
   end
 end
end

Which Ruby version am I really running?

Run this command:

rvm get stable --auto-dotfiles

and make sure to read all the output. RVM will tell you if something is wrong, which in your case might be because GEM_HOME is set to something different then PATH.

How to drop columns using Rails migration

first try to create a migration file running the command:

rails g migration RemoveAgeFromUsers age:string

and then on the root directory of the project run the migration running the command:

rails db:migrate

Add a reference column migration in Rails 4

[Using Rails 5]

Generate migration:

rails generate migration add_user_reference_to_uploads user:references

This will create the migration file:

class AddUserReferenceToUploads < ActiveRecord::Migration[5.1]
  def change
    add_reference :uploads, :user, foreign_key: true
  end
end

Now if you observe the schema file, you will see that the uploads table contains a new field. Something like: t.bigint "user_id" or t.integer "user_id".

Migrate database:

rails db:migrate

How do I get the name of a Ruby class?

You want to call .name on the object's class:

result.class.name

535-5.7.8 Username and Password not accepted

Time flies, the way I do without enabling less secured app is making a password for specific app

Step one: enable 2FA

Step two: create an app-specific password

After this, put the sixteen digits password to the settings and reload the app, enjoy!

  config.action_mailer.smtp_settings = {
    ...
    password: 'HERE', # <---
    authentication: 'plain',
    enable_starttls_auto: true
  }

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

I've tried both these and still get failure due to conflicts. At the end of my patience, I cloned master in another location, copied everything into the other branch and committed it. which let me continue. The "-X theirs" option should have done this for me, but it did not.

git merge -s recursive -X theirs master

error: 'merge' is not possible because you have unmerged files. hint: Fix them up in the work tree, hint: and then use 'git add/rm ' as hint: appropriate to mark resolution and make a commit, hint: or use 'git commit -a'. fatal: Exiting because of an unresolved conflict.

How to get the selected date value while using Bootstrap Datepicker?

There are many solutions here but probably the best one that works. Check the version of the script you want to use.

Well at least I can give you my 100% working solution for

version : 4.17.45

bootstrap-datetimejs https://github.com/Eonasdan/bootstrap-datetimepicker Copyright (c) 2015 Jonathan Peterson

JavaScript

var startdate = $('#startdate').val(); 

The output looks like: 12.09.2018 03:05

Rails 4: List of available datatypes

Rails4 has some added datatypes for Postgres.

For example, railscast #400 names two of them:

Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.

Besides, you can also use cidr, inet and macaddr. For more information:

https://blog.engineyard.com/2013/new-in-rails-4

Passing parameters in rails redirect_to

redirect_to :controller => "controller_name", :action => "action_name", :id => x.id

Correct MySQL configuration for Ruby on Rails Database.yml file

If you have multiple databases for testing and development this might help

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost
production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: DBNAME
  pool: 5
  username: usr
  password: paswd
  shost: localhost

How do I explicitly specify a Model's table-name mapping in Rails?

Rails >= 3.2 (including Rails 4+ and 5+):

class Countries < ActiveRecord::Base
  self.table_name = "cc"
end

Rails <= 3.1:

class Countries < ActiveRecord::Base
  self.set_table_name "cc"
  ...
end

How I can check if an object is null in ruby on rails 2?

You can check if an object is nil (null) by calling present? or blank? .

@object.present?

this will return false if the project is an empty string or nil .

or you can use

@object.blank?

this is the same as present? with a bang and you can use it if you don't like 'unless'. this will return true for an empty string or nil .

unable to install pg gem

gem install pg -- --with-pg-config=/usr/pgsql-9.1/bin/pg_config

Create a new Ruby on Rails application using MySQL instead of SQLite

For Rails 3 you can use this command to create a new project using mysql:

$ rails new projectname -d mysql

Elastic Search: how to see the indexed data

Aggregation Solution

Solving the problem by grouping the data - DrTech's answer used facets in managing this but, will be deprecated according to Elasticsearch 1.0 reference.

Warning

Facets are deprecated and will be removed in a future release. You are encouraged to
migrate to aggregations instead.

Facets are replaced by aggregates - Introduced in an accessible manner in the Elasticsearch Guide - which loads an example into sense..

Short Solution

The solution is the same except aggregations require aggs instead of facets and with a count of 0 which sets limit to max integer - the example code requires the Marvel Plugin

# Basic aggregation
GET /houses/occupier/_search?search_type=count
{
    "aggs" : {
        "indexed_occupier_names" : {    <= Whatever you want this to be
            "terms" : {
              "field" : "first_name",    <= Name of the field you want to aggregate
              "size" : 0
            }
        }
    }
}

Full Solution

Here is the Sense code to test it out - example of a houses index, with an occupier type, and a field first_name:

DELETE /houses

# Index example docs
POST /houses/occupier/_bulk
{ "index": {}}
{ "first_name": "john" }
{ "index": {}}
{ "first_name": "john" }
{ "index": {}}
{ "first_name": "mark" }


# Basic aggregation
GET /houses/occupier/_search?search_type=count
{
    "aggs" : {
        "indexed_occupier_names" : {
            "terms" : {
              "field" : "first_name",
              "size" : 0
            }
        }
    }
}

Response

Response showing the relevant aggregation code. With two keys in the index, John and Mark.

    ....
    "aggregations": {
      "indexed_occupier_names": {
         "buckets": [
            {
               "key": "john",     
               "doc_count": 2     <= 2 documents matching
            },                        
            {
               "key": "mark",
               "doc_count": 1     <= 1 document matching
            }
         ]
      }
   }
   ....

Postgres could not connect to server

This happened to me when I upgraded from 9.3.4 to 9.5 as the databases are incompatible without upgrading.

I used pg_upgrade as follows:

Stop postgres

$ brew services stop postgresql

Upgrade the databases:

$ pg_upgrade \
   -d /usr/local/var/postgres \
   -D /usr/local/var/postgres9.5 \
   -b /usr/local/Cellar/postgresql/9.3.4/bin/ \
   -B /usr/local/Cellar/postgresql/9.5.0/bin/ \
   -v

Archive the old databases:

 $ mv /usr/local/var/postgres /usr/local/var/postgres9.3.save
 $ mv /usr/local/var/postgres9.5 /usr/local/var/postgres

Restart postgres:

 $ brew services start postgresql

Updated Gems (for rails / active record) :

 $ gem uninstall pg
 $ gem uninstall activerecord-postgresql-adapter
 $ bundle install

How to put two divs on the same line with CSS in simple_form in rails?

why not use flexbox ? so wrap them into another div like that

_x000D_
_x000D_
.flexContainer { _x000D_
   _x000D_
  margin: 2px 10px;_x000D_
  display: flex;_x000D_
} _x000D_
_x000D_
.left {_x000D_
  flex-basis : 30%;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  flex-basis : 30%;_x000D_
}
_x000D_
<form id="new_production" class="simple_form new_production" novalidate="novalidate" method="post" action="/projects/1/productions" accept-charset="UTF-8">_x000D_
    <div style="margin:0;padding:0;display:inline">_x000D_
        <input type="hidden" value="?" name="utf8">_x000D_
        <input type="hidden" value="2UQCUU+tKiKKtEiDtLLNeDrfBDoHTUmz5Sl9+JRVjALat3hFM=" name="authenticity_token">_x000D_
    </div>_x000D_
    <div class="flexContainer">_x000D_
      <div class="left">Proj Name:</div>_x000D_
      <div class="right">must have a name</div>_x000D_
    </div>_x000D_
    <div class="input string required"> </div>_x000D_
 </form>
_x000D_
_x000D_
_x000D_

feel free to play with flex-basis percentage to get more customized space.

Change a column type from Date to DateTime during ROR migration

AFAIK, migrations are there to try to reshape data you care about (i.e. production) when making schema changes. So unless that's wrong, and since he did say he does not care about the data, why not just modify the column type in the original migration from date to datetime and re-run the migration? (Hope you've got tests:)).

form_for with nested resources

Be sure to have both objects created in controller: @post and @comment for the post, eg:

@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)

Then in view:

<%= form_for([@post, @comment]) do |f| %>

Be sure to explicitly define the array in the form_for, not just comma separated like you have above.

How to delete migration files in Rails 3

I just had this same problem:

  1. rails d migration fuu -this deleted the migration with the last timestamp
  2. rails d migration fuu -this deleted the other migration
  3. use git status to check that is not on the untracked files anymore
  4. rails g migration fuu

That fixed it for me

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

<% %> and <%- and -%> are for any Ruby code, but doesn't output the results (e.g. if statements). the two are the same.

<%= %> is for outputting the results of Ruby code

<%# %> is an ERB comment

Here's a good guide: http://api.rubyonrails.org/classes/ActionView/Base.html

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

As a Windows 10 user, I followed Dheerendra's answer, and it worked for me one day. The next day, I experienced the issue again, and his fix didn't work. For me, the fix was to update bundler with:

gem update bundler

I believe my version of bundler was more than a few months old.

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

None of the above answers fixed my issue.

The above answers are probably more likely the cause of your problem but my issue was that I was using the wrong bucket name. It was a valid bucket name, it just wasn't my bucket.

The bucket I was pointing to was in a different region that my lambda function so check your bucket name!

Rails select helper - Default selected value, how?

This should work for you. It just passes {:value => params[:pid] } to the html_options variable.

<%= f.select :project_id, @project_select, {}, {:value => params[:pid] } %>

Rails: How can I rename a database column in a Ruby on Rails migration?

Generate the migration file:

rails g migration FixName

# Creates db/migrate/xxxxxxxxxx.rb

Edit the migration to do your will.

class FixName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end

Add a default value to a column through a migration

change_column_default :employees, :foreign, false

Best way to create unique token in Rails?

If you want something that will be unique you can use something like this:

string = (Digest::MD5.hexdigest "#{ActiveSupport::SecureRandom.hex(10)}-#{DateTime.now.to_s}")

however this will generate string of 32 characters.

There is however other way:

require 'base64'

def after_create
update_attributes!(:token => Base64::encode64(id.to_s))
end

for example for id like 10000, generated token would be like "MTAwMDA=" (and you can easily decode it for id, just make

Base64::decode64(string)

Ruby on Rails: Where to define global constants?

Use a class method:

def self.colours
  ['white', 'red', 'black']
end

Then Model.colours will return that array. Alternatively, create an initializer and wrap the constants in a module to avoid namespace conflicts.

How to rollback a specific migration?

To roll back all migrations up to a particular version (e.g. 20181002222222), use:

rake db:migrate VERSION=20181002222222

(Note that this uses db:migrate -- not db:migrate:down as in other answers to this question.)

Assuming the specified migration version is older than the current version, this will roll back all migrations up to, but not including, the specified version.

For example, if rake db:migrate:status initially displays:

  (... some older migrations ...)
  up      20181001002039  Some migration description
  up      20181002222222  Some migration description
  up      20181003171932  Some migration description
  up      20181004211151  Some migration description
  up      20181005151403  Some migration description

Running:

rake db:migrate VERSION=20181002222222

Will result in:

  (... some older migrations ...)
  up      20181001002039  Some migration description
  up      20181002222222  Some migration description
  down    20181003171932  Some migration description
  down    20181004211151  Some migration description
  down    20181005151403  Some migration description

Reference: https://makandracards.com/makandra/845-migrate-or-revert-only-some-migrations

Rails - controller action name to string

In the specific case of a Rails action (as opposed to the general case of getting the current method name) you can use params[:action]

Alternatively you might want to look into customising the Rails log format so that the action/method name is included by the format rather than it being in your log message.

Rails 3.1 and Image Assets

In 3.1 you just get rid of the 'images' part of the path. So an image that lives in /assets/images/example.png will actually be accessible in a get request at this url - /assets/example.png

Because the assets/images folder gets generated along with a new 3.1 app, this is the convention that they probably want you to follow. I think that's where image_tag will look for it, but I haven't tested that yet.

Also, during the RailsConf keynote, I remember D2h saying the the public folder should not have much in it anymore, mostly just error pages and a favicon.

How to get a random number in Ruby

Don't forget to seed the RNG with srand() first.

incompatible character encodings: ASCII-8BIT and UTF-8

Try to find the exact line which causing this problem and then enforce UTF8 coding, this solution worked for me.

title.to_s.force_encoding("UTF-8")

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I have a project that uses generators a lot and needed this to be automatic, so I copied the index_name function from the rails source to override it. I added this in config/initializers/generated_index_name.rb:

# make indexes shorter for postgres
require "active_record/connection_adapters/abstract/schema_statements"
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module SchemaStatements
      def index_name(table_name, options) #:nodoc:
        if Hash === options
          if options[:column]
            "ix_#{table_name}_on_#{Array(options[:column]) * '__'}".slice(0,63)
          elsif options[:name]
            options[:name]
          else
            raise ArgumentError, "You must specify the index name"
          end
        else
          index_name(table_name, index_name_options(options))
        end
      end
    end
  end
end

It creates indexes like ix_assignments_on_case_id__project_id and just truncates it to 63 characters if it's still too long. That's still going to be non-unique if the table name is very long, but you can add complications like shortening the table name separately from the column names or actually checking for uniqueness.

Note, this is from a Rails 5.2 project; if you decide to do this, copy the source from your version.

Rails 4 LIKE query - ActiveRecord adds quotes

While string interpolation will work, as your question specifies rails 4, you could be using Arel for this and keeping your app database agnostic.

def self.search(query, page=1)
  query = "%#{query}%"
  name_match = arel_table[:name].matches(query)
  postal_match = arel_table[:postal_code].matches(query)
  where(name_match.or(postal_match)).page(page).per_page(5)
end

Rails: How to reference images in CSS within Rails 4

Only this snippet does not work for me:

background-image: url(image_path('transparent_2x2.png'));

But rename stylename.scss to stylename.css.scss helps me.

Transform DateTime into simple Date in Ruby on Rails

I recently wrote a gem to simplify this process and to neaten up your views, etc etc.

Check it out at: http://github.com/platform45/easy_dates

How do I see active SQL Server connections?

You can use the sp_who stored procedure.

Provides information about current users, sessions, and processes in an instance of the Microsoft SQL Server Database Engine. The information can be filtered to return only those processes that are not idle, that belong to a specific user, or that belong to a specific session.

How to round a floating point number up to a certain decimal place?

If you want to round, 8.84 is the incorrect answer. 8.833333333333 rounded is 8.83 not 8.84. If you want to always round up, then you can use math.ceil. Do both in a combination with string formatting, because rounding a float number itself doesn't make sense.

"%.2f" % (math.ceil(x * 100) / 100)

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

How can you dynamically create variables via a while loop?

NOTE: This should be considered a discussion rather than an actual answer.

An approximate approach is to operate __main__ in the module you want to create variables. For example there's a b.py:

#!/usr/bin/env python
# coding: utf-8


def set_vars():
    import __main__
    print '__main__', __main__
    __main__.B = 1

try:
    print B
except NameError as e:
    print e

set_vars()

print 'B: %s' % B

Running it would output

$ python b.py
name 'B' is not defined
__main__ <module '__main__' from 'b.py'>
B: 1

But this approach only works in a single module script, because the __main__ it import will always represent the module of the entry script being executed by python, this means that if b.py is involved by other code, the B variable will be created in the scope of the entry script instead of in b.py itself. Assume there is a script a.py:

#!/usr/bin/env python
# coding: utf-8

try:
    import b
except NameError as e:
    print e

print 'in a.py: B', B

Running it would output

$ python a.py
name 'B' is not defined
__main__ <module '__main__' from 'a.py'>
name 'B' is not defined
in a.py: B 1

Note that the __main__ is changed to 'a.py'.

How to stop mongo DB in one command

I followed the official MongoDB documentation for stopping with signals. One of the following commands can be used (PID represents the Process ID of the mongod process):

kill PID

which sends signal 15 (SIGTERM), or

kill -2 PID

which sends signal 2 (SIGINT).

Warning from MongoDB documentation:
Never use kill -9 (i.e. SIGKILL) to terminate a mongod instance.

If you have more than one instance running or you don't care about the PID, you could use pkill to send the signal to all running mongod processes:

pkill mongod

or

pkill -2 mongod

or, much more safer, only to the processes belonging to you:

pkill -U $USER mongod

or

pkill -2 -U $USER mongod

NOTE: If the DB is running as another user, but you have administrative rights, you have invoke the above commands with sudo, in order to run them. E.g.:

sudo pkill mongod
sudo pkill -2 mongod

PS
Note: I resorted to this option, because mongod --shutdown, although mentioned in the current MongoDB documentation, curiously doesn't work on my machine (macOS, mongodb v3.4.10, installed with homebrew):
Error parsing command line: unrecognised option '--shutdown'

PPS
(macOS specific) Before anyone wonders: no, I could not stop it with command
brew services stop mongodb
because I did not start it with
brew services start mongodb.
I had started mongod with a custom command line :-)

How to get previous page url using jquery

simple & sweet

window.location = document.referrer;

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

My problem was I could not work with localhost I needed to set it to localhost's IP address

network.bind_host: 127.0.0.1

What is the main difference between Inheritance and Polymorphism?

Inheritance is a concept related to code reuse. For example if I have a parent class say Animal and it contains certain attributes and methods (for this example say makeNoise() and sleep()) and I create two child classes called Dog and Cat. Since both dogs and cats go to sleep in the same fashion( I would assume) there is no need to add more functionality to the sleep() method in the Dog and Cat subclasses provided by the parent class Animal. However, a Dog barks and a Cat meows so although the Animal class might have a method for making a noise, a dog and a cat make different noises relative to each other and other animals. Thus, there is a need to redefine that behavior for their specific types. Thus the definition of polymorphism. Hope this helps.

Python math module

In

from math import sqrt

Using sqrt(4) works perfectly well. You need to only use math.sqrt(4) when you just use "import math".

How to get a variable type in Typescript?

For :

abc:number|string;

Use the JavaScript operator typeof:

if (typeof abc === "number") {
    // do something
}

TypeScript understands typeof

This is called a typeguard.

More

For classes you would use instanceof e.g.

class Foo {}
class Bar {} 

// Later
if (fooOrBar instanceof Foo){
  // TypeScript now knows that `fooOrBar` is `Foo`
}

There are also other type guards e.g. in etc https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

Postgresql, update if row with some unique value exists, else insert

I found this post more relevant in this scenario:

WITH upsert AS (
     UPDATE spider_count SET tally=tally+1 
     WHERE date='today' AND spider='Googlebot' 
     RETURNING *
)
INSERT INTO spider_count (spider, tally) 
SELECT 'Googlebot', 1 
WHERE NOT EXISTS (SELECT * FROM upsert)

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

Calling a method inside another method in same class

Java implicitly assumes a reference to the current object for methods called like this. So

// Test2.java
public class Test2 {
    public void testMethod() {
        testMethod2();
    }

    // ...
}

Is exactly the same as

// Test2.java
public class Test2 {
    public void testMethod() {
        this.testMethod2();
    }

    // ...
}

I prefer the second version to make more clear what you want to do.

TypeError: 'str' object is not callable (Python)

Check your input parameters, and make sure you don't have one named type. If so then you will have a clash and get this error.

calling a function from class in python - different way

Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

How to download a file with Node.js (without using third-party libraries)?

Don't forget to handle errors! The following code is based on Augusto Roman's answer.

var http = require('http');
var fs = require('fs');

var download = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(cb);  // close() is async, call cb after close completes.
    });
  }).on('error', function(err) { // Handle errors
    fs.unlink(dest); // Delete the file async. (But we don't check the result)
    if (cb) cb(err.message);
  });
};

MySQL - Operand should contain 1 column(s)

In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:

SELECT (p.column1, p.colum2, p.column3) FROM table1 p where p.column1 = 1;

And has to be:

SELECT p.column1, p.colum2, p.column3 FROM table1 p where p.column1 = 1;

Sounds silly, but it was causing this error and it took some time to figure it out.

How to detect the swipe left or Right in Android?

public class TransferMarket extends Activity {

    float x1,x2;
    float y1, y2;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_market);
    }

    // onTouchEvent () method gets called when User performs any touch event on screen

    // Method to handle touch event like left to right swap and right to left swap

    public boolean onTouchEvent(MotionEvent touchevent)
    {
        switch (touchevent.getAction())
        {
            // when user first touches the screen we get x and y coordinate
            case MotionEvent.ACTION_DOWN:
            {
                x1 = touchevent.getX();
                y1 = touchevent.getY();
                break;
            }
            case MotionEvent.ACTION_UP:
            {
                x2 = touchevent.getX();
                y2 = touchevent.getY();

                //if left to right sweep event on screen
                if (x1 < x2)
                {
                    Toast.makeText(this, "Left to Right Swap Performed", Toast.LENGTH_LONG).show();
                }

                // if right to left sweep event on screen
                if (x1 > x2)
                {
                    Toast.makeText(this, "Right to Left Swap Performed", Toast.LENGTH_LONG).show();
                }

                // if UP to Down sweep event on screen
                if (y1 < y2)
                {
                    Toast.makeText(this, "UP to Down Swap Performed", Toast.LENGTH_LONG).show();
                }

                //if Down to UP sweep event on screen
                if (y1 > y2)
                {
                    Toast.makeText(this, "Down to UP Swap Performed", Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
        return false;
    }

When to use "ON UPDATE CASCADE"

The ON UPDATE and ON DELETE specify which action will execute when a row in the parent table is updated and deleted. The following are permitted actions : NO ACTION, CASCADE, SET NULL, and SET DEFAULT.

Delete actions of rows in the parent table

If you delete one or more rows in the parent table, you can set one of the following actions:

  • ON DELETE NO ACTION: SQL Server raises an error and rolls back the delete action on the row in the parent table.
  • ON DELETE CASCADE: SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table.
  • ON DELETE SET NULL: SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must be nullable.
  • ON DELETE SET DEFAULT: SQL Server sets the rows in the child table to their default values if the corresponding rows in the parent table are deleted. To execute this action, the foreign key columns must have default definitions. Note that a nullable column has a default value of NULL if no default value specified. By default, SQL Server appliesON DELETE NO ACTION if you don’t explicitly specify any action.

Update action of rows in the parent table

If you update one or more rows in the parent table, you can set one of the following actions:

  • ON UPDATE NO ACTION: SQL Server raises an error and rolls back the update action on the row in the parent table.
  • ON UPDATE CASCADE: SQL Server updates the corresponding rows in the child table when the rows in the parent table are updated.
  • ON UPDATE SET NULL: SQL Server sets the rows in the child table to NULL when the corresponding row in the parent table is updated. Note that the foreign key columns must be nullable for this action to execute.
  • ON UPDATE SET DEFAULT: SQL Server sets the default values for the rows in the child table that have the corresponding rows in the parent table updated.
FOREIGN KEY (foreign_key_columns)
    REFERENCES parent_table(parent_key_columns)
    ON UPDATE <action> 
    ON DELETE <action>;

See the reference tutorial.

Error: unable to verify the first certificate in nodejs

Another dirty hack, which will make all your requests insecure:

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

VBA Subscript out of range - error 9

Option Explicit

Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook


TitleId = 4
Resultid = 0

Dim FileName1, FileName2 As String
Dim Difference As Long



'TestPassCount = 0
'TestFailCount = 0

'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count

If (TestDataRowCount <= 2) Then
  MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
  For RecordId = 3 To TestDataRowCount
    RefreshResultSheet

    'Source File row count
    SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
    Set sourcewb = Workbooks.Open(SrceFile)
    With sourcewb.Worksheets(1)
      SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      sourcewb.Close
    End With

    'Target File row count
    TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
    Set targetwb = Workbooks.Open(TrgtFile)
    With targetwb.Worksheets(1)
      TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      targetwb.Close
    End With

    ' Set Row Count Result Test data value
    TitleId = TitleId + 3
    Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value

    'Compare Source and Target Row count
    Resultid = TitleId + 1
    Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
    If (SourceRowCount = TargetRowCount) Then
       Worksheets("Result").Range("B" & Resultid).Value = "Passed"
       Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
       TestPassCount = TestPassCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Failed"
      Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
      TestFailCount = TestFailCount + 1
    End If


    'For comparison of two files

    FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
    FileName2 = Worksheets("TestData").Range("E" & RecordId).Value

    Set myWorkbook1 = Workbooks.Open(FileName1)
    Set myWorkbook2 = Workbooks.Open(FileName2)

    Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
    myWorkbook1.Close
    myWorkbook2.Close


    'MsgBox Difference

    'Set Result of data validation in result sheet
    Resultid = Resultid + 1

    Worksheets("Result").Activate
    Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"

    If Difference > 0 Then
        Worksheets("Result").Range("B" & Resultid).Value = "Failed"
        Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
        TestFailCount = TestFailCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Passed"
      Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
      TestPassCount = TestPassCount + 1
    End If


  Next RecordId
End If

UpdateTestExecData TestPassCount, TestFailCount
End Sub

Sub RefreshResultSheet()
  Worksheets("Result").Activate
  Worksheets("Result").Range("B1:B4").Select
  Selection.ClearContents
  Worksheets("Result").Range("D1:D4").Select
  Selection.ClearContents
  Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
  Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
  Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
  Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub

Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
  Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
  Worksheets("Result").Range("D2").Value = TestPassCount
  Worksheets("Result").Range("D3").Value = TestFailCount
  Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub

What is the volatile keyword useful for?

Absolutely, yes. (And not just in Java, but also in C#.) There are times when you need to get or set a value that is guaranteed to be an atomic operation on your given platform, an int or boolean, for example, but do not require the overhead of thread locking. The volatile keyword allows you to ensure that when you read the value that you get the current value and not a cached value that was just made obsolete by a write on another thread.

Simulate Keypress With jQuery

You could try this SendKeys jQuery plugin:

http://bililite.com/blog/2011/01/23/improved-sendkeys/

$(element).sendkeys(string) inserts string at the insertion point in an input, textarea or other element with contenteditable=true. If the insertion point is not currently in the element, it remembers where the insertion point was when sendkeys was last called (if the insertion point was never in the element, it appends to the end).

Remove all html tags from php string

In laravel you can use following syntax

 @php
   $description='<p>Rolling coverage</p><ul><li><a href="http://xys.com">Brexit deal: May admits she would have </a><br></li></ul></p>'
 @endphp
 {{  strip_tags($description)}}

Bold words in a string of strings.xml in Android

As David Olsson has said, you can use HTML in your string resources:

<resource>
    <string name="my_string">A string with <i>actual</i> <b>formatting</b>!</string>
</resources>

Then if you use getText(R.string.my_string) rather than getString(R.string.my_string) you get back a CharSequence rather than a String that contains the formatting embedded.

Creating csv file with php

Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows

I know I have added a lot of comments just for newbies :)

I have added an example so that you can summarize well.

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
    unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);

/** Now you can send email with attachments from the $filePath */

NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.

You have to add the following at the start of the above script.

ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

Bash script to check running process

Working one.

!/bin/bash
CHECK=$0
SERVICE=$1
DATE=`date`
OUTPUT=$(ps aux | grep -v grep | grep -v $CHECK |grep $1)
echo $OUTPUT
if [ "${#OUTPUT}" -gt 0 ] ;
then echo "$DATE: $SERVICE service running, everything is fine"
else echo "$DATE: $SERVICE is not running"
fi

Where can I download an offline installer of Cygwin?

If all you want is the UNIX command line tools I'd suggest not installing Cygwin. Cygwin wants to turn your Windows PC into a UNIX Workstation which is why it likes to install all its packages.

Have a look at GnuWin32 instead. It's Windows ports of the command line tools and nothing else. Here is the installer for the GnuWin32 diff.exe. There are offline installers for all the common tools.

(You asked for offline installers but in case you ever want one later there is a tool which will download and install everything for you.)

Method 2: make an offline install zip file for cygwin.

Don't mess with saving packages because the installed directory for cygwin can be canned in a zip file and expanded whenever you need it on any computer.

  1. Download Cygwin installer

  2. pick packages you want installed from gui.

  3. hit install and wait a really long time for everything to download.

  4. zip up the C:\Cygwin folder. Now you have your offline zip file for installing cygwin on any machine.

  5. Unzip this file on whatever computer you like. set cmd.exe paths appropriately to point to cygwin bin directory under windows control panel.

Is there a standardized method to swap two variables in Python?

Does not work for multidimensional arrays, because references are used here.

import numpy as np

# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)

# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)

See also Swap slices of Numpy arrays

Java: Multiple class declarations in one file

I believe you simply call PrivateImpl what it is: a non-public top-level class. You can also declare non-public top-level interfaces as well.

e.g., elsewhere on SO: Non-public top-level class vs static nested class

As for changes in behavior between versions, there was this discussion about something that "worked perfectly" in 1.2.2. but stopped working in 1.4 in sun's forum: Java Compiler - unable to declare a non public top level classes in a file.

Trim string in JavaScript?

Here's a very simple way:

function removeSpaces(string){
return string.split(' ').join('');
}

What is the difference between char s[] and char *s?

This declaration:

char s[] = "hello";

Creates one object - a char array of size 6, called s, initialised with the values 'h', 'e', 'l', 'l', 'o', '\0'. Where this array is allocated in memory, and how long it lives for, depends on where the declaration appears. If the declaration is within a function, it will live until the end of the block that it is declared in, and almost certainly be allocated on the stack; if it's outside a function, it will probably be stored within an "initialised data segment" that is loaded from the executable file into writeable memory when the program is run.

On the other hand, this declaration:

char *s ="hello";

Creates two objects:

  • a read-only array of 6 chars containing the values 'h', 'e', 'l', 'l', 'o', '\0', which has no name and has static storage duration (meaning that it lives for the entire life of the program); and
  • a variable of type pointer-to-char, called s, which is initialised with the location of the first character in that unnamed, read-only array.

The unnamed read-only array is typically located in the "text" segment of the program, which means it is loaded from disk into read-only memory, along with the code itself. The location of the s pointer variable in memory depends on where the declaration appears (just like in the first example).

How can I execute a PHP function in a form action?

I'm not sure I understand what you are trying to achieve as we don't have what username() is supposed to return but you might want to try something like that. I would also recommend you don't echo whole page and rather use something like that, it's much easier to read and maintain:

<?php
require_once ( 'username.php' );
if (isset($_POST)) {
  $textfield = $_POST['textfield']; // this will get you what was in the
                                    // textfield if the form was submitted
}
?>

<form name="form1" method="post" action="<?php echo($_SERVER['PHP_SELF']) ?">
  <p>Your username is: <?php echo(username()) ?></p>
  <p>
    <label>
      <input type="text" name="textfield" id="textfield">
    </label>
  </p>
  <p>
    <label>
      <input type="submit" name="button" id="button" value="Submit">
    </label>
  </p>
</form>

This will post the results in the same page. So first time you display the page, only the empty form is shown, if you press on submit, the textfield field will be in the $textfield variable and you can display it again as you want.

I don't know if the username() function was supposed to return you the URL of where you should send the results but that's what you'd want in the action attribute of your form. I've put the result down in a sample paragraph so you see how you can display the result. See the "Your username is..." part.


// Edit:

If you want to send the value without leaving the page, you want to use AJAX. Do a search on jQuery on StackOverflow or on Google.

You would probably want to have your function return the username instead of echo it though. But if you absolutely want to echo it from the function, just call it like that <?php username() ?> in your HTML form.

I think you will need to understand the flow of the client-server process of your pages before going further. Let's say that the sample code above is called form.php.

  1. Your form.php is called.
  2. The form.php generates the HTML and is sent to the client's browser.
  3. The client only sees the resulting HTML form.
  4. When the user presses the button, you have two choices: a) let the browser do its usual thing so send the values in the form fields to the page specified in action (in this case, the URL is defined by PHP_SELF which is the current page.php). Or b) use javascript to push this data to a page without refreshing the page, this is commonly called AJAX.
  5. A page, in your case, it could be changed to username.php, will then verify against the database if the username exists and then you want to regenerate HTML that contains the values you need, back to step 1.

node.js: cannot find module 'request'

I tried installing the module locally with version and it worked!!

npm install request@^2.*

Thanks.

Can the Android layout folder contain subfolders?

Well, the short answer is no. But you definitely can have multiple res folders. That, I think, is as close as you can get to having subfolders for the layout folder. Here's how you do it.

Why is there no SortedList in Java?

First line in the List API says it is an ordered collection (also known as a sequence). If you sort the list you can't maintain the order, so there is no TreeList in Java.
As API says Java List got inspired from Sequence and see the sequence properties http://en.wikipedia.org/wiki/Sequence_(mathematics)

It doesn't mean that you can't sort the list, but Java strict to his definition and doesn't provide sorted versions of lists by default.

Select objects based on value of variable in object using jq

Just try this one as a full copy paste in the shell and you will grasp it

# create the example file to  be working on .. 
cat << EOF > tmp.json
[  
 { "card_id": "id-00", "card_id_type": "card_id_type-00"},
 {"card_id": "id-01", "card_id_type": "card_id_type-01"},
 {  "card_id": "id-02", "card_id_type": "card_id_type-02"}
]
EOF


# pipe the content of the file to the  jq query, which gets the array of objects
# and select the attribute named "card_id" ONLY if it's neighbour attribute
# named "card_id_type" has the "card_id_type-01" value
# jq -r means give me ONLY the value of the jq query no quotes aka raw
cat tmp.json | jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id'

id-01

or with an aws cli command

 # list my vpcs or
 # list the values of the tags which names are "Name" 
 aws ec2 describe-vpcs | jq -r '.| .Vpcs[].Tags[]|select (.Key == "Name") | .Value'|sort  -nr

How do you subtract Dates in Java?

You can use the following approach:

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");

long d1=formater.parse("2001-1-1").getTime();
long d2=formater.parse("2001-1-2").getTime();

System.out.println(Math.abs((d1-d2)/(1000*60*60*24)));

Error inflating class android.support.design.widget.NavigationView

None of the above fixes worked for me.

What worked for me was changing

<item name="android:textColorSecondary">#FFFFFF</item>

to

<item name="android:textColorSecondary">@color/colorWhite</item>

You obviously need to add colorWhite to your colors.xml

What does Ruby have that Python doesn't, and vice versa?

Shamelessly copy/pasted from: Alex Martelli answer on "What's better about Ruby than Python" thread from comp.lang.python mailing list.

Aug 18 2003, 10:50 am Erik Max Francis wrote:

"Brandon J. Van Every" wrote:

What's better about Ruby than Python? I'm sure there's something. What is it?

Wouldn't it make much more sense to ask Ruby people this, rather than Python people?

Might, or might not, depending on one's purposes -- for example, if one's purposes include a "sociological study" of the Python community, then putting questions to that community is likely to prove more revealing of information about it, than putting them elsewhere:-).

Personally, I gladly took the opportunity to follow Dave Thomas' one-day Ruby tutorial at last OSCON. Below a thin veneer of syntax differences, I find Ruby and Python amazingly similar -- if I was computing the minimum spanning tree among just about any set of languages, I'm pretty sure Python and Ruby would be the first two leaves to coalesce into an intermediate node:-).

Sure, I do get weary, in Ruby, of typing the silly "end" at the end of each block (rather than just unindenting) -- but then I do get to avoid typing the equally-silly ':' which Python requires at the start of each block, so that's almost a wash:-). Other syntax differences such as '@foo' versus 'self.foo', or the higher significance of case in Ruby vs Python, are really just about as irrelevant to me.

Others no doubt base their choice of programming languages on just such issues, and they generate the hottest debates -- but to me that's just an example of one of Parkinson's Laws in action (the amount on debate on an issue is inversely proportional to the issue's actual importance).

Edit (by AM 6/19/2010 11:45): this is also known as "painting the bikeshed" (or, for short, "bikeshedding") -- the reference is, again, to Northcote Parkinson, who gave "debates on what color to paint the bikeshed" as a typical example of "hot debates on trivial topics". (end-of-Edit).

One syntax difference that I do find important, and in Python's favor -- but other people will no doubt think just the reverse -- is "how do you call a function which takes no parameters". In Python (like in C), to call a function you always apply the "call operator" -- trailing parentheses just after the object you're calling (inside those trailing parentheses go the args you're passing in the call -- if you're passing no args, then the parentheses are empty). This leaves the mere mention of any object, with no operator involved, as meaning just a reference to the object -- in any context, without special cases, exceptions, ad-hoc rules, and the like. In Ruby (like in Pascal), to call a function WITH arguments you pass the args (normally in parentheses, though that is not invariably the case) -- BUT if the function takes no args then simply mentioning the function implicitly calls it. This may meet the expectations of many people (at least, no doubt, those whose only previous experience of programming was with Pascal, or other languages with similar "implicit calling", such as Visual Basic) -- but to me, it means the mere mention of an object may EITHER mean a reference to the object, OR a call to the object, depending on the object's type -- and in those cases where I can't get a reference to the object by merely mentioning it I will need to use explicit "give me a reference to this, DON'T call it!" operators that aren't needed otherwise. I feel this impacts the "first-classness" of functions (or methods, or other callable objects) and the possibility of interchanging objects smoothly. Therefore, to me, this specific syntax difference is a serious black mark against Ruby -- but I do understand why others would thing otherwise, even though I could hardly disagree more vehemently with them:-).

Below the syntax, we get into some important differences in elementary semantics -- for example, strings in Ruby are mutable objects (like in C++), while in Python they are not mutable (like in Java, or I believe C#). Again, people who judge primarily by what they're already familiar with may think this is a plus for Ruby (unless they're familiar with Java or C#, of course:-). Me, I think immutable strings are an excellent idea (and I'm not surprised that Java, independently I think, reinvented that idea which was already in Python), though I wouldn't mind having a "mutable string buffer" type as well (and ideally one with better ease-of-use than Java's own "string buffers"); and I don't give this judgment because of familiarity -- before studying Java, apart from functional programming languages where all data are immutable, all the languages I knew had mutable strings -- yet when I first saw the immutable-string idea in Java (which I learned well before I learned Python), it immediately struck me as excellent, a very good fit for the reference-semantics of a higher level programming language (as opposed to the value-semantics that fit best with languages closer to the machine and farther from applications, such as C) with strings as a first-class, built-in (and pretty crucial) data type.

Ruby does have some advantages in elementary semantics -- for example, the removal of Python's "lists vs tuples" exceedingly subtle distinction. But mostly the score (as I keep it, with simplicity a big plus and subtle, clever distinctions a notable minus) is against Ruby (e.g., having both closed and half-open intervals, with the notations a..b and a...b [anybody wants to claim that it's obvious which is which?-)], is silly -- IMHO, of course!). Again, people who consider having a lot of similar but subtly different things at the core of a language a PLUS, rather than a MINUS, will of course count these "the other way around" from how I count them:-).

Don't be misled by these comparisons into thinking the two languages are very different, mind you. They aren't. But if I'm asked to compare "capelli d'angelo" to "spaghettini", after pointing out that these two kinds of pasta are just about undistinguishable to anybody and interchangeable in any dish you might want to prepare, I would then inevitably have to move into microscopic examination of how the lengths and diameters imperceptibly differ, how the ends of the strands are tapered in one case and not in the other, and so on -- to try and explain why I, personally, would rather have capelli d'angelo as the pasta in any kind of broth, but would prefer spaghettini as the pastasciutta to go with suitable sauces for such long thin pasta forms (olive oil, minced garlic, minced red peppers, and finely ground anchovies, for example - but if you sliced the garlic and peppers instead of mincing them, then you should choose the sounder body of spaghetti rather than the thinner evanescence of spaghettini, and would be well advised to forego the achovies and add instead some fresh spring basil [or even -- I'm a heretic...! -- light mint...] leaves -- at the very last moment before serving the dish). Ooops, sorry, it shows that I'm traveling abroad and haven't had pasta for a while, I guess. But the analogy is still pretty good!-)

So, back to Python and Ruby, we come to the two biggies (in terms of language proper -- leaving the libraries, and other important ancillaries such as tools and environments, how to embed/extend each language, etc, etc, out of it for now -- they wouldn't apply to all IMPLEMENTATIONS of each language anyway, e.g., Jython vs Classic Python being two implementations of the Python language!):

  1. Ruby's iterators and codeblocks vs Python's iterators and generators;

  2. Ruby's TOTAL, unbridled "dynamicity", including the ability
    to "reopen" any existing class, including all built-in ones, and change its behavior at run-time -- vs Python's vast but bounded dynamicity, which never changes the behavior of existing built-in classes and their instances.

Personally, I consider 1 a wash (the differences are so deep that I could easily see people hating either approach and revering the other, but on MY personal scales the pluses and minuses just about even up); and 2 a crucial issue -- one that makes Ruby much more suitable for "tinkering", BUT Python equally more suitable for use in large production applications. It's funny, in a way, because both languages are so MUCH more dynamic than most others, that in the end the key difference between them from my POV should hinge on that -- that Ruby "goes to eleven" in this regard (the reference here is to "Spinal Tap", of course). In Ruby, there are no limits to my creativity -- if I decide that all string comparisons must become case-insensitive, I CAN DO THAT! I.e., I can dynamically alter the built-in string class so that a = "Hello World" b = "hello world" if a == b print "equal!\n" else print "different!\n" end WILL print "equal". In python, there is NO way I can do that. For the purposes of metaprogramming, implementing experimental frameworks, and the like, this amazing dynamic ability of Ruby is extremely appealing. BUT -- if we're talking about large applications, developed by many people and maintained by even more, including all kinds of libraries from diverse sources, and needing to go into production in client sites... well, I don't WANT a language that is QUITE so dynamic, thank you very much. I loathe the very idea of some library unwittingly breaking other unrelated ones that rely on those strings being different -- that's the kind of deep and deeply hidden "channel", between pieces of code that LOOK separate and SHOULD BE separate, that spells d-e-a-t-h in large-scale programming. By letting any module affect the behavior of any other "covertly", the ability to mutate the semantics of built-in types is just a BAD idea for production application programming, just as it's cool for tinkering.

If I had to use Ruby for such a large application, I would try to rely on coding-style restrictions, lots of tests (to be rerun whenever ANYTHING changes -- even what should be totally unrelated...), and the like, to prohibit use of this language feature. But NOT having the feature in the first place is even better, in my opinion -- just as Python itself would be an even better language for application programming if a certain number of built-ins could be "nailed down", so I KNEW that, e.g., len("ciao") is 4 (rather than having to worry subliminally about whether somebody's changed the binding of name 'len' in the builtins module...). I do hope that eventually Python does "nail down" its built-ins.

But the problem's minor, since rebinding built-ins is quite a deprecated as well as a rare practice in Python. In Ruby, it strikes me as major -- just like the too powerful macro facilities of other languages (such as, say, Dylan) present similar risks in my own opinion (I do hope that Python never gets such a powerful macro system, no matter the allure of "letting people define their own domain-specific little languages embedded in the language itself" -- it would, IMHO, impair Python's wonderful usefulness for application programming, by presenting an "attractive nuisance" to the would-be tinkerer who lurks in every programmer's heart...).

Alex

Remove all occurrences of a value from a list?

Remove all occurrences of a value from a Python list

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list():
    for list in lists:
      if(list!=7):
         print(list)
remove_values_from_list()

Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

Alternatively,

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list(remove):
    for list in lists:
      if(list!=remove):
        print(list)
remove_values_from_list(7)

Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

AngularJS is rendering <br> as text not as a newline

You need to either use ng-bind-html-unsafe ... or you need to include the ngSanitize module and use ng-bind-html:

with ng-bind-html-unsafe

Use this if you trust the source of the HTML you're rendering it will render the raw output of whatever you put into it.

<div><h4>Categories</h4><span ng-bind-html-unsafe="q.CATEGORY"></span></div>

OR with ng-bind-html

Use this if you DON'T trust the source of the HTML (i.e. it's user input). It will sanitize the html to make sure it doesn't include things like script tags or other sources of potential security risks.

Make sure you include this:

<script src="http://code.angularjs.org/1.0.4/angular-sanitize.min.js"></script>

Then reference it in your application module:

var app = angular.module('myApp', ['ngSanitize']);

THEN use it:

<div><h4>Categories</h4><span ng-bind-html="q.CATEGORY"></span></div>

creating batch script to unzip a file without additional zip tools

Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

To unzip file you can use this script :

zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

How to implement a queue using two stacks?

public class QueueUsingStacks<T>
{
    private LinkedListStack<T> stack1;
    private LinkedListStack<T> stack2;

    public QueueUsingStacks()
    {
        stack1=new LinkedListStack<T>();
        stack2 = new LinkedListStack<T>();

    }
    public void Copy(LinkedListStack<T> source,LinkedListStack<T> dest )
    {
        while(source.Head!=null)
        {
            dest.Push(source.Head.Data);
            source.Head = source.Head.Next;
        }
    }
    public void Enqueue(T entry)
    {

       stack1.Push(entry);
    }
    public T Dequeue()
    {
        T obj;
        if (stack2 != null)
        {
            Copy(stack1, stack2);
             obj = stack2.Pop();
            Copy(stack2, stack1);
        }
        else
        {
            throw new Exception("Stack is empty");
        }
        return obj;
    }

    public void Display()
    {
        stack1.Display();
    }


}

For every enqueue operation, we add to the top of the stack1. For every dequeue, we empty the content's of stack1 into stack2, and remove the element at top of the stack.Time complexity is O(n) for dequeue, as we have to copy the stack1 to stack2. time complexity of enqueue is the same as a regular stack

IPython/Jupyter Problems saving notebook as PDF

If you are using sagemath cloud version, you can simply go to the left corner,
select File --> Download as --> Pdf via LaTeX (.pdf)
Check the screenshot if you want.

Screenshot Convert ipynb to pdf

If it dosn't work for any reason, you can try another way.
select File --> Print Preview and then on the preview
right click --> Print and then select save as pdf.

Delete worksheet in Excel using VBA

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

Regex replace (in Python) - a simpler way?

>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

Count number of days between two dates

Rails has some built in helpers that might solve this for you. One thing to keep in mind is that this is part of the Actionview Helpers, so they wont be available directly from the console.

Try this

<% start_time =  "2012-03-02 14:46:21 +0100" %>
<% end_time   =  "2012-04-02 14:46:21 +0200" %>
<%= distance_of_time_in_words(start_time, end_time)  %>

 "about 1 month"

Use Ant for running program with command line arguments

Extending Richard Cook's answer.

Here's the ant task to run any program (including, but not limited to Java programs):

<target name="run">
   <exec executable="name-of-executable">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </exec>
</target>

Here's the task to run a Java program from a .jar file:

<target name="run-java">
   <java jar="path for jar">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </java>
</target>

You can invoke either from the command line like this:

ant -Darg0=Hello -Darg1=World run

Make sure to use the -Darg syntax; if you ran this:

ant run arg0 arg1

then ant would try to run targets arg0 and arg1.

Vue template or render function not defined yet I am using neither?

When used with storybook and typescirpt, I had to add

.storybook/webpack.config.js

const path = require('path');

module.exports = async ({ config, mode }) => {

    config.module.rules.push({
        test: /\.ts$/,
        exclude: /node_modules/,
        use: [
            {
                loader: 'ts-loader',
                options: {
                    appendTsSuffixTo: [/\.vue$/],
                    transpileOnly: true
                },
            }
        ],
    });

    return config;
};

best way to preserve numpy arrays on disk

The lookup time is slow because when you use mmap to does not load content of array to memory when you invoke load method. Data is lazy loaded when particular data is needed. And this happens in lookup in your case. But second lookup won`t be so slow.

This is nice feature of mmap when you have a big array you do not have to load whole data into memory.

To solve your can use joblib you can dump any object you want using joblib.dump even two or more numpy arrays, see the example

firstArray = np.arange(100)
secondArray = np.arange(50)
# I will put two arrays in dictionary and save to one file
my_dict = {'first' : firstArray, 'second' : secondArray}
joblib.dump(my_dict, 'file_name.dat')

How to handle the `onKeyPress` event in ReactJS?

If you wanted to pass a dynamic param through to a function, inside a dynamic input::

<Input 
  onKeyPress={(event) => {
    if (event.key === "Enter") {
      this.doSearch(data.searchParam)
    }
  }}
  placeholder={data.placeholderText} />
/>

Hope this helps someone. :)

C# - What does the Assert() method do? Is it still useful?

Assertions feature heavily in Design by Contract (DbC) which as I understand was introducted/endorsed by Meyer, Bertand. 1997. Object-Oriented Software Contruction.

An important feature is that they mustn't produce side-effects, for example you can handle an exception or take a different course of action with an if statement(defensive programming).

Assertions are used to check the pre/post conditions of the contract, the client/supplier relationship - the client must ensure that the pre-conditions of the supplier are met eg. sends £5 and the supplier must ensure the post-conditions are met eg. delivers 12 roses. (Just simple explanation of client/supplier - can accept less and deliver more, but about Assertions). C# also introduces Trace.Assert(), which can be used for release code.

To answer the question yes they still useful, but can add complexity+readability to code and time+difficultly to maintain. Should we still use them? Yes, Will we all use them? Probably not, or not to the extent of how Meyer describes.

(Even the OU Java course that I learnt this technique on only showed simple examples and the rest of there code didn't enforce the DbC assertion rules on most of code, but was assumed to be used to assure program correctness!)

Windows batch script to move files

You can try this:

:backup move C:\FilesToBeBackedUp\*.* E:\BackupPlace\ timeout 36000 goto backup

If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.

Oracle database: How to read a BLOB?

You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2()).

SELECT b FROM foo;
-- (BLOB)

SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000

This is handy because you this is the same format used for inserting into BLOB columns:

CREATE GLOBAL TEMPORARY TABLE foo (
    b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');

DESC foo;
-- Name Null Type 
-- ---- ---- ---- 
-- B        BLOB 

However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR for a more complicated approach that will allow you to see substrings of the BLOB.

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

What is the difference between a var and val definition in Scala?

As so many others have said, the object assigned to a val cannot be replaced, and the object assigned to a var can. However, said object can have its internal state modified. For example:

class A(n: Int) {
  var value = n
}

class B(n: Int) {
  val value = new A(n)
}

object Test {
  def main(args: Array[String]) {
    val x = new B(5)
    x = new B(6) // Doesn't work, because I can't replace the object created on the line above with this new one.
    x.value = new A(6) // Doesn't work, because I can't replace the object assigned to B.value for a new one.
    x.value.value = 6 // Works, because A.value can receive a new object.
  }
}

So, even though we can't change the object assigned to x, we could change the state of that object. At the root of it, however, there was a var.

Now, immutability is a good thing for many reasons. First, if an object doesn't change internal state, you don't have to worry if some other part of your code is changing it. For example:

x = new B(0)
f(x)
if (x.value.value == 0)
  println("f didn't do anything to x")
else
  println("f did something to x")

This becomes particularly important with multithreaded systems. In a multithreaded system, the following can happen:

x = new B(1)
f(x)
if (x.value.value == 1) {
  print(x.value.value) // Can be different than 1!
}

If you use val exclusively, and only use immutable data structures (that is, avoid arrays, everything in scala.collection.mutable, etc.), you can rest assured this won't happen. That is, unless there's some code, perhaps even a framework, doing reflection tricks -- reflection can change "immutable" values, unfortunately.

That's one reason, but there is another reason for it. When you use var, you can be tempted into reusing the same var for multiple purposes. This has some problems:

  • It will be more difficult for people reading the code to know what is the value of a variable in a certain part of the code.
  • You may forget to re-initialize the variable in some code path, and end up passing wrong values downstream in the code.

Simply put, using val is safer and leads to more readable code.

We can, then, go the other direction. If val is that better, why have var at all? Well, some languages did take that route, but there are situations in which mutability improves performance, a lot.

For example, take an immutable Queue. When you either enqueue or dequeue things in it, you get a new Queue object. How then, would you go about processing all items in it?

I'll go through that with an example. Let's say you have a queue of digits, and you want to compose a number out of them. For example, if I have a queue with 2, 1, 3, in that order, I want to get back the number 213. Let's first solve it with a mutable.Queue:

def toNum(q: scala.collection.mutable.Queue[Int]) = {
  var num = 0
  while (!q.isEmpty) {
    num *= 10
    num += q.dequeue
  }
  num
}

This code is fast and easy to understand. Its main drawback is that the queue that is passed is modified by toNum, so you have to make a copy of it beforehand. That's the kind of object management that immutability makes you free from.

Now, let's covert it to an immutable.Queue:

def toNum(q: scala.collection.immutable.Queue[Int]) = {
  def recurse(qr: scala.collection.immutable.Queue[Int], num: Int): Int = {
    if (qr.isEmpty)
      num
    else {
      val (digit, newQ) = qr.dequeue
      recurse(newQ, num * 10 + digit)
    }
  }
  recurse(q, 0)
}

Because I can't reuse some variable to keep track of my num, like in the previous example, I need to resort to recursion. In this case, it is a tail-recursion, which has pretty good performance. But that is not always the case: sometimes there is just no good (readable, simple) tail recursion solution.

Note, however, that I can rewrite that code to use an immutable.Queue and a var at the same time! For example:

def toNum(q: scala.collection.immutable.Queue[Int]) = {
  var qr = q
  var num = 0
  while (!qr.isEmpty) {
    val (digit, newQ) = qr.dequeue
    num *= 10
    num += digit
    qr = newQ
  }
  num
}

This code is still efficient, does not require recursion, and you don't need to worry whether you have to make a copy of your queue or not before calling toNum. Naturally, I avoided reusing variables for other purposes, and no code outside this function sees them, so I don't need to worry about their values changing from one line to the next -- except when I explicitly do so.

Scala opted to let the programmer do that, if the programmer deemed it to be the best solution. Other languages have chosen to make such code difficult. The price Scala (and any language with widespread mutability) pays is that the compiler doesn't have as much leeway in optimizing the code as it could otherwise. Java's answer to that is optimizing the code based on the run-time profile. We could go on and on about pros and cons to each side.

Personally, I think Scala strikes the right balance, for now. It is not perfect, by far. I think both Clojure and Haskell have very interesting notions not adopted by Scala, but Scala has its own strengths as well. We'll see what comes up on the future.

Image vs Bitmap class

Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.

You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.

Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.

Javascript logical "!==" operator?

The !== opererator tests whether values are not equal or not the same type. i.e.

var x = 5;
var y = '5';
var 1 = y !== x; // true
var 2 = y != x; // false

How can I update a row in a DataTable in VB.NET?

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

List of IP Space used by Facebook

# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
  iptables -A FORWARD -p all -d $ip -j REJECT
done

How to force a line break in a long word in a DIV?

word-break: normal seems better to use than word-break: break-word because break-word breaks initials such as EN

word-break: normal

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

The only way that cleanly solved this issue for me (.NET 4.6.1) was to not only add a Nuget reference to System.Net.Http V4.3.4 for the project that actually used System.Net.Http, but also to the startup project (a test project in my case).

(Which is strange, because the correct System.Net.Http.dll existed in the bin directory of the test project and the .config assemblyBingings looked OK, too.)

How to import set of icons into Android Studio project

what u need to do is icons downloaded from material design, open that folder there are lots of icons categories specified, open any of it choose any icon and go to this folder -> drawable-anydpi-v21. this folder contains xml files copy any xml file and paste it to this location -> C:\Users\Username\AndroidStudioProjects\ur project name\app\src\main\res\drawable. That's it !! now you can use the icon in ur project.

Using jQuery to see if a div has a child with a certain class

Simple Way

if ($('#text-field > p.filled-text').length != 0)

using lodash .groupBy. how to add your own keys for grouped output?

Here is an updated version using lodash 4 and ES6

const result = _.chain(data)
    .groupBy("color")
    .toPairs()
    .map(pair => _.zipObject(['color', 'users'], pair))
    .value();

How to use export with Python on Linux

One line solution:

eval `python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'`
echo $python_include_path  # prints /home/<usr>/anaconda3/include/python3.6m" in my case

Breakdown:

Python call

python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'

It's launching a python script that

  1. imports sysconfig
  2. gets the python include path corresponding to this python binary (use "which python" to see which one is being used)
  3. prints the script "python_include_path={0}" with {0} being the path from 2

Eval call

eval `python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'`

It's executing in the current bash instance the output from the python script. In my case, its executing:

python_include_path=/home/<usr>/anaconda3/include/python3.6m

In other words, it's setting the environment variable "python_include_path" with that path for this shell instance.

Inspired by: http://blog.tintoy.io/2017/06/exporting-environment-variables-from-python-to-bash/

How can I know if a branch has been already merged into master?

You can use the git merge-base command to find the latest common commit between the two branches. If that commit is the same as your branch head, then the branch has been completely merged.

Note that git branch -d does this sort of thing already because it will refuse to delete a branch that hasn't already been completely merged.

Spring cannot find bean xml configuration file when it does exist

Gradle : v4.10.3

IDE : IntelliJ

I was facing this issue when using gradle to run my build and test. Copying the applicationContext.xml all over the place did not help. Even specifying the complete path as below did not help !

context = new ClassPathXmlApplicationContext("C:\\...\\applicationContext.xml");

The solution (for gradle at least) lies in the way gradle processes resources. For my gradle project I had laid out the workspace as defined at https://docs.gradle.org/current/userguide/java_plugin.html#sec:java_project_layout

When running a test using default gradle set of tasks includes a "processTestResources" step, which looks for test resources at C:\.....\src\test\resources (Gradle helpfully provides the complete path).

Your .properties file and applicationContext.xml need to be in this directory. If the resources directory is not present (as it was in my case), you need to create it copy the file(s) there. After this, simply specifying the file name worked just fine.

context = new ClassPathXmlApplicationContext("applicationContext.xml");

How to get every first element in 2 dimensional list

You can get it like

[ x[0] for x in a]

which will return a list of the first element of each list in a

What is __init__.py for?

__init__.py will treat the directory it is in as a loadable module.

For people who prefer reading code, I put Two-Bit Alchemist's comment here.

$ find /tmp/mydir/
/tmp/mydir/
/tmp/mydir//spam
/tmp/mydir//spam/__init__.py
/tmp/mydir//spam/module.py
$ cd ~
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
>>> module.myfun(3)
9
>>> exit()
$ 
$ rm /tmp/mydir/spam/__init__.py*
$ 
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named spam
>>> 

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

How to send an email using PHP?

The core way to send emails from PHP is to use its built in mail() function, but there are a couple of ready-to-use SDKs which can ease the integration:

  1. Swiftmailer
  2. PHPMailer
  3. Pepipost (works over HTTP hence SMTP port block issue can be avoided)
  4. Sendmail

P.S. I am employed with Pepipost.

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

Read and overwrite a file in Python

Probably it would be easier and neater to close the file after text = re.sub('foobar', 'bar', text), re-open it for writing (thus clearing old contents), and write your updated text to it.

div background color, to change onhover

you could just contain the div in anchor tag like this:

_x000D_
_x000D_
a{_x000D_
  text-decoration:none;_x000D_
  color:#ffffff;_x000D_
}_x000D_
a div{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:#ff4500;_x000D_
}_x000D_
a div:hover{_x000D_
  background:#0078d7;_x000D_
}
_x000D_
<body>_x000D_
<a href="http://example.com">_x000D_
<div>_x000D_
Hover me_x000D_
</div>_x000D_
</a>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to refresh the data in a jqGrid?

var newdata= //You call Ajax peticion//

$("#idGrid").clearGridData();

$("#idGrid").jqGrid('setGridParam', {data:newdata)});
$("#idGrid").trigger("reloadGrid");

in event update data table

How to pass variable as a parameter in Execute SQL Task SSIS?

Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes

https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task

Web.Config Debug/Release

It is possible using ConfigTransform build target available as a Nuget package - https://www.nuget.org/packages/CodeAssassin.ConfigTransform/

All "web.*.config" transform files will be transformed and output as a series of "web.*.config.transformed" files in the build output directory regardless of the chosen build configuration.

The same applies to "app.*.config" transform files in non-web projects.

and then adding the following target to your *.csproj.

<Target Name="TransformActiveConfiguration" Condition="Exists('$(ProjectDir)/Web.$(Configuration).config')" BeforeTargets="Compile" >
    <TransformXml Source="$(ProjectDir)/Web.Config" Transform="$(ProjectDir)/Web.$(Configuration).config" Destination="$(TargetDir)/Web.config" />
</Target>

Posting an answer as this is the first Stackoverflow post that appears in Google on the subject.

TypeError : Unhashable type

... and so you should do something like this:

set(tuple ((a,b) for a in range(3)) for b in range(3))

... and if needed convert back to list

Easier way to debug a Windows service

To debug Windows Services I combine GFlags and a .reg file created by regedit.

  1. Run GFlags, specifying the exe-name and vsjitdebugger
  2. Run regedit and go to the location where GFlags sets his options
  3. Choose "Export Key" from the file-menu
  4. Save that file somewhere with the .reg extension
  5. Anytime you want to debug the service: doubleclick on the .reg file
  6. If you want to stop debugging, doubleclick on the second .reg file

Or save the following snippets and replace servicename.exe with the desired executable name.


debugon.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe]
"GlobalFlag"="0x00000000"
"Debugger"="vsjitdebugger.exe"

debugoff.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe]
"GlobalFlag"="0x00000000"

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

I am sorry, I forget to answer this question. After few days of googling I found, that problem was caused by hyperthreading (or hyper - v). I decided to edit my boot.ini file with option to start up windows with hyperthreading turned off. I followed this tutorial and now everything works perfect

Angular no provider for NameService

You could also have the dependencies declared in the bootstrap-command like:

bootstrap(MyAppComponent,[NameService]);

At least that's what worked for me in alpha40.

this is the link: http://www.syntaxsuccess.com/viewarticle/dependency-injection-in-angular-2.0

Fastest way of finding differences between two files in unix?

You could try..

comm -13 <(sort file1) <(sort file2) > file3

or

grep -Fxvf file1 file2 > file3

or

diff file1 file2 | grep "<" | sed 's/^<//g'  > file3

or

join -v 2 <(sort file1) <(sort file2) > file3

Setting a max height on a table

<table  style="border: 1px solid red">
            <thead>
                <tr>
                    <td>Header stays put, no scrolling</td>
                </tr>
            </thead>
            <tbody id="tbodyMain" style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
                <tr>
                    <td>cell 1/1</td>
                    <td>cell 1/2</td>
                </tr>
                <tr>
                    <td>cell 2/1</td>
                    <td>cell 2/2</td>
                </tr>
                <tr>
                    <td>cell 3/1</td>
                    <td>cell 3/2</td>
                </tr>
            </tbody>
        </table>


Javascript Section

<script>
$(document).ready(function(){
   var maxHeight = Math.max.apply(null, $("body").map(function () { return $(this).height(); }).get());
   // alert(maxHeight);
    var borderheight =3 ; 
    // Added some pixed into maxheight 
    // If you set border then need to add this "borderheight" to maxheight varialbe
   $("#tbodyMain").css("min-height", parseInt(maxHeight + borderheight) + "px");             
});

</script>


please, refer How to set maximum possible height to your Table Body
Fiddle Here

Android Service Stops When App Is Closed

<service android:name=".Service2"
            android:process="@string/app_name"
            android:exported="true"
            android:isolatedProcess="true"
            />

Declare this in your manifest. Give a custom name to your process and make that process isolated and exported .

How to make an Android Spinner with initial text "Select One"?

I'd just use a RadioGroup with RadioButtons if you only have three choices, you can make them all unchecked at first.

How to uninstall a package installed with pip install --user

Be careful though, for those who using pip install --user some_pkg inside a virtual environment.

$ path/to/python -m venv ~/my_py_venv
$ source ~/my_py_venv/bin/activate
(my_py_venv) $ pip install --user some_pkg
(my_py_venv) $ pip uninstall some_pkg
WARNING: Skipping some_pkg as it is not installed.
(my_py_venv) $ pip list
# Even `pip list` will not properly list the `some_pkg` in this case

In this case, you have to deactivate the current virtual environment, then use the corresponding python/pip executable to list or uninstall the user site packages:

(my_py_venv) $ deactivate
$ path/to/python -m pip list
$ path/to/python -m pip uninstall some_pkg

Note that this issue was reported few years ago. And it seems that the current conclusion is: --user is not valid inside a virtual env's pip, since a user location doesn't really make sense for a virtual environment.

Insert node at a certain position in a linked list C++

I had some problems with the insertion process just like you, so here is the code how I have solved the problem:

void add_by_position(int data, int pos)
  {
        link *node = new link;
        link *linker = head;

        node->data = data;
        for (int i = 0; i < pos; i++){
            linker = linker->next;
        }
        node->next = linker;
        linker = head;
        for (int i = 0; i < pos - 1; i++){
            linker = linker->next;
        }
        linker->next = node;
        boundaries++;
    }

HTML CSS How to stop a table cell from expanding

It's entirely possible if your code has enough relative logic to work with.

Simply use the viewport units though for some the math may be a bit more complicated. I used this to prevent list items from bloating certain table columns with much longer text.

ol {max-width: 10vw; padding: 0; overflow: hidden;}

Apparently max-width on colgroup elements do not work which is pretty lame to be dependent entirely on child elements to control something on the parent.

The listener supports no services

for listener support no services you can use the following command to set local_listener paramter in your spfile use your listener port and server ip address

alter system set local_listener='(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.101)(PORT=1520)))' sid='testdb' scope=spfile;

Eclipse 3.5 Unable to install plugins

I had a similar problem setting up eclipse.

I changed: NATIVE connection to MANUAL and cleared the proxy settings for SOCKS in Windows -> Preferences -> General -> Network connection. That fixed the problem for me.

How does one Display a Hyperlink in React Native App?

React Native documentation suggests using Linking:

Reference

Here is a very basic use case:

import { Linking } from 'react-native';

const url="https://google.com"

<Text onPress={() => Linking.openURL(url)}>
    {url}
</Text>

You can use either functional or class component notation, dealers choice.

Build a basic Python iterator

I see some of you doing return self in __iter__. I just wanted to note that __iter__ itself can be a generator (thus removing the need for __next__ and raising StopIteration exceptions)

class range:
  def __init__(self,a,b):
    self.a = a
    self.b = b
  def __iter__(self):
    i = self.a
    while i < self.b:
      yield i
      i+=1

Of course here one might as well directly make a generator, but for more complex classes it can be useful.

What's the difference between equal?, eql?, ===, and ==?

I wrote a simple test for all the above.

def eq(a, b)
  puts "#{[a, '==',  b]} : #{a == b}"
  puts "#{[a, '===', b]} : #{a === b}"
  puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
  puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end

eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)

How to create a DataFrame from a text file in Spark

Update - as of Spark 1.6, you can simply use the built-in csv data source:

spark: SparkSession = // create the Spark Session
val df = spark.read.csv("file.txt")

You can also use various options to control the CSV parsing, e.g.:

val df = spark.read.option("header", "false").csv("file.txt")

For Spark version < 1.6: The easiest way is to use spark-csv - include it in your dependencies and follow the README, it allows setting a custom delimiter (;), can read CSV headers (if you have them), and it can infer the schema types (with the cost of an extra scan of the data).

Alternatively, if you know the schema you can create a case-class that represents it and map your RDD elements into instances of this class before transforming into a DataFrame, e.g.:

case class Record(id: Int, name: String)

val myFile1 = myFile.map(x=>x.split(";")).map {
  case Array(id, name) => Record(id.toInt, name)
} 

myFile1.toDF() // DataFrame will have columns "id" and "name"

Define the selected option with the old input in Laravel / Blade

Laravel 6 or above: just use the old() function for instance @if (old('cat')==$cat->id), it will do the rest of the work for you.

How its works: select tag store the selected option value into its name attribute in bellow case if you select any option it will store into cat. At the first time when page loaded there is nothing inside cat, when user chose a option the value of that selected option is stored into cat so when user were redirected old() function pull the previous value from cat.

 {!!Form::open(['action'=>'CategoryController@storecat', 'method'=>'POST']) !!}
        <div class="form-group">
            <select name="cat" id="cat" class="form-control input-lg">
                <option value="">Select App</option>
                @foreach ($cats as $cat)
                    @if (old('cat')==$cat->id)
                        <option value={{$cat->id}} selected>{{ $cat->title }}</option>
                    @else
                        <option value={{$cat->id}} >{{ $cat->title }}</option>
                    @endif
                @endforeach
            </select>
        </div>

        <div class="from-group">
            {{Form::label('name','Category name:')}}
            {{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Category name'])}}
        </div>
    <br>
    {!!Form::submit('Submit', ['class'=>'btn btn-primary'])!!}
    {!!Form::close()!!}

boto3 client NoRegionError: You must specify a region error only sometimes

For those using CloudFormation template. You can set AWS_DEFAULT_REGION environment variable using UserData and AWS::Region. For example,

MyInstance1:
    Type: AWS::EC2::Instance                
    Properties:                           
        ImageId: ami-04b9e92b5572fa0d1 #ubuntu
        InstanceType: t2.micro
        UserData: 
            Fn::Base64: !Sub |
                    #!/bin/bash -x

                    echo "export AWS_DEFAULT_REGION=${AWS::Region}" >> /etc/profile

Is there a command line utility for rendering GitHub flavored Markdown?

Improving upon @barry-stae and @Sandeep answers for regular users of elinks you would add the following to .bashrc:

function mdviewer() {
  pandoc $* | elinks --force-html
}

Don't forget to install pandoc (and elinks).

HTML5 tag for horizontal line break

You can still use <hr> as a horizontal line, and you probably should. In HTML5 it defines a thematic break in content, without making any promises about how it is displayed. The attributes that aren't supported in the HTML5 spec are all related to the tag's appearance. The appearance should be set in CSS, not in the HTML itself.

So use the <hr> tag without attributes, then style it in CSS to appear the way you want.

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

how to remove only one style property with jquery

The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Since your styles are inline, you can write:

$(selector).css("-moz-user-select", "");

JavaScript private methods

The apotheosis of the Module Pattern: The Revealing Module Pattern

A neat little extension to a very robust pattern.

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

How to set child process' environment variable in Makefile

Make variables are not exported into the environment of processes make invokes... by default. However you can use make's export to force them to do so. Change:

test: NODE_ENV = test

to this:

test: export NODE_ENV = test

(assuming you have a sufficiently modern version of GNU make >= 3.77 ).

Removing multiple keys from a dictionary safely

Using dict.pop:

d = {'some': 'data'}
entries_to_remove = ('any', 'iterable')
for k in entries_to_remove:
    d.pop(k, None)

What is the max size of VARCHAR2 in PL/SQL and SQL?

As per official documentation link shared by Andre Kirpitch, Oracle 10g gives a maximum size of 4000 bytes or characters for varchar2. If you are using a higher version of oracle (for example Oracle 12c), you can get a maximum size upto 32767 bytes or characters for varchar2. To utilize the extended datatype feature of oracle 12, you need to start oracle in upgrade mode. Follow the below steps in command prompt:

1) Login as sysdba (sqlplus / as sysdba)

2) SHUTDOWN IMMEDIATE;

3) STARTUP UPGRADE;

4) ALTER SYSTEM SET max_string_size=extended;

5) Oracle\product\12.1.0.2\rdbms\admin\utl32k.sql

6) SHUTDOWN IMMEDIATE;

7) STARTUP;

Maven build failed: "Unable to locate the Javac Compiler in: jre or jdk issue"

I changed the configuration of maven-compiler-plugin to add executable and fork with value true.

<configuration>
    <fork>true</fork>
    <source>1.6</source>
    <target>1.6</target>
    <executable>C:\Program Files\Java\jdk1.6.0_18\bin\javac</executable>
</configuration>

It worked for me.

Boolean checking in the 'if' condition

The former. The latter merely adds verbosity.

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

How to save user input into a variable in html and js

It doesn't work because name is a reserved word in JavaScript. Change the function name to something else.

See http://www.quackit.com/javascript/javascript_reserved_words.cfm

<form id="form" onsubmit="return false;">
    <input style="position:absolute; top:80%; left:5%; width:40%;" type="text" id="userInput" />
    <input style="position:absolute; top:50%; left:5%; width:40%;" type="submit" onclick="othername();" />
</form>

function othername() {
    var input = document.getElementById("userInput").value;
    alert(input);
}

Store mysql query output into a shell variable

My two cents here:

myvariable=$(mysql database -u $user -p$password -sse "SELECT A, B, C FROM table_a" 2>&1 \
   | grep -v "Using a password")

Removes both the column names and the annoying (but necessary) password warning. Thanks @Dominic Bartl and John for this answer.

Get the year from specified date php

$Y_date = split("-","2068-06-15");
$year = $Y_date[0];

You can use explode also

Run cron job only if it isn't already running

I'd suggest the following as an improvement to rsanden's answer (I'd post as a comment, but don't have enough reputation...):

#!/usr/bin/env bash

PIDFILE="$HOME/tmp/myprogram.pid"

if [ -e "${PIDFILE}" ] && (ps -p $(cat ${PIDFILE}) > /dev/null); then
  echo "Already running."
  exit 99
fi

/path/to/myprogram

This avoids possible false matches (and the overhead of grepping), and it suppresses output and relies only on exit status of ps.

Save Screen (program) output to a file

A different answer if you need to save the output of your whole scrollback buffer from an already actively running screen:

Ctrl-a [ g SPACE G $ >.

This will save your whole buffer to /tmp/screen-exchange

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

<meta charset="utf-8"> was introduced with/for HTML5.

As mentioned in the documentation, both are valid. However, <meta charset="utf-8"> is only for HTML5 (and easier to type/remember).

In due time, the old style is bound to become deprecated in the near future. I'd stick to the new <meta charset="utf-8">.

There's only one way, but up. In tech's case, that's phasing out the old (really, REALLY fast)

Documentation: HTML meta charset Attribute—W3Schools

Efficiently sorting a numpy array in descending order?

You could sort the array first (Ascending by default) and then apply np.flip() (https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html)

FYI It works with datetime objects as well.

Example:

    x = np.array([2,3,1,0]) 
    x_sort_asc=np.sort(x) 
    print(x_sort_asc)

    >>> array([0, 1, 2, 3])

    x_sort_desc=np.flip(x_sort_asc) 
    print(x_sort_desc)

    >>> array([3,2,1,0])

Flutter position stack widget in center

Have a look at this solution I came up with

Positioned( child: SizedBox( child: CircularProgressIndicator(), width: 50, height: 50,), left: MediaQuery.of(context).size.width / 2 - 25);

How to draw checkbox or tick mark in GitHub Markdown table?

Edit the document or wiki page, and use the - [ ] and - [x] syntax to update your task list. Furthermore you can refer to this link.

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

I 'tripped' across my solution after 2 days...XCODE 4.0

I've just upgraded to XCode 4.0 and this code signing issue has been a stunning frustrastion. And I've been doing this for over a year various versions...so if you are having problems, you are not alone.

I have recertified, reprovisioned, drag and dropped, manually edit the project file, deleted PROVISIIONING paths, stopped/started XCODE, stopped started keychain, checked spelling, checked bundle ID's, check my birth certificate, the phase of the moon, and taught my dog morse code...none of it worked!!!!

--bottom line---

  1. Goto Targets... Build Settings tab
  2. Go to the Code Signing identity block
    • Check Debug AND Distribution have the same code signing information ..in my case "IPhone Distribution:, dont let DEBUG be blank or not filled in.

If the Debug mode was not the same, it failed the Distribution mode as well...go figure. Hope that helps someone...

Figure: This shows how to find the relevant settings in XCode 4.5.

enter image description here

Checkboxes in web pages – how to make them bigger?

Here's a trick that works in most recent browsers (IE9+) as a CSS only solution that can be improved with javascript to support IE8 and below.

<div>
  <input type="checkbox" id="checkboxID" name="checkboxName" value="whatever" />
  <label for="checkboxID"> </label>
</div>

Style the label with what you want the checkbox to look like

#checkboxID
{
  position: absolute fixed;
  margin-right: 2000px;
  right: 100%;
}
#checkboxID + label
{
  /* unchecked state */
}
#checkboxID:checked + label
{
  /* checked state */
}

For javascript, you'll be able to add classes to the label to show the state. Also, it would be wise to use the following function:

$('label[for]').live('click', function(e){
  $('#' + $(this).attr('for') ).click();
  return false;
});

EDIT to modify #checkboxID styles

Update int column in table with unique incrementing values

simple query would be, just set a variable to some number you want. then update the column you need by incrementing 1 from that number. for all the rows it'll update each row id by incrementing 1

SET @a  = 50000835 ;  
UPDATE `civicrm_contact` SET external_identifier = @a:=@a+1 
WHERE external_identifier IS NULL;

Clearing <input type='file' /> using jQuery

It's easy lol (works in all browsers [except opera]):

$('input[type=file]').each(function(){
    $(this).after($(this).clone(true)).remove();
});

JS Fiddle: http://jsfiddle.net/cw84x/1/

How to keep a git branch in sync with master

Yeah I agree with your approach. To merge mobiledevicesupport into master you can use

git checkout master
git pull origin master //Get all latest commits of master branch
git merge mobiledevicesupport

Similarly you can also merge master in mobiledevicesupport.

Q. If cross merging is an issue or not.

A. Well it depends upon the commits made in mobile* branch and master branch from the last time they were synced. Take this example: After last sync, following commits happen to these branches

Master branch: A -> B -> C [where A,B,C are commits]
Mobile branch: D -> E

Now, suppose commit B made some changes to file a.txt and commit D also made some changes to a.txt. Let us have a look at the impact of each operation of merging now,

git checkout master //Switches to master branch
git pull // Get the commits you don't have. May be your fellow workers have made them.
git merge mobiledevicesupport // It will try to add D and E in master branch.

Now, there are two types of merging possible

  1. Fast forward merge
  2. True merge (Requires manual effort)

Git will first try to make FF merge and if it finds any conflicts are not resolvable by git. It fails the merge and asks you to merge. In this case, a new commit will occur which is responsible for resolving conflicts in a.txt.

So Bottom line is Cross merging is not an issue and ultimately you have to do it and that is what syncing means. Make sure you dirty your hands in merging branches before doing anything in production.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

If the question is docker related... the official nginx docker images do this by making softlinks towards stdout/stderr

RUN ln -sf /dev/stdout /var/log/nginx/access.log && ln -sf /dev/stderr /var/log/nginx/error.log

REF: https://microbadger.com/images/nginx

MySQL: How to copy rows, but change a few fields?

INSERT INTO Table
          ( Event_ID
          , col2
           ...
          )
     SELECT "155"
          , col2
           ...
      FROM Table WHERE Event_ID = "120"

Here, the col2, ... represent the remaining columns (the ones other than Event_ID) in your table.

MySQL Update Column +1?

You can do:

UPDATE categories SET posts = posts + 1 WHERE category_id = 42;

boundingRectWithSize for NSAttributedString returning wrong size

One thing I was noticing is that the rect that would come back from (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context would have a larger width than what I passed in. When this happened my string would be truncated. I resolved it like this:

NSString *aLongString = ...
NSInteger width = //some width;            
UIFont *font = //your font;
CGRect rect = [aLongString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                        options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)
                                     attributes:@{ NSFontAttributeName : font,
                                                   NSForegroundColorAttributeName : [UIColor whiteColor]}
                                        context:nil];

if(rect.size.width > width)
{
    return rect.size.height + font.lineHeight;
}
return rect.size.height;

For some more context; I had multi line text and I was trying to find the right height to display it in. boundRectWithSize was sometimes returning a width larger than what I would specify, thus when I used my past in width and the calculated height to display my text, it would truncate. From testing when boundingRectWithSize used the wrong width the amount it would make the height short by was 1 line. So I would check if the width was greater and if so add the font's lineHeight to provide enough space to avoid truncation.

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

FB OpenGraph og:image not pulling images (possibly https?)

Similar symptoms (Facebook et al not correctly fetching og:image and other assets over https) can occur when the site's https certificate is not fully compliant.

Your site's https cert may seem valid (green key in the browser and all), but it will not scrape correctly if it's missing an intermediate or chain certificate. This can lead to many wasted hours checking and rechecking all the various caches and meta tags.

Might not have been your problem, but could be other's with similar symptoms (like mine). There's many ways to check your cert - the one I happened to use: https://www.sslshopper.com/ssl-checker.html

Could not locate Gemfile

Is very simple. when it says 'Could not locate Gemfile' it means in the folder you are currently in or a directory you are in, there is No a file named GemFile. Therefore in your command prompt give an explicit or full path of the there folder where such file name "Gemfile" is e.g cd C:\Users\Administrator\Desktop\RubyProject\demo.

It will definitely be solved in a minute.

How to remove a file from the index in git?

Depending on your workflow, this may be the kind of thing that you need rarely enough that there's little point in trying to figure out a command-line solution (unless you happen to be working without a graphical interface for some reason).

Just use one of the GUI-based tools that support index management, for example:

  • git gui <-- uses the Tk windowing framework -- similar style to gitk
  • git cola <-- a more modern-style GUI interface

These let you move files in and out of the index by point-and-click. They even have support for selecting and moving portions of a file (individual changes) to and from the index.


How about a different perspective: If you mess up while using one of the suggested, rather cryptic, commands:

  • git rm --cached [file]
  • git reset HEAD <file>

...you stand a real chance of losing data -- or at least making it hard to find. Unless you really need to do this with very high frequency, using a GUI tool is likely to be safer.


Working without the index

Based on the comments and votes, I've come to realize that a lot of people use the index all the time. I don't. Here's how:

  • Commit my entire working copy (the typical case): git commit -a
  • Commit just a few files: git commit (list of files)
  • Commit all but a few modified files: git commit -a then amend via git gui
  • Graphically review all changes to working copy: git difftool --dir-diff --tool=meld

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

I was also faced the same issue with mongodb 2.6.

What solved my problem was I just run mongod --repair command

and then start mongod.exe

It's worked for me

Check if a string is null or empty in XSLT

Something like this works for me:

<xsl:choose>
  <xsl:when test="string(number(categoryName)) = 'NaN'"> - </xsl:when> 
  <xsl:otherwise> 
    <xsl:number value="categoryName" />
  </xsl:otherwise>
</xsl:choose>

Or the other way around:

<xsl:choose>
  <xsl:when test="string(number(categoryName)) != 'NaN'">
    <xsl:number value="categoryName" />
  </xsl:when> 
  <xsl:otherwise> - </xsl:otherwise>
</xsl:choose>

Note: If you don't check null values or handle null values, IE7 returns -2147483648 instead of NaN.

Prevent multiple instances of a given app in .NET?

This is the code for VB.Net

Private Shared Sub Main()
    Using mutex As New Mutex(False, appGuid)
        If Not mutex.WaitOne(0, False) Then
              MessageBox.Show("Instance already running", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return
        End If

        Application.Run(New Form1())
    End Using
End Sub

This is the code for C#

private static void Main()
{
    using (Mutex mutex = new Mutex(false, appGuid)) {
        if (!mutex.WaitOne(0, false)) {
            MessageBox.Show("Instance already running", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }

        Application.Run(new Form1());
    }
}

How to import XML file into MySQL database table using XML_LOAD(); function

Since ID is auto increment, you can also specify ID=NULL as,

LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;

Can I force pip to reinstall the current version?

--force-reinstall

doesn't appear to force reinstall using python2.7 with pip-1.5

I've had to use

--no-deps --ignore-installed

jQuery - Create hidden form element on the fly

$('<input>').attr('type','hidden').appendTo('form');

To answer your second question:

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'bar'
}).appendTo('form');

Calling a Javascript Function from Console

you can invoke it using window.function_name() or directly function_name()

Why is list initialization (using curly braces) better than the alternatives?

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

List initialization does not allow narrowing (§iso.8.5.4). That is:

  • An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char.
  • A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float.
  • A floating-point value cannot be converted to an integer type.
  • An integer value cannot be converted to a floating-point type.

Example:

void fun(double val, int val2) {

    int x2 = val;    // if val == 7.9, x2 becomes 7 (bad)

    char c2 = val2;  // if val2 == 1025, c2 becomes 1 (bad)

    int x3 {val};    // error: possible truncation (good)

    char c3 {val2};  // error: possible narrowing (good)

    char c4 {24};    // OK: 24 can be represented exactly as a char (good)

    char c5 {264};   // error (assuming 8-bit chars): 264 cannot be 
                     // represented as a char (good)

    int x4 {2.0};    // error: no double to int value conversion (good)

}

The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.

Example:

auto z1 {99};   // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99;   // z3 is an int

Conclusion

Prefer {} initialization over alternatives unless you have a strong reason not to.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

In my case on mac (Catalina - Xampp) there was no loaded file so I had to do this first.

sudo cp /etc/php.ini.default /etc/php.ini
sudo nano /etc/php.ini

Then change memory_limit = 512M

Then Restart Apache and check if file loaded

php -i | grep php.ini

Result was

Configuration File (php.ini) Path => /etc
Loaded Configuration File => /etc/php.ini

Finally Check

php -r "echo ini_get('memory_limit').PHP_EOL;"

Advantages of std::for_each over for loop

Mostly you'll have to iterate over the whole collection. Therefore I suggest you write your own for_each() variant, taking only 2 parameters. This will allow you to rewrite Terry Mahaffey's example as:

for_each(container, [](int& i) {
    i += 10;
});

I think this is indeed more readable than a for loop. However, this requires the C++0x compiler extensions.

How can I sort a List alphabetically?

descending alphabet:

List<String> list;
...
Collections.sort(list);
Collections.reverse(list);

Adding maven nexus repo to my pom.xml

If you don't want or you cannot modify the settings.xml file, you can create a new one in your root project, and call maven passing it as a parameter with the -s parameter:

$ mvn COMMAND ... -s settings.xml

Carriage Return\Line feed in Java

The method newLine() ensures a platform-compatible new line is added (0Dh 0Ah for DOS, 0Dh for older Macs, 0Ah for Unix/Linux). Java has no way of knowing on which platform you are going to send the text. This conversion should be taken care of by the mail sending entities.

What is the difference between README and README.md in GitHub projects?

.md is markdown. README.md is used to generate the html summary you see at the bottom of projects. Github has their own flavor of Markdown.

Order of Preference: If you have two files named README and README.md, the file named README.md is preferred, and it will be used to generate github's html summary.


FWIW, Stack Overflow uses local Markdown modifications as well (also see Stack Overflow's C# Markdown Processor)

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

Converting between datetime and Pandas Timestamp objects

To answer the question of going from an existing python datetime to a pandas Timestamp do the following:

    import time, calendar, pandas as pd
    from datetime import datetime
    
    def to_posix_ts(d: datetime, utc:bool=True) -> float:
        tt=d.timetuple()
        return (calendar.timegm(tt) if utc else time.mktime(tt)) + round(d.microsecond/1000000, 0)
    
    def pd_timestamp_from_datetime(d: datetime) -> pd.Timestamp:
        return pd.to_datetime(to_posix_ts(d), unit='s')
    
    dt = pd_timestamp_from_datetime(datetime.now())
    print('({}) {}'.format(type(dt), dt))

Output:

(<class 'pandas._libs.tslibs.timestamps.Timestamp'>) 2020-09-05 23:38:55

I was hoping for a more elegant way to do this but the to_posix_ts is already in my standard tool chain so I'm moving on.

MySQL duplicate entry error even though there is no duplicate entry

Your code and schema are OK. You probably trying on previous version of table.

http://sqlfiddle.com/#!2/9dc64/1/0

Your table even has no UNIQUE, so that error is impossible on that table.

Backup data from that table, drop it and re-create.

Maybe you tried to run that CREATE TABLE IF NOT EXIST. It was not created, you have old version, but there was no error because of IF NOT EXIST.

You may run SQL like this to see current table structure:

DESCRIBE my_table;

Edit - added later:

Try to run this:

DROP TABLE `my_table`; --make backup - it deletes table

CREATE TABLE `my_table` (
  `number` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `money` int(11) NOT NULL,
  PRIMARY KEY (`number`,`name`),
  UNIQUE (`number`, `name`) --added unique on 2 rows
) ENGINE=MyISAM;

Rails: How can I set default values in ActiveRecord?

class Item < ActiveRecord::Base
  def status
    self[:status] or ACTIVE
  end

  before_save{ self.status ||= ACTIVE }
end

Close pre-existing figures in matplotlib when running from eclipse

Nothing works in my case using the scripts above but I was able to close these figures from eclipse console bar by clicking on Terminate ALL (two red nested squares icon).

Amazon S3 direct file upload from client browser - private key disclosure

Here is how you generate a policy document using node and serverless

"use strict";

const uniqid = require('uniqid');
const crypto = require('crypto');

class Token {

    /**
     * @param {Object} config SSM Parameter store JSON config
     */
    constructor(config) {

        // Ensure some required properties are set in the SSM configuration object
        this.constructor._validateConfig(config);

        this.region = config.region; // AWS region e.g. us-west-2
        this.bucket = config.bucket; // Bucket name only
        this.bucketAcl = config.bucketAcl; // Bucket access policy [private, public-read]
        this.accessKey = config.accessKey; // Access key
        this.secretKey = config.secretKey; // Access key secret

        // Create a really unique videoKey, with folder prefix
        this.key = uniqid() + uniqid.process();

        // The policy requires the date to be this format e.g. 20181109
        const date = new Date().toISOString();
        this.dateString = date.substr(0, 4) + date.substr(5, 2) + date.substr(8, 2);

        // The number of minutes the policy will need to be used by before it expires
        this.policyExpireMinutes = 15;

        // HMAC encryption algorithm used to encrypt everything in the request
        this.encryptionAlgorithm = 'sha256';

        // Client uses encryption algorithm key while making request to S3
        this.clientEncryptionAlgorithm = 'AWS4-HMAC-SHA256';
    }

    /**
     * Returns the parameters that FE will use to directly upload to s3
     *
     * @returns {Object}
     */
    getS3FormParameters() {
        const credentialPath = this._amazonCredentialPath();
        const policy = this._s3UploadPolicy(credentialPath);
        const policyBase64 = new Buffer(JSON.stringify(policy)).toString('base64');
        const signature = this._s3UploadSignature(policyBase64);

        return {
            'key': this.key,
            'acl': this.bucketAcl,
            'success_action_status': '201',
            'policy': policyBase64,
            'endpoint': "https://" + this.bucket + ".s3-accelerate.amazonaws.com",
            'x-amz-algorithm': this.clientEncryptionAlgorithm,
            'x-amz-credential': credentialPath,
            'x-amz-date': this.dateString + 'T000000Z',
            'x-amz-signature': signature
        }
    }

    /**
     * Ensure all required properties are set in SSM Parameter Store Config
     *
     * @param {Object} config
     * @private
     */
    static _validateConfig(config) {
        if (!config.hasOwnProperty('bucket')) {
            throw "'bucket' is required in SSM Parameter Store Config";
        }
        if (!config.hasOwnProperty('region')) {
            throw "'region' is required in SSM Parameter Store Config";
        }
        if (!config.hasOwnProperty('accessKey')) {
            throw "'accessKey' is required in SSM Parameter Store Config";
        }
        if (!config.hasOwnProperty('secretKey')) {
            throw "'secretKey' is required in SSM Parameter Store Config";
        }
    }

    /**
     * Create a special string called a credentials path used in constructing an upload policy
     *
     * @returns {String}
     * @private
     */
    _amazonCredentialPath() {
        return this.accessKey + '/' + this.dateString + '/' + this.region + '/s3/aws4_request';
    }

    /**
     * Create an upload policy
     *
     * @param {String} credentialPath
     *
     * @returns {{expiration: string, conditions: *[]}}
     * @private
     */
    _s3UploadPolicy(credentialPath) {
        return {
            expiration: this._getPolicyExpirationISODate(),
            conditions: [
                {bucket: this.bucket},
                {key: this.key},
                {acl: this.bucketAcl},
                {success_action_status: "201"},
                {'x-amz-algorithm': 'AWS4-HMAC-SHA256'},
                {'x-amz-credential': credentialPath},
                {'x-amz-date': this.dateString + 'T000000Z'}
            ],
        }
    }

    /**
     * ISO formatted date string of when the policy will expire
     *
     * @returns {String}
     * @private
     */
    _getPolicyExpirationISODate() {
        return new Date((new Date).getTime() + (this.policyExpireMinutes * 60 * 1000)).toISOString();
    }

    /**
     * HMAC encode a string by a given key
     *
     * @param {String} key
     * @param {String} string
     *
     * @returns {String}
     * @private
     */
    _encryptHmac(key, string) {
        const hmac = crypto.createHmac(
            this.encryptionAlgorithm, key
        );
        hmac.end(string);

        return hmac.read();
    }

    /**
     * Create an upload signature from provided params
     * https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html#signing-request-intro
     *
     * @param policyBase64
     *
     * @returns {String}
     * @private
     */
    _s3UploadSignature(policyBase64) {
        const dateKey = this._encryptHmac('AWS4' + this.secretKey, this.dateString);
        const dateRegionKey = this._encryptHmac(dateKey, this.region);
        const dateRegionServiceKey = this._encryptHmac(dateRegionKey, 's3');
        const signingKey = this._encryptHmac(dateRegionServiceKey, 'aws4_request');

        return this._encryptHmac(signingKey, policyBase64).toString('hex');
    }
}

module.exports = Token;

The configuration object used is stored in SSM Parameter Store and looks like this

{
    "bucket": "my-bucket-name",
    "region": "us-west-2",
    "bucketAcl": "private",
    "accessKey": "MY_ACCESS_KEY",
    "secretKey": "MY_SECRET_ACCESS_KEY",
}

Iterate all files in a directory using a 'for' loop

It could also use the forfiles command:

forfiles /s 

and also check if it is a directory

forfiles /p c:\ /s /m *.* /c "cmd /c if @isdir==true echo @file is a directory"

Matplotlib - How to plot a high resolution graph?

You can save your graph as svg for a lossless quality:

import matplotlib.pylab as plt

x = range(10)

plt.figure()
plt.plot(x,x)
plt.savefig("graph.svg")

Enter export password to generate a P12 certificate

The selected answer apparently does not work anymore in 2019 (at least for me).

I was trying to export a certificate using openssl (version 1.1.0) and the parameter -password doesn't work.

According to that link in the original answer (the same info is in man openssl), openssl has two parameter for passwords and they are -passin for the input parts and -passout for output files.

For the -export command, I used -passin for the password of my key file and -passout to create a new password for my P12 file.

So the complete command without any prompt was like below:

openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass:keypassphrase -passout pass:certificatepassword

If you does not want a password, you can use pass: like below:

openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass: -passout pass:

It will works fine with a key without password and the output certificate will be created without password too.

Open Redis port for remote connections

In my case, I'm using redis-stable

Go to redis-stable path 
 cd /home/ubuntu/software/redis-stable

Open the redis.conf

vim redis.conf

Change the bind 127.0.0.1 to bind 0.0.0.0

change the protected-mode yes to protected-mode no

Restart the redis-server:

/etc/init.d/redis-server stop
 redis-server redis.conf

In Angular, What is 'pathmatch: full' and what effect does it have?

pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match is the prefix path

pathMatch = 'prefix' tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.

Ref: https://angular.io/guide/router#set-up-redirects

pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.

pathMatch: 'prefix' means, the first route where the path matches the start of the URL is chosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.

Shell script to delete directories older than n days

OR

rm -rf `find /path/to/base/dir/* -type d -mtime +10`

Updated, faster version of it:

find /path/to/base/dir/* -mtime +10 -print0 | xargs -0 rm -f

What's the actual use of 'fail' in JUnit test case?

I think the usual use case is to call it when no exception was thrown in a negative test.

Something like the following pseudo-code:

test_addNilThrowsNullPointerException()
{
    try {
        foo.add(NIL);                      // we expect a NullPointerException here
        fail("No NullPointerException");   // cause the test to fail if we reach this            
     } catch (NullNullPointerException e) {
        // OK got the expected exception
    }
}

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

// detect IE8 and above, and Edge
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
    ... do something
}

Explanation:

document.documentMode

An IE only property, first available in IE8.

/Edge/

A regular expression to search for the string 'Edge' - which we then test against the 'navigator.userAgent' property

Update Mar 2020

@Jam comments that the latest version of Edge now reports Edg as the user agent. So the check would be:

if (document.documentMode || /Edge/.test(navigator.userAgent) || /Edg/.test(navigator.userAgent)) {
    ... do something
}

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

How to conclude your merge of a file?

The easiest solution I found for this:

git commit -m "fixing merge conflicts"
git push

How to add Options Menu to Fragment in Android

Call the super method:

Java:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Add your menu entries here
        super.onCreateOptionsMenu(menu, inflater);
    }

Kotlin:

    override fun void onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        // TODO Add your menu entries here
        super.onCreateOptionsMenu(menu, inflater)
    }

Put log statements in the code to see if the method is not being called or if the menu is not being amended by your code.

Also ensure you are calling setHasOptionsMenu(boolean) in onCreate(Bundle) to notify the fragment that it should participate in options menu handling.

Floating divs in Bootstrap layout

I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding

style="position: relative; bottom: 0px"

to your Widget2 tag. Also try:

style="position: absolute; bottom: 0px"

if you want to snap your widget to the bottom of the screen.

I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.

Excel VBA function to print an array to the workbook

A more elegant way is to assign the whole array at once:

Sub PrintArray(Data, SheetName, StartRow, StartCol)

    Dim Rng As Range

    With Sheets(SheetName)
        Set Rng = .Range(.Cells(StartRow, StartCol), _
            .Cells(UBound(Data, 1) - LBound(Data, 1) + StartRow, _
            UBound(Data, 2) - LBound(Data, 2) + StartCol))
    End With
    Rng.Value2 = Data

End Sub

But watch out: it only works up to a size of about 8,000 cells. Then Excel throws a strange error. The maximum size isn't fixed and differs very much from Excel installation to Excel installation.

The request was aborted: Could not create SSL/TLS secure channel

In my case I had this problem when a Windows service tried to connected to a web service. Looking in Windows events finally I found a error code.

Event ID 36888 (Schannel) is raised:

The following fatal alert was generated: 40. The internal error state is 808.

Finally it was related with a Windows Hotfix. In my case: KB3172605 and KB3177186

The proposed solution in vmware forum was add a registry entry in windows. After adding the following registry all works fine.

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\KeyExchangeAlgorithms\Diffie-Hellman]

"ClientMinKeyBitLength"=dword:00000200

Apparently it's related with a missing value in the https handshake in the client side.

List your Windows HotFix:

wmic qfe list

Solution Thread:

https://communities.vmware.com/message/2604912#2604912

Hope it's helps.

Maven and adding JARs to system scope

I don't know the real reason but Maven pushes developers to install all libraries (custom too) into some maven repositories, so scope:system is not well liked, A simple workaround is to use maven-install-plugin

follow the usage:

write your dependency in this way

<dependency>
    <groupId>com.mylib</groupId>
    <artifactId>mylib-core</artifactId>
    <version>0.0.1</version>
</dependency>

then, add maven-install-plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-install-plugin</artifactId>
    <version>2.5.2</version>
    <executions>
        <execution>
            <id>install-external</id>
            <phase>clean</phase>
            <configuration>
                <file>${basedir}/lib/mylib-core-0.0.1.jar</file>
                <repositoryLayout>default</repositoryLayout>
                <groupId>com.mylib</groupId>
                <artifactId>mylib-core</artifactId>
                <version>0.0.1</version>
                <packaging>jar</packaging>
                <generatePom>true</generatePom>
            </configuration>
            <goals>
                <goal>install-file</goal>
            </goals>
        </execution>
    </executions>
</plugin>

pay attention to phase:clean, to install your custom library into your repository, you have to run mvn clean and then mvn install

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

One possible reason for this error is: your annual subscription has been renewed. Once the subscription is renewed, all devices related to the active provision profiles will be detached.

  1. The admin must reactivate the list of devices for the new subscribed year.
  2. The admin must delete last year provision profiles. (all are useless).
  3. The admin must regenerate new provision profiles for the new year with the list of devices of his choice.

After this, rebuild project with Xcode and the error will disappear.

How do I make Git use the editor of my choice for commits?

In windows 7, while adding the "Sublime" editor it was still giving me an error:

Aborting commit due to empty commit message.

Sublime was not able to keep the focus.

To fix this I opened the .gitconfig file in c:/users/username/ folder and added the following line with --wait option outside the single quotes.

[core]
      editor = 'F:/Program Files/Sublime Text 2/sublime_text.exe' --wait

Hope its helpful to somebody facing similar issue with Sublime.

Media Queries - In between two widths

just wanted to leave my .scss example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.

Im looking forward for your feedback!

// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;

// Prepare your "function"
@mixin in-between {
     @media (min-width:$widthSmall) and (max-width:$widthMedium) {
        @content;
     }
}


// Apply your "function"
main {
   @include in-between {
      //Do something between two media queries
      padding-bottom: 20px;
   }
}

How do I print out the contents of an object in Rails for easy debugging?

I generally first try .inspect, if that doesn't give me what I want, I'll switch to .to_yaml.

class User
  attr_accessor :name, :age
end

user = User.new
user.name = "John Smith"
user.age = 30

puts user.inspect
#=> #<User:0x423270c @name="John Smith", @age=30>
puts user.to_yaml
#=> --- !ruby/object:User
#=> age: 30
#=> name: John Smith

Hope that helps.

Where is the correct location to put Log4j.properties in an Eclipse project?

Put log4j.properties in the runtime classpath.

This forum shows some posts about possible ways to do it.

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Start -> Control Panel -> Programs and Features, search for the Add-ons you would like to uninstall and click on particular one to uninstall.

Yes, I tried uninstalling from IE, Tools -> Manage Add-ons and then click "More Information" link at the bottom, however the "Remove" button was disabled. This didn't work.

Above mentioned solution for uninstalling from "Programs and Features" works.

How can I create an object based on an interface file definition in TypeScript?

Here is another approach:

You can simply create an ESLint friendly object like this

const modal: IModal = {} as IModal;

Or a default instance based on the interface and with sensible defaults, if any

const defaultModal: IModal = {
    content: "",
    form: "",
    href: "",
    $form: {} as JQuery,
    $message: {} as JQuery,
    $modal: {} as JQuery,
    $submits: {} as JQuery
};

Then variations of the default instance simply by overriding some properties

const confirmationModal: IModal = {
    ...defaultModal,     // all properties/values from defaultModal
    form: "confirmForm"  // override form only
}

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

I found next workaround. You may escape the redirection after processing POST request by manipulating history object.

So you have the HTML form:

<form method=POST action='/process.php'>
 <input type=submit value=OK>
</form>

When you process this form on your server you instead of redirecting user to /the/result/page by setting up the Location header like this:

$cat process.php
<?php 
     process POST data here
     ... 
     header('Location: /the/result/page');
     exit();
?>

enter image description here

After processing POSTed data you render small <script> and the result /the/result/page

<?php 
     process POST data here
     render the <script>         // see below
     render `/the/result/page`   // OK
?>

The <script> you should render:

<script>
    window.onload = function() {
        history.replaceState("", "", "/the/result/page");
    }
</script>

The result is:

enter image description here

as you can see the form data is POSTed to process.php script.
This script process POSTed data and rendering /the/result/page at once with:

  1. no redirection
  2. no rePOST data when you refresh page (F5)
  3. no rePOST when you navigate to previous/next page through the browser history

UPD

As another solution I ask feature request the Mozilla FireFox team to allow users to setup NextPage header which will work like Location header and make post/redirect/get pattern obsolete.

In short. When server process form POST data successfully it:

  1. Setup NextPage header instead of Location
  2. Render the result of processing POST form data as it would render for GET request in post/redirect/get pattern

The browser in turn when see the NextPage header:

  1. Adjust window.location with NextPage value
  2. When user refresh the page the browser will negotiate GET request to NextPage instead of rePOST form data

I think this would be excelent if implemented, would not? =)

How do I drag and drop files into an application?

The solution of Judah Himango and Hans Passant is available in the Designer (I am currently using VS2015):

enter image description here

enter image description here

Command not found when using sudo

Try chmod u+x foo.sh instead of chmod +x foo.sh if you have trouble with the guides above. This worked for me when the other solutions did not.

How to return first 5 objects of Array in Swift?

The Prefix function is definitely the most efficient way of solving this problem, but you can also use for-in loops like the following:

let array = [1,2,3,4,5,6,7,8,9]
let maxNum = 5
var iterationNumber = 0
var firstNumbers = [Int()]
if array.count > maxNum{
  for i in array{
    iterationNumber += 1
    if iterationNumber <= maxNum{
      firstNumbers.append(i)
    }
  }
  firstNumbers.remove(at: 0)
  print(firstNumbers)
} else {
  print("There were not \(maxNum) items in the array.")
}

This solution takes up many lines of code but checks to see if there are enough items in the array to carry out the program, then continues and solves the problem. This solution uses many basic functions including array.count, which returns the amount of items in the array, not the position of last item in the array. It also uses array.append, which adds things onto the end of the array. Lastly, it uses array.remove, which removes the array's item that has a specified position.

I have tested it it and it works for at least swift 5.

How to change the style of a DatePicker in android?

As AlertDialog.THEME attributes are deprecated, while creating DatePickerDialog you should pass one of these parameters for int themeResId

  • android.R.style.Theme_DeviceDefault_Dialog_Alert
  • android.R.style.Theme_DeviceDefault_Light_Dialog_Alert
  • android.R.style.Theme_Material_Light_Dialog_Alert
  • android.R.style.Theme_Material_Dialog_Alert

How to check that Request.QueryString has a specific value or not in ASP.NET?

You can also try:

if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
   return;

Function return value in PowerShell

This part of PowerShell is probably the most stupid aspect. Any extraneous output generated during a function will pollute the result. Sometimes there isn't any output, and then under some conditions there is some other unplanned output, in addition to your planned return value.

So, I remove the assignment from the original function call, so the output ends up on the screen, and then step through until something I didn't plan for pops out in the debugger window (using the PowerShell ISE).

Even things like reserving variables in outer scopes cause output, like [boolean]$isEnabled which will annoyingly spit a False out unless you make it [boolean]$isEnabled = $false.

Another good one is $someCollection.Add("thing") which spits out the new collection count.

How to make an embedded video not autoplay

I had the same problem and came across this post. Nothing worked. After randomly playing around, I found that <embed ........ play="false"> stopped it from playing automatically. I now have the problem that I can't get a controller to appear, so can't start the movie! :S

YouTube iframe API: how do I control an iframe player that's already in the HTML?

You can do this with far less code:

function callPlayer(func, args) {
    var i = 0,
        iframes = document.getElementsByTagName('iframe'),
        src = '';
    for (i = 0; i < iframes.length; i += 1) {
        src = iframes[i].getAttribute('src');
        if (src && src.indexOf('youtube.com/embed') !== -1) {
            iframes[i].contentWindow.postMessage(JSON.stringify({
                'event': 'command',
                'func': func,
                'args': args || []
            }), '*');
        }
    }
}

Working example: http://jsfiddle.net/kmturley/g6P5H/296/

Finding the length of a Character Array in C

If you have an array, then you can find the number of elements in the array by dividing the size of the array in bytes by the size of each element in bytes:

char x[10];
int elements_in_x = sizeof(x) / sizeof(x[0]);

For the specific case of char, since sizeof(char) == 1, sizeof(x) will yield the same result.

If you only have a pointer to an array, then there's no way to find the number of elements in the pointed-to array. You have to keep track of that yourself. For example, given:

char x[10];
char* pointer_to_x = x;

there is no way to tell from just pointer_to_x that it points to an array of 10 elements. You have to keep track of that information yourself.

There are numerous ways to do that: you can either store the number of elements in a variable or you can encode the contents of the array such that you can get its size somehow by analyzing its contents (this is effectively what null-terminated strings do: they place a '\0' character at the end of the string so that you know when the string ends).

How to deploy a React App on Apache web server

As said in the post, React is a browser based technology. It only renders a view in an HTML document.

To be able to have access to your "React App", you need to:

  1. Bundle your React app in a bundle
  2. Have Apache pointing to your html file in your server, and allowing access externally.

You might have all the informations here: https://httpd.apache.org/docs/trunk/getting-started.html for the Apache server, and here to make your javascript bundle https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr

Check if a string is a date value

None of the answers here address checking whether the date is invalid such as February 31. This function addresses that by checking if the returned month is equivalent to the original month and making sure a valid year was presented.

//expected input dd/mm/yyyy or dd.mm.yyyy or dd-mm-yyyy
function isValidDate(s) {
  var separators = ['\\.', '\\-', '\\/'];
  var bits = s.split(new RegExp(separators.join('|'), 'g'));
  var d = new Date(bits[2], bits[1] - 1, bits[0]);
  return d.getFullYear() == bits[2] && d.getMonth() + 1 == bits[1];
} 

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

Socket transport "ssl" in PHP not enabled

Ran into the same problem on Laravel 4 trying to send e-mail using SSL encryption.

Having WAMPServer 2.2 on Windows 7 64bit I only enabled php_openssl in the php.ini, restarted WAMPServer and worked flawlessly.

Did following:

  • Click WampServer -> PHP -> PHP extensions -> php_openssl
  • Restart WampServer

How to get client IP address using jQuery

jQuery can handle JSONP, just pass an url formatted with the callback=? parameter to the $.getJSON method, for example:

_x000D_
_x000D_
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
    console.log(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

This example is of a really simple JSONP service implemented on with api.ipify.org.

If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.

Commenting multiple lines in DOS batch file

You can use a goto to skip over code.

goto comment
...skip this...
:comment

jsPDF multi page PDF with HTML renderer

I have the same working issue. Searching in MrRio github I found this: https://github.com/MrRio/jsPDF/issues/101

Basically, you have to check the actual page size always before adding new content

doc = new jsPdf();
...
pageHeight= doc.internal.pageSize.height;

// Before adding new content
y = 500 // Height position of new content
if (y >= pageHeight)
{
  doc.addPage();
  y = 0 // Restart height position
}
doc.text(x, y, "value");

Extracting numbers from vectors of strings

We can also use str_extract from stringr

years<-c("20 years old", "1 years old")
as.integer(stringr::str_extract(years, "\\d+"))
#[1] 20  1

If there are multiple numbers in the string and we want to extract all of them, we may use str_extract_all which unlike str_extract returns all the macthes.

years<-c("20 years old and 21", "1 years old")
stringr::str_extract(years, "\\d+")
#[1] "20"  "1"

stringr::str_extract_all(years, "\\d+")

#[[1]]
#[1] "20" "21"

#[[2]]
#[1] "1"