Ruby function to capitalize all words in a string

The task is to write a function, which capitalize all words (blank as a separator) in a string. Because the standard String.capitalize method changes only the first word in a string.

Here’s the code I have written:

def capitalizeAllWords(str)
    caps = str.split(" ").map do |word| 
        word.capitalize
    end
    caps.join " "
end

puts capitalizeAllWords "Red orange green blue indigo violet" 
# Prints: "Red Orange Green Blue Indigo Violet"

Could the task be accomplished with writing less code? Any other improvements-suggestions concerning the function?

ruby on rails – Unable to run sidekiq as service in CentOS 8

I have following service file.

(Unit)
Description=xxx_sidekiq
After=syslog.target network.target


(Service)
Type=notify
WatchdogSec=10

WorkingDirectory=/home/xxx/project/matchspace/appointment-ms
ExecStart=/home/xxx/.rvm/wrappers/ruby-2.6.4/bundle exec sidekiq -e production
User=developer
Group=developer
UMask=0002

Environment=MALLOC_ARENA_MAX=2

RestartSec=1
Restart=on-failure

StandardOutput=syslog
StandardError=syslog

SyslogIdentifier=xxx_sidekiq

(Install)
WantedBy=multi-user.target

When I start the service as sudo systemctl start xxx_sidekiq.service I get following error

Jun  4 05:55:23 cnctest systemd(23391): xxx_sidekiq.service: Failed to execute command: Permission denied
Jun  4 05:55:23 cnctest systemd(23391): xxx_sidekiq.service: Failed at step EXEC spawning /home/xxx/.rvm/wrappers/ruby-2.6.4/bundle: Permission denied

The reason for Permission denied is given as

Jun  4 05:55:23 cnctest platform-python(23362): SELinux is preventing /usr/lib/systemd/systemd from read access on the lnk_file ruby-2.6.4.#012#012*****  Plugin catchall (100. confidence) suggests   **************************#012#012If you believe that systemd should be allowed read access on the ruby-2.6.4 lnk_file by default.#012Then you should report this as a bug.#012You can generate a local policy module to allow this access.#012Do#012allow this access for now by executing:#012# ausearch -c '(bundle)' --raw | audit2allow -M my-bundle#012# semodule -X 300 -i my-bundle.pp#012

How can I solve this problem.

ruby – Sharing ActiveRecord class between two Rails app with gem

We have several Rails applications using the same ActiveRecord, Book. For simplicity let us assume we have only these two:

  • BookWarehouseApp (that deals how new book are added, or other inventory processes)
  • BookLibraryApp (that deals with how book are being borrowed and returned)

BookWarehouseApp has read and write access to the books table in a Postgres DB.
BookLibraryApp has a read-only access to the same books table (in production and dev). In test env, BookLibraryApp has write access too (to allow for test setup).

Both are tested in a classical Rails + MiniTest setup.

Now there is a lot of shared behavior between BookWarehouseApp::Book and BookLibraryApp::Book (and for example BookWarehouseApp::Book has a lot of validation/creation code that is absent of
BookLibraryApp::Book, so they are not identical. Moreover, they both inherit from ApplicationRecord in their respective app and both ApplicationRecord classes have their respective life in their own app. We also have other objects that deal with books (call them BookSerializer and BookPoro).

To avoid maintaining the same code in two places, we are thinking of extracting Book, BookSerializer and BookPoro to a gem.

If Book was not an ActiveRecord, it would be fairly straightforward. But now I am bit confused about the best way to setup that gem and test it up.

Among the options, I have considered and the difficulties I see (possibly because I have never done that before):

  1. Define a Book (including ActiveModel::Model) class in the gem. It will be overridden in apps that require the gem, but it will allow us to factorize and test other poros that depend on it.

    • pros: no DB setup required to test the gem, no migration to write for future users of the gem
    • cons: we are not sharing actual Book behavior (only poros) and we are not making life easy for future users of the gem, we cannot share any ActiveRecord type hook (or at least not test it in a convincing fashion).
  2. Define a BookLike/Bookable concern/module in the scope of the gem and let BookWarehouseApp::Book and BookLibraryApp::Book extend/include it.

    • pros: no DB setup, behavior shared, no migration to write
    • cons: we are not making life easy for future users of the gem, cannot share ActiveRecord type hooks (or least not test them)
  3. Define a Book class that inherit from ActiveRecord::Base and inherit from it in the apps.

    • pros: possible to test the full behavior
    • cons: how can we deal with the fact that each app has an ApplicationRecord class with different behaviors, suppose to setup DB interaction to test the gem, suppose to write some kind of migration generator to really offer a plug and play experience to future users.

I am thinking option 2 is reasonable, but it is not obvious how to deal with the underlying schema of books. A possibility is to have a FakeBook class there (for test purposes) that uses ActiveModel attr_accessors. We could also simply give an example of migration for users of the gem (in the spirit of ‘we are all adults and can copy paste a migration’).

Any idea or suggestion on how to deal with this situation welcome.

PHP-FPM to Ruby | Web Hosting Talk

PHP-FPM to Ruby | Web Hosting Talk


‘);
var sidebar_align = ‘right’;
var content_container_margin = parseInt(‘350px’);
var sidebar_width = parseInt(‘330px’);
//–>









  1. PHP-FPM to Ruby


    Hello Im hearing mod-php fancies more to ruby than php-fpm ,can I run ruby with php-fpm?













Similar Threads


  1. Replies: 5


    Last Post: 03-12-2013, 01:12 AM


  2. Replies: 4


    Last Post: 01-02-2013, 04:21 PM


  3. Replies: 33


    Last Post: 07-25-2011, 01:01 PM


  4. Replies: 0


    Last Post: 11-06-2010, 12:33 PM


  5. Replies: 0


    Last Post: 03-15-2010, 12:09 PM



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  








Is Python Still Better than Ruby as a Machine Learning Language?

Is Python Still Better than Ruby as a Machine Learning Language? | Web Hosting Talk


‘);
var sidebar_align = ‘right’;
var content_container_margin = parseInt(‘350px’);
var sidebar_width = parseInt(‘330px’);
//–>









  1. Post Is Python Still Better than Ruby as a Machine Learning Language?


    Which programming language is good for Machine Learning Language?

    Python or Ruby?













Similar Threads


  1. Replies: 28


    Last Post: 12-07-2009, 11:09 PM


  2. Replies: 49


    Last Post: 09-06-2002, 03:05 AM


  3. Replies: 11


    Last Post: 08-21-2002, 05:41 PM


  4. Replies: 18


    Last Post: 03-03-2002, 10:20 AM


  5. Replies: 2


    Last Post: 03-03-2001, 02:13 PM

Tags for this Thread



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  








Ruby simple interactive interpreter – Code Review Stack Exchange

This is my first Ruby code and a solution to this problem https://www.codewars.com/kata/53005a7b26d12be55c000243/train/ruby The task is to make a simple interpreter that will take expressions and calculate the results. I’m just looking for general feedback on following Ruby standard practices and ways I could shorten the code by omitting parentheses for example


  def input expr
    if expr.strip == ""
      return ""
    end
    # puts expr
    tokens = tokenize(expr).map{ |a| a(0) }    
    parsedTokens = parseTokens tokens
    if parsedTokens.length == 1
      if !@variables.key? parsedTokens(0).name
        raise 'unitialized variable'
      end
      return @variables(parsedTokens(0).name)
    end
    # todo can the user enter just a number?
    leastPrecedentNode = partition parsedTokens
    rootOfBuiltTree = buildTree leastPrecedentNode
    result = calculateRecursive rootOfBuiltTree
    result
  end

  private

  class OperatorInfo
      @@operators = { '=' => 0, '+' => 1, '-' => 1, '*' => 2, '/' => 2, '%' => 2 }
      @@assignmentOperator = '='

      def self.operators
        @@operators
      end

      def self.assignmentOperator
        @@assignmentOperator
      end
  end

  class ParseUnit
    attr_reader :overallIndex
    attr_reader :nestLevel
    attr_reader :indexInLevel

    def initialize(overallIndex, nestLevelArg, indexInLevelArg)
      @overallIndex = overallIndex
      @nestLevel = nestLevelArg
      @indexInLevel = indexInLevelArg
    end
  end

  class ConstantParse < ParseUnit
    attr_reader :value

    def initialize(value, overallIndex, nestLevel, indexInLevel)
      super(overallIndex, nestLevel, indexInLevel)
      @value = value
    end
  end

  class OperatorParse < ParseUnit
    attr_reader :operator
    attr_reader :priority

    def initialize(operator, overallIndex, nestLevel, indexInLevel)
      super(overallIndex, nestLevel, indexInLevel)
      @operator = operator
      @priority = OperatorInfo.operators(operator)
    end
  end

  class VariableParse < ParseUnit
    attr_reader :name

    def initialize(name, overallIndex, nestLevel, indexInLevel)
      super(overallIndex, nestLevel, indexInLevel)
      @name = name
    end
  end

  def parseTokens (tokens)
    ret = ()
    nestLevel = 0
    indexes = (0)
    overallIndex = 0
    tokens.each do | t | 
      # can be operator, constant number, paren, variable 
      # puts "curToken is #{t}"

      case t       
      #operator
      when OperatorInfo.operators.keys.include?(t).to_s == 'true' ? t : ''
        ret.push OperatorParse.new t, overallIndex, nestLevel, indexes(nestLevel)
          overallIndex += 1
          indexes(nestLevel) += 1 
      # is a constant number
      when /Ad+z/        
        ret.push ConstantParse.new t.to_i, overallIndex, nestLevel, indexes(nestLevel)
        overallIndex += 1
        indexes(nestLevel) += 1
      when '('
        nestLevel += 1
        if indexes.length <= nestLevel
          indexes.push(0)
        end
      when ')'
        nestLevel -= 1
      #variable
      when String
        ret.push VariableParse.new t, overallIndex, nestLevel, indexes(nestLevel)
        overallIndex += 1
        indexes(nestLevel) += 1
      else
        puts "error in parse tokens with token #{t}"
      end
    end
    ret
  end

  class OperatorNode
    attr_reader :operator
    attr_reader :left
    attr_reader :right

    def initialize(operator, left, right)
      @left = left
      @right = right
      @operator = operator
      @priority = OperatorInfo.operators(operator) 
    end
  end

  def partition(parsedTokens)
    opTokens = parsedTokens.select { |token| token.is_a?(OperatorParse) }
    op = leastPrecedentOp opTokens
    left = parsedTokens.select { |x| x.overallIndex < op.overallIndex }
    right = parsedTokens.select { |x| x.overallIndex > op.overallIndex }
    OperatorNode.new op, left, right
  end

  def leastPrecedentOp opTokens
    if opTokens.length == 1 
      return opTokens(0)
    end
    # todo dry out this sort with the next one
    sortedByNestLevel = opTokens.sort_by { |x| x.nestLevel }
    nestLevelTies = sortedByNestLevel.select { |x| x.nestLevel == sortedByNestLevel(0).nestLevel }
    if nestLevelTies.length == 1
      return nestLevelTies(0)
    end
    sortedByPriority = nestLevelTies.sort_by { |x| x.priority }
    priorityTies = sortedByPriority.select { |x| x.priority == sortedByPriority(0).priority }
    if priorityTies.length == 1
      return priorityTies(0)
    end
    sortedByIndexInLevel = priorityTies.sort_by { |x| x.indexInLevel * -1 }
    sortedByIndexInLevel(0)
  end

  def buildTree(opNode)
    # puts opNode
    # base case
    leftIsSingle = opNode.left.length == 1
    rightIsSingle = opNode.right.length == 1
    if leftIsSingle && rightIsSingle
      return OperatorNode.new opNode.operator.operator, opNode.left, opNode.right   
    end
    # recursive call
    leftRet = nil
    if leftIsSingle
      leftRet = opNode.left(0)
    else
      leftPart = partition opNode.left
      leftRet = buildTree leftPart
    end

    rightRet = nil
    if rightIsSingle
      rightRet = opNode.right(0)
    else
      rightPart = partition opNode.right
      rightRet = buildTree rightPart
    end

    # combine and return
    OperatorNode.new opNode.operator.operator, leftRet, rightRet
  end

  def calculateRecursive node
    # base case
    if isLeaf? node, nil
      return getValue node
    end    
    leftIsLeaf = isLeaf? node, node.left
    rightIsLeaf = isLeaf? node, node.right
    if leftIsLeaf && rightIsLeaf
      if node.operator == OperatorInfo.assignmentOperator
        return calculateImpl node.operator, node.left(0).name, (getValue node.right)
      end
      leftVal = getValue node.left
      rightVal = getValue node.right
      return calculateImpl node.operator, leftVal, rightVal
    end
    # recursive call
    leftResult = nil
    if leftIsLeaf && node.operator != OperatorInfo.assignmentOperator
      leftResult = getValue node.left
    elsif leftIsLeaf && node.operator
      leftResult = node.left.name
    else
      leftResult = calculateRecursive node.left
    end
    rightResult = nil
    if rightIsLeaf
      rightResult = getValue node.right
    else
      rightResult = calculateRecursive node.right
    end
    # combine and return
    result = calculateImpl node.operator, leftResult, rightResult
    result
  end

  def isLeaf?(parent, node)
    # if parent
    isConstant = node.is_a? ConstantParse 
    if node.is_a? Array 
      isConstant = node(0).is_a? ConstantParse
    end
    isVariable = node.is_a? VariableParse
    if node.is_a? Array 
      isVariable = node(0).is_a? VariableParse
    end
    return isConstant || isVariable
  end

  def getValue node
    nodeVal = nil
    if node.is_a? Array
      nodeVal = node(0)
    else
      nodeVal = node
    end
    if nodeVal.is_a? ConstantParse
      return nodeVal.value
    end
    if nodeVal.is_a? VariableParse
      if @variables.key? nodeVal.name
        return @variables(nodeVal.name)
      end
      return nodeVal.name
    end
  end

  def calculateImpl(operator, left, right)
    #puts "#{left} #{operator} #{right}"
    case operator
    when '+'
      return left + right
    when '-'
      return left - right
    when '/'
      return left.to_f / right
    when '*'
      return left * right
    when '%'
      return left % right
    when '='
      @variables(left) = right
      return right
    end
  end

  def initialize
    @variables = {}
  end  

  def tokenize program
    return () if program == ''
    regex = /s*((-+*/%=())|(A-Za-z_)(A-Za-z0-9_)*|(0-9)*.?(0-9)+)s*/
    program.scan(regex).select { |s| !(s =~ /^s*$/) }
  end
end

functional programming – Ruby Exercise: Implement your own “#group_by” method

Task:

“Implement a method ‘gruppiere’, in a way that it can be invoked on all enumerable objects (Enumerable). The method receives a block and returns a hash. The items of the enumerable a grouped within the hash according to the return-value of the block.”

What they like to have is an own implementation of Ruby’s “#group_by”-method: Ruby-Docs Enumerable

My solution:

module Enumerable
    def gruppiere()
        ret = {}

        self.each { |item| 
            key = yield item

            if ret(key) == nil
                tmp = ()
                tmp << item
                ret(key) = tmp
            else
                ret(key) << item
            end
        }

        ret
    end
end

puts (1, 2, 3, 4).gruppiere { |i| i % 2 == 0 } # Result: {false=>(1, 3), true=>(2, 4)}

Works well. But I’m sure it could be done better.

Is there a less verbose way to solve the task?

Is my code written in a good way and manner? What could be improved?

testes unitários – Problema com END no Ruby

Estou fazendo um curso de QA e sou iniciante tanto em ruby quanto em QA, esse é um exercício sobre saques de caixa eletrônico, o erro que acontece é que Visual Studio diz que esperava um END na ultima linha do código, porém eu coloquei esse END e identei.

Segue o código:

class ContaCorrente
    attr_accessor :saldo, :mensagem

    def initializer(saldo)
        self.saldo = saldo
    end

    def saca(valor)
    if (valor > self.saldo)
        self.mensagem = 'Saldo insuficiente para saque'
    elsif(valor > 700)
        self.mensagem = 'Limite maximo para saque é 700'
    else
        self.saldo -= valor
    end

end
describe ContaCorrente do

    describe 'Saque' do
        context 'quando o valor é positivo' do
            before(:all) do
                @conta = ContaCorrente.new(1000.00)
                @conta.saca(200.00)
            end   
            it 'entao atualiza saldo' do
                expect(@conta.saldo).to eql 800.00
            end
        end

        context 'quando o saldo é zero' do
            before(:all) do
              @conta = ContaCorrente.new(0.00)
              @conta.saca(100.00)
            end
            it 'vejo mensagem' do
                expect(@conta.mensagem).to eql 'Saldo insuficiente para saque'
            end
            it 'e o saldo final com zeros' do
                expect(@conta.saldo).to eql 0.00
            end
        end

        context 'quando o saldo é insuficiente' do
            before(:all) do
              @conta = ContaCorrente.new(100.00)
              @conta.saca(101.00)
            end
            it 'vejo mensagem' do
                expect(@conta.mensagem).to eql 'Saldo insuficiente para saque'
            end
            it 'e o saldo final com zeros' do
                expect(@conta.saldo).to eql 100.00
            end
        end 

        context 'quando o valor do saque é maior que o limite' do
            before(:all) do
                @conta = ContaCorrente.new(1000.00)
                @conta.saca(701.00)
            end
            it 'vejo mensagem' do
                expect(@conta.mensagem).to eql 'Limite maximo para saque é 700'
            end
            it 'saldo mermanace o mesmo' do
                expect(@conta.saldo).to eql 1000.00
            end
        end
    end
end

Ruby – Sending commands to multiple servers using Net::SSH

The idea

At my work, I’m tasked with retrieving logs for a list of online orders from a total of 12 servers. To do this, I SSH into them (with a jump host in between) one by one, run the script for every order, then parse the output. Overall, a very tedious process that I’m sure can be automated.

W -> J -> S

W = My Windows VM

J = Red Hat jump box

S = The Red Hat production servers

So the basic idea is the following:

  1. Connect to every server by SSH

  2. On every server, run the commands for all orders which are passed by command line

  3. Associate each output with the order

Here is what I’ve come up with so far, and it is working on my home lab. But before I bring it in to work to propose it and try it on production servers, I want to know how the code can be cleaned up or done more efficiently.

The code

require 'net/ssh'
require 'io/console'
require 'pp'

ORDERS = ARGV.dup()     
ARGV.clear()            

SERVERS = (
    "prod1",
    "prod2",
    "prod3"
)

COMMAND = "aux_search.sh"

CONFIG = "C:/Users/myuser/.ssh/config"

RESULTS = ORDERS.each_with_object({}) { |k, v| v(k) = "" }

puts("Enter your username: ")
USERNAME = gets().chomp()
puts("Enter your password for accessing the servers: ")
SERVERPASSWORD = STDIN.noecho(&:gets).chomp()
puts("Enter your sudo password: ")
SUDOPASSWORD = STDIN.noecho(&:gets).chomp()

SESSIONS = ()
SERVERS.each do |server|
    session = Net::SSH.start(server, USERNAME, :password => SERVERPASSWORD, :config => CONFIG, 
        :verbose => :debug, :auth_methods => ("publickey", "password"), :verify_host_key => :accept_new)

    SESSIONS << session
end

SESSIONS.each do |ssh|
    ORDERS.each do |order|
        ssh.open_channel() do |channel|
            channel.on_data do |_, data|
                RESULTS(order).concat(data)
                if data.match(/(sudo)/)  
                    channel.send_data("#{SUDOPASSWORD}n")
                end
            end

            channel.request_pty() do |_, success|
                raise "Failed to request TTY for order #{order}" unless success
            end

            channel.exec("sudo ./#{COMMAND} #{order}") do |_, success| 
                raise "Could not execute command #{COMMAND} #{order}" unless success
            end
        end
    end
    ssh.loop()
end

puts("===Results===")
pp(RESULTS)

My ssh config

Host jumpbox
    HostName 192.168.16.2
    User johrus2
    IdentityFile C:Usersmyuser.sshid_rsa3
    Port 22

Host prod1
    HostName 192.168.16.3
    User johrus2
    IdentityFile C:Usersmyuser.sshid_rsa3
    ProxyJump jumpbox
    Port 22

Host prod2
    HostName 192.168.16.4
    User johrus2
    IdentityFile C:Usersmyuser.sshid_rsa3
    ProxyJump jumpbox
    Port 22

Host prod3
    HostName 192.168.16.5
    User johrus2
    IdentityFile C:Usersmyuser.sshid_rsa3
    ProxyJump jumpbox
    Port 22

```

DreamProxies - Cheapest USA Elite Private Proxies 100 Private Proxies 200 Private Proxies 400 Private Proxies 1000 Private Proxies 2000 Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive Proxies-free.com New Proxy Lists Every Day Proxies123