Python: simplemysql wrapper. Weird (no) Data transfer - sql

I need to say, that i actually learn programming and i try to solve this (propably) simple problem since hours. I want to check if a username already exists and if so, print a message, else write the Data for the new user into the DB. The script (check = db.getOne...) always returns "None" but read = db.getOne seems to read the Data. Where is the difference between them?
The query read = db.getOne("upers", ["logn"]) receives Data, but there is no Data saved in the DB. How can it be and how can i avoid the "None" problem and instead find the user? Sorry if my question seems crazy and like a spaghetti question, but im new to python (and stack overflow). Thanks in Advance for any Hints and Help!
The script:
import MySQLdb
from simplemysql import SimpleMysql
#Dokumentation: http://nadh.in/code/simplemysql/
db = SimpleMysql(
host='localhost',
user = '1234',
db = 'name',
passwd = '1234',
keep_alive=True
)
def createu(u, p, m):
username = u
password = p
mail = m
check = db.getOne("upers",
["logn"],
("logn = %s", [username])
)
print check
if check == None:
db.insert("upers",
{"logn": username, "pw": password, "mail": mail}
)
print "seems to work!"
else:
print "something is wrong!"
check = 0
u='test'
p = 'lol'
m = '123#lol.de'
createu(u, p, m)
read = db.getOne("upers", ["logn"])
print read
The Output:
None
seems to work!
Row(logn=u'test')
Also i cant imagine how the u finds its way into the output of the sql query.
I had many different approaches to get a simple database up and running and the simplesql wrapper seems to fit really good for a beginner like me, so i hope someone can point me in the right direction.
edit: It seems the data isn't even saved in the DB. When i log in to phpmyAdmin it cant find any data in the DB. But how can it be that i am able to read the Data with python? Magic?! oO
Another important question for me is: How can i extract the information from the print read result: Row(logn=u'test')

Related

Pymongo: insert_many() gives "TypeError: document must be instance of dict" for list of dicts

I haven't been able to find any relevant solutions to my problem when googling, so I thought I'd try here.
I have a program where I parse though folders for a certain kind of trace files, and then save these in a MongoDB database. Like so:
posts = function(source_path)
client = pymongo.MongoClient()
db = client.database
collection = db.collection
insert = collection.insert_many(posts)
def function(...):
....
post = parse(trace)
posts.append(post)
return posts
def parse(...):
....
post = {'Thing1': thing,
'Thing2': other_thing,
etc}
return post
However, when I get to "insert = collection.insert_many(posts)", it returns an error:
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
According to the debugger, "posts" is a list of about 1000 dicts, which should be vaild input according to all of my research. If I construct a smaller list of dicts and insert_many(), it works flawlessly.
Does anyone know what the issue may be?
Some more debugging revealed the issue to be that the "parse" function sometimes returned None rather than a dict. Easily fixed.

Filter records based on groups [Odoo]

I am trying to filter the records based on their group id. I have written a domain filter in menu action like this
[('pending_approver','in',[g.id for g in user.groups_id])]
pending_approver is a Many2one field with res.groups
Have a look on this for more clarification.
def _default_approver(self):
obj = self.env['approval_heirarchy.approval_rules'].search([('id', '=', 1)], limit=1)
if obj.x_approver_ids:
val = obj.x_approver_ids[0].x_user_ids
return obj.x_approver_ids[0].x_user_ids.id
pending_approver = fields.Many2one('res.groups', string="Pending Approver", readonly=True,default=_default_approver)
Whenever run the application prompt an Odoo Client Error:
Uncaught Error: Expected "]", got "(name)"
I've searched a lot but didn't find any solution.
Any help will be a great regard for me. Thanks in Advance!
if self.user_has_groups('sales_team.group_sale_manager') is True:
code part...
this code may help you.....any queries please free to ask

pseudo randomization in loop PsychoPy

I know other people have asked similar questions in past but I am still stuck on how to solve the problem and was hoping someone could offer some help. Using PsychoPy, I would like to present different images, specifically 16 emotional trials, 16 neutral trials and 16 face trials. I would like to pseudo randomize the loop such that there would not be more than 2 consecutive emotional trials. I created the experiment in Builder but compiled a script after reading through previous posts on pseudo randomization.
I have read the previous posts that suggest creating randomized excel files and using those, but considering how many trials I have, I think that would be too many and was hoping for some help with coding. I have tried to implement and tweak some of the code that has been posted for my experiment, but to no avail.
Does anyone have any advice for my situation?
Thank you,
Rae
Here's an approach that will always converge very quickly, given that you have 16 of each type and only reject runs of more than two emotion trials. #brittUWaterloo's suggestion to generate trials offline is very good--this what I do myself typically. (I like to have a small number of random orders, do them forward for some subjects and backwards for others, and prescreen them to make sure there are no weird or unintended juxtapositions.) But the algorithm below is certainly safe enough to do within an experiment if you prefer.
This first example assumes that you can represent a given trial using a string, such as 'e' for an emotion trial, 'n' neutral, 'f' face. This would work with 'emo', 'neut', 'face' as well, not just single letters, just change eee to emoemoemo in the code:
import random
trials = ['e'] * 16 + ['n'] * 16 + ['f'] * 16
while 'eee' in ''.join(trials):
random.shuffle(trials)
print trials
Here's a more general way of doing it, where the trial codes are not restricted to be strings (although they are strings here for illustration):
import random
def run_of_3(trials, obj):
# detect if there's a run of at least 3 objects 'obj'
for i in range(2, len(trials)):
if trials[i-2: i+1] == [obj] * 3:
return True
return False
tr = ['e'] * 16 + ['n'] * 16 + ['f'] * 16
while run_of_3(tr, 'e'):
random.shuffle(tr)
print tr
Edit: To create a PsychoPy-style conditions file from the trial list, just write the values into a file like this:
with open('emo_neu_face.csv', 'wb') as f:
f.write('stim\n') # this is a 'header' row
f.write('\n'.join(tr)) # these are the values
Then you can use that as a conditions file in a Builder loop in the regular way. You could also open this in Excel, and so on.
This is not quite right, but hopefully will give you some ideas. I think you could occassionally get caught in an infinite cycle in the elif statement if the last three items ended up the same, but you could add some sort of a counter there. In any case this shows a strategy you could adapt. Rather than put this in the experimental code, I would generate the trial sequence separately at the command line, and then save a successful output as a list in the experimental code to show to all participants, and know things wouldn't crash during an actual run.
import random as r
#making some dummy data
abc = ['f']*10 + ['e']*10 + ['d']*10
def f (l1,l2):
#just looking at the output to see how it works; can delete
print "l1 = " + str(l1)
print l2
if not l2:
#checks if second list is empty, if so, we are done
out = list(l1)
elif (l1[-1] == l1[-2] and l1[-1] == l2[0]):
#shuffling changes list in place, have to copy it to use it
r.shuffle(l2)
t = list(l2)
f (l1,t)
else:
print "i am here"
l1.append(l2.pop(0))
f(l1,l2)
return l1
You would then run it with something like newlist = f(abc[0:2],abc[2:-1])

oxid import old data SQL

I have an old oxid-version. I exported my old seo-data from the table "oxseo" to get the keywords and description for each article. Now i want to import these fields in my new version of the shop. My articles are already there, but not the seodata.
My first idea was to collect all the data i need from a csv-export of my old data.
For example, my output array could look something like:
$article = array();
$keywords = array();
$desc = array();
foreach($line as $l) {
$keywords[$i] = current_keyword
$desc[$i] = current_description
$oxid[$i] = current_oxid
}
So lets just assume I already have my filled array.
If i check the oxid's, they are still the same. So, from my exported CSV, picking a random OXID, looking for it in my new DB shows me the correct article.
Now my first thought was, to look in oxobject2seodata. I know that the data for the articles are stored in there, but i can't find a way to connect those, since the "oxid" from the old version is not the same as the objectId in the new version. In oxarticles, however, there is no "objectId".
Thank you in advance for any hints and tips
The field OXID in oxarticles table should match the field OXOBJECTID in oxobject2seodata table.
SELECT oa.OXID, o2s.* from oxobject2seodata o2s, oxarticles oa WHERE o2s.OXOBJECTID = oa.OXID AND oa.OXID = '[OXID-of-article]';
-- or
SELECT o2s.* from oxobject2seodata o2s WHERE o2s.OXOBJECTID = '[OXID-of-article]';

ruby on rails store sql result on a variable

Newbie here. I am trying to store the result of my search onto a variable.
#answer = q.answers.select(:name) which runs
"SELECT name FROM "answers" WHERE "answers"."question_id" = 1;" and returns
"t" for true.
It runs fine on the command line and shows the right result. But I want to compare that result to another variable.
How do i extract that result? #answer[0], or #answer, or answer_var = #answer[0]
i.e.
if #answer == some_other_variable OR
if #answer[0] == some_other_variable OR
if answer_var == some_other_variable
what value do #answer[0] and #answer[0] hold and how can I print the value to the log file? not the web page. I know it must be simple, but I can't get my head around it.
Thanks.
It's not really an answer to your question but...
If you want to follow "the rails way", you should better use Models and not deal with SQL at all.
E.g. :
#answer = q.answers.first # answers is an array, take the first
if #answer.name == ...
For the logging, I suggest you that : http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger