I want create a #conn before all test case and can be used for all test case so i did something like:
class SQLTest < Test::Unit::TestCase
def self.before_suite
#conn = PG.connect(dbname:'MapSwitcher',host:'localhost', user:'Lin')
end
def test_employee_table_have_5_entries
result = #conn.exec("SELECT COUNT(*) FROM employees")
assert_equal(result.getvalue(0,0).to_i, 5)
end
end
And I got an error:
noMethodError: private method `exec' called for nil:NilClass
it seems like the #conn can't be accessed in the test case,
class SQLTest < MiniTest::Unit::TestCase
def setup
#conn = PG.connect(dbname:'MapSwitcher',host:'localhost', user:'Lin')
end
def test_employee_table_have_5_entries
result = #conn.exec("SELECT COUNT(*) FROM employees")
assert_equal(result.getvalue(0,0).to_i, 5)
end
end
Related
I have PostgreSQL query which starts with DO:
do
$$
DECLARE
temprow record;
BEGIN
for temprow in
select *
from generate_series(1, 100)
where generate_series % 2 = 0
loop
with cte_input(val) as (select val from (values (temprow.generate_series)) as t(val))
insert
into tmp_table(input_value, value_100)
select cte_input.val as input_value, cte_input.val::float / 100 as value_100
from cte_input;
commit;
end loop;
END
$$ LANGUAGE plpgsql;
How I can run this query with Python and psycopg2?
Is it right way to use temporary function if I need to run this query with some dynamic changes few times?
UPD
Thank you #erwin-brandstetter for information about COMMIT.
I deleted COMMIT from query block and add it in Python code: ps_cursor.execute('COMMIT').
I write code in this way:
import concurrent.futures
import psycopg2 as pg
from psycopg2 import pool
features = [(1, name_of_feature_1), ...] # list of features
list_query = []
for feature in features:
feature_id = feature[0]
name_feature = feature[1]
query = f"""--Feature:{feature_id}
create or replace procedure pg_temp.proc_feature_{feature_id}_values()
language plpgsql
as
$$
DECLARE
temprow record;
BEGIN
for temprow in
select *
from tmp_maternal_sample
where maternal_sample = 1000
loop
insert
into tmp_feature_values(feature_id,
feature_values_array,
maternal_sample)
select feature_id,
array_agg(t_rank.{name_feature}) f_values,
temprow.maternal_sample
from t_rank
....
....
end loop;
end
$$;
call pg_temp.proc_feature_{feature_id}_values();
"""
list_query.append(query)
def load_query(query):
ps_connection = threaded_postgreSQL_pool.getconn()
if (ps_connection):
print(f"Successfully recived connection from connection pool for Query {query[:15]} ")
ps_cursor = ps_connection.cursor()
ps_cursor.execute(query)
ps_cursor.execute('COMMIT')
ps_cursor.close()
result = f'Query {query[:15]} finished'
print(result)
return result
try:
threaded_postgreSQL_pool = pool.ThreadedConnectionPool(1, 32, user, password, host, port, database)
if (threaded_postgreSQL_pool):
print("Connection pool created successfully using ThreadedConnectionPool")
with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
future_to_sql = {executor.submit(load_query, query): query for query in list_query}
for future in concurrent.futures.as_completed(future_to_sql):
sql = future_to_sql[future]
try:
data = future.result()
except Exception as exc:
print('%s generated an exception: %s' % (sql[:15], exc))
else:
print('%s page is %s bytes' % (sql[:15], data))
except (Exception, pg.DatabaseError) as error:
print("Error while connecting to PostgreSQL", error)
finally:
if threaded_postgreSQL_pool:
threaded_postgreSQL_pool.closeall
print('Threaded PG connection pool is closed')
It's safe to assume Postgres 11 or later, because:
COMMIT works in one plpgsql code block, but not in another?
Your DO statement is convoluted without obvious reason. Simpler:
DO
LANGUAGE plpgsql
$do$
DECLARE
i int;
BEGIN
FOR i IN
SELECT generate_series(2, 100, 2)
LOOP
INSERT INTO tmp_table(input_value, value_100)
VALUES (i, i::float / 100);
-- COMMIT; -- ?
END LOOP;
END
$do$;
Which boils down to just this - even including the creation of that temp table:
CREATE TEMP TABLE tmp_table AS
SELECT g AS input_value, g::float / 100 AS value_100
FROM generate_series(2, 100, 2) g;
db<>fiddle here
Some setups (like dbfiddle.uk) still don't allow transaction handling with COMMIT. Not sure you even need that?
Either way, just execute the raw SQL.
When I use log4r in rails 6, I report the following error
This is the complete error information
.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/activesupport-6.0.3.2/lib/active_support/tagged_logging.rb:22:in `call': wrong number of arguments (given 0, expected 4) (ArgumentError)
config/initializers/log4r_patch.rb
class Log4r::Logger
def formatter()
Proc.new{|severity, time, progname, msg|
formatted_severity = sprintf("%-5s",severity.to_s)
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S")
"[#{formatted_severity} #{formatted_time} #{$$}]\n #{msg}\n"
}
end
def formatter=(temp)
end
end
refer to: https://www.thegreatcodeadventure.com/building-a-custom-logger-in-rails/
I am trying to write API for user model, where i have to return only two columns with some modification(appending string)
Every thing work's fine, I even get the correct result, but when I see status code its showing '500', when i check the logs its showed the following error
[active_model_serializers] Rendered ActiveModel::Serializer::Null with Hash
following is the code
1. users_controller.rb
class Api::V1::UsersController < Api::V1::ApiController
# GET
def pl_details
render json: {pl: current_user.pl_url, enabled: current_user.personal_calendar_enabled}, status: :success
end
...
end
user.rb
...
def pl_url
return "#{Rails.application.secrets.app_host}/#{self.calendar_url_token}"
end
...
user_serializer.rb
class UserSerializer < ActiveModel::Serializer
attributes :id, :firstname, :lastname, :email
end
Never mind,
I just did it other way around,I used a separate Serializer to avoid the error, following is the approach
class Api::V1::UsersController < Api::V1::ApiController
# GET
def pl_details
render json: current_user,serializer: PLSerializer, status: :success
end
...
end
and inside PLSerializer
class PLSerializer < ActiveModel::Serializer
attributes :pl, :personal_calendar_enabled
def personal_link
current_user.pl_url
end
end
I am using awesome WM and I want to run a lua function after a client is created/deleted. Specifically, I want to change the name of a tag to the name of one of the clients that are on the tag.
I do this with a timer, but I think the best way to do this would be to register a callback function to awesomeWM that it will invoke when a client is created/removed.
Are there some hooks/callbacks that I can implement to tell awesome to do this for me?
---------------------------------------------UPDATE----------------------------------------
I tried using the signals, but i cant find the correct signal that changes calls my function AFTER the window is created and attached to the tag. I tried this with manage/unmanage tagged/untagged, and tag.new, etc, but no one helps.
Any ideas?
here is the code:
override_name_char = "<"
function tag_name_from_client(c)
if string.match(c.name, "Mozilla Firefox") then
return "Firefox"
end
if string.match(c.name, "Sublime Text") then
return "Sublime"
end
if string.match(c.name, "/bin/bash") then
return "Shell"
end
return ""
end
function tag_name_from_tag(tag)
if tag.name:match(override_name_char) then
return tag.name
end
for _, c in pairs(tag:clients()) do
return " "..tostring(awful.tag.getidx(tag)).." "..tag_name_from_client(c)
end
return tostring(awful.tag.getidx(tag))
end
function refresh_tag_name()
for s = 1, screen.count() do
for _,tag in pairs(awful.tag.gettags(s)) do
tag.name = tag_name_from_tag(tag)
end
end
end
client.connect_signal("tagged", refresh_tag_name)
client.connect_signal("untagged", refresh_tag_name)
--tag_timer = timer({timeout = 0.5})
--tag_timer:connect_signal("timeout", function()
--refresh_tag_name()
--end)
--tag_timer:start()
Thanks in advance for any help regarding this.
One of possible ways for v3.5.6, try this in your rc.lua
local naughty = require("naughty")
client.connect_signal("manage", function (c)
--filter client by class name
if c.class:lower() == "gedit" then
-- do things on client start
naughty.notify({text = "Gedit launched!"})
-- add exit signal for this client
c:connect_signal("unmanage", function() naughty.notify({text = "Gedit closed!"}) end)
end
end)
"A new client is created" is the manage signal.
"A new client was destroyed" is the unmanage signal.
So, something like the following (untested):
local function choose_name_for_tag(t)
for _, c in ipairs(t:clients() do
return "has client: " .. tostring(c.name or "unknown")
end
return "has no clients"
end
local function update_state()
for _, t in pairs(root.tags()) do
t.name = choose_name_for_tag(t)
end
end
client.connect_signal("manage", update_state)
client.connect_signal("unmanage", update_state)
tag.connect_signal("tagged", function(t)
t.name = choose_name_for_tag(t)
end)
tag.connect_signal("untagged", function(t)
t.name = choose_name_for_tag(t)
end)
I am trying to add an attirubute to objects that i created.Here i created bird display objects but i want to add those birds a spesific attiribute like typeOfBird and then i want to reach those attiributes like bird.typeOfBird . How can i do that?
module(...,package.seeall)
function new(params)
local bird=display.newImage(params.img,params.x,params.y)
function bird:touch(event)
local t = event.target
local phase = event.phase
if "began" == phase then
-- Make target the top-most object
local parent = t.parent
parent:insert( t )
display.getCurrentStage():setFocus( t )
t.isFocus = true
elseif t.isFocus then
if "moved" == phase then
t.x = event.x
t.y = event.y
elseif "ended" == phase or "cancelled" == phase then
display.getCurrentStage():setFocus( nil )
t.isFocus = false
end
end
return true
end
It looks like bird objects are already simple lua tables,
so you can just get and set the values as normal. So for example you could add lines like:
if self.typeOfBird == "gull" then ... end
and
self.typeOfBird = "parrot"
to your bird:touch function.
Or
bird.typeOfBird = "gull"
in your new function.