问:
Erc20 tokens deposit/withdraw on ruby
I use Peatio based exchange. Ethereum deposit/withdraw are working, but Binance coin doesn't work. I can't generate binance coin address. My codes below. Is it wring? I reall need help.

require 'net/http'
require 'uri'
require 'json'

class CoinRPC

  class JSONRPCError < RuntimeError; end
  class ConnectionRefusedError < StandardError; end

  def initialize(uri)
    @uri = URI.parse(uri)
  end

  def self.[](currency)
    c = Currency.find_by_code(currency.to_s)
    if c && c.rpc
      name = c[:handler] || 'BTC'
      "::CoinRPC::#{name}".constantize.new(c.rpc)
    end
  end

  def method_missing(name, *args)
    handle name, *args
  end

  def handle
    raise "Not implemented"
  end

  class BTC < self
    def handle(name, *args)
      post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
      resp = JSON.parse( http_post_request(post_body) )
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      result.symbolize_keys! if result.is_a? Hash
      result
    end

    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      http.request(request).body
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def safe_getbalance
      begin
        getbalance
      rescue
        'N/A'
      end
    end
  end

  class ETH < self
def handle(name, *args)
  post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => args, 'id' => '1' }.to_json
  resp = JSON.parse( http_post_request(post_body) )
  raise JSONRPCError, resp['error'] if resp['error']
  result = resp['result']
  result.symbolize_keys! if result.is_a? Hash
  result
end
def http_post_request(post_body)
  http    = Net::HTTP.new(@uri.host, @uri.port)
  request = Net::HTTP::Post.new(@uri.request_uri)
  request.basic_auth @uri.user, @uri.password
  request.content_type = 'application/json'
  request.body = post_body
  http.request(request).body
rescue Errno::ECONNREFUSED => e
  raise ConnectionRefusedError
end

def safe_getbalance
  begin
    (open(@uri.host + '/cgi-bin/total.cgi').read.rstrip.to_f)
  rescue
    'N/A'
  end
end
  end

  class BNB < self
def handle(name, *args)
  post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => args, 'id' => '1' }.to_json
  resp = JSON.parse( http_post_request(post_body) )
  raise JSONRPCError, resp['error'] if resp['error']
  result = resp['result']
  result.symbolize_keys! if result.is_a? Hash
  result
end
def http_post_request(post_body)
  http    = Net::HTTP.new(@uri.host, @uri.port)
  request = Net::HTTP::Post.new(@uri.request_uri)
  request.basic_auth @uri.user, @uri.password
  request.content_type = 'application/json'
  request.body = post_body
  http.request(request).body
rescue Errno::ECONNREFUSED => e
  raise ConnectionRefusedError
end

def safe_getbalance
  begin
    (open(@uri.host + '/cgi-bin/total.cgi').read.rstrip.to_f)
  rescue
    'N/A'
  end
end
  end
end```

答:
My code is parameterized for Binance currencies, I haven't tested the ETH network system, but I verified that the codes are similar.
It costs nothing to test ...</p>

```<code>require 'net/http'
require 'uri'
require 'json'

class CoinRPC

  class JSONRPCError < RuntimeError; end
  class ConnectionRefusedError < StandardError; end

  def initialize(coin)
    @uri = URI.parse(coin.rpc)
    @rest = coin.rest
    @coin = coin
  end

  def self.[](currency)
    c = Currency.find_by_code(currency.to_s)
    if c && c.rpc
      if c.proto == 'ETH'
        name = 'ETH'
      elsif c.proto == 'BTC'
        name = 'BTC'
      elsif c.proto == 'OLD_BTC'
        name = 'OLD_BTC'
      elsif c.proto == 'WOA_BTC'
        name = 'WOA_BTC'
      elsif c.proto == 'CNT'
        name = 'CNT'
      else
        name = c[:handler]
      end
      Rails.logger.info "Making class " + name.to_s + "(" + currency.to_s + ")\n"
      "::CoinRPC::#{name.to_s}".constantize.new(c)
    end
  end

  def method_missing(name, *args)
    handle name, *args
  end

  def handle
    raise "Not implemented"
  end

  class BTC < self
    def handle(name, *args)
      post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
      resp = JSON.parse( http_post_request(post_body) )
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      result.symbolize_keys! if result.is_a? Hash
      result
    end
    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      http.request(request).body
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      @reply = http.request(request).body
      # Rails.logger.info @reply
      return @reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def getnewaddress(name, digest)
      @newaddress = handle("getnewaddress", name)
    end

    def safe_getblockchaininfo
      begin
        getblockchaininfo
      rescue
        'N/A'
      end
    end

    def safe_getbalance
      begin
        getbalance
      rescue
        'N/A'
      end
    end
  end

  class OLD_BTC < self
    def handle(name, *args)
      post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
      resp = JSON.parse( http_post_request(post_body) )
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      result.symbolize_keys! if result.is_a? Hash
      result
    end
    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      http.request(request).body
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def getnewaddress(name, digest)
      @newaddress = handle("getnewaddress", name)
    end

    def getblockchaininfo
      @getinfo = getinfo()
      {
        blocks: Integer(@getinfo[:blocks]),
        headers: 0,
        mediantime: 0
      }
    end

    def safe_getbalance
      begin
        getbalance
      rescue
        'N/A'
      end
    end
  end

 class WOA_BTC < self
    def handle(name, *args)
      post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
      Rails.logger.info "WOA_BTC " +  post_body
      resp = JSON.parse( http_post_request(post_body) )
      Rails.logger.info resp
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']

      result.symbolize_keys! if result.is_a? Hash
      result
    end

    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      #Rails.logger.info post_body
      @reply = http.request(request).body
      #Rails.logger.info @reply
      return @reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def sendtoaddress(from, address, amount)
      handle("sendtoaddress", address, amount)
    end

    def getnewaddress(name, digest)
      @newaddress = handle("getnewaddress", "")
    end

    def getblockchaininfo
      @getinfo = getinfo()
      {
        blocks: Integer(@getinfo[:blocks]),
        headers: 0,
        mediantime: 0
      }
    end

    def safe_getbalance
      begin
        getbalance
      rescue
        'N/A'
      end
    end
  end

  class ETH < self
    def handle(name, *args)
      post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => args, 'id' => '1' }.to_json
      resp = JSON.parse( http_post_request(post_body) )
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      result.symbolize_keys! if result.is_a? Hash
      result
    end
    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      http.request(request).body
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def safe_getbalance
      begin
        (open(@uri.host + '/cgi-bin/total.cgi').read.rstrip.to_f)
      rescue
        'N/A'
      end
    end

    def getblockchaininfo
      @lastBlock = eth_getBlockByNumber("latest", true)
      #Rails.logger.info @lastBlock
      #Rails.logger.info "number = " + Integer(@lastBlock[:number]).to_s + ", timestamp = " + Integer(@lastBlock[:timestamp]).to_s

      {
        blocks: Integer(@lastBlock[:number]),
        headers: 0,
        mediantime: Integer(@lastBlock[:timestamp])
      }
    end
  end

  class LISK < self
    def handle(name, *args)
      post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => args, 'id' => '1' }.to_json
      Rails.logger.info "LISK -> " + post_body
      resp = JSON.parse( http_post_request(post_body) )
      Rails.logger.info "LISK <- " + resp.to_json
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      result.symbolize_keys! if result.is_a? Hash
      result
    end

    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      @reply = http.request(request).body
      return @reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def http_post_request_body(post_url, post_body)
      Rails.logger.info "LISK -> " + post_url + " / " + post_body
      uri     = URI.parse(post_url)
      http    = Net::HTTP.new(uri.host, uri.port)
      request = Net::HTTP::Post.new(uri.request_uri)
      request.basic_auth uri.user, uri.password
      request.content_type = 'application/json'
      request.body = post_body
      reply = JSON.parse(http.request(request).body)
      raise JSONRPCError, reply['error'] if reply['error']
      Rails.logger.info "LISK <- " + reply.to_json
      return reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def http_get_request(get_url)
      Rails.logger.info "LISK -> " + get_url
      uri     = URI.parse(get_url)
      http    = Net::HTTP.new(uri.host, uri.port)
      request = Net::HTTP::Get.new(uri.request_uri)
      request.basic_auth uri.user, uri.password
      request.content_type = ""
      request.body = ""
      reply = http.request(request).body
      result = JSON.parse(reply)
      raise JSONRPCError, result['error'] if result['error']
      Rails.logger.info "LISK <- " + result.to_json
      return result
    end

    def http_put_request_body(post_url, post_body)
      Rails.logger.info "LISK -> " + post_url + " / " + post_body
      uri     = URI.parse(post_url)
      http    = Net::HTTP.new(uri.host, uri.port)
      request = Net::HTTP::Put.new(uri.request_uri)
      request.basic_auth uri.user, uri.password
      request.content_type = 'application/json'
      request.body = post_body
      reply = JSON.parse(http.request(request).body)
      raise JSONRPCError, reply['error'] if reply['error']
      Rails.logger.info "LISK <- " + reply.to_json
      return reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def safe_getbalance
      begin
        getbalance
      rescue => ex
        Rails.logger.info  "[error]: " + ex.message + "\n" + ex.backtrace.join("\n") + "\n"
        'N/A'
      end
    end

    def getbalance
      result = http_get_request("#{@rest}/api/accounts/getBalance?address=#{@coin.base_account}")
      balance = result['balance'].to_f / 100000000.0
      return balance
    end

    def gettransaction(txid)
      transaction = http_get_request("#{@rest}/api/transactions/get?id=#{txid}")

      {
        confirmations: transaction['transaction']['confirmations'],
        time: Time.now.to_i,
        details:
        [
          address: transaction['transaction']['recipientId'],
          amount: transaction['transaction']['amount'].to_f / 100000000.0,
          category: "receive"
        ]
      }
    end

    def settxfee
    end

    def sendtoaddress(from, address, amount)
      parameters =
      {
        secret: from,
        amount: Integer(amount * 100000000.0),
        recipientId: address
      }.to_json
      result = http_put_request_body("#{@rest}/api/transactions", parameters)
      return result['transactionId']
    end

    # digest - simple form usermail & number
    def getnewaddress(base_account, digest)
      parameters =
      {
        secret: digest
      }.to_json

      result = http_post_request_body("#{@rest}/api/accounts/open", parameters)
      return result['account']['address']
    end

    def getfee(size)
      return (12000000.0/100000000.0).to_f
    end

    def validateaddress(address)
    end

    def getblockchaininfo

      result = http_get_request("#{@rest}/api/blocks/getStatus")

      {
        blocks: Integer(result['height']),
        headers: 0,
        mediantime: 0
      }
    end
  end

  class CNT < self
    def handle(name, *args)
      post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => args, 'id' => '1' }.to_json
      Rails.logger.info "CNT -> " + post_body
      resp = JSON.parse( http_post_request(post_body) )
      Rails.logger.info "CNT <- " + resp.to_json
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      #result.symbolize_keys! if result.is_a? Hash
      result
    end

    def handle_one(name, arg)
      post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => arg, 'id' => '1' }.to_json
      Rails.logger.info "CNT -> " + post_body
      resp = JSON.parse( http_post_request(post_body) )
      Rails.logger.info "CNT <- " + resp.to_json
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      #result.symbolize_keys! if result.is_a? Hash
      result
    end

    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      #request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      @reply = http.request(request).body
      return @reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def safe_getbalance
      begin
        getbalance
      rescue => ex
        Rails.logger.info  "[error]: " + ex.message + "\n" + ex.backtrace.join("\n") + "\n"
        'N/A'
      end
    end

    def getbalance
      result = handle("getbalance")
      balance = result['balance'].to_f / 1000000000.0
      return balance
    end

    def gettransaction(txid)
      parameters =
      {
        txid: txid
      }
      transaction = handle_one("get_transfer_by_txid", parameters)
      confirmations = Integer(transaction['transfer']['height'])
      if confirmations > 0
        result = handle("getheight", "")
        confirmations = Integer(result['height']) - confirmations
      end
      result =  {
          confirmations: confirmations,
          time: Time.now.to_i,
          details:[]
        }
      if transaction['transfer']['destinations'] == nil
        return result
      end
      transaction['transfer']['destinations'].each do |destination|
        tx = {
            address: destination['address'],
            amount: destination['amount'].to_f / 1000000000.0,
            category: "receive"
          }
        result[:details].push(tx)
      end
      return result
    end

    def settxfee
    end

    def sendtoaddress(from, address, amount)
      parameters =
      {
        account_index: 0,
        destinations:
        [
          {
            amount: Integer(amount * 1000000000.0),
            address: address
          }
        ],
        get_tx_key: true
      }

      result = handle_one("transfer", parameters)
      return result['tx_hash']
    end

    def getnewaddress(name, digest)
      parameters =
      {
        account_index: 0,
        label: ""
      }.to_json

      result = handle_one("create_address", parameters)
      return result['address']
    end

    def getfee(size)
      return (30000000.0/1000000000.0).to_f
    end

    def validateaddress(address)
    end

    def getblockchaininfo

      result = handle("getheight", "")

      {
        blocks: Integer(result['height']),
        headers: 0,
        mediantime: 0
      }
    end
  end

end
</code>```

Title: Erc20 tokens deposit/withdraw on ruby

Body:
My code is parameterized for Binance currencies, I haven't tested the ETH network system, but I verified that the codes are similar.
It costs nothing to test ...

require 'net/http'
require 'uri'
require 'json'

class CoinRPC

  class JSONRPCError < RuntimeError; end
  class ConnectionRefusedError < StandardError; end

  def initialize(coin)
    @uri = URI.parse(coin.rpc)
    @rest = coin.rest
    @coin = coin
  end

  def self.[](currency)
    c = Currency.find_by_code(currency.to_s)
    if c && c.rpc
      if c.proto == 'ETH'
        name = 'ETH'
      elsif c.proto == 'BTC'
        name = 'BTC'
      elsif c.proto == 'OLD_BTC'
        name = 'OLD_BTC'
      elsif c.proto == 'WOA_BTC'
        name = 'WOA_BTC'
      elsif c.proto == 'CNT'
        name = 'CNT'
      else
        name = c[:handler]
      end
      Rails.logger.info "Making class " + name.to_s + "(" + currency.to_s + ")\n"
      "::CoinRPC::#{name.to_s}".constantize.new(c)
    end
  end

  def method_missing(name, *args)
    handle name, *args
  end

  def handle
    raise "Not implemented"
  end

  class BTC < self
    def handle(name, *args)
      post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
      resp = JSON.parse( http_post_request(post_body) )
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      result.symbolize_keys! if result.is_a? Hash
      result
    end
    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      http.request(request).body
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      @reply = http.request(request).body
      # Rails.logger.info @reply
      return @reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def getnewaddress(name, digest)
      @newaddress = handle("getnewaddress", name)
    end

    def safe_getblockchaininfo
      begin
        getblockchaininfo
      rescue
        'N/A'
      end
    end

    def safe_getbalance
      begin
        getbalance
      rescue
        'N/A'
      end
    end
  end

  class OLD_BTC < self
    def handle(name, *args)
      post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
      resp = JSON.parse( http_post_request(post_body) )
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      result.symbolize_keys! if result.is_a? Hash
      result
    end
    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      http.request(request).body
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def getnewaddress(name, digest)
      @newaddress = handle("getnewaddress", name)
    end

    def getblockchaininfo
      @getinfo = getinfo()
      {
        blocks: Integer(@getinfo[:blocks]),
        headers: 0,
        mediantime: 0
      }
    end

    def safe_getbalance
      begin
        getbalance
      rescue
        'N/A'
      end
    end
  end

 class WOA_BTC < self
    def handle(name, *args)
      post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
      Rails.logger.info "WOA_BTC " +  post_body
      resp = JSON.parse( http_post_request(post_body) )
      Rails.logger.info resp
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']

      result.symbolize_keys! if result.is_a? Hash
      result
    end

    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      #Rails.logger.info post_body
      @reply = http.request(request).body
      #Rails.logger.info @reply
      return @reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def sendtoaddress(from, address, amount)
      handle("sendtoaddress", address, amount)
    end

    def getnewaddress(name, digest)
      @newaddress = handle("getnewaddress", "")
    end

    def getblockchaininfo
      @getinfo = getinfo()
      {
        blocks: Integer(@getinfo[:blocks]),
        headers: 0,
        mediantime: 0
      }
    end

    def safe_getbalance
      begin
        getbalance
      rescue
        'N/A'
      end
    end
  end

  class ETH < self
    def handle(name, *args)
      post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => args, 'id' => '1' }.to_json
      resp = JSON.parse( http_post_request(post_body) )
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      result.symbolize_keys! if result.is_a? Hash
      result
    end
    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      http.request(request).body
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def safe_getbalance
      begin
        (open(@uri.host + '/cgi-bin/total.cgi').read.rstrip.to_f)
      rescue
        'N/A'
      end
    end

    def getblockchaininfo
      @lastBlock = eth_getBlockByNumber("latest", true)
      #Rails.logger.info @lastBlock
      #Rails.logger.info "number = " + Integer(@lastBlock[:number]).to_s + ", timestamp = " + Integer(@lastBlock[:timestamp]).to_s

      {
        blocks: Integer(@lastBlock[:number]),
        headers: 0,
        mediantime: Integer(@lastBlock[:timestamp])
      }
    end
  end

  class LISK < self
    def handle(name, *args)
      post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => args, 'id' => '1' }.to_json
      Rails.logger.info "LISK -> " + post_body
      resp = JSON.parse( http_post_request(post_body) )
      Rails.logger.info "LISK <- " + resp.to_json
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      result.symbolize_keys! if result.is_a? Hash
      result
    end

    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      @reply = http.request(request).body
      return @reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def http_post_request_body(post_url, post_body)
      Rails.logger.info "LISK -> " + post_url + " / " + post_body
      uri     = URI.parse(post_url)
      http    = Net::HTTP.new(uri.host, uri.port)
      request = Net::HTTP::Post.new(uri.request_uri)
      request.basic_auth uri.user, uri.password
      request.content_type = 'application/json'
      request.body = post_body
      reply = JSON.parse(http.request(request).body)
      raise JSONRPCError, reply['error'] if reply['error']
      Rails.logger.info "LISK <- " + reply.to_json
      return reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def http_get_request(get_url)
      Rails.logger.info "LISK -> " + get_url
      uri     = URI.parse(get_url)
      http    = Net::HTTP.new(uri.host, uri.port)
      request = Net::HTTP::Get.new(uri.request_uri)
      request.basic_auth uri.user, uri.password
      request.content_type = ""
      request.body = ""
      reply = http.request(request).body
      result = JSON.parse(reply)
      raise JSONRPCError, result['error'] if result['error']
      Rails.logger.info "LISK <- " + result.to_json
      return result
    end

    def http_put_request_body(post_url, post_body)
      Rails.logger.info "LISK -> " + post_url + " / " + post_body
      uri     = URI.parse(post_url)
      http    = Net::HTTP.new(uri.host, uri.port)
      request = Net::HTTP::Put.new(uri.request_uri)
      request.basic_auth uri.user, uri.password
      request.content_type = 'application/json'
      request.body = post_body
      reply = JSON.parse(http.request(request).body)
      raise JSONRPCError, reply['error'] if reply['error']
      Rails.logger.info "LISK <- " + reply.to_json
      return reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def safe_getbalance
      begin
        getbalance
      rescue => ex
        Rails.logger.info  "[error]: " + ex.message + "\n" + ex.backtrace.join("\n") + "\n"
        'N/A'
      end
    end

    def getbalance
      result = http_get_request("#{@rest}/api/accounts/getBalance?address=#{@coin.base_account}")
      balance = result['balance'].to_f / 100000000.0
      return balance
    end

    def gettransaction(txid)
      transaction = http_get_request("#{@rest}/api/transactions/get?id=#{txid}")

      {
        confirmations: transaction['transaction']['confirmations'],
        time: Time.now.to_i,
        details:
        [
          address: transaction['transaction']['recipientId'],
          amount: transaction['transaction']['amount'].to_f / 100000000.0,
          category: "receive"
        ]
      }
    end

    def settxfee
    end

    def sendtoaddress(from, address, amount)
      parameters =
      {
        secret: from,
        amount: Integer(amount * 100000000.0),
        recipientId: address
      }.to_json
      result = http_put_request_body("#{@rest}/api/transactions", parameters)
      return result['transactionId']
    end

    # digest - simple form usermail & number
    def getnewaddress(base_account, digest)
      parameters =
      {
        secret: digest
      }.to_json

      result = http_post_request_body("#{@rest}/api/accounts/open", parameters)
      return result['account']['address']
    end

    def getfee(size)
      return (12000000.0/100000000.0).to_f
    end

    def validateaddress(address)
    end

    def getblockchaininfo

      result = http_get_request("#{@rest}/api/blocks/getStatus")

      {
        blocks: Integer(result['height']),
        headers: 0,
        mediantime: 0
      }
    end
  end

  class CNT < self
    def handle(name, *args)
      post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => args, 'id' => '1' }.to_json
      Rails.logger.info "CNT -> " + post_body
      resp = JSON.parse( http_post_request(post_body) )
      Rails.logger.info "CNT <- " + resp.to_json
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      #result.symbolize_keys! if result.is_a? Hash
      result
    end

    def handle_one(name, arg)
      post_body = {"jsonrpc" => "2.0", 'method' => name, 'params' => arg, 'id' => '1' }.to_json
      Rails.logger.info "CNT -> " + post_body
      resp = JSON.parse( http_post_request(post_body) )
      Rails.logger.info "CNT <- " + resp.to_json
      raise JSONRPCError, resp['error'] if resp['error']
      result = resp['result']
      #result.symbolize_keys! if result.is_a? Hash
      result
    end

    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      #request.basic_auth @uri.user, @uri.password
      request.content_type = 'application/json'
      request.body = post_body
      @reply = http.request(request).body
      return @reply
    rescue Errno::ECONNREFUSED => e
      raise ConnectionRefusedError
    end

    def safe_getbalance
      begin
        getbalance
      rescue => ex
        Rails.logger.info  "[error]: " + ex.message + "\n" + ex.backtrace.join("\n") + "\n"
        'N/A'
      end
    end

    def getbalance
      result = handle("getbalance")
      balance = result['balance'].to_f / 1000000000.0
      return balance
    end

    def gettransaction(txid)
      parameters =
      {
        txid: txid
      }
      transaction = handle_one("get_transfer_by_txid", parameters)
      confirmations = Integer(transaction['transfer']['height'])
      if confirmations > 0
        result = handle("getheight", "")
        confirmations = Integer(result['height']) - confirmations
      end
      result =  {
          confirmations: confirmations,
          time: Time.now.to_i,
          details:[]
        }
      if transaction['transfer']['destinations'] == nil
        return result
      end
      transaction['transfer']['destinations'].each do |destination|
        tx = {
            address: destination['address'],
            amount: destination['amount'].to_f / 1000000000.0,
            category: "receive"
          }
        result[:details].push(tx)
      end
      return result
    end

    def settxfee
    end

    def sendtoaddress(from, address, amount)
      parameters =
      {
        account_index: 0,
        destinations:
        [
          {
            amount: Integer(amount * 1000000000.0),
            address: address
          }
        ],
        get_tx_key: true
      }

      result = handle_one("transfer", parameters)
      return result['tx_hash']
    end

    def getnewaddress(name, digest)
      parameters =
      {
        account_index: 0,
        label: ""
      }.to_json

      result = handle_one("create_address", parameters)
      return result['address']
    end

    def getfee(size)
      return (30000000.0/1000000000.0).to_f
    end

    def validateaddress(address)
    end

    def getblockchaininfo

      result = handle("getheight", "")

      {
        blocks: Integer(result['height']),
        headers: 0,
        mediantime: 0
      }
    end
  end

end


来源: stackexchange

问:
How can I get calculated value with different two column on PostgreSQL + Rails?
here is table

title

post_count

comment_count

I would like to get sum of post_count and comment_count.
What I did is like this, but does not work.

```<code>.select("count(tables.post_count + tables.comment_count) AS field_name").where("field_name >= ?", 3)
</code>```

答:
Try something like this

# Assuming your model is named Table
Table.
  select(:id, 'post_count + comment_count AS field_name').
  where('post_count + comment_count > 3') # Condition you added at the end of your question
```

This would return ActiveRecords with two fields:

the record id

the "field_name" column

But I'm not entirely sure this is what you are looking for.

ContentLicense: CC BY-SA 4.0

Body:
here is table

title

post_count

comment_count

I would like to get sum of post_count and comment_count.
What I did is like this, but does not work.

.select("count(tables.post_count + tables.comment_count) AS field_name").where("field_name >= ?", 3)

Body:
Try something like this

# Assuming your model is named Table
Table.
  select(:id, 'post_count + comment_count AS field_name').
  where('post_count + comment_count > 3') # Condition you added at the end of your question

This would return ActiveRecords with two fields:

the record id

the "field_name" column

But I'm not entirely sure this is what you are looking for.


问:
PHP setting to enable <?=
I just upgraded my WAMP.

A lot of my code used to use <?=$variable?> for a quick echo statement. Does anyone know the php setting to turn this back on?

答:
Just set

```<code>short_open_tag=On
</code>```

in php.ini

Title: PHP setting to enable <?=

Body:
Just set

short_open_tag=On

in php.ini

ContentLicense: CC BY-SA 3.0


问:
Checking all points in a list are inside a rectangle
I've written the below code but for some reason it only works with the first point inside my list:

```<code>def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
    x1, y1 = firstCorner[0], firstCorner[1]
    x2, y2 = secondCorner[0], secondCorner[1]

    for i in range(len(pointList)):
        xa = pointList[i][0]
        ya = pointList[i][1]

        if (xa in range(x1,x2+1)) and (ya in range(y1,y2+1)):
            return True
        elif (xa in range(x2,x1+1)) and (ya in range(y2,y1+1)):
            return True
        else:
            return False
</code>```

This code only works to check the first coordinates inside my list:

```<code>allIn((0,0), (5,5), [(1,1), (0,0), (5,5)])
</code>```

returns True

however

```<code>allIn((0,0), (5,5), [(1,1), (8,0), (5,6)])
</code>```

also returns True

Any suggestions?

答:
You can change your function to:

```<code>def all_in(first_corner=(0,0), second_corner=(0,0), point_list=None):
   point_list = point_list or []
   x1, y1 = first_corner[0], first_corner[1]
   x2, y2 = second_corner[0], second_corner[1]
   return all(p[0] in range(x1,x2+1) and p[1] in range(y1,y2+1) for p in point_list)
</code>```

This avoid checking for any point, and return False as soon as a point is not inside the rectangle.

Body:
I've written the below code but for some reason it only works with the first point inside my list:

def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
    x1, y1 = firstCorner[0], firstCorner[1]
    x2, y2 = secondCorner[0], secondCorner[1]

    for i in range(len(pointList)):
        xa = pointList[i][0]
        ya = pointList[i][1]

        if (xa in range(x1,x2+1)) and (ya in range(y1,y2+1)):
            return True
        elif (xa in range(x2,x1+1)) and (ya in range(y2,y1+1)):
            return True
        else:
            return False

This code only works to check the first coordinates inside my list:

allIn((0,0), (5,5), [(1,1), (0,0), (5,5)])

returns True

however

allIn((0,0), (5,5), [(1,1), (8,0), (5,6)])

also returns True

Any suggestions?

Body:
You can change your function to:

def all_in(first_corner=(0,0), second_corner=(0,0), point_list=None):
   point_list = point_list or []
   x1, y1 = first_corner[0], first_corner[1]
   x2, y2 = second_corner[0], second_corner[1]
   return all(p[0] in range(x1,x2+1) and p[1] in range(y1,y2+1) for p in point_list)

This avoid checking for any point, and return False as soon as a point is not inside the rectangle.


问:
How to hide stack navigation header from a single screen in react-navigation v5
My app has 5 components (screens), I am using stack navigation version 5, I need the headers for all screens except one screen, I tried to do this via option inside screens like this:

This is my code:

```<code>const Stack = createStackNavigator();
const MainStack = () => ({
    return(
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen name="MyTabs" component={MyTabs} />
                <Stack.Screen name="Direct" component={Direct} />
                <Stack.Screen name="Like" component={Like} />
                <Stack.Screen name="Search" component={Search} />
                <Stack.Screen name="Home" component={Home} />
            </Stack.Navigator>
        </NavigationContainer>
    )
)}
</code>```

答: use options={{ headerShown: false }}

Body:
My app has 5 components (screens), I am using stack navigation version 5, I need the headers for all screens except one screen, I tried to do this via option inside screens like this:

This is my code:

const Stack = createStackNavigator();
const MainStack = () => ({
    return(
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen name="MyTabs" component={MyTabs} />
                <Stack.Screen name="Direct" component={Direct} />
                <Stack.Screen name="Like" component={Like} />
                <Stack.Screen name="Search" component={Search} />
                <Stack.Screen name="Home" component={Home} />
            </Stack.Navigator>
        </NavigationContainer>
    )
)}

Body: use options={{ headerShown: false }}


问:
How to fix "E: The list of sources could not be read" could not be read error?
I have added these two lines in etc/apt/sources.list.d/webmin.list

```<code> `deb http://download.webmin.com/download/repository sarge contribdeb`
 `http://download.webmin.com/download/repository sarge contrib`
</code>```

Now, on running the "sudo apt-get update", i am getting the following errors:

```<code> 1. E: Type 'http://download.webmin.com/download/repository' is not known on
    line 2 in source list /etc/apt/sources.list.d/webmin.list.
 2. E: The list of sources could not be read
</code>```

Thanks in advance !!

答:
To rectify this error all you need to do is the following:

1) rm /etc/apt/sources.list

2) nano /etc/apt/sources.list

3) paste the following and save:

```<code>deb http://http.kali.org/kali kali-rolling main non-free contrib
deb-src http://http.kali.org/kali kali-rolling main non-free contrib
deb http://http.kali.org/kali kali-rolling main non-free contrib
</code>```

save the file.

4) sudo apt-get update

If this doesn't work wait for few days and try again as the link might be broken!

Body:
I have added these two lines in etc/apt/sources.list.d/webmin.list

 `deb http://download.webmin.com/download/repository sarge contribdeb`
 `http://download.webmin.com/download/repository sarge contrib`

Now, on running the "sudo apt-get update", i am getting the following errors:

 1. E: Type 'http://download.webmin.com/download/repository' is not known on
    line 2 in source list /etc/apt/sources.list.d/webmin.list.
 2. E: The list of sources could not be read

Thanks in advance !!

Body:
To rectify this error all you need to do is the following:

1) rm /etc/apt/sources.list

2) nano /etc/apt/sources.list

3) paste the following and save:

deb http://http.kali.org/kali kali-rolling main non-free contrib
deb-src http://http.kali.org/kali kali-rolling main non-free contrib
deb http://http.kali.org/kali kali-rolling main non-free contrib

save the file.

4) sudo apt-get update

If this doesn't work wait for few days and try again as the link might be broken!


问:
F# templating engine similar to, say, mako?
Does one exist?

The closest I've found is - https://github.com/Antaris/RazorEngine ; but I'm not overjoyed by it (in particular, I can't get it to work.)

答:
In addition to those mentioned by Patryk Ćwiek, I'd look at Fue.

Here's a basic template in Fue:

```<code>let html = "<div>{{{name}}}</div>"
let compiledHtml = init |> add "name" "Roman" |> fromText html
// compiledHtml now contains "<div>Roman</div>"
</code>```

Fue is written in F# and has support for F# types such as options and Discriminated unions:

```<code><!--Option types-->
<div fs-if="someOption.IsSome">{{{someOption.Value}}}</div>
<div fs-if="someOption.IsNone">Nothing</div>

<!--Discriminated Union
type UserAccess =
    | Anonymous
    | Admin of section:string
-->
    <div fs-du="item" fs-case="Anonymous">Anonymous</div>
    <div fs-du="item" fs-case="Admin(section)">{{{section}}}</div>
</code>```

Fue on Github

Fue on Nuget

Body:
In addition to those mentioned by Patryk Ćwiek, I'd look at Fue.

Here's a basic template in Fue:

let html = "<div>{{{name}}}</div>"
let compiledHtml = init |> add "name" "Roman" |> fromText html
// compiledHtml now contains "<div>Roman</div>"

Fue is written in F# and has support for F# types such as options and Discriminated unions:

<!--Option types-->
<div fs-if="someOption.IsSome">{{{someOption.Value}}}</div>
<div fs-if="someOption.IsNone">Nothing</div>

<!--Discriminated Union
type UserAccess =
    | Anonymous
    | Admin of section:string
-->
    <div fs-du="item" fs-case="Anonymous">Anonymous</div>
    <div fs-du="item" fs-case="Admin(section)">{{{section}}}</div>

Fue on Github

Fue on Nuget


问:
Read multiple excel files from a folder into pandas
I would like to read several excel files contained into a folder in the Desktop of my MacBook into pandas.

The folder in the desktop is contains a folder (project dataset) with all the excel files and the Jupiter notebook page where I am writing the code (draft progetto)

I wrote the following code:

```<code>path = os.getcwd()
files = os.listdir(path)
files
</code>```

Output:

```<code>['.DS_Store', 'draft progetto.ipynb', '.ipynb_checkpoints', 'project_dataset']
</code>```

Then when I run:

```<code>files_xls = [f for f in files if f[3:] == 'xlsx']
files_xls
</code>```

I GET AN EMPTY LIST AS OUTPUT!!
WHY IS THIS?

答:
IIUC,

this is something that can be done much easier with pathlib and unix matching using the glob module.

```<code>from pathlib import Path
import pandas as pd

#one liner
your_path = 'path_to_excel_files'
df = pd.concat([pd.read_excel(f) for f in Path(your_path).rglob('*.xlsx')])
</code>```

Breaking it down.

```<code># find the excel files
# if you want to change the path do Path('your_path')...
files = [file for file in Path.cwd.rglob('*.xlsx')]

#create a list of dataframes.
dfs_list = [pd.read_excel(file) for file in files])

#concat
df = pd.concat(dfs_list)
</code>```

Body:
I would like to read several excel files contained into a folder in the Desktop of my MacBook into pandas.

The folder in the desktop is contains a folder (project dataset) with all the excel files and the Jupiter notebook page where I am writing the code (draft progetto)

I wrote the following code:

path = os.getcwd()
files = os.listdir(path)
files

Output:

['.DS_Store', 'draft progetto.ipynb', '.ipynb_checkpoints', 'project_dataset']

Then when I run:

files_xls = [f for f in files if f[3:] == 'xlsx']
files_xls

I GET AN EMPTY LIST AS OUTPUT!!
WHY IS THIS?

Body:
IIUC,

this is something that can be done much easier with pathlib and unix matching using the glob module.

from pathlib import Path
import pandas as pd

#one liner
your_path = 'path_to_excel_files'
df = pd.concat([pd.read_excel(f) for f in Path(your_path).rglob('*.xlsx')])

Breaking it down.

# find the excel files
# if you want to change the path do Path('your_path')...
files = [file for file in Path.cwd.rglob('*.xlsx')]

#create a list of dataframes.
dfs_list = [pd.read_excel(file) for file in files])

#concat
df = pd.concat(dfs_list)


问:
the counter of for of loop in javascript
I am studying javascript, and learning for loop. I am sure it's basic part but I can't get how the counter variable works..

I am making the battle application, and this is the function that is executed when user clicks the battle log, then it will show the last log and the index of it in console.log.

The battle log in the function is the array that stores nested arrays of users input.

```<code>let lastLoggedEntry;

function printLogHandler() {

  let i = 0;

  for (const logEntry of battleLog) {
    if ((!lastLoggedEntry && lastLoggedEntry !== 0) || lastLoggedEntry < i) {
      console.log(`#${i}`);
      for (const key in logEntry) {
        console.log(`${key} => ${logEntry[key]}`);
      }
      lastLoggedEntry = i;
      break;
    }

    i++;
  }
}
</code>```

My question is the initial valuable is set in outside of the for loop(i = 0). but when the user clicks the battle log again, and this function executes again, how for loops has been saving the data of last i and logEntry's value? ( second time when user clisks, it will be i = 1, and logEntry = 0 already)

Also, how can it skip "let i = 0" from second time? because its not only for loop, it executes the function, I thought javascript reads let i = 0 again and it will reset to 0. ( it won't of course but I want to understand why)

Hopefully, you guys could help me out. Thank you,

答:
A few things:

There is missing closure in the sample provided. There should be another closing bracket for the code to validate.

lastLoggedEntry must be defined as a variable before it is used.

It is not clear what the contents of battleLog are.

I think if you clarify these things it may be easier to answer your question.

Body:
I am studying javascript, and learning for loop. I am sure it's basic part but I can't get how the counter variable works..

I am making the battle application, and this is the function that is executed when user clicks the battle log, then it will show the last log and the index of it in console.log.

The battle log in the function is the array that stores nested arrays of users input.

let lastLoggedEntry;

function printLogHandler() {

  let i = 0;

  for (const logEntry of battleLog) {
    if ((!lastLoggedEntry && lastLoggedEntry !== 0) || lastLoggedEntry < i) {
      console.log(`#${i}`);
      for (const key in logEntry) {
        console.log(`${key} => ${logEntry[key]}`);
      }
      lastLoggedEntry = i;
      break;
    }

    i++;
  }
}

My question is the initial valuable is set in outside of the for loop(i = 0). but when the user clicks the battle log again, and this function executes again, how for loops has been saving the data of last i and logEntry's value? ( second time when user clisks, it will be i = 1, and logEntry = 0 already)

Also, how can it skip "let i = 0" from second time? because its not only for loop, it executes the function, I thought javascript reads let i = 0 again and it will reset to 0. ( it won't of course but I want to understand why)

Hopefully, you guys could help me out. Thank you,


问:
Scroll algorithm -- improving fetch and display of data
I would like to set out somewhat of a theoretical problem.

Suppose that I have an infinite scroll, implemented something like as described here: https://medium.com/frontend-journeys/how-virtual-infinite-scrolling-works-239f7ee5aa58. There's nothing fancy to it, suffice it to say that it is a table of data, say NxN, and the user can scroll down and to the right, like a spreadsheet, and it will only show the data in the current view plus minus a handle.

Now, let's also say that it takes approximately 10ms to "fetch and display" the data in that view, with a function such as:

```<code>get_data(start_col, end_col, start_row, end_row);
</code>```

This loads instantly when clicking somewhere in the scroll bar or doing a 'slight scroll' to render the necessary data. However, let's also assume that for every 'unfinished fetch event', that it takes double the time to render the necessary view data (due to memory, gc, and a few other things). So, if I scroll from left-to-right in a slow deliberate fashion, I might generate   100+ scroll events that would trigger the loading of data -- at first there's zero noticeably delay. The fetch happens in under 10ms, but soon it starts taking 20ms, and then 40ms, and now we have something like a noticeable delay, until it will reach over a second to load the necessary data. Additionally, we cannot use something like a debounce/delay, as any delay will be apparent -- the data needs to load instantly when a user clicks/scrolls to a place in the grid.

What considerations would I need to take into account and what would a sample algorithm look like to accomplish this? Here is an example of the user interaction I'd like to have on the data, assuming a 10000 x 10000 spreadsheet (though Excel can load all the data at once) -- https://gyazo.com/0772f941f43f9d14f884b7afeac9f414.

答:
I think you should not send a request at any scroll event. only if by this scroll the user reach the end of the scroll.

```<code>if(e.target.scrollHeight - e.target.offsetHeight === 0) {
    // the element reach the end of vertical scroll
}
if(e.target.scrollWidth - e.target.offsetWidth === 0) {
   // the element reach the end of horizontal scroll
}
</code>```

You also can specify a width which will defined as close enough for fetch a new data (e.i. e.target.scrollHeight - e.target.offsetHeight <= 150)

Body:
I would like to set out somewhat of a theoretical problem.

Suppose that I have an infinite scroll, implemented something like as described here: https://medium.com/frontend-journeys/how-virtual-infinite-scrolling-works-239f7ee5aa58. There's nothing fancy to it, suffice it to say that it is a table of data, say NxN, and the user can scroll down and to the right, like a spreadsheet, and it will only show the data in the current view plus minus a handle.

Now, let's also say that it takes approximately 10ms to "fetch and display" the data in that view, with a function such as:

get_data(start_col, end_col, start_row, end_row);

This loads instantly when clicking somewhere in the scroll bar or doing a 'slight scroll' to render the necessary data. However, let's also assume that for every 'unfinished fetch event', that it takes double the time to render the necessary view data (due to memory, gc, and a few other things). So, if I scroll from left-to-right in a slow deliberate fashion, I might generate   100+ scroll events that would trigger the loading of data -- at first there's zero noticeably delay. The fetch happens in under 10ms, but soon it starts taking 20ms, and then 40ms, and now we have something like a noticeable delay, until it will reach over a second to load the necessary data. Additionally, we cannot use something like a debounce/delay, as any delay will be apparent -- the data needs to load instantly when a user clicks/scrolls to a place in the grid.

What considerations would I need to take into account and what would a sample algorithm look like to accomplish this? Here is an example of the user interaction I'd like to have on the data, assuming a 10000 x 10000 spreadsheet (though Excel can load all the data at once) -- https://gyazo.com/0772f941f43f9d14f884b7afeac9f414.

Body:
I think you should not send a request at any scroll event. only if by this scroll the user reach the end of the scroll.

if(e.target.scrollHeight - e.target.offsetHeight === 0) {
    // the element reach the end of vertical scroll
}
if(e.target.scrollWidth - e.target.offsetWidth === 0) {
   // the element reach the end of horizontal scroll
}

You also can specify a width which will defined as close enough for fetch a new data (e.i. e.target.scrollHeight - e.target.offsetHeight <= 150)


问:
How to find better algorithm for my prefix matcher algorithm
I was solving online problem and the task was something like this:

There are two arrays: numbers and prefixes.

Array numbers contains numbers: “+432112345”, “+9990”, “+4450505”

Array prefixes contains prefixes: “+4321”, “+43211”, “+7700”, “+4452”, “+4”

Find longest prefix for each number. If no prefix found for number, match with empty string.

For example:

“+432112345” matches with the longest prefix “+43211” (not +4321, cause 43211 is longer).

“+9990” doesn't match with anything, so empty string "".

“+4450505” matches with “+4”  (“+4452” doesn’t match because of the 2).

I came up with the most straight forward solution where I loop through each number with each prefix. So each time new number, I check prefixes, if some prefix is longer than last one, I will change.

Map<String, String> numsAndPrefixes = new HashMap<>();

for (String number : A) {
    for (String prefix : B) {
        if (number.contains(prefix)) {
            // if map already contains this number, check for prefixes.
            // if longer exists, switch longer one
            if (numsAndPrefixes.containsKey(number)) {
                int prefixLength = prefix.length();
                int currentLen = numsAndPrefixes.get(number).length();
                if (prefixLength > currentLen) {
                    numsAndPrefixes.put(number, prefix);
                }
            } else {
                numsAndPrefixes.put(number, prefix);
            }
        } else if (!number.contains(prefix) && !numsAndPrefixes.containsKey(number)){
            numsAndPrefixes.put(number, "");
        }
    }
}
```

So it will have two for loops. I see that each time I am doing the same job over and over, e.g checking for prefixes. It works, but it is slow.  The problem is that I can’t come up with anything better.

Could someone explain how they would approach to find better algorithm?

And more general, how do you proceed if you have somewhat working solution and trying to find better one? What knowledge am I still missing?

答:
The data structure you need is trie.

Add all prefixes in trie

For each string S in numbers:

Start from the root of trie

For each character in S:

If there is a link from current node, associated with current character, go by this link to the next node

If there is no link, then you reached the longest prefix - prefix stored in the current node is the answer for S

This algorithm works in O(length(prefixes) + length(numbers))

Body:
I was solving online problem and the task was something like this:

There are two arrays: numbers and prefixes.

Array numbers contains numbers: “+432112345”, “+9990”, “+4450505”

Array prefixes contains prefixes: “+4321”, “+43211”, “+7700”, “+4452”, “+4”

Find longest prefix for each number. If no prefix found for number, match with empty string.

For example:

“+432112345” matches with the longest prefix “+43211” (not +4321, cause 43211 is longer).

“+9990” doesn't match with anything, so empty string "".

“+4450505” matches with “+4”  (“+4452” doesn’t match because of the 2).

I came up with the most straight forward solution where I loop through each number with each prefix. So each time new number, I check prefixes, if some prefix is longer than last one, I will change.

Map<String, String> numsAndPrefixes = new HashMap<>();

for (String number : A) {
    for (String prefix : B) {
        if (number.contains(prefix)) {
            // if map already contains this number, check for prefixes.
            // if longer exists, switch longer one
            if (numsAndPrefixes.containsKey(number)) {
                int prefixLength = prefix.length();
                int currentLen = numsAndPrefixes.get(number).length();
                if (prefixLength > currentLen) {
                    numsAndPrefixes.put(number, prefix);
                }
            } else {
                numsAndPrefixes.put(number, prefix);
            }
        } else if (!number.contains(prefix) && !numsAndPrefixes.containsKey(number)){
            numsAndPrefixes.put(number, "");
        }
    }
}

So it will have two for loops. I see that each time I am doing the same job over and over, e.g checking for prefixes. It works, but it is slow.  The problem is that I can’t come up with anything better.

Could someone explain how they would approach to find better algorithm?

And more general, how do you proceed if you have somewhat working solution and trying to find better one? What knowledge am I still missing?


问:
Run first request multiple times and other request single time in a single thread
I Have 5 HTTP request in single thread, I want to run first request multiple times and then other request only single time

I can't use multiple thread as all request are depends on each other.

答:
Put first request under Loop Controller with Loop Count as the times you want to repeat

JMeter will loop through them a certain number of times, in addition to the loop value you specified for the Thread Group. For example, if you add one HTTP Request to a Loop Controller with a loop count of two, and configure the Thread Group loop count to three, JMeter will send a total of 2 * 3 = 6 HTTP Requests.

Choose request(s) you want to execute multiple times and then:

Right Click -> Insert Parent -> Logic Controller -> Loop Controller


答: Set your short_open_tag to 1 inside your php.ini</p>

Title: PHP setting to enable <?=

Body:
I just upgraded my WAMP.

A lot of my code used to use <?=$variable?> for a quick echo statement. Does anyone know the php setting to turn this back on?


问:
C Program Printing Wrong Message | Logical Operator Problem?
I am new to coding in C and trying to write a program that prints the message 'You may enter' if your age is 15 or over, and your gender is equal to male. Kindly see what I've got below. When you enter your age as 15 or over and your gender as male, the program prints the wrong message. I think it could be a problem with my logical operators but I can't quite figure out why. Could you assist?</p>

```<code>#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int age;
    char gen;

    printf("How old are you?\n");
    scanf("%d", &age);

    printf("What is your gender? (m/f) \n");
    scanf("%s", &gen);

    if(age >= 15 && gen == 'm')
    {
         write(1, "You man enter\n", 15);
    }

    if(age < 14 || gen == 'f')
    {
        write(1, "No entry\n", 9);
    }

    return 0;
}
</code>```

答:
Change this:

```<code>scanf("%s", &gen);
</code>```

to this:

```<code>scanf(" %c", &gen);
</code>```

since gen is a character, not a string.

Note the space I left before the format specifier for characters, which is there to inform the method to automatically eat whitespaces and special characters (remove it and see what happens). For more, ready my initial reaction to this Caution when reading char with scanf (C).

Body:
I am new to coding in C and trying to write a program that prints the message 'You may enter' if your age is 15 or over, and your gender is equal to male. Kindly see what I've got below. When you enter your age as 15 or over and your gender as male, the program prints the wrong message. I think it could be a problem with my logical operators but I can't quite figure out why. Could you assist?

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int age;
    char gen;

    printf("How old are you?\n");
    scanf("%d", &age);

    printf("What is your gender? (m/f) \n");
    scanf("%s", &gen);

    if(age >= 15 && gen == 'm')
    {
         write(1, "You man enter\n", 15);
    }

    if(age < 14 || gen == 'f')
    {
        write(1, "No entry\n", 9);
    }

    return 0;
}

Body:
Change this:

scanf("%s", &gen);

to this:

scanf(" %c", &gen);

since gen is a character, not a string.

Note the space I left before the format specifier for characters, which is there to inform the method to automatically eat whitespaces and special characters (remove it and see what happens). For more, ready my initial reaction to this Caution when reading char with scanf (C).


问:
Get func placeholder values from a snippet to appear after hitting tab at top level code level
New to swift and xcode, version 11.3.1.

If I hit func<tab> in a class, the placeholder values pop in nicely and I can tab through them to complete them.

However, when I have a simple playground file open and hit func<tab> I don't see any placeholder values. Just the keyword func appears.

How do I turn on these placeholder values for top-level functions?

答:
I'm not sure if there is a better answer but here is what worked to get the func snippet to show up while editing a "playground" file:

1) Edit snippets file with: sudo vim /Applications/Xcode.app/Contents/PlugIns/IDESourceEditor.framework/Versions/A/Resources/SystemCodeSnippets.codesnippets

2) Search for snippet and find the related scope key and modify the array of the scope key to <string>All</string>:

```<code>        <key>IDECodeSnippetCompletionScopes</key>
        <array>
            <string>All</string>
        </array>
</code>```

Yes, I could create my own snippet which is the same as the built-in snippet but then I have two different snippets that do the same thing, which I found annoying.

Body:
I'm not sure if there is a better answer but here is what worked to get the func snippet to show up while editing a "playground" file:

1) Edit snippets file with: sudo vim /Applications/Xcode.app/Contents/PlugIns/IDESourceEditor.framework/Versions/A/Resources/SystemCodeSnippets.codesnippets

2) Search for snippet and find the related scope key and modify the array of the scope key to <string>All</string>:

        <key>IDECodeSnippetCompletionScopes</key>
        <array>
            <string>All</string>
        </array>

Yes, I could create my own snippet which is the same as the built-in snippet but then I have two different snippets that do the same thing, which I found annoying.


问:
VB.Net there's an Exception Unhandled when I clear out PriceTxt just because the DiscountTxt doesn't get the value
My problem here is that whenever I put a Value Price on the PriceTxt the DiscountTxt will compute for its discount but when I clear out the PriceTxt it gets an Exception saying "Conversion from String "" to type 'Double' is not valid". I tried getting the logical if statement that if the PriceTxt.Text = "" The DiscountTxt will set back to 0 which means no value to be computed.

```<code> Dim percentage As Decimal = 0.1
    If PriceTxt.MaxLength > 11 Then
        DiscountTxt.Text = (PriceTxt.Text * percentage)
        DiscountTxt.Text = PriceTxt.Text - DiscountTxt.Text
    End If

    If PriceTxt.Text = "" Then
        DiscountTxt.ResetText()
    End If
</code>```

Nah couldn't think of Else if and Else on it since it doesn't work either.

答:
I believe you're looking at MaxLength instead of Length here.

Here's another way to do that, using TryParse.  It returns True IF it was able to squeeze the value into the target.  Please see prc as the first.

```<code> Dim percentage As Decimal = 0.1
 Dim prc as Decimal

    If decimal.TryParse(PriceTxt.Text, prc) then 'puts it in a double, if it is.
        DiscountTxt.Text = (prc * percentage)
        Dim discount as Decimal
        If decimal.TryParse(DiscountTxt.Text, discount) Then
           DiscountTxt.Text = prc - discount 'Or is this a total box?
        End If

    End If

    If PriceTxt.Text = "" Then
        DiscountTxt.ResetText()
    End If
</code>```

Body:
My problem here is that whenever I put a Value Price on the PriceTxt the DiscountTxt will compute for its discount but when I clear out the PriceTxt it gets an Exception saying "Conversion from String "" to type 'Double' is not valid". I tried getting the logical if statement that if the PriceTxt.Text = "" The DiscountTxt will set back to 0 which means no value to be computed.

 Dim percentage As Decimal = 0.1
    If PriceTxt.MaxLength > 11 Then
        DiscountTxt.Text = (PriceTxt.Text * percentage)
        DiscountTxt.Text = PriceTxt.Text - DiscountTxt.Text
    End If

    If PriceTxt.Text = "" Then
        DiscountTxt.ResetText()
    End If

Nah couldn't think of Else if and Else on it since it doesn't work either.

Body:
I believe you're looking at MaxLength instead of Length here.

Here's another way to do that, using TryParse.  It returns True IF it was able to squeeze the value into the target.  Please see prc as the first.

 Dim percentage As Decimal = 0.1
 Dim prc as Decimal

    If decimal.TryParse(PriceTxt.Text, prc) then 'puts it in a double, if it is.
        DiscountTxt.Text = (prc * percentage)
        Dim discount as Decimal
        If decimal.TryParse(DiscountTxt.Text, discount) Then
           DiscountTxt.Text = prc - discount 'Or is this a total box?
        End If

    End If

    If PriceTxt.Text = "" Then
        DiscountTxt.ResetText()
    End If


问:
Return path location for File in Javascript/HTML
Yes, I am trying to drag and drop a file into my browser. I would like to then take the path for that file, and assign it to some variable in my JS code.

Below is my failing attempt to make it work. Please show me some example to achieve this.

```<code><body>

<script>
function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    output = [];
    var source = evt.dataTransfer.files();
    for (i=0, f; f=source[i], i++){
        outpush.push(source[i])
    }
    console.log(outpush[0]);
}

window.addEventListener("dragover",function(e){
  e = e || event;
  e.preventDefault();
},false);

window.addEventListener("drop",function(e){
  e = e || event;
  e.preventDefault();
  handleFileSelect(e);
},false);
</script>

</body>
</html>
</code>```

答:
Issues

evt.dataTransfer.files() is not a function. It should be replaced with evt.dataTransfer.items.

Your for loop is invalid, it should be changed from

```<code>for (i=0, f; f=source[i], i++){
    outpush.push(source[i])
}
</code>```

...to...

```<code>for (i=0; i < evt.dataTransfer.items.length; i++){
    output.push(source[i]);
}
</code>```

The part inside the brackets of the for loop is invalid.

You are trying to add the file to outpush, which does not exist. You should be adding the file to the array output, which you did create.

You can not get the path of the file, as JavaScript has no access to the host computer (for security reasons). You can still manage the file though using source[index].getAsFile().

Corrected code

I have provided a jsfiddle.

```

Body:
Issues

evt.dataTransfer.files() is not a function. It should be replaced with evt.dataTransfer.items.

Your for loop is invalid, it should be changed from

for (i=0, f; f=source[i], i++){
    outpush.push(source[i])
}

...to...

for (i=0; i < evt.dataTransfer.items.length; i++){
    output.push(source[i]);
}

The part inside the brackets of the for loop is invalid.

You are trying to add the file to outpush, which does not exist. You should be adding the file to the array output, which you did create.

You can not get the path of the file, as JavaScript has no access to the host computer (for security reasons). You can still manage the file though using source[index].getAsFile().

Corrected code

I have provided a jsfiddle.

<html>

<body>

  <script>
    function handleFileSelect(evt) {
      evt.stopPropagation();
      evt.preventDefault();
      output = [];
      var source = evt.dataTransfer.items;
      for (i = 0; i < evt.dataTransfer.items.length; i++) {
        output.push(source[i]);
      }
      console.log(output[0]);
    }

    window.addEventListener("dragover", function(e) {
      e = e || event;
      e.preventDefault();
    }, false);

    window.addEventListener("drop", function(e) {
      e = e || event;
      e.preventDefault();
      handleFileSelect(e);
    }, false);
  </script>

</body>

</html>


问:
Find maximum value of a column and return the corresponding row values using Pandas

Using Python Pandas I am trying to find the Country & Place with the maximum value.

This returns the maximum value:

```<code>data.groupby(['Country','Place'])['Value'].max()
</code>```

But how do I get the corresponding Country and Place name?

答:
You can use:</p>
```<code>print(df[df['Value']==df['Value'].max()])
</code>```

Body:
Using Python Pandas I am trying to find the Country & Place with the maximum value.

This returns the maximum value:

data.groupby(['Country','Place'])['Value'].max()

But how do I get the corresponding Country and Place name?

Body:
You can use:

print(df[df['Value']==df['Value'].max()])


问:
Corona SDK. Lua. display.newText() - my updated score text is overlapping old one without erasing
I'm developing clone version of Nintendo Tetris game using Corona SDK. There are two text objects on the top of my screen: one represents current level, another one represents current score. Every time I fill in line with blocks my program erases this line and add some scores and +1 level. The problem is that once I update my score and level variables and use myText.text to refresh my texts it doesn't erase old text and creates the new text that overlapping the old one.

My code is following:
1) I declare two local variables at the begging of my scene

```<code>local scoreText
local levelText
</code>```

2) I have function that erases the line and updates texts

```<code>function eraseLines()
            -- some code that erases lines
            scores = scores + 10
            scoreText.text = "Score:"..scores
            level = level + 1
            levelText.text = "Level:"..level
end
</code>```

3) In scene:show(event) I create our texts

```<code>function scene:show( event )
    -- some code
    scoreText = display.newText("Score:"..scores, halfW*0.5, 20 )
    levelText = display.newText("Level:".. level, halfW*1.5, 20 )
    sceneGroup:insert( scoreText )
    sceneGroup:insert( levelText )
    scoreText:setFillColor( 0, 0, 0 )
    levelText:setFillColor( 0, 0, 0 )
end
</code>```

Please help me to find out why overlapping happens

答:
Here's a poorly constructed single script for displaying score

```<code>    local scoreCounter = {}
    local frameTime = 0
    scoreCount = 0
    finalScore = nil
    local tempText = nil

    local function update( event )
         frameTime = frameTime + 1

         --after every 7 frames score will increase
         if(frameTime % 7 == 0) then
            scoreCount = scoreCount + 1
            tempText.text = scoreCount
            frameTime = 0
         end
    end

    -- here is a memory leak I guess
    function scoreCounter.displayScore(xCoordinate, yCoordinate)
        tempText = display.newText(scoreCount, xCoordinate, yCoordinate)
    end

    Runtime:addEventListener("enterFrame", update)

    return scoreCounter
</code>```

Usage:

```<code>local scoreCounter = require("pathtoluafile")
scoreCounter.displayScore(xCoordinate, yCoordinate)
</code>```

Body:
I'm developing clone version of Nintendo Tetris game using Corona SDK. There are two text objects on the top of my screen: one represents current level, another one represents current score. Every time I fill in line with blocks my program erases this line and add some scores and +1 level. The problem is that once I update my score and level variables and use myText.text to refresh my texts it doesn't erase old text and creates the new text that overlapping the old one.

My code is following:
1) I declare two local variables at the begging of my scene

local scoreText
local levelText

2) I have function that erases the line and updates texts

function eraseLines()
            -- some code that erases lines
            scores = scores + 10
            scoreText.text = "Score:"..scores
            level = level + 1
            levelText.text = "Level:"..level
end

3) In scene:show(event) I create our texts

function scene:show( event )
    -- some code
    scoreText = display.newText("Score:"..scores, halfW*0.5, 20 )
    levelText = display.newText("Level:".. level, halfW*1.5, 20 )
    sceneGroup:insert( scoreText )
    sceneGroup:insert( levelText )
    scoreText:setFillColor( 0, 0, 0 )
    levelText:setFillColor( 0, 0, 0 )
end

Please help me to find out why overlapping happens

Body:
Here's a poorly constructed single script for displaying score

    local scoreCounter = {}
    local frameTime = 0
    scoreCount = 0
    finalScore = nil
    local tempText = nil

    local function update( event )
         frameTime = frameTime + 1

         --after every 7 frames score will increase
         if(frameTime % 7 == 0) then
            scoreCount = scoreCount + 1
            tempText.text = scoreCount
            frameTime = 0
         end
    end

    -- here is a memory leak I guess
    function scoreCounter.displayScore(xCoordinate, yCoordinate)
        tempText = display.newText(scoreCount, xCoordinate, yCoordinate)
    end

    Runtime:addEventListener("enterFrame", update)

    return scoreCounter

Usage:

local scoreCounter = require("pathtoluafile")
scoreCounter.displayScore(xCoordinate, yCoordinate)


问:
Does this algorithm have time and space complexity O(n) or O(1)?

Update:
  - Wikipedia says o(n) not O(n) so this algorithm isn't an in-place solution.
  - Debating whether this solution runs in O(n) or O(1).

This is my solution for LeetCode question Flatten Binary Tree to Linked List. In terms of time and space complexity analysis, I'm not quite sure it's O(1) according to some explanations. I think it's O(n) because of the use of the stack. Is my analysis correct?

According to Wikipedia, O(n) is still accepted as in-place.

More broadly, in-place means that the algorithm does not use extra space for manipulating the input but may require a small though nonconstant extra space for its operation. Usually, this space is O(log n), though sometimes anything in o(n) is allowed.

/**
 * Function flattens a binary tree.
 * Time = O(n) because we iterate through all nodes.
 * Space = O(n) because we use a stack.
 * @param {root} root Input tree.
 */
var flatten = function(root) {
    // If reach end of leaf node, return.
    if (root === null) return;

    let stack = [];
    let currentNode = root;

    while (true) {
        // Push right branch to stack first,
        if (currentNode.right) stack.push(currentNode.right);
        // then left branch.
        if (currentNode.left) stack.push(currentNode.left);
        // If there are branches in stack:
        if (stack.length > 0) {
            // Change the current currentNode right branch to the last element of the stack:
            currentNode.right = stack.pop();
            // Change left branch to null
            currentNode.left = null;
            // Advance by changing current currentNode to the right currentNode.
            currentNode = currentNode.right;
        }
        else break;
    }
}
```

答:
Yes, the algorithm uses Theta(N) worst-case time and worst-case additional space where N is the number of nodes in the tree. The time complexity is is clear, because you push and pop each node once.

The space complexity is a bit more tricky, but consider for example a tree that is a list where the next elements of the list are the left children, but assume it has additionally for each of these list nodes one right child which itself does not have any children.

With that example your algorithm will walk through the left-hand nodes, adding the right-hand ones to the stack, but only popping those once the end of the original list is reached, i.e. there will be about N/2 elements in the stack.

Best-case, the time complexity is still Theta(N), because you always iterate over all nodes, but the best-case space complexity is Theta(1), because e.g. a tree that is already a list will never increase the stack size to more than 1.

This would usually not be considered an in-place algorithm, because it uses additional Theta(N) space, at least worst-case. As explained in the Wikipedia article, an in-place algorithm should require o(N) additional space or, I would say, usually only O(1) or slightly more than that, e.g. O((ln N)^k) for some k maximum. Whether one should count worst-case or average-case is another question.

o(N) is the little-o notation, not the big-O notation. It means the the time/space is asymptotically smaller than c*N for every c > 0. Theta(N) is therefore never o(N).

Also, Theta(N) means that not only is it O(N), meaning asymptotically smaller then c*N for some c > 0, but also that it is asymptotically larger than c*N for some c.

If you want an in-place algorithm by the stricter definition, you should not require any additional container of dynamic size.


问:
How do I subscript a boolean function in a data frame in Python?
I have dataframe that looks like this:

```<code>    key             Candidate   Position duplicates
0   0-39-1  SHRI. BISHNU PADA RAY    1    False
1   0-39-1  SHRI. KULDEEP RAI SHARMA 2    False
2   0-39-1  SHRI TAPAN KUMAR BEPARI  3    False
3   0-39-1  SHRI. P. R. GANESHAN     4    False
4   0-39-1  SMTI. R. S. UMA BHARATTH 5    True
</code>```

I want to have a value 1 if the duplicate value is True and 0 if it is False. There are only these 2 values that this column has. I read a lot of answers for this and have already tried out the following:

df["duplicates"] = int(df["duplicates"]==True)
df["flag_numeric"][df["duplicates"]==True] = 1

And several other trivial solutions but each time I get the following error:
'bool' object is not subscriptable

Since I am new to python, can someone please help me find the right answer?

答:
Something like this:</p>

```<code>df["duplicates"] = df.duplicates.map(int)
</code>```

Body:
I have dataframe that looks like this:

    key             Candidate   Position duplicates
0   0-39-1  SHRI. BISHNU PADA RAY    1    False
1   0-39-1  SHRI. KULDEEP RAI SHARMA 2    False
2   0-39-1  SHRI TAPAN KUMAR BEPARI  3    False
3   0-39-1  SHRI. P. R. GANESHAN     4    False
4   0-39-1  SMTI. R. S. UMA BHARATTH 5    True

I want to have a value 1 if the duplicate value is True and 0 if it is False. There are only these 2 values that this column has. I read a lot of answers for this and have already tried out the following:

df["duplicates"] = int(df["duplicates"]==True)
df["flag_numeric"][df["duplicates"]==True] = 1

And several other trivial solutions but each time I get the following error:
'bool' object is not subscriptable

Since I am new to python, can someone please help me find the right answer?

Body:
Something like this:

df["duplicates"] = df.duplicates.map(int)


问:
Unable to start Node JS service using node-windows
I have installed node-windows module and created windows service using below script. It has created  a windows service , however, it is not starting and throwing below error

Script to create service

```<code> var Service = require('node-windows').Service;

    // Create a new service object
    var svc = new Service({
      name:'Node HtmlToPDF',
      description: 'Node JS Application which converts Html String to PDF',
      script: 'C:\\Users\\Dell\\eclipse-workspace\\HtmlToPDF\app.js',
      wait: 2,
      grow: .5
    });

    // Listen for the "install" event, which indicates the
    // process is available as a service.
    svc.on('install',function(){
      svc.start();
    });

    svc.install();
</code>```

Below is the message it throws when i try to start and it never starts. Is there any other configuration needs to be done? I have tried to start with SC START and also with NET START but didn't work

```<code>C:\WINDOWS\system32>sc start nodehtmltopdf.exe

SERVICE_NAME: nodehtmltopdf.exe
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 2  START_PENDING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x7d0
        PID                : 17888
        FLAGS              :

C:\WINDOWS\system32>net start nodehtmltopdf.exe
The Node HtmlToPDF service is starting.
The Node HtmlToPDF service was started successfully.
</code>```

答:
It was my mistake and after updating the path as below, it worked. Missed one slash on last.</p>

```<code>script: 'C:\\Users\\Dell\\eclipse-workspace\\HtmlToPDF\\app.js'
</code>```

Body:
I have installed node-windows module and created windows service using below script. It has created  a windows service , however, it is not starting and throwing below error

Script to create service

 var Service = require('node-windows').Service;

    // Create a new service object
    var svc = new Service({
      name:'Node HtmlToPDF',
      description: 'Node JS Application which converts Html String to PDF',
      script: 'C:\\Users\\Dell\\eclipse-workspace\\HtmlToPDF\app.js',
      wait: 2,
      grow: .5
    });

    // Listen for the "install" event, which indicates the
    // process is available as a service.
    svc.on('install',function(){
      svc.start();
    });

    svc.install();

Below is the message it throws when i try to start and it never starts. Is there any other configuration needs to be done? I have tried to start with SC START and also with NET START but didn't work

C:\WINDOWS\system32>sc start nodehtmltopdf.exe

SERVICE_NAME: nodehtmltopdf.exe
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 2  START_PENDING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x7d0
        PID                : 17888
        FLAGS              :

C:\WINDOWS\system32>net start nodehtmltopdf.exe
The Node HtmlToPDF service is starting.
The Node HtmlToPDF service was started successfully.

Body:
It was my mistake and after updating the path as below, it worked. Missed one slash on last.

script: 'C:\\Users\\Dell\\eclipse-workspace\\HtmlToPDF\\app.js'


答:
Converting boolean to 0 and 1 can be accomplished by casting to int. Use astype method for this:

```<code>df['duplicates'].astype(int)
</code>```

Title: How do I subscript a boolean function in a data frame in Python?

Body:
Converting boolean to 0 and 1 can be accomplished by casting to int. Use astype method for this:

df['duplicates'].astype(int)


答:
[df["duplicates"]==True] = 1

Double equal-sign == outside the bracket is also required, make it like: df[df['column_name'] == value] == 1

So in your case it would be:

if df[df['duplicates'] == True]: #the double square brackets are important
    return 1
else
    return 0
```

Hope this helps!

Body:
[df["duplicates"]==True] = 1

Double equal-sign == outside the bracket is also required, make it like: df[df['column_name'] == value] == 1

So in your case it would be:

if df[df['duplicates'] == True]: #the double square brackets are important
    return 1
else
    return 0

Hope this helps!


问:
Javascript : How can I put this data in better way ? (string to array/object)
I have a string that could look like this :

```<code>str = "4bobsCat3carsOfThisGarage10this1that0whatever";
</code>```

My string always starts with a number from 0 to 99, I have multiple character chains made up of lower and upper case letters separated by numbers from 0 to 99. This string is basically :

number from 0 to 99

characters a to z or A to Z

This pattern repeats itself a couple times.
I want to create an object/array to class this weird kind of data in a better way ...
It would be great if I could get something like :

```<code>array = [4, "bobsCat", 3, "carsOfThisGarage", 10, "this", 1, "that", 0, "whatever"]
</code>```

Or like this :

```<code>object["bobsCat"] = {number : 4};
object["carsOfThisGarage"] = {number : 3};
object["this"] = {number : 10};
object["that"] = {number : 1};
object["whatever"] = {number : 0}
</code>```

Thanks !

答:
You can do it with a regex</p>

```<code>let str = "4bobsCat3carsOfThisGarage10this1that0whatever";
let rx = /(\d{1,2})([a-zA-Z]+)/g;

var rxResult = null;
while (rxResult = rx.exec(str)) {
    // rxResult[1] will be your number
    // rxResult[2] will be text
    console.log(rxResult[1], rxResult[2]);
}
</code>```

Body:
I have a string that could look like this :

str = "4bobsCat3carsOfThisGarage10this1that0whatever";

My string always starts with a number from 0 to 99, I have multiple character chains made up of lower and upper case letters separated by numbers from 0 to 99. This string is basically :

number from 0 to 99

characters a to z or A to Z

This pattern repeats itself a couple times.
I want to create an object/array to class this weird kind of data in a better way ...
It would be great if I could get something like :

array = [4, "bobsCat", 3, "carsOfThisGarage", 10, "this", 1, "that", 0, "whatever"]

Or like this :

object["bobsCat"] = {number : 4};
object["carsOfThisGarage"] = {number : 3};
object["this"] = {number : 10};
object["that"] = {number : 1};
object["whatever"] = {number : 0}

Thanks !

Body:
You can do it with a regex

let str = "4bobsCat3carsOfThisGarage10this1that0whatever";
let rx = /(\d{1,2})([a-zA-Z]+)/g;

var rxResult = null;
while (rxResult = rx.exec(str)) {
    // rxResult[1] will be your number
    // rxResult[2] will be text
    console.log(rxResult[1], rxResult[2]);
}


问:
Count number of users who have permission to a folder python
Is it possible to count the number of users who have permission to a file with python ?

I have tried the os module with stat but I don’t know how to count the number of users who have permission to read the file.

答:
Since you're looking for OS-specific information, I'm inclined to just suggest going straight to doing a shell command.

You can run something like this shell command in the python script.

```<code>namei -o README.md | awk '{print $2}' | tail +2 # lists the users. awk chooses the 2nd column and tail skips the first line.
</code>```

Body:
Since you're looking for OS-specific information, I'm inclined to just suggest going straight to doing a shell command.

You can run something like this shell command in the python script.

namei -o README.md | awk '{print $2}' | tail +2 # lists the users. awk chooses the 2nd column and tail skips the first line.


问:
Remove duplicates from the string in CPP
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

```<code>#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}
</code>```

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

答:
This might be a bit advanced for newcomers to C++ but another solution makes use of the erase-remove idiom:

```<code>std::string removeDuplicates(const std::string& s) {
    std::string result = s;
    std::unordered_set<char> seen;

    result.erase(std::remove_if(result.begin(), result.end(), [&seen](char c)
        {
            if (seen.find(c) != seen.end())
                return true;

            seen.insert(c);
            return false;
        }),
    result.end());

    return result;
}
</code>```

It basically uses a set to store characters that have been seen, shuffles the characters to be removed down to the tail (using std::remove_if) and erases the tail from the string.

Working version here.

Body:
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

Body:
This might be a bit advanced for newcomers to C++ but another solution makes use of the erase-remove idiom:

std::string removeDuplicates(const std::string& s) {
    std::string result = s;
    std::unordered_set<char> seen;

    result.erase(std::remove_if(result.begin(), result.end(), [&seen](char c)
        {
            if (seen.find(c) != seen.end())
                return true;

            seen.insert(c);
            return false;
        }),
    result.end());

    return result;
}

It basically uses a set to store characters that have been seen, shuffles the characters to be removed down to the tail (using std::remove_if) and erases the tail from the string.

Working version here.


答:
Try this one:

```<code>str.split(/(\d+)/)
</code>```

You can also remove empty strings ("") by:

```<code>str.split(/(\d+)/).filter(Boolean)
</code>```

Title: Javascript : How can I put this data in better way ? (string to array/object)

Body:
Try this one:

str.split(/(\d+)/)

You can also remove empty strings ("") by:

str.split(/(\d+)/).filter(Boolean)


问:
Python - converting strings in an array to dates
I have read an array of strings from a TXT file and saved it as an array (of over thousand values) using such a line:

```<code>dates = np.genfromtxt('filename.txt', delimiter=";", usecols=(0), dtype=None)
</code>```

Next, I would like to convert strings into dates. I tried to use the line:

```<code>dates2 = dt.datetime.strptime([dates], '"%Y-%m-%d"').date()
</code>```

however, I got an error:

TypeError: must be string, not list

I figured out that such a code works fine:

```<code>data1='"2010-02-28"'
data1_1 = dt.datetime.strptime(data1, '"%Y-%m-%d"').date()
</code>```

How should I deal with the described problem?

答:
You can use split for faster result:</p>
```<code>from datetime import datetime
today = datetime.now().strftime("%Y-%m-%d").split('-')
</code>```

Body:
I have read an array of strings from a TXT file and saved it as an array (of over thousand values) using such a line:

dates = np.genfromtxt('filename.txt', delimiter=";", usecols=(0), dtype=None)

Next, I would like to convert strings into dates. I tried to use the line:

dates2 = dt.datetime.strptime([dates], '"%Y-%m-%d"').date()

however, I got an error:

TypeError: must be string, not list

I figured out that such a code works fine:

data1='"2010-02-28"'
data1_1 = dt.datetime.strptime(data1, '"%Y-%m-%d"').date()

How should I deal with the described problem?

Body:
You can use split for faster result:

from datetime import datetime
today = datetime.now().strftime("%Y-%m-%d").split('-')


问:
zip and filter in python
Hi I am struggling with this can someone help?
"Write code using zip and filter so that these lists (l1 and l2) are combined into one big list and assigned to the variable opposites if they are both longer than 3 characters each."
data:

```<code>l1 = ['left', 'up', 'front']
l2 = ['right', 'down', 'back']
</code>```

this is what I have:

```<code>l3=list(zip(l1,l2))
opposites=list(filter(lambda s:len(s)>3,l3))
</code>```

The problem is that I need two arguments to be more than length 3.

答:
I do it like this, using list comprehensions:</p>

```<code>opposites = [(w1,w2) for (w1,w2) in list(zip(l1,l2)) if len(w1) > 3 and len(w2) > 3]
</code>```

Title: zip and filter in python

Body:
Hi I am struggling with this can someone help?
"Write code using zip and filter so that these lists (l1 and l2) are combined into one big list and assigned to the variable opposites if they are both longer than 3 characters each."
data:

l1 = ['left', 'up', 'front']
l2 = ['right', 'down', 'back']

this is what I have:

l3=list(zip(l1,l2))
opposites=list(filter(lambda s:len(s)>3,l3))

The problem is that I need two arguments to be more than length 3.

Body:
I do it like this, using list comprehensions:

opposites = [(w1,w2) for (w1,w2) in list(zip(l1,l2)) if len(w1) > 3 and len(w2) > 3]