Error on cronjob java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0) - mysql

Hello this is the error i am receiving and cannot seem to spot what is wrong with my SQL statement. Figured a extra pair of eyes couldn't hurt
UPDATE sales SET state_name =?, sales_id =null, sales_timer =null where entity_id =?
here is the function that houses that statement
(defn release
[m]
(db/execute!
(core/db)
(str "UPDATE sales SET state_name =?, sales_id =null, sales_timer =null where entity_id =?")
[(name (m :current-state))
(m :entity-id)]))
and here is the error we receive the error from
(defn get-unfinished-sales
[]
(db/query
(score/db)
(str "select * from sales where state_name = 'in-progress'")))
(defn unlock-sales
[usales]
(doall (map (fn [sale]
(->
(score/put-batch
{:user core/system-user
:messages [{:entity-id (sale :entity-id)
:message-type "release"
:message {}}]
}
:sales)
(core/log-result-if-failure))) usales)))
(defn
run
[& args]
(->>
(get-unfinished-sales)
(filter (fn [row] (not (nil? (row :sales-timer)))))
(filter (fn [row] (> (t/in-hours (t/interval (row :sales-timer) (t/now))) 1)))
(unlock-sales)))

Your call to db/execute! should put the SQL string as the first item in the vector with the parameters:
(defn release
[m]
(db/execute!
(core/db)
["UPDATE sales SET state_name =?, sales_id =null, sales_timer =null where entity_id =?"
(name (m :current-state))
(m :entity-id)]))

Related

Class cast exception in clojure

Getting clojure.core$count cannot be cast to java.lang.Number error for defined variable count
(defroutes jobs-routes
(context "/jobs" []
(POST "/jobValidation" [name status req] (insert-job jobName jobStatus req)))
In this method I've define a variable count to store the value of total count from the query
(defn insert-job [jobName jobStatus req]
(let [count (db/insert-job {:job-name name :status status})])
(when (> count 0) (println (format "true" )))
(insert-job req) ;
)
Query: db/insert-job
-- :name insert-jobWithValidation :? :*
SELECT count(*) FROM job_history WHERE job_name = :job-name and status = :status
Problem
I want to check that whether If I'm getting out value greater than 0 so I can print something any if count is any positive value then I can perform something new
Your let block has no body, you're closing it right after definitions vector:
(let [count (db/insert-job {:job-name name :status status})])
Note that you are shadowing core function count here.
So when you call this line:
(when (> count 0) (println (format "true" ))), the value of count is count function:
count
=> #object[clojure.core$count 0x69c6a700 "clojure.core$count#69c6a700"]
(> count 0)
Execution error (ClassCastException)
class clojure.core$count cannot be cast to class java.lang.Number
There are some other errors and style inaccuracies:
the names of your variables don't match (jobName jobStatus vs name status)
you're calling (insert-job req) with only one argument, but this function has three
(> ... 0) is pos?
(format "true") is just "true"
Possible fix (maybe you will still have to modify it somehow):
(defn insert-job [job-name job-status req]
(let [my-count (db/insert-job {:job-name job-name :status job-status})]
(if (pos? my-count)
(println "true")
(insert-job job-name job-status req))))
that is probably because of your hugsql query header:
:? :* - returns the rowset, which is not a number.
maybe :? :1 would be more suitable here. Anyway, the query doesn't return a count(*), it rather returns a hash-map (in case of :1) or a list of one hashmap (in case of :*), you would still need to retrieve the value from there.
Something like that (untested):
-- :name insert-jobWithValidation :? :1
SELECT count(*) as amount FROM job_history WHERE job_name = :job-name and status = :status
(defn insert-job [name status req]
(let [res (db/insert-job {:job-name name :status status})]
(when (-> res :amount pos?)
(println true))
(insert-job req)))
UPD: omg, let with no body, indeed, #Martin Půda, thanks )
i would say, what you want is something like that:
-- :name count-jobs-by-name-and-status :? :1
SELECT count(*) as amount FROM job_history WHERE job_name = :job-name and status = :status
(defn insert-job-if-not-exists [name status req]
(if (->> {:job-name name :status status}
db/count-jobs-by-name-and-status
:amount
pos?)
(println "job already exists")
(insert-job req)))

How to double loop over a vector of strings in Clojure?

I have this function that checks the cities in a csv file if they have over a population of 500000.
I saved all the found cities to a vector but now want to loop over the vector twice in order to find the pairs of cities that are close to each other(less than 500km)(i already have a function that checks if two cities are close)
Here is what I have so far:
(defn closest-city-pairs []
(with-open [rdr (reader)]
(vec
(for [line (drop 1 (line-seq rdr))
:let [y (string/split line #",")]
:when (= true (large(y 0)))]
(let [newVec (conj [] (y 0))]
(for[x newVec
y newVec
:when (= true (close x y))]
(let [newNewVec (conj [] (x y))]
(println newNewVec))))))))
It doesn't seem to want to print but my logic and all the parentheses seem to make sense and in order? Any help would be great
(require '[clojure.math.combinatorics :as comb])
(require '[clojure.data.csv :as csv])
(with-open [r (io/reader "cities.csv")]
(let [cities (->> (csv/read-csv r) (into [] (comp cat (filter large-city?))))]
(filter close-to-each-other? (comb/combinations cities 2))))
Here is an outline of what you can do, written as a unit test:
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test))
(def nums [1 2 3 11 12 13])
(defn close?
[x y]
(<= (Math/abs (- x y)) 5))
(dotest
(let [close-pairs (vec
(for [x nums
y nums
:when (and (not= x y)
(close? x y))]
[x y]))]
(spyx close-pairs))
)
with result:
close-pairs => [[1 2] [1 3] [2 1] [2 3] [3 1] [3 2]
[11 12] [11 13] [12 11] [12 13] [13 11] [13 12]]
so we get a lot of duplicates. We can eliminate them by simply sending the output into a set, then removing duplicate sets:
(let [close-pairs (vec
(distinct
(for [x nums
y nums
:when (and (not= x y)
(close? x y))]
#{x y})))]
(spyx close-pairs))
with result:
close-pairs => [#{1 2} #{1 3} #{3 2} #{12 11} #{13 11} #{13 12}]
You can avoid the set trick (and the work duplication) if you get fancier with the for expression, and use indexes for each value. See the docs for the indexed function
(indexed [:a :b :c]) => ([0 :a] [1 :b] [2 :c])
And we can then use the :when clause like so:
(dotest
(let [nums-indexed (indexed nums)
close-pairs (vec
(for [[ix x] nums-indexed
[iy y] nums-indexed
:when (and (< ix iy)
(close? x y) )]
[x y]))]
(spyx close-pairs)))
with result:
close-pairs => [[1 2] [1 3] [2 3] [11 12] [11 13] [12 13]]
One could reduce the duplicate looping even further with judicious use of the :while clause, but that is left as an exercise for the reader.
P.S. You'll need to add [tupelo "0.9.169"] to :dependencies in your project.clj to access the spyx and indexed functions.

JessRuleEngine : Undefining accumulate

I want to count elements in a list that have the same ID
(defrule UniqueIdentifier_testfile
(P (ID_Jess ?id_context) (k $?ass))
?c <- (accumulate (bind ?count 0) ;; initializer
(bind ?count (+ ?count 1)) ;; action
?count ;; result
(and
(P (ID_Jess ?id_as1&:(member$ ?id_as1 ?ass)) (id ?id_ref1))
(P (ID_Jess ?id_as2&:(member$ ?id_as2 ?ass)) (id ?id_ref2))
(and (neq ?id_as1 ?id_as2) (eq ?id_ref1 ?id_ref2))
)
) ;; CE
(test (neq ?c 0))
=>
(printout t "UniqueIdentifier_testfile --> FIRE ! (" ?id_context ":P).id :{"?ass"} -> 'id' not uniques" crlf)
)
As you can see :
a fact of type P has a "real" ID which is reified in the slot "ID_Jess" and an other slot "id" which I'd like to test if it is unique too.
In modelling words :
(deftemplate P
(slot ID_Jess)
(slot id )
(slot m )
(multislot k )
)
It all looks fine, and "compile" allright. But the execution gives me that error :
Jess reported an error in routine HasLHS.addPattern.
Message: Variable used before definition: c.
Program text: ( defrule UniqueIdentifier [...]) at line 70 in file <eval pipe>.
at jess.HasLHS.a(Unknown Source)
...
Anybody got a clue why that ?c is not defined after the accumulate has been executed ?
Even if the condition is never fulfilled, the counter (?count) which is binded as result will at least be a defined '0'.. Am I wrong ?
If I specify an easier conditional element, the accumulate function executes as expected..

Error using "apply" function in Clojure: "Don't know how to create ISeq from: java.lang.Long"

Working on the following example in "Clojure in Action" (p. 63):
(defn basic-item-total [price quantity]
(* price quantity))
(defn with-line-item-conditions [f price quantity]
{:pre [(> price 0) (> quantity 0)]
:post [(> % 1)]}
(apply f price quantity))
Evaluating on the REPL:
(with-line-item-conditions basic-item-total 20 1)
Results in the following exception being thrown:
Don't know how to create ISeq from: java.lang.Long
[Thrown class java.lang.IllegalArgumentException]
It appears the exception is being thrown after the apply procedure is evaluated.
The last argument to apply is supposed to be a sequence of arguments. In your case, the usage might look more like this:
(defn with-line-item-conditions [f price quantity]
{:pre [(> price 0) (> quantity 0)]
:post [(> % 1)]}
(apply f [price quantity]))
apply is useful when you're working with a list of arguments. In your case, you can simply call the function:
(defn with-line-item-conditions [f price quantity]
{:pre [(> price 0) (> quantity 0)]
:post [(> % 1)]}
(f price quantity))

Returning parameter for Lisp function

I'm trying to get this function to display the literal expr2 and expr1 as they
are entered. The data that is entered is of the form (+ x y).
(DEFUN deriv (expr var) ; function name and arguments
(COND ( (ATOM expr) ; check for atomic expression (variable or constant)
(IF (EQL expr var)
1
0
) )
( (EQL (FIRST expr) '+) (deriv-add (SECOND expr) (THIRD expr) var) )
( (EQL (FIRST expr) '-) (deriv-minus (SECOND expr) (THIRD expr) var) )
( (EQL (FIRST expr) '*) (deriv-multi (SECOND expr) (THIRD expr) var) )
( (EQL (FIRST expr) '/) (deriv-divide (SECOND expr) (THIRD expr) var) )
( T (ERROR "UNKNOWN arithmetic operator"))
)
)
(DEFUN deriv-multi (expr1 expr2 var)
(LIST '+ (* (deriv expr1 var) expr2) (* expr1 (deriv expr2 var)))
)
(SETQ e2 '(* (+ x y) (+ y 7)) )
(DERIV e2 'x)
This is a good basic introduction to Lisp:
http://www.cs.cmu.edu/~dst/LispBook/
'Common Lisp: A Gentle Introduction to Symbolic Computation' by David S. Touretzky.
Free PDF.
Btw., your function displays nothing. It calls the function 'LIST'. Why are there parentheses around expr1and expr2?
About your code:
it is good coding style in Lisp to use self-explaining code. Since you can use symbols to really name things (and not be abbreviations of concepts), you can use descriptive symbols. Entering longer symbols is then usually done by using symbol completion in the editor. This allows you to get rid of the comments.
don't add additional space. Write compact code.
format your code nice and compact.
use indentation and additional lines where it helps reading the code
Example:
(defun derive (expression variable)
(if (atom expression)
(if (eql expression variable) 1 0)
(funcall (case (first expression)
(+ #'derive-addition)
(- #'derive-subtraction)
(* #'derive-multiplication)
(/ #'derive-division)
(otherwise (error "unknown arithmetic operator")))
(second expression) (third expression) variable)))
(defun derive-multiplication (expression1 expression2 variable)
(list '+
(* (derive expression1 variable)
expression2)
(* expression1
(derive expression2 variable))))
Above function still has an error, which is easy to fix. You don't want to execute the multiplication.
(defun test ()
(assert (equal (derive '(* (+ x y) (+ y 7)) 'x)
'(+ (* (+ 1 0)
(+ y 7))
(* (+ x y)
(+ 0 0)))))))