How can I have ruby logger log output to stdout as well as file?

Question: Someting like a tee functionality in logger.
Comment: Adding `| tee` before the file worked for me, so `Logger.new("| tee test.log")`. **Note the pipe.** This was from a tip on https://coderwall.com/p/y_b3ra/log-to-stdout-and-a-file-at-the-same-time
Comment: @mjwatts Use `tee --append test.log` to prevent overwrites.
Answer: You can write a pseudo IO class that will write to multiple IO objects.  Something like:
class MultiIO
  def initialize(*targets)
     @targets = targets
  end

  def write(*args)
    @targets.each {|t| t.write(*args)}
  end

  def close
    @targets.each(&:close)
  end
end

Then set that as your log file:
log_file = File.open("log/debug.log", "a")
Logger.new MultiIO.new(STDOUT, log_file)

Every time Logger calls puts on your MultiIO object, it will write to both STDOUT and your log file.
Edit: I went ahead and figured out the rest of the interface.  A log device must respond to write and close (not puts).  As long as MultiIO responds to those and proxies them to the real IO objects, this should work.
Comment: Note in Ruby 2.2, `@targets.each(&:close)` is depreciated.
Comment: if you look at the ctor of logger you will see that this will mess up log rotation.
`def initialize(log = nil, opt = {})
      @dev = @filename = @shift_age = @shift_size = nil
      @mutex = LogDeviceMutex.new
      if log.respond_to?(:write) and log.respond_to?(:close)
 @dev = log
      else
 @dev = open_logfile(log)
 @dev.sync = true
 @filename = log
 @shift_age = opt[:shift_age] || 7
 @shift_size = opt[:shift_size] || 1048576
      end
    end`
Comment: Worked for me until I realized I needed to periodically call :close on log_file to get log_file to update what logger had logged (essentially a "save"). STDOUT did not like :close being called on it, sort of defeating the MultoIO idea. Added a hack to skip :close except for class File, but wish I had a more elegant solution.
Answer: @David's solution is very good. I've made a generic delegator class for multiple targets based on his code.
require 'logger'

class MultiDelegator
  def initialize(*targets)
    @targets = targets
  end

  def self.delegate(*methods)
    methods.each do |m|
      define_method(m) do |*args|
        @targets.map { |t| t.send(m, *args) }
      end
    end
    self
  end

  class <<self
    alias to new
  end
end

log_file = File.open("debug.log", "a")
log = Logger.new MultiDelegator.delegate(:write, :close).to(STDOUT, log_file)

Comment: It's separation of concerns. MultiDelegator only knows about delegating calls to multiple targets. The fact that a logging device needs a write and a close method is implemented in the caller. This makes MultiDelegator usable in other situations than logging.
Comment: I really like your solution, but it is not good as a generic delegator that can be used multiple times as every delegation pollutes all instances with new methods. I posted an answer bellow (http://stackoverflow.com/a/36659911/123376) that fixes this problem. I posted an answer rather than an edit since it may be educational to see the difference between the two implementations as I also posted examples.
Comment: Could you please explain, how this is better or what are enhanced utilities of this approach than the plain one suggested by David
Comment: Nice solution. I tried to use this to tee the output from my rake tasks to a log file. In order to get it to work with puts though (to be able to call $stdout.puts without getting "private method `puts' called"), I had to add a few more methods:
log_file = File.open("tmp/rake.log", "a")
$stdout = MultiDelegator.delegate(:write, :close, :puts, :print).to(STDOUT, log_file)
Would be nice if it were possible to create a Tee class that inherited from MultiDelegator, like you can do with the Delegator class in stdlib...
Comment: I came up with a Delegator-like implementation of this that I called DelegatorToAll. This way you don't have to list all the methods you want to delegate, since it will delegate all methods that are defined in the delegate class (IO):

class Tee < DelegateToAllClass(IO)
end

$stdout = Tee.new(STDOUT, File.open("#{__FILE__}.log", "a"))

See https://gist.github.com/TylerRick/4990898 for more details.
Comment: I am in love with your answer.
Comment: I really don't like Ruby, but this is nice. Well done.
Comment: Stick to David Answer. One example that simple thing doesn't need to be complicated.
Answer: If you're in Rails 3 or 4, as this blog post points out, Rails 4 has this functionality built in. So you can do:
# config/environment/production.rb
file_logger = Logger.new(Rails.root.join("log/alternative-output.log"))
config.logger.extend(ActiveSupport::Logger.broadcast(file_logger))

Or if you're on Rails 3, you can backport it:
# config/initializers/alternative_output_log.rb

# backported from rails4
module ActiveSupport
  class Logger < ::Logger
    # Broadcasts logs to multiple loggers. Returns a module to be
    # `extended`'ed into other logger instances.
    def self.broadcast(logger)
      Module.new do
        define_method(:add) do |*args, &block|
          logger.add(*args, &block)
          super(*args, &block)
        end

        define_method(:<<) do |x|
          logger << x
          super(x)
        end

        define_method(:close) do
          logger.close
          super()
        end

        define_method(:progname=) do |name|
          logger.progname = name
          super(name)
        end

        define_method(:formatter=) do |formatter|
          logger.formatter = formatter
          super(formatter)
        end

        define_method(:level=) do |level|
          logger.level = level
          super(level)
        end
      end
    end
  end
end

file_logger = Logger.new(Rails.root.join("log/alternative-output.log"))
Rails.logger.extend(ActiveSupport::Logger.broadcast(file_logger))

Comment: is this applicable outside of rails, or rails only?
Comment: It's based on ActiveSupport, so if you have that dependency already, you can `extend` any `ActiveSupport::Logger` instance as shown above.
Comment: Thanks, it was helpful.
Comment: I think this is the simplest and most effective answer, although I had some weirdness using the `config.logger.extend()` inside my environment configuration. Instead, I set `config.logger` to `STDOUT` in my environment, then extended the logger in different initializers.
Answer: For those who like it simple:
log = Logger.new("| tee test.log") # note the pipe ( '|' )
log.info "hi" # will log to both STDOUT and test.log

source
Or print the message in the Logger formatter:
log = Logger.new("test.log")
log.formatter = proc do |severity, datetime, progname, msg|
    puts msg
    msg
end
log.info "hi" # will log to both STDOUT and test.log

I'm actually using this technique to print to a log file, a cloud logger service (logentries) and if it's dev environment - also print to STDOUT.
Comment: `"| tee test.log"` will overwrites  the old outputs, may be `"| tee -a test.log"` instead
Comment: `No such file or directory @ rb_sysopen`
Answer: You can also add multiple device logging functionality directly into the Logger:
require 'logger'

class Logger
  # Creates or opens a secondary log file.
  def attach(name)
    @logdev.attach(name)
  end

  # Closes a secondary log file.
  def detach(name)
    @logdev.detach(name)
  end

  class LogDevice # :nodoc:
    attr_reader :devs

    def attach(log)
      @devs ||= {}
      @devs[log] = open_logfile(log)
    end

    def detach(log)
      @devs ||= {}
      @devs[log].close
      @devs.delete(log)
    end

    alias_method :old_write, :write
    def write(message)
      old_write(message)

      @devs ||= {}
      @devs.each do |log, dev|
        dev.write(message)
      end
    end
  end
end

For instance:
logger = Logger.new(STDOUT)
logger.warn('This message goes to stdout')

logger.attach('logfile.txt')
logger.warn('This message goes both to stdout and logfile.txt')

logger.detach('logfile.txt')
logger.warn('This message goes just to stdout')

Answer: While I quite like the other suggestions, I found I had this same issue but wanted the ability to have different logging levels for STDERR and the file.
I ended up with a routing strategy that multiplexes at the logger level rather than at the IO level, so that each logger could then operate at independent log-levels:
class MultiLogger
  def initialize(*targets)
    @targets = targets
  end

  %w(log debug info warn error fatal unknown).each do |m|
    define_method(m) do |*args|
      @targets.map { |t| t.send(m, *args) }
    end
  end
end

stderr_log = Logger.new(STDERR)
file_log = Logger.new(File.open('logger.log', 'a'))

stderr_log.level = Logger::INFO
file_log.level = Logger::DEBUG

log = MultiLogger.new(stderr_log, file_log)

Comment: I like this solution best as it is (1) simple, and (2) encourages you to re-use your Logger classes instead of assuming everything goes to a file.  In my case I'd like to log to STDOUT and a GELF appender for Graylog.  Having a `MultiLogger` like @dsz describes is a great fit. Thanks for sharing!
Comment: Added section to handle pseudovariables (setters/getters)
Answer: Here's another implementation, inspired by @jonas054's answer.
This uses a pattern similar to Delegator. This way you don't have to list all the methods you want to delegate, since it will delegate all methods that are defined in any of the target objects:
class Tee < DelegateToAllClass(IO)
end

$stdout = Tee.new(STDOUT, File.open("#{__FILE__}.log", "a"))

You should be able to use this with Logger as well.
delegate_to_all.rb is available from here: https://gist.github.com/TylerRick/4990898
Answer: Quick and dirty (ref: https://coderwall.com/p/y_b3ra/log-to-stdout-and-a-file-at-the-same-time)
require 'logger'
ll=Logger.new('| tee script.log')
ll.info('test')

Answer: I have written a little RubyGem that allows you to do several of these things:
# Pipe calls to an instance of Ruby's logger class to $stdout
require 'teerb'

log_file = File.open("debug.log", "a")
logger = Logger.new(TeeRb::IODelegate.new(log_file, STDOUT))

logger.warn "warn"
$stderr.puts "stderr hello"
puts "stdout hello"

You can find the code on github: teerb
Comment: Thanks. This is quite clean.
Answer: @jonas054's answer above is great, but it pollutes the MultiDelegator class with every new delegate. If you use MultiDelegator several times, it will keep adding methods to the class, which is undesirable. (See bellow for example)
Here is the same implementation, but using anonymous classes so the methods don't pollute the delegator class.
class BetterMultiDelegator

  def self.delegate(*methods)
    Class.new do
      def initialize(*targets)
        @targets = targets
      end

      methods.each do |m|
        define_method(m) do |*args|
          @targets.map { |t| t.send(m, *args) }
        end
      end

      class <<self
        alias to new
      end
    end # new class
  end # delegate

end

Here is an example of the method pollution with the original implementation, contrasted with the modified implementation:
tee = MultiDelegator.delegate(:write).to(STDOUT)
tee.respond_to? :write
# => true
tee.respond_to? :size
# => false

All is good above. tee has a write method, but no size method as expected. Now, consider when we create another delegate:
tee2 = MultiDelegator.delegate(:size).to("bar")
tee2.respond_to? :size
# => true
tee2.respond_to? :write
# => true   !!!!! Bad
tee.respond_to? :size
# => true   !!!!! Bad

Oh no, tee2 responds to size as expected, but it also responds to write because of the first delegate. Even tee now responds to size because of the method pollution.
Contrast this to the anonymous class solution, everything is as expected:
see = BetterMultiDelegator.delegate(:write).to(STDOUT)
see.respond_to? :write
# => true
see.respond_to? :size
# => false

see2 = BetterMultiDelegator.delegate(:size).to("bar")
see2.respond_to? :size
# => true
see2.respond_to? :write
# => false
see.respond_to? :size
# => false

Answer: Are you restricted to the standard logger?
If not you may use log4r:
require 'log4r'

LOGGER = Log4r::Logger.new('mylog')
LOGGER.outputters << Log4r::StdoutOutputter.new('stdout')
LOGGER.outputters << Log4r::FileOutputter.new('file', :filename => 'test.log') #attach to existing log-file

LOGGER.info('aa') #Writs on STDOUT and sends to file

One advantage: You could also define different log-levels for stdout and file.
Answer: If you're okay with using ActiveSupport, then I would highly recommend checking out ActiveSupport::Logger.broadcast, which is an excellent and very concise way to add additional log destinations to a logger.
In fact, if you are using Rails 4+ (as of this commit), you don't need to do anything to get the desired behavior — at least if you're using the rails console. Whenever you use the rails console, Rails automatically extends Rails.logger such that it outputs both to its usual file destination (log/production.log, for example) and STDERR:
    console do |app|
      …
      unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDERR, STDOUT)
        console = ActiveSupport::Logger.new(STDERR)
        Rails.logger.extend ActiveSupport::Logger.broadcast console
      end
      ActiveRecord::Base.verbose_query_logs = false
    end

For some unknown and unfortunate reason, this method is undocumented but you can refer to the source code or blog posts to learn how it works or see examples.
https://www.joshmcarthur.com/til/2018/08/16/logging-to-multiple-destinations-using-activesupport-4.html has another example:
require "active_support/logger"
console_logger = ActiveSupport::Logger.new(STDOUT)
file_logger = ActiveSupport::Logger.new("my_log.log")
combined_logger = console_logger.extend(ActiveSupport::Logger.broadcast(file_logger))

combined_logger.debug "Debug level"
…

Answer: I went to the same idea of "Delegating all methods to sub-elements" that other people already explored, but am returning for each of them the return value of the last call of the method.
If I didn't, it broke logger-colors which were expecting an Integer and map was returning an Array.
class MultiIO
  def self.delegate_all
    IO.methods.each do |m|
      define_method(m) do |*args|
        ret = nil
        @targets.each { |t| ret = t.send(m, *args) }
        ret
      end
    end
  end

  def initialize(*targets)
    @targets = targets
    MultiIO.delegate_all
  end
end

This will redelegate every method to all targets, and return only the return value of the last call.
Also, if you want colors, STDOUT or STDERR must be put last, since it's the only two were colors are supposed to be output. But then, it will also output colors to your file.
logger = Logger.new MultiIO.new(File.open("log/test.log", 'w'), STDOUT)
logger.error "Roses are red"
logger.unknown "Violets are blue"

Answer: One more way.
If you're using tagged logging and need tags in another logfile as well, you could do it in this way
# backported from rails4
# config/initializers/active_support_logger.rb
module ActiveSupport
 class Logger < ::Logger

 # Broadcasts logs to multiple loggers. Returns a module to be
 # `extended`'ed into other logger instances.
 def self.broadcast(logger)
  Module.new do
    define_method(:add) do |*args, &block|
      logger.add(*args, &block)
      super(*args, &block)
    end

    define_method(:<<) do |x|
      logger << x
      super(x)
    end

    define_method(:close) do
      logger.close
      super()
    end

    define_method(:progname=) do |name|
      logger.progname = name
      super(name)
    end

    define_method(:formatter=) do |formatter|
      logger.formatter = formatter
      super(formatter)
    end

    define_method(:level=) do |level|
      logger.level = level
      super(level)
    end

   end # Module.new
 end # broadcast

 def initialize(*args)
   super
   @formatter = SimpleFormatter.new
 end

  # Simple formatter which only displays the message.
  class SimpleFormatter < ::Logger::Formatter
   # This method is invoked when a log event occurs
   def call(severity, time, progname, msg)
   element = caller[4] ? caller[4].split("/").last : "UNDEFINED"
    "#{Thread.current[:activesupport_tagged_logging_tags]||nil } # {time.to_s(:db)} #{severity} #{element} -- #{String === msg ? msg : msg.inspect}\n"
   end
  end

 end # class Logger
end # module ActiveSupport

custom_logger = ActiveSupport::Logger.new(Rails.root.join("log/alternative_#{Rails.env}.log"))
Rails.logger.extend(ActiveSupport::Logger.broadcast(custom_logger))

After this you'll get uuid tags in alternative logger
["fbfea87d1d8cc101a4ff9d12461ae810"] 2015-03-12 16:54:04 INFO logger.rb:28:in `call_app' --
["fbfea87d1d8cc101a4ff9d12461ae810"] 2015-03-12 16:54:04 INFO   logger.rb:31:in `call_app' -- Started POST "/psp/entrypoint" for 192.168.56.1 at 2015-03-12 16:54:04 +0700

Hope that helps someone.
Comment: Simple, reliable and works brilliantly. Thanks!

Note that `ActiveSupport::Logger` works out of the box with this - you just need to use `Rails.logger.extend` with `ActiveSupport::Logger.broadcast(...)`.
Answer: One more option ;-)
require 'logger'

class MultiDelegator
  def initialize(*targets)
    @targets = targets
  end

  def method_missing(method_sym, *arguments, &block)
    @targets.each do |target|
      target.send(method_sym, *arguments, &block) if target.respond_to?(method_sym)
    end
  end
end

log = MultiDelegator.new(Logger.new(STDOUT), Logger.new(File.open("debug.log", "a")))

log.info('Hello ...')

Answer: This is a simplification of @rado's solution.
def delegator(*methods)
  Class.new do
    def initialize(*targets)
      @targets = targets
    end

    methods.each do |m|
      define_method(m) do |*args|
        @targets.map { |t| t.send(m, *args) }
      end
    end

    class << self
      alias for new
    end
  end # new class
end # delegate

It has all the same benefits as his without the need of the outer class wrapper. Its a useful utility to have in a separate ruby file.
Use it as a one-liner to generate delegator instances like so:
IO_delegator_instance = delegator(:write, :read).for(STDOUT, STDERR)
IO_delegator_instance.write("blah")

OR use it as a factory like so:
logger_delegator_class = delegator(:log, :warn, :error)
secret_delegator = logger_delegator_class(main_logger, secret_logger)
secret_delegator.warn("secret")

general_delegator = logger_delegator_class(main_logger, debug_logger, other_logger)
general_delegator.log("message")

Answer: You can use Loog::Tee object from loog gem:
require 'loog'
logger = Loog::Tee.new(first, second)

Exactly what you are looking for.
Answer: I also has this need recently so I implemented a library that does this. I just discovered this StackOverflow question, so I'm putting it out there for anyone that needs it: https://github.com/agis/multi_io.
Compared to the other solutions mentioned here, this strives to be an IO object of its own, so it can be used as a drop-in replacement for other regular IO objects (files, sockets etc.)
That said, I've not yet implemented all the standard IO methods, but those that are, follow the IO semantics (e.g. for example, #write returns the sum of the number of bytes written to all the underlying IO targets).
Answer: You can inherit Logger and override the write method:
class LoggerWithStdout < Logger
  def initialize(*)
    super

    def @logdev.write(msg)
      super

      puts msg
    end
  end
end

logger = LoggerWithStdout.new('path/to/log_file.log')

Answer: Use IO.popen with tee.
Method: IO.popen — Documentation for core (3.0.2)
$logger = Logger.new(IO.popen(["tee", "-a", "debug.log"], "wb"))

Answer: I like the MultiIO approach. It works well with Ruby Logger. If you use pure IO it stops working because it lacks some methods that IO objects are expected to have. Pipes were mentioned before here: How can I have ruby logger log output to stdout as well as file?. Here is what works best for me.
def watch(cmd)
  output = StringIO.new
  IO.popen(cmd) do |fd|
    until fd.eof?
      bit = fd.getc
      output << bit
      $stdout.putc bit
    end
  end
  output.rewind
  [output.read, $?.success?]
ensure
  output.close
end

result, success = watch('./my/shell_command as a String')

Note I know this doesn't answer the question directly but it is strongly related. Whenever I searched for output to multiple IOs I came across this thread.So, I hope you find this useful too.
Answer: I think your STDOUT is used for critical runtime info and errors raised.
So I use
  $log = Logger.new('process.log', 'daily')

to log debug and regular logging, and then wrote a few
  puts "doing stuff..."

where I need to see STDOUT information that my scripts were running at all!
Bah, just my 10 cents :-)


Were Cara's victims in "Long Live the King" targets of opportunity, or were they picked on purpose (and by whom)?

Question: In Being Human (the original British series) season 2 episode 3 "Long Live the King", Cara kills some teenagers after Mitchell has ordered that there should be no killing of humans. The teenagers are apparently an opportunistic target: we see Cara seeming to fancy them in a mall, and Cara isn't the subtle type. Yet Chief constable Wilson implies to Mitchell in one of their confrontations that the victims were targeted as they all had prior run-ins with the police. So was this just a coincidence that Wilson does not believe in, was there some deeper plot that Mitchell failed to uncover, or am I missing something?
Answer: First let me say, I was attempting to clean my house while I was watching this episode, so I certainly wouldn't take my interpretation of this as gospel.  However, I too was a little intrigued by this particular scene and I re-watched it.
I was under the impression that Cara's hunger was completely out of control by this point.  I recall she observed the teenagers at the mall, and they appeared to be bullying another girl (playing keep-away with the girl's purse or something to that effect).  Just from Cara's appearance, it seems to me that she was probably a girl who was bullied/picked on before she became a vamp.
Then the scene changes and you see her killing one girl, but she walks away and leaves the other unharmed (possibly the girl who was being bullied?  I'm not 100% sure).  It just seemed more personal than random to me, but maybe I'm overthinking it.

Were Cara's victims in “Long Live the King” targets of opportunity, or were they picked on purpose (and by whom)?


How to enforce that one row in a parent table MUST be associated with at least a row in a child table

Question: I have a one to many relationship enforced via FK, classic example order and order_item, whereby a fk on the order_item to the order table enforces that one item belongs to one order, and one order CAN have 1 or more item. I'd need to change the "CAN" to "MUST", basically any order must at least have one item associated with it.
What would be the best way to enforce this.
Many thanks
Comment: I think you'll need to do this via triggers.
Answer: There is no declarative referential integrity to enforce one or more children in SQL Server.  You have to enforce this with application logic.
Note too that if you are using a foreign key constraint on the child, you can't save the child until the primary key of the parent is known.  This means that you need to have a transactional wrapper (BEGIN TRAN / COMMIT) around the insert of the parent and it's first child, so that the parent is not kept unless the child is also successfully inserted.


Are there any Open d6 pre-made modules/adventures out there?

Question: I have looked and looked online but haven't found a single site that has any pre-made adventure for Open d6. I was hoping that someone would know of a site where I could find some.
Answer: Part of the problem is that you're probably searching for "open d6" adventures, when most publishers don't treat Open D6 as separate from D6 System and use the original term instead. Since "Open D6" is technically just the name of an open-licensed document that provides rules from D6 System, and "D6 System" has much more name recognition than "Open D6", this isn't that odd. It would be like searching for "d20 SRD adventures" when really most of those adventures are for D&D 3.5e. There are exceptions, of course, but they're rare:

d6 Magazine contains Open D6 adventures, among other things

Another issue with searching for "Open D6" adventures is that many publishers are using the core of Open D6 as a foundation to build their own game on top of, and releasing adventures for that game specifically. Examples include Mini Six, a very popular, streamlined variant of Open D6, which appears to be as or even more popular than the OGL core alone; Mighty Six, a superhero RPG based on Open D6; Heaven's Shadow, an RPG that is based on Mini Six instead of directly on Open D6; and Breachworld, another self-contained RPG based on Mini Six rather than Open D6. Some examples of such adventures written for a game based on Open D6 rather than advertised for Open D6 itself:

NOTB: Mission Little Rock is an adventure for D6 Epic, as an example of an adventure not for Open D6, but for a system based on Open D6.
Similarly, The Road to Azamar is an adventure for Azamar the RPG, itself based on Open D6.

(Notably, Azamar is by the same studio that does d6 Magazine, which just underlines how small the Open D6–based segment of the RPG industry is.)
But a third part of the problem is that there just isn't much adventure support for a niche system like D6 System / Open D6, especially since it can work with any genre or setting, making an adventure "for Open D6" not necessarily useful for every GM running Open D6, and therefore much less worthwhile publishing. What's out there is mostly settings powered by Open D6, new games built on top of Open D6 (or built on top of a game built on top of Open D6!), and new rules compatible with Open D6. Adventures are mostly left up to the GM to create to suit the setting they're using, though there are a few rare exceptions, like in d6 Magazine or adventures for one of the RPGs based on Open D6.
The expectation really seems to be that Open D6 GMs will create their own adventures that suit their individual games, or they'll be playing with old or new D6 System material that isn't directly Open D6.
Comment: @TheDiamante Having a pre-made adventure does make learning RPGs easier, yes. Unfortunately, starting with a free RPG and looking for free adventures does have the downside that they are quite hard to find! It's worth noting though, that *Azamar* is a free download, and so is the introductory adventure I mentioned. I haven't played them and can't recommend them personally, but downloadable and $0 does compete well with base Open D6.
Comment: Thanks for the help. Me, along with the people whom I am to play with, are completely new to RPGs and were going to play with this system. I thought it seemed pretty fun, though I feel that it would be easier, if not better, to use a pre-made adventure for our first game.
Answer: Below is a list of few OpenD6/D6 System adventures that are ready to go with the included mini setting.

Journey to the Forge
Paranormal Investigators & Exterminators
Tales of War

While there are lots of setting books for D6 System, your question was specifically for adventures. So unless I found an adventure buried in the book, I didn't list it above. Some adventures were only ready for Mini-Six, so I only included them if the adventure included instructions on using the adventure for Open D6. The threshold being that it supports 6 attributes rather than only 4 attributes, or that it explicitly includes the OpenD6 logo.


How to encode binary sequence if the number of bits are odd to e.g. 4-PAM? (Beginner)

Question: I'm new to signal constellation and trying to understand how M-PAM works. If there is a binary sequence that has on odd number of bits and I want to send a 4-PAM signal, there will be one bit left after encoding a symbol by two bits ($k=2$). For example: the sequence $1001001$ will be encoded as $10\rightarrow3$, $01\rightarrow-1$, $00\rightarrow-3$ and the last bit will be by itself. How do I encode the last bit? What about 16-PAM? Will I need to express the sequence in more bits?
Comment: start to group bits from lsb and the problem will go. in general, the problems like this are solved with **communication protocol**
Answer: This problem is solved in the upper layers of the communication system, not at the PHY.
For example, in the data link layer (DLL), the transmission unit is a frame. Frames are designed to be compatible with the PHY, so that problems like the one you describe don't occur. Also, many DLL protocols allow for fixed-size frames to be padded, or for variable-size frames, which provide some flexibility.


What if the code found in github with MIT license was stolen by someone and uploaded there?

Question: What would happen if a piece of code from a proprietary source was uploaded by someone without permission to github with the MIT license and thousands of people have used it. Even if the company who owns the code requests github to drop the repository, what would prevent the endless spread of the code by users believing it to have MIT license. What should the owner do in such cases to prevent it from happening?
Answer: If it was something important to the owner, they would file injunctions/suits against everybody that they find the code in, and make those very public. This isn't unlike what the RIAA did to individual downloaders of pirated music files, filing over 18,000 lawsuits. They could subpoena GitHub for information related to IP addresses for who downloaded the code and go after them. It is unlikely that they would get a financial award but they could have the court order them to stop using it.
Eventually the RIAA found that filing these lawsuits was more trouble than it was worth and started going after the internet service providers. These reduced the number of lawsuits and forced ISP's to moderate its own users, blocking some sites and protocols that programs like Napster relied on. Basically they shifted responsibility from themselves to the ISP's.
Answer: Legally, everyone downloading the software would be committing copyright infringement. You could sue the uploader for statutory damages (maximum $150,000) or actual damages; people who have worked years to collect some wealth usually don't do that kind of nonsense, so you might win a judgement but most likely won't collect any damages because there is no money.
GitHub uses the Git software which makes it possible that anyone who downloaded your software and then tries to download a newer version will have all illegal files on their own computer automatically removed with one file left explaining what happens. Since Github is a company with money that could be sued for helping with copyright infringement and could be made to pay, they will help you. What I described is easily circumvented but would turn the downloader from an innocent person who was tricked into committing copyright infringement into a deliberate infringer if they do that.
As a result there is likely to be very little commercial use of your software. People who would want to use it will very quickly figure out that it is legal poison, and important for a commercial user is also the fact that there will be no updates ever.
Should you find out at some point in the future that a money-making product uses your code illegally, you could sue them for copyright infringement or offer an (expensive) license which to some degree they would have to accept.


Sending Click with user32.dll, messages appear in spy++ but button isn't clicked

Question: I have problems with sending a Click to an application with the user32.dll. the button does not be clicked, but in spy++ the message do appear.
i'm using win7 x64
The code is written in c#:
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern IntPtr FindWindow(string strClassName, string strWindowName);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lpClassName, string lpWindowTitle);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SendMessage(IntPtr hwnd, uint Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    static extern IntPtr GetWindow(IntPtr hWnd, uint wCmd);

    //
    // Finds a window in the whole tree of childs for a parent window.
    //
    static IntPtr FindWindowRecursive(IntPtr hParent, string szClass, string szCaption)
    {
        IntPtr hResult = FindWindowEx(hParent, IntPtr.Zero, szClass, szCaption);
        if (hResult != IntPtr.Zero)
            return hResult; // found it

        // enumerate all childs and if found one that has childs go in
        IntPtr hChild = FindWindowEx(hParent, IntPtr.Zero, null, null); // first child
        if (hChild != IntPtr.Zero)
        {
            // let's enumerate
            do
            {
                hResult = FindWindowRecursive(hChild, szClass, szCaption);
                if (hResult != IntPtr.Zero)
                    return hResult;  // found it
            } while ((hChild = GetWindow(hChild, GW_HWNDNEXT)) != IntPtr.Zero);
        }

        return IntPtr.Zero; // no childs, so no window was found
    }

    static void Main(string[] args)
    {
        IntPtr win = FindWindow("Omnipage17_MainWnd_Class", "Unbenanntes OmniPage-Dokument 1 - OmniPage");
                SetForegroundWindow(win);
        ShowWindowAsync(win, SW_RESTORE);
        IntPtr ButtonHandle = FindWindowRecursive(win, "BarButton", "c");
        SetActiveWindow(win);
        //sEND Lbuttondown
        IntPtr ptr = SendMessage(ButtonHandle, 0x0201, new IntPtr(0x0001), MakeLParam(81,28));
        //Thread.Sleep(10);
        //Mousemove
        ptr = SendMessage(ButtonHandle, 0x0200, new IntPtr(0x0001), MakeLParam(86,24));
        //lbuttonup
        ptr = SendMessage(ButtonHandle, 0x0202, new IntPtr(0x0001), MakeLParam(81, 28));

        //SendMessage(ButtonHandle, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
    }

Here are the messages of spy++ of that button:

If i send the the messages i get following:
i don't if that is that problem but the lbuttondown, buttoup appears 2 times ( S + R ) and if i'm clicking it manuelly it gets 1 message (P)
also tried to do it with WM_CLICK but then i have the same problem with it
Edit:
Using now PostMessage so spy++ shows the same messages as i click it manually, but still the button seems not to be clicked

With this library I have the same problem.
code:
SetForegroundWindow(win);
Rectangle re;
GetWindowRect(ButtonHandle, out re);

Cursor.Position = new Point((re.X + re.Width)/2, (re.Y + re.Height)/2);
WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.LBUTTON);
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.LBUTTON);

Message are sent, but button isn't be clicked

Edit:
thanks for that link (http://www.hanselman.com/blog/IntroducingLync2010SuperSimpleAutoAnswerVideoKioskWithFullScreen.aspx), but also with this library i have the same problem :/
code:
SetForegroundWindow(win);
Rectangle re;
GetWindowRect(ButtonHandle, out re);

Cursor.Position = new Point((re.X + re.Width)/2, (re.Y + re.Height)/2);
WindowsInput.InputSimulator.SimulateKeyDown(WindowsInput.VirtualKeyCode.LBUTTON);
WindowsInput.InputSimulator.SimulateKeyUp(WindowsInput.VirtualKeyCode.LBUTTON);

Message are sent, but button isn't be clicked

Edit2:
Answer of user was deleted, because i posted my comment as an answer:

This is not an answer, this belongs in your question. It doesn't match
  your code, clearly you are still posting BM_CLICK. Which is wrong, it
  should be sent and you should either send BM_CLICK or post the mouse
  messages. And you are looking at the wrong window, it is button's
  parent that gets the BN_CLICK notification and acts on it. Having the
  processs' keyboard state wrong would be a typical failure mode. – Hans
  Passant 18 hours ago

Regarding to that, why should it be the parents windows? bcs in spy++ (screenshot below i serached for that button (Class: BarButton) and the handle i get from user32.dll is also the same as that one in spy++
Answer: Scott Hanselman recent blogged with something similar to this http://www.hanselman.com/blog/IntroducingLync2010SuperSimpleAutoAnswerVideoKioskWithFullScreen.aspx


SQL for OrientDB - how to merge elements by ID and sum up attributes

Question: I'm using SQL with Orient DB version 2.2. I want to merge elements of a class when they have the same ID and append the attribute of the one element to the attribute of the other one. This attribute is of type "embeddedset".
Let's assume I have 3 elements of the same class like this
+-------+------------+--------------+
| Elem  |     ID     | setAttribute |
+-------+------------+--------------+
|   1   |    id1     |    name1     |
|   2   |    id2     |    name1     |
|   3   |    id1     |    name2     |
+-------+------------+--------------+

I want to end up with this:
+-------+------------+--------------+
| Elem  |     ID     | setAttribute |
+-------+------------+--------------+
|   1   |    id1     | name1, name2 |
|   2   |    id2     |    name1     |
+-------+------------+--------------+

I tried as a start to find all the matches:
SELECT FROM (MATCH {class:elementClass,as:element1}, {class:elementClass, as:element2} RETURN element1, element2) WHERE (element1.id == element2.id AND element1.@rid <> element2.@rid)

However, unfortunately I dont know how to continue?
Thanks a lot!
Answer: You can try like below
select Elem, ID, $a.setAttribute from
(select  from t )
let $a=(select  from t where ID=$parent.current.ID)
group by ID


Load a SAGA RGB composite in QGIS

Question: I have created a RGB composite in SAGA GIS using the RGB composite tool. A one band raster is created, which can be visualised in SAGA using the option RGB coded values. When I try to import this raster in QGIS, the image is loaded in grayscale, because the RGB values are stored as a single number, for example "6512354". In SAGA this numbers are recognized, but not in QGIS. Is there any way I can visualise  the RGB coded values in QGIS?
Answer: When you have RGB(A) composite in SAGA, please remember you are dealing with an image, not a single-band raster.
There is no mention in your post but I think you have exported the file by either Export GeoTIFF or Export Raster command. These commands export a single-band raster, and your composite (multi-band) data will be deteriorated in the process.
Export your composite as an image by Export Image (bmp, jpg, pcx, png, tif) tool.

From Tool panel, go to Import / Export | Images | Export Image (bmp, jpg, pcx, png, tif)
>> Grid: your Composite
Image File: your output filename
Coloring : rgb coded values
Execute the tool. It will output RGB Tiff image, tfw, and prj files.

Now you should be able to open the Tiff file in QGIS.
Comment: Thanks for you answer. Yes, I was using the Export GeoTIFF  tool. Regarding the procedure you explain, it works, but the drawback is that the output is an image and I want to apply some enhancement to the raster in QGIS. Anyway you answered the question, so I will mark it as solved.

Load a SAGA RGB composite in QGIS


Fully Connected Neural Networks That Act Partially Connected

Question: This might sound like a slightly odd question, but is there a good technique to make a fully connected neural network act as if it's partially connected - by having certain edges not propagate a signal either forward or back?
I have several small neural networks, each of which is structurally identical - they all have the same inputs, all have a single output, and the same number and size of hidden layers.
I was hoping to take advantage of hardware acceleration by putting them in the same NN, so rather than having five networks with 5 input, 1 output and a single hidden layer of 20 neurones each, I'd have a single network with 5 inputs, 5 outputs, and a hidden layer with 100 neurones.
But I need them to not cross-contaminate one-another - to operate as if they were distinct networks and not learn based on one-another.
I know I can manually set the initial weights to zero between the different sub-networks, which works fine initially - but during training the error-correction ends up connecting the various networks together.
It occurs to me that I might be able to have another matrix very similar to weights, but this time being a simple '1' (open) or '0' (closed) multiplier I could attach to the learning rate - 'closed' links would be multiplied by 0 during training, resulting in no change.
But if anyone knows if there's a different technique that works, I'd love to know.
Answer:
I know I can manually set the initial weights to zero between the different sub-networks, which works fine initially - but during training the error-correction ends up connecting the various networks together.

This is the approach I would take as well. To prevent them from connecting during training, you should freeze the weights of the zero-entries, for example, by masking out the frozen parameters during each forward pass: https://discuss.pytorch.org/t/how-to-freeze-part-of-the-weight-matrix-during-training/137389.


My iPad2 won't charge and needs activation

Question: I have had similar activation question as others; my iPad2 says activation needed. My problem is I cannot charge my ipad to get to iTunes.  My cable is  fine, my port is fine, but it will not charge past 2% and will not stay on long enough for me to enter my password.  I have tried the hard reboot (hold power and home button down x 1 minute). Nothing.
Comment: Try charging it via the charge block plugged into an outlet.  Don't use your computer's USB port to charge this time.  Leave it plugged-in and charging for a few hours and then see if it holds a charge.  You have an old battery and it's probably near the end of its life.  Don't forget to take a backup, too.
Answer: If the stock charger isnt working on the iPad, schedule a repair with Apple to get the battery tested for diagnostics and possibly replaced. You may have to pay if out of warranty.
As for activation lock-
You will need to remember the password. If you forgot the password, go to http://appleid.apple.com and choose "Forgot Apple ID or password" option below the sign in. It'll take you to http://iforgot.apple.com and then just add your apple ID email address and the captcha code. Once you hit continue (if it asks for a verification code then you need to check your other devices and see if you can get the code from a device that is signed into the same apple id). If you are already signed into the other device with the same account. Go to settings on the device, then your name (or iCloud then your name) and look for password and security. Once you find that, select change password. If you try to do it through the website it may have you go through account recovery, which takes some time before they let you reset your password.
(If it doesnt ask for a verification code then you'll need to choose reset password and ask to either send to email or answer security questions to reset the password.)
If you cant get the password for that account via either method then you'll need to provide Apple with a proof of purchase. You can either check your email for a receipt or contact your carrier/location where you purchased it. Without the receipt AppleCare can't help you.
If you bought the iPad from someone else and they are logged in, then you need to contact them and have them sign in (or reset their password to sign in via the methods mentioned above.)


Enable  tags in CKEditor?

Question: I have the CKEditor module installed, and it has a place to configure the allowed tags, but the list of allowed tags that you are allowed to... allow is very anemic. Is there a way to stop it from stripping  tags (or any other tag for that matter)?
Answer: This answer is for future reference
Checkout the WYSIWYG Filter

The WYSIWYG Filter module provides an input filter that allows site
  administrators configure which HTML elements, attributes and style
  properties are allowed. It also may add rel="nofollow" to posted links
  based on filter options. It can do so with no additional parsing on
  user input. That is, it may apply nofollow rules while parsing HTML
  elements and attributes.
The filter is based on whitelists that can be defined from the filter
  settings panel. Rules for HTML element and attributes are defined
  using the same syntax of the TinyMCE valid_elements option.
HTML attributes related to DOM events (on*) are not allowed for
  security reasons (to prevent XSS, etc.).
The following elements cannot be whitelisted due to security reasons,
  to prevent users from breaking site layout and/or to avoid posting
  invalid HTML. Forbidden elements: applet, area, base, basefont, body,
  button, embed, form, frame, frameset, head, html, iframe, input,
  isindex, label, link, map, meta, noframes, noscript, object, optgroup,
  option, param, script, select, style, textarea, title.

Please refer to the project page for more details.
Answer: If you go to admin/config/content/formats/ you can select the text_format that ckeditor module is being used on and then adjust the relevant filters for the text format. The one you will want to look at is Limit allowed HTML tags where you can add exceptions for whichever you like.
Comment: The problem is CKEditor stripping the tags at the JS level, not drupal.

Enable  tags in CKEditor?


Could an AI be sentient?

Question: In theory, could an AI become sentient, as in learning and becoming self-aware, all from its source code?
Answer: In theory, if one could build a computing device that matched or exceeded the cognitive capabilities of a sentient being, it should be possible.
(Singlarity adherents believe we will one day be able to transfer the human mind into an artificial computing platform, and it logically follows that one could "hack" such a mind, or build from the ground up, to create a truly Artificial Intelligence.)
But this may be like fusion power, where the old adage is that it is "always 20 years away."
Answer: Yes, an AI program can become sentient. Ray Kurzweil while giving a lecture at Singularity University on The Accelerating Future stated that human body is basically composed of approximately 23,000 little software programs called GENES. If you think about it, they are actually programs, composed of sequences of data. They are not written in C++ or Java, instead they use 3-D Protein Interaction. They evolve with time and their evolution is the reason that species are able to survive even when their surroundings experience tragic changes.
We are on the edge of a breakthrough where software will be able to do the same (evolving by themselves) efficiently. Today this is done one a basic level. Artificial Neural Network is a good example.

It is predicted that we will be able to reverse engineer human brain by 2029. Prior to this we will be able to write codes that can stimulate human brain.

AI programs can be categorized into three:

Artificial Narrow Intelligence (ANI): This is a basic AI program that is good at good one thing. These programs are prominent nowadays. AI programs playing board games (like Chess, Reversi etc.) are example of these. They are good in only one thing.
Artificial General Intelligence (AGI): This is level 2 AI. This will be having a IQ level equivalent of humans. It will be able to do multiple tasks efficiently just like humans. This is where a program can have understanding of it's environment just like humans. Perception, rational behavior and others will be part of this program.
Artificial Super Intelligence (ASI): This is basically the ultimate level of AI. Average predicted date for a successful ASI is between 2045-2080. Ability of this program will be way more than that of combined intelligence of all humans on the planet. Things this program can do and think, will be beyond any (or all) human(s) to understand or comprehend.

Could an AI be sentient?


Is it good, that every PHP class implements a Singleton pattern

Question: is it good, that every PHP class implements a Singleton pattern? I think, it will be less memory usage because of it. Is it right opinion? Thanks!
Comment: Thanks all! I got an answer. My question is incorrect.
Answer: Software is meant to model the reality. that's the way the OOP exists. that said, Singleton is not a hammer for all nails. You can use it in certain models, but there are others which simply will not adjust.
Take for example, model a list of persons. If you decide to create a Person class, then you will not be allowed to have more than one person on your model.
Answer: If all your classes are singletons, why use classes?
Singletons are useful in some cases, but tend to be over-used.  If you can get away with singletons, then you probably don't need classes for their intended object-oriented uses.  They can still be useful for code modularization, though.
In general, classes are most useful when you do have multiple instances of the class.  Classes are blueprints for objects, so you can create many objects with similar behavior but, typically, different internal state.
So, if all your classes are Singletons, I would step back and ask a couple questions:

Do you need classes?
Are you thinking correctly about how your software models the problem you're trying to solve?
Answer: There is a simple rule: If it's definitly sure that a class is only to be used once, implement Singleton. If it needs to be used more than once, don't do it.
If your programm has only classes with one single instance it looks like a major code smell and is not suitable for object-oriented programming.
Answer: This seems like a very bad idea. I would recommend keeping any data you need between requests in a session (if per user) or a cache (if per server). As far as memory usage, it should not make that much of a difference.
Answer: Actually it is (combined with factory), take Kohana 3 Framework for example;
it uses singleton / factory combination where ever it's possible.
Answer: It is possible, it just would not be OOP design. OOP is meant to simplify structing with 3 main properties:  inheritance (ie common classes share the same interface), polymorphism (ie subclassing) and  encapsulation (ie having a blackbox approach to your objects).
Singleton, although they can be extended and abstracted, usually aren't so that basically takes OOP goodies out of your reach. It would be some sort of  original procedural programming with everything namespaced in global scope.


Books to learn physics, being a math major

Question: What books would you recommend to learn physics, being a a Math major, from classical mechanics, electricity, etc. to modern physics?
Comment: I actually suggest that to learn physics you take an advanced lab course or two!  I think that if you approach theoretical physics like a mathematician you will not properly develop your physical intuition.  That being said, the best books in my opinion for your purpose are the [Landau](http://books.google.com/books?id=e-xASAehg1sC&printsec=frontcover&dq=landau+mechanics&hl=en&ei=2cEcTbbHMIXGsAPI482mDw&sa=X&oi=book_result&ct=book-thumbnail&resnum=1&sqi=2&ved=0CCwQ6wEwAA#v=onepage&q&f=false) series, especially books 1,2,3, and 5.  Also see the three volume Feynman lectures.
Comment: [This](http://physics.stackexchange.com/) might be a better place for your question...
Comment: This might be too: http://www.phys.uu.nl/~thooft/theorist.html
Comment: I think the question is on-topic but should be clarified: lots of people study both math and physics at the undergraduate level.  When you say "being a Math major", do you mean that you want books that take a more mathematically rigorous approach than most books written by physicists, or just that you know some mathematics beyond calculus so you can handle more math-intensive treatments?  (Or something else?)
Comment: Yes, I want books that take a more mathematically rigorous approach.
Comment: Related post on Phys.SE: http://physics.stackexchange.com/q/6047/2451
Comment: @timur The new address of this site is http://www.staff.science.uu.nl/~gadda001/goodtheorist/classmech.html.
Answer: As for mechanics I'd recommend:
Stefan Banach - Mechanics (1951)
Arnold VI - Mathematical Methods of Classical Mechanics
I also recommend Griffiths books:
Griffiths - Introduction to Electrodynamics
Griffiths - Introduction to Quantum Mechanics
Comment: +1 for Arnold's Mathematical Methods of Classical Mechanics
Answer: If you want a solid and consistent approach to physics from the theoretical point of view (I assume that as a mathematician you don't want an experimentalist's point of view) then you can't go past the series by Landau and Lifshitz - "Course of Theoretical Physics" (Amazon).

Mechanics.
The Classical Theory of Fields.
Quantum Mechanics: Non-Relativistic Theory.
Relativistic Quantum Theory.
Statistical Physics.
Fluid Mechanics.
Theory of Elasticity.
Electrodynamics of Continuous Media.
Statistical Physics, Part 2.
Physical Kinetics.
Comment: These are some of the most elegant books ever written on the subject of physics.
Comment: Old but definitely worth reading. It's a kind of Feynman lectures at a higher level.
Comment: @timur - they are a little dated, but still more modern than most uni physics courses. It would be good for a math major to see and use index notation - too many have a unhealthy disrespect for it! I haven't read Thirring...
Comment: I think these are great textbooks on physics, but I wouldn't recommend them to someone who wants to start learning physics, even if he is a math major.
Comment: Landau-Lifshitz is great but somehow dated (For example no manifold is mentioned and it uses index notation for tensors). Thirring's 4 volumes seem to be more modern and I heard that in some way can replace Landau-Lifshitz. Please comment if anyone knows how close it is to the truth.
Comment: @becko - Any particular reason?
Answer: Michael Spivak gave me a small volume he wrote on mechanics from the mathematicians perspective, and he is said to be preparing to release a longer book on physics explicitly for mathematicians.  In the meantime you might like Max Born's Atomic Physics.  I myself enjoyed, and learned from, at least looking at J.C.Maxwell's E&M.
Comment: The first volume of Spivak's "Physics for Mathematicians" is already available, actually.
Comment: Here's a link for a set of lectures of Spivak called Elementary Mechanics from a Mathematician's Point of View: http://math.uga.edu/~shifrin/Spivak_physics.pdf
Comment: Great! Did anyone here read Spivak's book? I like the way he writes.
Comment: Sounds promising. I love Spivak's other books.
Comment: @becko The link is broken, is there a new one?
Comment: Here is the new link for Spivak's book: http://alpha.math.uga.edu/~shifrin/Spivak_physics.pdf
Answer: I will assume you are getting started - once you finish the equivalent of the first year of calculus-based physics, then you should dig in / branch out depending on your interests (optics, dynamics, modern physics - i.e. 20th century - E&M, etc.)
For an overview of it all, I recommend the Feynman Lectures on Physics, supplemented liberally with any of the solid textbooks (such as the following) and I suppose some Wikipedia.  I like the Feynman lectures because they are entertaining, conversational, and provide a great insight into physics.  Here are some example introductory texts - I can personally vouch for HLR.

Fundamentals of Physics - Halliday, Resnick, & Walker. Link is to current edition, but this is the book that many of us have used for decades, including myself at a small liberal arts school.  It's also the book used at Stanford.  I think you can use any edition from the last 10-20 years...
Physics for Scientists and Engineers - Serway and Jewett (CalTech's intro book)
University Physics - Young, Hugh, Ford and Freedman (one of MIT's intro books)

Frankly, I recommend you go to the syllabus of the introductory, calculus-based physics from a school you respect and select that textbook as a reference.
I did a physics major as an undergraduate, in addition to my studies in mathematics and engineering.  I still find that the first year's material is the most useful content, although I think that the concepts covered in introductory Modern Physics courses are really cool.  If you are interested, in addition to the Feynman lectures that I have read on the side, I was quite impressed with the text we used: Modern Physics - Serway, Moses, Moyer.  While remaining very readable, it provides more of a textbook approach, whereas Feynman is a lecture style.
Comment: I recommend avoiding University Physics by Young et al. It's not a bad book, but it's very much a heavily marketed textbook, meaning it lacks elegance and beauty and is overshadowed by other books for self-study (e.g., Landau and Lifshitz). University Physics is analogous to those massive tomes used in freshman calculus classes; L&L is analogous to Spivak's Calculus books.
Comment: For math rigor, I agree with the Landau & Lifshitz recommendation (which I gave +1), but I will leave this answer for others interested in a general treatment of physics. Feynman is not lacking mathematics, but it is not as rigorous. I also used both Griffiths books (E&M and quantum) and those are great. For optics consider [Goodman](http://www.amazon.com/Introduction-Fourier-Optics-Joseph-Goodman/dp/0974707724/) or [Gaskill](http://www.amazon.com/Linear-Systems-Fourier-Transforms-Applied/dp/0471292885) - I prefer the latter, but it may be more of an EE/controls style than a math style.
Comment: My impression was that Goldstein ans Jackson were The standard textbooks for mechanics and electrodynamics, respectively. No one mentioned them here so are they not that popular after all?
Comment: I'm not as familiar with Goldstein, but Jackson is one of the strongest books on E&M and is very well known.  Griffiths is popular with some professors (and I liked him) because he is more accessible.  As one well-written review on Amazon (by 'Reviewer') puts it, Griffiths's E&M is "a foundation that will give [undergraduate juniors/seniors] the experience and confidence to eventually tackle more difficult texts like Jackson".
Answer: I started in math as an undergrad (topology/geometry) and then went into physics for grad school.  I know your pain... :) Most of the books people have suggested already are excellent works that provide physical intuition and if you're going to do some physics for real then make sure you read 'em.  That said, most of what was mentioned does NOT present stuff the way a math guy likes so -- assuming you are a junior or senior in a math undergrad program -- my recommendations are,
For geometry and dynamical systems as applied to Classical Mechanics:

Classical Dynamics: A Contemporary Approach
Jorge V. José (Author)

For (functional) analysis applied to Quantum Mechanics:

Quantum Mechanics in Hilbert Space: Second Edition (Dover Books on Physics) [Paperback]
Eduard Prugovecki (Author)

For Lie Groups and using them like a physicist:

Lie Groups for Pedestrians [Paperback]
Harry J. Lipkin (Author)
Lie Algebras In Particle Physics: from Isospin To Unified Theories [Paperback]
Howard Georgi (Author)

For understanding quantum and path integrals:

Quantum Mechanics and Path Integrals
Richard P. Feynman (Author), Albert R. Hibbs  (Author), Daniel F. Styer (Author)
Modern Quantum Mechanics (Revised Edition) [Hardcover]
J. J. Sakurai (Author)

You gotta understand rotation stone cold:

Rotations, Quaternions, and Double Groups [Paperback]
Simon L. Altmann (Author)
The Theory of Spinors by Elie Cartan
Clifford Algebras and Spinors (London Mathematical Society Lecture Note Series) by Pertti Lounesto

And differential forms are required:

Differential Forms with Applications to the Physical Sciences [Paperback]
Harley Flanders (Author)

For general relativity:

Gravitation (Physics Series) [Paperback]
Charles W. Misner (Author)
Kip S. Thorne (Author)
John Archibald Wheeler (Author)
Advanced General Relativity (Cambridge Monographs on Mathematical Physics) [Paperback]
John Stewart (Author)

For stat mech:

Equilibrium Statistical Physics (3rd Edition) [Paperback] Michael Plischke (Author)
(Author), Birger Bergersen (Author)

and for a final one-shot book that tries to hit everything under the sun:

The Geometry of Physics: An Introduction, Second Edition [Paperback] Theodore Frankel (Author)
Answer:
Kleppner/Kolenkow's  An Introduction to Mechanics
David Morin's Introduction to Classical Mechanics
Purcell's Electricity and Magnetism
A.P. French's Principles of Modern Physics

These books have more math than the typical introductory physics textbooks. But they also introduce the "physicists" way of thinking (e.g. how to gain physical intuition).
Answer: I would suggest the following books in addition to several good recommendations above :
1.) Classical Dynamics : A Modern Perspective by E.C.G. Sudarshan and  N.Mukunda . You may like Arnold's book mentioned above.
2.) For Quantum Mechanics, I would recommend Merzbacher's and Weinberg's books in addition to Sakurai's book suggested above.
3.) Advanced Classical Field Theory by G. Sardanashvily,G.Giachetta,L.Mangiarotti. This requires lots of mathematical prerequisites. A lighter introduction to some topics would be 'Gauge theory and variational principles' by D. Bleecker
4.) General Relativity by R. Wald


Epson XP-205 printer driver failed After Ubuntu 18.04 Update

Question: The printer was working fine on Ubuntu 16.04 until I updated the system to 18.04.  Ever since the system can't see the printer.  Can you please point me to where I can get an updated driver and how to install it.  This only seems to have effected the printer as the scanner works fine.
Thanks
Answer: Google "epson drivers for linux" should get you what you need.  It pointed me to this page: https://epson.com/Support/wa00821 There you will find both drivers to download as well as documentation.
I noticed that there are recent driver updates for your XP-205 printer.
I also found this answer informative.
If it is a networked printer, make sure you don't have a firewall or vpn that may be preventing your computer from seeing other devices on your LAN.


Media library with variable availability

Question: I have a collection of movies:
A laptop might have a subset of these internally; the complete library might be available on a connected external disk.  Various subsets might be available in the network, both as files and/or as Windows streaming.
How can I see my total library? what is currently available? And how can I easily launch available items?
I am mostly thinking about Windows clients, though I also have Android
Answer: Using Zoom Player, you can specify multiple drives/folders into a virtual category that combines them all.  Sources not available (drives disconnected or non-mapped network drives) will not be listed.


Would overclocking a raspberry pi to "Medium" be dangerous to the Pi?

Question: I am new to overclocking and just bought a Raspberry Pi to learn more about computers and run a Java server on. I was wondering: Would overclocking my Raspberry Pi to the "Medium" setting be dangerous? I have heard of the SD cards corrupting and a lot of other bad things that can happen when you overclock, and I am a bit worried about breaking my $35 computer prematurely (I am a cheapskate obviously). Thanks for your help!
Answer: Overclocking can cause system stability and SD card issues, but assuming you have a good power supply, moderate amounts of overclocking are normally problem free. If you look at the various overclocking options, the top option mentions that some Pi's have problems at that speed, but you should have no problems with the medium option.
I would suggest backing up your Pi, and then overclock your Pi. If things seem to be working well over time, you may then want to try the next higher setting (again backing up first). Until you reach a speed that causes problems and then back off to the next lowest speed.
On a personal note I am running my Pi's at 950 MHZ without problem.
Comment: Thanks for your help! I have decided to overclock at the prebuilt Medium setting, and will back up the SD card periodically. I wonder if there is a program that automatically does this...


Is Guinness really different in Ireland, compared to what's sold in the US?

Question: I've never liked the taste of Guinness, on tap or from the can. But I have heard that it's much better tasting in Ireland, and the export one is completely different. Is there any truth to this, and if so, what are the differences?
Answer: Guinness can taste slightly different and have a different head based on where it's coming from. A big factor in this is how long the beer you're getting has been in the keg. People in Ireland drink Guinness a lot more than in the states, so kegs are replaced more frequently i.e. fresher beer. This is why if you go to a bar in Ireland and not a lot of people are drinking Guinness, you shouldn't get one.
Another possible reason you've heard this is that most people visit Dublin when they're in Ireland and have a pint at the Guinness store house. They ensure all the beer there is top of the line and it really is much better there than any other place I've had it.
Answer: There are a few questions here, so let me address them individually:
Guinness Draft, the "standard" Guinness is not always brewed in Ireland, so that may be one reason for a different taste in Ireland than in US. As gannolly commented, the age of the beer also affects the taste, as well as the cleanliness of the beerline (if the beer is on tap).
Guinness has a few beers, one of their biggest beers is a Foreign Extra Stout. This is brewed in various counties. This is a higher ABV, roastier beer. I think it has double the ABV of a "standard" Guinness.
One other important fact is emotions. If I am sitting in the Guinness Brewery, looking out over Dublin, drinking a fresh, perfectly poured Guinness, I am in a very happy place. This happiness will affect my overall experience of the beer. If you take that same keg, keep it cool and fly it overnight to the US and taste it there, it will still be good, but it will not be as good, because you are missing the experience. This said, the beer can also be just as good, because you remember the feeling of drinking that beer in Dublin.
Here are links to the various Guinness Breweries and the beers that are brewed there.
http://www.ratebeer.com/brewers/st-jamess-gate-diageo/13/
http://www.ratebeer.com/brewers/guinness-cameroon/13088/
http://www.ratebeer.com/brewers/guinness-nigeria/3194/
http://www.ratebeer.com/brewers/guinness-ghana/5070/
Comment: That emotional aspect can't be overstated. Beer consumers aren't impartial observers.
Answer: In foreign countries, a particular brand of beer is often produced under a licence to a local brewer.
The accuracy with which these local brewers reproduce the original beer varies greatly.
For example, Australians noticed a change in the local Guinness when the local licensee changed from CUB to Lion recently: http://www.news.com.au/national/south-australia/lion-brews-the-first-guinness-in-south-australia-in-40-years/story-fndo4dzn-1226508692750
Answer: I just returned from a two week vacation in Ireland, Northern Ireland, Scotland and England.  Guinness served in Ireland and Northern Ireland is very different than what you get in Guinness in the states. The Guinness in Ireland is silky, creamy and thick. Almost milkshake like.  It is very delicious and after you have one there than here you will understand.  I think it is a freshness issue.
Answer: I just returned from Ireland 2 weeks ago. I rode a motorcycle around most of the country for 8 days and spent a couple of days in Dublin. I drank the black stuff all over the country, including at the Storehouse. Here is my take: In the States, I only drink the nitro pub cans. I am not fond of any of the other packaged Guinness stouts sold here. I also find that draught Guinness Stout will vary more outside Ireland, mainly because of how it might be handled or poured. Bottom Line for me: The nitro pub cans are nearly identical to any pour you are are going to get in Ireland, except for this one small thing: I found Irish Guinness to be ever so slightly more minerally and even a tad salty than anywhere else.
Answer: I do t believe this. I've had Guinness in draft in the UK and Europe and as far as I can tell, it's the same as the Guinness I've had in USA. Yea freshness and proper storage and proper nitro mix makes a difference but if you have Guinness at a reputable pub it is the same. An Irish pub in New York or Chicago surely goes through a keg of Guinness as fast as any pub in Ireland.
Comment: I am unsure why you cannot tell the difference - they are worlds apart. They are made differently, by different brewers under licence. They have differing treatment for shipping purposes. Even kegs are different. Guinness in Dublin is even different to Guinness in London or Edinburgh - which is down to shipping, as they are brewed in the same brewery.


Working Android with Arduino

Question: Has anyone tried to make Android and Arduino communicate with each other?
I found a couple of projects online:

Amarino
Android-Arduino

What do  you guys suggest is the best way to make those two communicate?
Comment: This question is now moot with the Android Open Hardware Interface: http://developer.android.com/guide/topics/usb/adk.html
Answer: Either build a serial cable for your Android phone, like this one for the G1,
http://www.instructables.com/id/Android-G1-Serial-To-Arduino/.
Or add a Bluetooth module to your Arduino,
or use an Ethernet-shield for your Arduino and connect via TCP/IP.
Which one to use depends on your project and your budget. I don't know if the serial cable option exists for phones other than the G1. The Bluetooth module has the advantage of beeing wireless for both, the Arduino and the phone, and using the Ethernet-shield you could make the Arduino worldwide accessible by using port-forwarding on your firewall.
Answer: I've been  working with Amarino since they started and I haven't had a problem since. However I have no experience with other projects since I have only worked with one.
These are my two favorite opensource devices though. Way to go with not joining the iPhone band wagon. It really pleases me when there is someone who takes the initiative to go far and beyond, because it shows that your thinking about the long run. Most people don't.
Answer: A solution to this is to make the Arduino act as USB host and have it talk the Android Debug Bridge (ADB) protocol. This works with any stock, unrooted Android device. More information here:
code.google.com/p/microbridge
Answer: Your options seem to boil down to connecting the two using a serial interface, or via Bluetooth (I'm guessing you'll either need a Bluetooth shield or something similar). There are many resources on the Internet dealing with setting up Arduinos with both of these.
You may also be able to set up some sort of basic server on the Arduino and be able to interface the phone to it via a console, or through a specially defined interface on the phone, or even a web based interface. There seem to be a fair few robot designs being controlled by Android/Arduino maybe have a look at these.
Without some more ideas about what you intend to do once they're linked it's difficult to be more specific, although if you root your Android phone you will be able to install a cut down version of Debian on it, and then you will be able to apt-get install various packages. With this in mind, there becomes little difference between connecting your Arduino to a computer and connecting it to your Android phone.
[EDIT]: If nothing else you could make an Arduino based one of these: Android Controlled Statue.
Answer: I heard someone talking about this before and they were trying to do it via USB but they stated the problem with it was Android does not fully support USB Host. If that is the only issue it seems like it should be easy enough to port over the USB host drivers?!?! Maybe I am simplifying it to much.
Answer: I liked Nikolaus answer.
I think the best way to connect is writing a TCP/IP server in the Arduino (Example can be found easily on the internet), and using or the Ethernet Shield (~10U$S) or the Wifi Shield(~10U$S). The TCP/IP server for both solutions uses the same code, the only difference is the INIT.
Mobility:  If you need you Arduino to be on the move, buy the Wifi shield.
Static: IF you are static, and only want to control from the Android phone, use the ETH shield (Lower cost).
Adrian

Working Android with Arduino


Will changing the order of Channel Images categories screw anything up?

Question: I've set up a "Channel Images" field that has a comma-separated list of categories. The client wants to modify the order of that list. If I change the order of those categories, will that mess anything up? Will any existing category assignments be lost?
Answer: Haven't used channel images but technically speaking, changing order of categories is purely a visual order, EE refers categories internally by ID.
Simply changing an order does not generally affect anything assigned to it.
Comment: However, in "Channel Images," the categories list is a single text string, with categories separated by commas. So my question remains: if I modify that list -- by rearranging or renaming the categories, or deleting categories -- will that screw up any existing category assignments?
Comment: Are the categories EE category IDs or ChannelImages category IDs?
Comment: Channel Images.


How should I fill voids left after removing Victorian skirting boards?

Question: I've taken out the existing skirting boards and it's left this big gap between the floor and existing plaster/wall. Fixing standard 12.5mm plasterboard to the existing batons would stick out proud of the existing part of the wall. Should I instead fill in the area using bonding/Thistle Hardwall? Then I can plaster over it to meet the existing wall, and pop on regular skirting.
Comment: You do realize that covering gaps between floor and walls is what skirting boards (or other trim) are for, right?
Comment: Paging @Tetsujin for translation…
Comment: Plasterboard would be a nightmare on that wall; you'd have to knock all the lumps flat first, then glue it on because there's no room for a wood frame of any type. @AloysiusDefenestrate - afaik, Hardwall & Bonding are two types of 'mud' US [Hardwall doesn't get sucked dry so easily on old brick compared to Bonding, otherwise they're very similar]. Skim might be 'spackle' but tbh, I get lost in the US names just as you transpondians get lost in ours. I wish we had a definitive "name US = name UK" resource.
Comment: @keshlam yes, but I don't want my skirting boards to come up as high  as the previous ones
Comment: Fit some plasterboard into the space, tape/mud/sand the junction between that and the existing plaster, paint once you have that junction close enough to invisible,, apply new skirting.
Answer: Hardwall*, then skim.
Leave space at the bottom, don't try to make a perfect match to the floor.
You'll have to decide whether you're going to nail your new skirting to the [possibly shortened] original wooden spacers, or remove them & 'No More Nails' the new skirting to the wall. Actual nails are more readily removable without pulling the skim off if you need to get behind them again at any point in future, but glue is quicker & easier to put up.
*Hardwall is just a no-brainer on old victorian brick. Browning will get sucked dry much too quickly.


What are some real world applications of OSPF?

Question: When I search for OSPF real world application or implementation, I always get the explanation of how OSPF works or how to calculate the cost. My question is, is there any real life scenarios of how OSPF works?
Comment: OSPF is an open industry standard, while EIGRP is a Cisco proprietary protocol.
Comment: Did any answer help you? if so, you should accept the answer so that the question does not keep popping up forever, looking for an answer. Alternatively, you could post and accept your own answer.
Answer:
is there any condition where OSPF is better used than anything else
(e.g EIGRP), or what kind of network is suitable using OSPF?

In a heterogeneous network, all the router vendors will support the open-standard OSPF. For EIGRP, you would need a Cisco-only network, and it would close you from using routers from any other vendors. It would also create big problems in the event you merge with another company.
RIP is also an open standard that is supported by most vendors, but it has severe limitations, such as hop count and convergence time.
IS-IS is another open standard routing protocol, and it found a niche in telecommunications companies.
Overall, OSPF is open and well understood by people in the industry, and it is trusted to do the job over a wide range of equipment and network sizes. Most shops want to use products that do not lock them into particular vendors, and their employees and prospective employees understand.
Comment: I think EIGRP became an open standard in 2016 very much like what YouTube did with QUIC. Correct me if I am wrong.
Comment: In 2016 (many years after the fact), there was [an Informational RFC published](https://tools.ietf.org/html/rfc7868) describing Cisco's EIGRP. That was far too late to the party for it to actually find support among router vendors. EIGRP is essentially a Cisco-proprietary protocol because there is no industry-wide support for it.
Answer: Network topology might affect the choice of a routing protocol and make one protocol more desirable than another.  The most common example is a large hub and spoke topology.  In that topology, EIGRP can handle routing updates more efficiently than OSPF.
The bigger difference in protocols comes down to the practical implementations of them.  As others have pointed out, EIGRP is a Cisco-proprietary protocol*, so that may be important if you have a multi-vendor environment.
Another example of practical implementations is OSPF vs IS-IS.  Most large ISPs use IS-IS for their internal routing, even though IS-IS and OSPF use the same algorithms and have similar performance.  From an operational point of view, IS-IS has fewer features, and therefore is "simpler" than OSPF. To many ISPs, that simplicity also means reliability -- there are fewer things to go wrong, which makes it more desirable than OSPF.
*EIGRP is a defined standard (RFC 7868), but hardly anyone outside of Cisco has implemented it.
Answer: OSPF is likely the most popular routing protocol within private networks. OSPF peers exchange information about the networks they are connected to, plus injected static routes. That enables fast and reliable route propagation.
Comment: thank you for responding! my question is more like is there any condition where OSPF is better used than anything else (e.g EIGRP), or what kind of network is suitable using OSPF?
Comment: OSPF is preferred for private (trusted) route exchange because it's less complicated than the alternatives. OSPF puts little emphasis on security, so it's less suited for exterior gateway exchange.
Comment: The argument for fast convergence is not really cutting it for OSPF because it's supported with all protocols.  Even late versions of RIP support triggered updates.  For small-enough networks, RIP can be most efficient.
Answer: 1. OSPF
1.1 Marketing view
OSPF's advantage is made of multiple points that make it appealing:

More efficient than RIP with large networks thanks to OSPF being a link-state protocol, and due to the problem with RIP that it's too naive (it periodically sends the full routing table, which is very inefficient).  Note that RIP's limitation is not due to fundamental flaw with distance-vectors routing protocols, but rather due to specific choices made within RIP.  A distance-vector protocol can still be efficient, but RIP is just not one.
That it's an open protocol that's wide spread on routers from various vendors.  This can allow you to incorporate various routers from different vendors with each other.  But this is not enough by itself, since IS-IS is also an open protocol like OSFP.
Its configuration is based on IP addresses.  This makes it easier for some people like IS-IS which is based on CLNS addresses for its configuration.
OSPF is more wide spread than IS-IS.  In part because of the fact that IP addresses won against CLNS addresses.  IS-IS was made by ISO for CLNS addresses and CLNS lost the battle.  This battle loss is only historic, as IS-IS supports routing for IP networks, and ironically, IS-IS supported IPv6 before OSPF.

Due to those reasons, people go with OSPF.  In other words, OSPF fills a point where it's more efficient than RIP for large networks for being a little harder to use (arguable) and being the most wide-spread open routing protocol after RIP.
1.2 Technical view
But is OSPF technically any better?  The answer is no.
Both EIGRP and IS-IS are technically better than OSPF.  OSPF has this needless requirement that all areas must connect to area 0 (backbone).  IS-IS does not have such requirement.  OSPF's requirement of having all areas connect to a backbone is going to limit the way your network growth in the future, and imposes a burden on routers inside your backbone area by requiring to make them computationally more capable (since all other areas talk to each other via the backbone).  This is really a bad design by OSPF.
2. IS-IS
IS-IS on the other hand, does not have the backbone concept.  You can attach your areas to each other without needing to have them go through a given area. If you want to have a backbone area, then you can arrange your IS-IS areas such that they end up all going through an area of your choice.  But if you don't want, then you don't!  IS-IS also solves the shortest-path-first problem within an area like OSPF.  As said, IS-IS is also an open protocol, but it's configurations requires selection of CLNS addresses (not IP) which confuses some people, and IS-IS is less wide spread.  IS-IS is more popular with service provide where the network engineers are more knowledgeable and can purchase higher-end equipment that implement IS-IS.
3. EIGRP
But, technically, the best in terms of computational needs is really EIGRP in my view.  Unlike OSPF and IS-IS (which solve the shortest-path problem for all links in a given area), EIGRP distributes such computation across all routers inside a given administrative region, such that each router does its own part and passes his work on.  Eventually EIGRP routers converge to the correct solution, without needing every router to solve the shortest-path-first problem for all networks in the administrative region (or area as named in IS-IS/OSPF).  Such administrative regions are also defined more flexibly by EIGRP by means of route summarisation between routers (practically you can reach an identical effect to areas).
But the major drawback of EIGRP is the fact that it's not an open protocol.  This is a huge problem as it will lock you, as a company, from freely replacing your routers by non-Cisco routers.  Being locked to a specific vendor is a danger.  This is why, even if your routers are 100% Cisco routers, I'd suggest that you avoid EIGRP in order to give yourself room should you one day stumble upon a moment where plugging a non-Cisco router is needed.
EIGRP is a purely distance vector routing protocol and is an example that RIP's problem is not due to a fundamental flaw in open-distance-ness, but rather due to RIP being too simple to handle large networks.
Extra nuggets

RIP can still be the most efficient protocol for stable-enough small-enough networks.  If the routing table is small, then RIP's messages can be smaller than the link-state messages of OSPF/IS-IS (some of which use padding which makes their messages possibly larger than RIP's updates if RIP's routing table is small enough).
EIGRP is often told by Cisco to be a "hybrid" routing protocol, as a marketing trick to avoid the bad reputation of some distance vector protocols such as RIP.  But technically EIGRP is a distance-vector routing as it purely learns by rumour.
The real hybrid routing protocols are actually OSPF and IS-IS, because they are link-state only within an area, and operate  purely in a distance-vector manner between areas.  In fact the concept of areas are made with them only because solving the shortest-path-first problem for too-large networks is too expensive.  Hence the shortest-path-first is solved within an area, and the inter-area becomes the cheap distance vector method of learning by rumour from neighbouring routers of other areas.  Worth nothing that OSPF and IS-IS being "hybrid" does not give them any special points.  I'd argue that this hybrid-ness of OSPF/IS-IS is a downside as it implies increased complexity of protocol's implementation.

Summary
If I to rank routing protocols from purely a technical perspective, I'd say that RIP is needed since it's the most efficient choice for small-enough networks out of all of them.  IS-IS is needed for being the best available interior routing protocol that is an open protocol.  EIGRP is needed as the best interior routing protocol for those that swore the oath to never leave Cisco.  But OSPF is just not needed from a purely technical perspective.  OSPF is only needed due to the human factor (people being used to IP addressing in configs) and due to historical events that made OSPF become more wide-spread than IS-IS.
Note to new OP
Oh, and welcome to the world of computer networking!  You will see confusing names due to historical reasons, more sub-optimal solution that exist today simply because people are just used to them, and people that blindly defend protocols as-if protocols are always right (which is not true by the way, protocols have mistakes).  Plus some new cool tech that's being cooked in the labs.
That said, I have to say that you are doing the right thing.  Your approach is logical and are asking the right questions.  The world of networking has some accumulated mess due to historical reasons, and also has some real genius behind some of its protocols.  This is why it is sometimes confusing as you ask yourself: why do we have X?  Is X a genius that I am not foreseeing yet?  Or is X an ancient mistake that we are stuck with?  Or is it just some dudes that thought that everything must be in XML?
Buckle-up for the ride is gonna be fun!
Comment: I have no idea who voted down on your answer, but remember that voting is meant to be anonymous, so trying to force a voter to reveal identity by commenting defeats the anonymity. I would imagine it is because the voter does not believe your answer, while very complete, addresses the OP's comment "_my question is more like is there any condition where OSPF is better used than anything else (e.g EIGRP), or what kind of network is suitable using OSPF?_"
Comment: **Ones who down-vote this post:** kindly specify your reason.
Comment: @RonMaupin - I don't care about his identity.  Yes privacy is a valid point.  I just want to know his/her reason.  We probably need a new feature where one can post a comment without revealing his ID (e.g. some tick box to hide ID).
Comment: I believe that has been proposed on [metase] a few times. I understand your frustration. I often get a vote down on an answer that has a dozen or more votes and has been accepted by the OP. It really makes you wonder what the voter was thinking, but, or course, everyone is entitled to an opinion and free to vote in any way they want.


How do I reference LaTeX help in my bibliography?

Question: Basically I'm trying to reference properly for my dissertation, and I wondered if there's a manual somewhere I can quote - I can't find one.
Answer: Academic standards do not require you to cite the typesetting software you composed your dissertation with. It's a tool you used, not an intellectual input to your work. You wouldn't cite the manufacturer of your printer either.
Of course the opposite is true if you are writing a dissertation about computer typesetting.
Your question though has one more aspect that is of some generic interest: It is a bit strange to acknowledge a software by citing a manual you had never consulted while using the software. It might be more appropriate to cite the software as such, and not a manual.


Kali linux(Virtual Box) doesn't detect the physical wifi adapter ( Intel® Dual Band Wireless-AC 3160)?

Question: I have the Kali 4.14.0-kali3-amd64 #1 SMP Debian 4.14.12-2kali1 (2018-01-08) x86_64GNU/linux I followed the instructions Linux* Support for Intel® Wireless Adapters depicted here for my specific card Intel® Dual Band Wireless-AC 3160 I copied the content into home/lib/firmware/but still Linux Kali doesn't detect the wi-fi adaptor. What can I do to remedy it?
Answer: It might be that virtual box does not detect the USB drive?
If that's the case you should add a USB controller in the VM settings.


Interference fit in acrylic/plexiglass (PMMA)

Question: I'm trying to fit a shaft into a hole in an acrylic piece that is 5mm thick to cause an interference fit. The shaft has a max. diameter of ⌀5mm and a min. diameter of ⌀4.988mm. I have access to a laser cutter with a precision of 0.2mm. This basically means that i have to cut the hole in the acrylic to a diameter of less than ⌀4.788mm, to ensure an interference fit right? Lets say I cut the hole in the acrylic, using a diameter of ⌀4.788mm, the diameter could be as low as ⌀4.588mm. Would the shaft of ⌀5mm even fit in this hole? Given the material and uncertainty in the laser cutter, what diameter do you think is suitable? Thanks
Comment: laser printer? A device used to apply toner in image form on paper? Laser cutter? I did not want to edit it without a clarification.
Comment: Apologies. Yes, a laser cutter is what I meant.
Comment: Did you take into account that laser cutters dont make straight holes. but the sides are allways a bit angled. 0.2 mm sounds awfully inaccurate to me.
Answer: Presuming laser cutter and not laser printer, the project you suggest would be most effectively approached by creating test pieces. With 5 mm thick acrylic, there are enough variables to make it difficult to provide certain answers.
Cast acrylic behaves differently from extruded acrylic. High power lasers are able to use higher travel speeds than lower powered lasers, changing the characteristics of the hole.
A 5 mm diameter hole is small enough that high travel speeds are not likely regardless of the performance of the laser. Laser cutters typically slow for circles and curves and especially for right angle corner cuts. This changes the profile of the cut and the surface rendered by such a cut.
If your project allows for creating test pieces, consider to use a variety of hole sizes and cutting profiles, testing your holes with pin gauges or with the shaft to determine correct settings.
Kerf settings in the software that create the laser job can be adjusted to provide more precision for inside dimensions, but I suspect the tests would give you simpler results.
With such a thick material, a low power laser may have some divergence as it nears the lower edge of the material and may create a non-cylindrical hole. The variation may not be a factor in your project, but the above suggested tests will ascertain that consideration.
Answer: There are a couple of issues. Firstly laser cutting may well not provide good enough tolerances or surface finish to reliably produce the fit you need and you woudl probably be better off drilling the holes, possibly using the laser to create a reference mark or pilot hole.
Secondly poly-carbonate and acrylic don't really like this sort of interference fit and the advice is generally to give holes decent clearance as the stresses involved tend to cause cracks, especially if the holes aren't polished and chamfered.
You would probably be better off drilling a hole with adequate clearance and using an adhesive to secure the shaft.
Comment: Your post brings an oversight on my part. Temperature changes will be different with two different materials, perhaps resulting in the cracks you describe, if the fit is too tight.


highest and lowest in aftermarket seems extreme?

Question: We all want to buy lower and sell higher on the stock. But sometimes, particularly in the aftermarket and pre-market time, even though there is no special news on that stock, we still can see a crazy highest price or lowest price is drawn on a candlestick. I understand the lowest price might be real because everybody tends to buy lower. But how the highest price can be true? Is it the real event somebody bought that stock at that high price? Any expert can explain this to me, please? thanks.
Comment: Can you give a specific example?
Answer: For every trade that occurs,  there is a buyer and a seller. Ignoring special circumstances like the seller just needs the money, one of these traders is wrong.
Your premise is that the  lowest price might be real because everybody tends to buy lower.  I'd ask you this in return.  The market is up 50% in 9 months and is it trading at record highs.  Why is anyone buying anything?  The answer is that many believe that the market is going higher.  They may be right, they may be wrong but either way, they are expressing their outlook with their dollars.
As to your question about the pre- and post market, that's a  bit of a different beast.  It tends to be illiquid with much wider spreads and because of reduced volume, it is more volatile.  It takes far fewer shares to move price after hours and that is reflected in wider price swings.  With many stocks, that same share volume that moved after hours price would likely be swallowed during the regular trading session, barely moving price, if at all. And to a lesser extent, sometimes, that crazy price is just that, caused by a fat fingered trade and sometimes it's just bad data.
A word of caution: Do not trade during after hours unless you are an experienced, decisive  trader.  The exception to this would be if you are either closing or hedging an existing position at a good price.
Answer: There is always a buyer at the highest price and a seller at the lowest price. It isn't necessarily bad, though. The seller at the lowest price could have bought a year ago at an even lower price. The buyer at the high price may expect that the stock will continue to grow and not be concerned with the entry price. If you had bought Amazon at the "high" price for a day 5 years ago (somewhere round 670), you'd still have about a 400% return.
Buy-and-hold investors shouldn't worry about daily fluctuations - they are looking for long term growth. Only day traders stress over the daily high/low.
Answer: There's much less trade volume after hours, and low volume (almost?) always means higher volatility.
This is what you see.
Answer: The after-hour trades are typically for very small quantities, but they are really happening as shown.
Anecdotal: For a while, I made some bucks by entering low buy and high sell limit orders after 4 pm for some less frequently traded securities, and here and there 1 or 5 shares get traded. Overall, it's not worth the effort, as you have to clean up every morning what you bought and sold, so it's an hour work for 50 or 200 $ every other day maybe.
In a nutshell, after hours, "the kids are playing", and you can steal some chocolate from them if you care to.
For heavy volume stock, like AMZN or TSLA, after hours is normal business, with a bit more volatility.


Can you identify these 1x2 and 2x2 bricks with grooves?

Question: As far as I understand, these are modified with groove bricks. However, search for 'groove' on BrickLink gives only left one. Which are the other two? Which other parts have similar vertical groove and do not have 'groove' word in the name?
Answer: Actually found via Google pictures. On bricklink need to use 'grooves' in search, partial matches do not work there.
Comment: They do if you put an asterisk (\*) at the end of the search word, such as "groove\*". I am not sure about other placeholder symbols.
Answer: Here are the listings from Bricklink.com (left to right).
Brick, Modified 1 x 2 with Groove
https://www.bricklink.com/v2/catalog/catalogitem.page?P=4216#T=C
Brick, Modified 2 x 2 with Grooves and Axle Hole
https://www.bricklink.com/v2/catalog/catalogitem.page?P=90258#T=C
I'm not sure about the last one. Maybe:
Brick, Modified 2 x 2 x 6 with Groove
https://www.bricklink.com/v2/catalog/catalogitem.page?P=6056#T=C