Nim: Can't access fields of object returned by a procedure - lexer

I was trying to write a lexer in Nim. Sorry, if this sounds a bit idiotic because I started using nim yesterday, so my problem is that I created a type such as what follows
import position
type
Error* = object
pos_start : position.Position
pos_end : position.Position
name: string
details: string
then I went on to create a procedure that returns an instance of this type,
proc IllegalCharacterError*(pos_start : position.Position, pos_end : position.Position, details : string) : Error =
return Error(pos_start: pos_start, pos_end: pos_end, name: "IllegalCharacterError", details: details)
Now, everything works fine except when I, from another module, try to access fields of this returned instance I get error
from errors import nil
from position import nil
var current_char = "2"
let pos = position.Position(idx: -1, ln: 0, col: -1, fn: fn, ftxt: text)
let error = errors.IllegalCharacterError(pos, pos, current_char)
echo error.name
The last line is the one that throws the error and following is the error that appeared during compilation
Error: undeclared field: 'name' for type errors.Error [declared in C:\Users\Mlogix\Desktop\testNim\errors.nim(4, 3)]
Thanks, any help would be really appreciated.

Ok, finally after an hour I realized that my fields weren't public. For anyone from the future, I changed my type code to
import position
type
Error* = object
pos_start* : position.Position
pos_end* : position.Position
name*: string
details*: string
and it worked. Hooray.

Related

How could I be getting an expected str instance, NoneType found error when I'm using a default get in Python3?

I see this error:
data["source_domain"], data["ip_address"]])
TypeError: sequence item 3: expected str instance, NoneType found
But this is my code leading up to that error:
data["segment_user_id"] = record.get("userId", "")
traits = record.get("traits", {})
data.update({
# country_name -> country
trait.replace("country_name", "country"): traits.get(trait, "")
for trait in ["first_name", "last_name", "email", "country_name", "city", "ip_address"]
})
# Add composite key
to_hash = ''.join([data["project_id"], data["anonymous_id"], data["source_system"], data["segment_user_id"],
data["source_domain"], data["ip_address"]])
data["message_composite_key"] = hashlib.md5(to_hash.encode()).hexdigest()
It seems like the sequence number 3 which is data["segment_user_id"] is None. But how could this be? Isn't my record.get("userId", "") code ensuring that this always gets set to empty string?

Typecasting in Groovy

I am trying to parse an yaml file in Groovy. However I am facing issue while typecasting the result to Map object.
Here is my logic
import org.yaml.snakeyaml.Yaml
import java.util.Map
Reader reader = null
int tokenCount = 0
def Map map = null
StringTokenizer st = new java.util.StringTokenizer("Country.State.City", ".")
reader = new FileReader("filepath")
String val = null
Yaml yaml = new Yaml()
map = (Map) yaml.load(reader)
tokenCount = st.countTokens()
for (i=1; i < tokenCount; i++) {
String token = st.nextToken()
map = (Map) map.get(token)
}
val = map.get(st.nextToken()).toString()
However I am getting error at line:
map = (Map) map.get(token)
where it says:
"org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'some value' with class 'java.lang.String' to class 'java.util.Map' error at line: 15"..
Where I am going wrong?
your provided yaml file is syntactically incorrect. This is a fixed version:
location: C:\\Users\\amah11\\Desktop\\New folder
type: hi
Header:
Code:
Start: 0
End: 2
value: H00
Owner:
Start: 3
End: 5
value: AIM
User:
Start: 6
End: 8
Value: AIM
number: 1
Note that Code: **Static** in the original messes things up. And all the keys on the final level need a space after the : (e.g. Start:3 is wrong).
The actual error message is:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Static Start:0 End:2 value:H00' with class 'java.lang.String' to class 'java.util.Map'
which is rather clear in showing, that there is something wrong with the original file.
You might want to consider using an editor, that detects errors like this right away.
An alternative to the original code, would be the use of inject on the tokenizer:
def map = new Yaml().load(new FileReader("cardconfig.yml"))
println new StringTokenizer('Header.Code.End', '.').inject(map) { r, s -> r.get(s) }
BTW: you don't need to import java.util in groovy.

Odd behaviour of insertNewObjectForEntityForName leading to NSInternalInconsistencyException

I have a rather odd case of getting a core data error whilst experimenting with Swift. I am not sure whether it comes from Swift (beta error?) or whether it is me. However, here is the setup for my test cases (in VTModelTests.swift).
var bundle = NSBundle(forClass: VTModelTests.self)
var url = bundle.URLForResource("VTDocument", withExtension:"momd")
appleModel = NSManagedObjectModel(contentsOfURL: url)
assert (appleModel != nil)
var coord = NSPersistentStoreCoordinator(managedObjectModel: appleModel);
var store = coord.addPersistentStoreWithType(NSInMemoryStoreType,configuration:nil,URL:nil,options:nil,error:nil);
assert (store != nil)
ctx = NSManagedObjectContext();
ctx!.persistentStoreCoordinator=coord
ctx!.retainsRegisteredObjects=true;
var drwName = "Drawing"
var descs = ctx!.persistentStoreCoordinator.managedObjectModel.entitiesByName
for e : AnyObject in descs.allKeys{
assert (descs.objectForKey(e).name == e as String )
if (e as String == drwName) {
NSLog("yeah")
}
}
model = NSEntityDescription.insertNewObjectForEntityForName(drwName,inManagedObjectContext: ctx) as Drawing
My error message looks like this:
2014-06-22 22:12:25.584 xctest[63792:303] yeah
<unknown>:0: error: -[_TtC12VTModelTests12BaseTypeTest testTreeStructure] : failed: caught "NSInternalInconsistencyException", "+entityForName: could not locate an entity named 'Drawing' in this model."
In short, I can "prove" that the entity name is there (the 'yeah' in the log), but core data is showing the issue that the name would not be in the model. Previous versions of the loop printed out the entities and that looked good. I don't have any second versions, and a new changed name ('Model' is now called 'Drawing') is correctly shown in the model data when all entities are printed. The compiled model is in the resulting bundle.
Can anybody explain? Or do I have to wait for the next beta release of Xcode 6? What else did I overlook? Many thanks in advance!
I can confirm the issue. Not an answer but the way around I use is to split insertNewObjectForEntityForName into:
let entity = NSEntityDescription.entityForName("Photo", inManagedObjectContext:context)
let photo = Photo(entity:entity, insertIntoManagedObjectContext:context)

Parallel with Foreach and doMC packages in Linux- Error with mclapply

I want to run parallel computing in Linux.
After i managed to do so in Windows i need to run the function below in Linux. I changed the package doSnow to doMC that suppose to work in Linux but i get an error related to mclapply.
Code:
foreachFunc = function(Data) {
RowFunction<-function(d)
{
(chisq.test(d)$p.value)}
P<-as.matrix(apply(Data,1,RowFunction))
return(P)}
library(doMC)
library(foreach)
number_of_cpus=4
cl<-makeCluster(number_of_cpus)
registerDoMC(cl)
Chunks<-c(1:NROW(Data_new))%%4
P<-foreach(i=0:3, .combine=rbind, mc.cores=4) %dopar% {
foreachFunc(Data_new[Chunks==i, ])}
stopCluster(cl)
Error:
Error in mclapply(argsList, FUN, mc.preschedule = preschedule, mc.set.seed = set.seed, :
(list) object cannot be coerced to type 'integer'
Read vignette("gettingstartedMC"). I can reproduce your error like this:
number_of_cpus=4
cl<-makeCluster(number_of_cpus)
registerDoMC(cl)
P<-foreach(i=0:3) %dopar% i
#Error in mclapply(argsList, FUN, mc.preschedule = preschedule, mc.set.seed = set.seed, :
# (list) object cannot be coerced to type 'integer'
stopCluster(cl)
This works as expected:
registerDoMC(cores=4)
P<-foreach(i=0:3) %dopar% i
Explanation: registerDoMC expects an integer value for its first argument. You gave it a list, i.e. the return object of makeCluster.

cx_Oracle gives OCI-22062 invalid input string when calling function with bool parameter

I have a strange problem. When I try to call an oracle stored function using cursor.call_func method I receive an OCI-22062 exception. I'm using Python 3.2 and cx_Oracle 5.1.2. It generally looks like this:
This is the function header for package pkg_planista:
FUNCTION zatwierdz_plan (p_pl_id IN dz_plany.ID%TYPE,
p_czy_nowy_algorytm IN BOOLEAN DEFAULT FALSE,
p_czy_prz_grup IN BOOLEAN DEFAULT FALSE
) RETURN NUMBER;
This is what I do:
print(proc_name, retType, params, keyword_params)
res = self.cursor.callfunc(proc_name, retType, params, keyword_params)
This print above prints:
pkg_planista.zatwierdz_plan <class 'int'> [83, False] {}
And when the callfunc is executed, the OCI-22062 error is raised: cx_Oracle.DatabaseError: OCI-22062: invalid input string [False]
How should I pass the boolean parameter to make it work?
I had to find a workaround for this problem, because I couldn't find a way to make the callfunc work as it should.
In this workaround I use one temporary table that was created for some other purpose, but it's just what I need.
I changed callfunc to execute and made it like this:
self.cursor.execute("""
declare
result number;
begin
result := pkg_planista.zatwierdz_plan(:pid, :alg = 1);
INSERT INTO tmp_dz_v_planista_pracownicy values (result);
end;
""", {'pid': pl_id, 'alg': int(new_algorithm)})
ret = self.cursor.execute("SELECT * FROM tmp_dz_v_planista_pracownicy")
This way I can call the function and receive it's return value. The tmp_dz_v_planista_pracownicy table is just a temporary table with one column of type NUMBER.

Resources