I am getting an index out of range error - class

My function takes a table of the form dictionary and returns the table after applying the query which the person asked. I have several other methods but I am having trouble with the equal condition method . This is what I've tried.
class Table():
def where_con(self,table,conditions):
for condition in conditions:
if ('='in condition):
print(table.get_dict())
print(condition)
self = table.equal_condition(table,condition)
return(self)
elif('>'in condition):
new_table = table.greater_condition(table, condition)
return(self)
def equal_condition(self,table,condition):
'''(Table, string) -> Table
This Function takes in a table and a condition and applies the
condition and returns a new table with the condition applied
REQ: Table must have the contents of the condition
REQ: The condition must have proper syntax
REQ: The condition must contain the equal sign in string form
'''
number_rows = table.num_rows()
print(number_rows)
dictionary = table.get_dict()
print(dictionary)
condition = condition.split('=')
print(condition)
#new_table = Table()
# Adding Coloums Name in Self
for col in dictionary:
self.add_column({col: []})
# If the Second part is a string
if ("'" in condition[1]):
condition[1] = condition[1].strip("'")
i=0
while(i<number_rows):
print(i)
i=i+1
if (dictionary[condition[0]][i] == condition[1]):
for key in self.get_dict():
self = self.update_column(key,dictionary[key][i])
#i=i+1
else:
i=0
while(i<number_rows):
print(i)
if (dictionary[condition[0]][i] == dictionary[condition[1]][i]):
for key in self.get_dict():
self.update_column(key,dictionary[key][i])
i=i+1
return self
So when I give an input as
>>>a = Table()
>>>a.set_dict({'w.critic_rating': ['5', '5', '5', '5'], 'o.for': ['Directing', 'Acting', 'Directing', 'Acting'], 'w.title': ['Titanic', 'Titanic', 'Avatar', 'Avatar'], 'o.title': ['Avatar', 'Titanic', 'Avatar', 'Titanic'], 'w w.your_rating': ['4.5', '4.5', '5', '5'], 'w.average_rating': ['4.75', '4.75', '5', '5']})
>>>d = Table()
>>>f = where_con(a,"w.title=o.title")
4
{'o.for': ['Directing', 'Acting', 'Directing', 'Acting'], 'o.title': ['Avatar', 'Titanic', 'Avatar', 'Titanic'], 'w.critic_rating': ['5', '5', '5', '5'], 'w.your_rating': ['4.5', '4.5', '5', '5'], 'w.average_rating': ['4.75', '4.75', '5', '5'], 'w.title': ['Titanic', 'Titanic', 'Avatar', 'Avatar']}
['w.title', 'o.title']
0
Traceback (most recent call last):
Python Shell, prompt 2, line 1
File "C:\Users\Abhinav\Desktop\MAde_answer\database.py", line 205, in <module>
if (dictionary[condition[0]][i] == dictionary[condition[1]][i]):
builtins.IndexError: list index out of range
Why is this happening and how can I fix it . Any help is appreciated.

Related

Flutter list not update after do change the list

I have list data and try to change the value in position [0] to be value 5.
List<String> imagesVal = ['1', '2', '3', '4'];
Then I have change function
void changeImage(id, file, mediaID) {
setState(() {
imagesVal[0] = '5';
})
print(imagesVal);
});
The result is: ['5', '2', '3', '4']
Then I have save button
Future _save() async {
print(imagesVal);
});
When tap the button, I got result still old value: ['1', '2', '3', '4']
My question, how to get the latest update value? On above example it should be get the value ['5', '2', '3', '4']
You should have declared the list inside the build method of stateful widget by mistake. Please move it outside the build method.

how to convert numbers from one language to english or forcing the user to write in english only?

I would like to convert Arabic numbers into english or force the user to enter english numbers only, so how to do so?
i.e 123 = ١٢٣ and so on.
For converting numbers you can simply write a function like this:
Map persianNumberMap = {
'۰': '0',
'۱': '1',
'۲': '2',
'۳': '3',
'۴': '4',
'۵': '5',
'۶': '6',
'۷': '7',
'۸': '8',
'۹': '9'
};
String convertPersianNumberToEnglish(String number) {
String converted = number;
persianNumberMap.forEach((key, value) => converted.replaceAll(key, value));
return converted;
}
But you can also use FilteringTextInputFormatter to restrict inputs of a TextField:
TextField(inputFormatters: [
FilteringTextInputFormatter.allow(RegExp("[0-9]")),
])
This TextField will only accept English number characters.

How to use ARRAY of INET in flask-sqlalchemy?

I have a user model with array of ips field in my flask application. I want to use postgresql array of inet type:
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import ARRAY, INET, Integer, Unicode, Column
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
login = Column(Unicode(15))
password = Column(Unicode(34))
name = Column(Unicode(100))
permitted_ips = Column(ARRAY(INET))
But when i make query i get bad answer:
user = User.query.get(84)
print user.permitted_ips
#['{', '1', '7', '2', '.', '2', '0', '.', '2', '5', '.', '2', ',', '1', '7', '2', '.', '2', '0', '.', '2', '5', '.', '3', '}']
instead of ['172.20.25.2', '172.20.25.3']. Current version of sqlalchemy is 0.9.10. I tried the latest one but result was the same. Is it possible to fix that?
I found that Arrays are not parsed automatically so you need to create a generic type caster with psycopg2 library.
# needed imports
from psycopg2 import STRING
from psycopg2.extensions import register_type, new_array_type
Registering the array type, it will be done one time.
# to see the oid of inet. As pointed out by #univerio the oid should never
# change, so you don't need to fetch it every time your app starts.
tp = db.engine.execute("select typarray from pg_type where typname = 'inet'")
print(tp.fetchone())
# (1041,)
# registering the array type
register_type(new_array_type((1041,), 'INET[]', STRING))
Now you can fetch the array and it will be parsed properly.
# fetch data
ips = db.engine.execute("select permitted_ips from users where id = 1")
print(ips.fetchone()[0])
# ['172.20.25.2', '172.20.25.3'].

does CakePHPs Containable-behavior support custom expressions as conditions?

Community,
I'm currently facing an issue with the containable-behavior setting conditions based on the datasources expression-builder. I'm using CakePHP 2.6.2 with a PostgreSQL database.
What works so far:
I wrote a behavior that dynamically adds conditions to find-operations to restrict the results based on a privileges table. Im using subqueries with the buildstatement() and expression() functions provided by cake. I followed this article from the CakeBook:
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
Here is a simplyfied code-snippet, in fact its two OR-statements:
$conditionsSubQueryRecord = array(
'Privilege.objecttable' => $model->table,
'Privilege.objectid = '.$model->alias.'.'.$model->primaryKey,
'Privilege.read' => true,
'Privilege.id' => $this->recordPermissions
);
$dsPrivilege = $this->privilegeModel->getDataSource();
$subQueryRecordPrivs = $dsPrivilege->buildStatement(
array(
'fields' => array('"'.$this->privilegeModel->alias.'"."id"'),
'table' => $dsPrivilege->fullTableName($this->privilegeModel),
'alias' => $this->privilegeModel->alias,
'limit' => null,
'offset' => null,
'joins' => array(),
'conditions' => $conditionsSubQueryRecord,
'order' => null,
'group' => null
),
$this->privilegeModel
);
$subQueryRecordPrivs = ' EXISTS (' . $subQueryRecordPrivs . ') ';
$subQueryRecordPrivsExpression = $dsPrivilege->expression($subQueryRecordPrivs);
I'm adding the statement to my condition array then in my behaviors beforeFind()-hook. This works all very well so far. The condition is added, the results are filtered.
The conditions are ignored for my contained models:
My problem is now to use this condition on contained models. I wrote an recursive algorithm that walks along all the contained modelsand if the model actsAs my behavior I am attaching the same conditions to its conditions-array. But when I execute my search, the condition is ignored on the contained models and only attached to the primary model.
This is the complete condition string I'm executing:
array(
'conditions' => array(
'Requestinstance.id' => (int) 4,
(int) 0 => object(stdClass) {
type => 'expression'
value => ' EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'requestinstances' AND "Privilege"."objectid" = "Requestinstance"."id" AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" = (8)) OR EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'requestinstances' AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" IN (7, 13, 6, 9, 10, 12) AND "Privilege"."objectid" IS NULL) '
}
),
'fields' => null,
'joins' => array(),
'limit' => (int) 1,
'offset' => null,
'order' => array(
(int) 0 => null
),
'page' => (int) 1,
'group' => null,
'callbacks' => true,
'contain' => array(
'Requesttype' => array(
'Steptype' => array(
'order' => array(
(int) 0 => 'RequesttypesSteptype.phase ASC'
),
'conditions' => object(stdClass) {
type => 'expression'
value => ' EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'steptypes' AND "Privilege"."objectid" = "Steptype"."id" AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" = (8)) OR EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'steptypes' AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" IN (7, 13, 6, 9, 10, 12) AND "Privilege"."objectid" IS NULL) '
}
),
(int) 0 => 'RequesttypesSteptype',
'conditions' => object(stdClass) {
type => 'expression'
value => ' EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'requesttypes' AND "Privilege"."objectid" = "Requesttype"."id" AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" = (8)) OR EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS "Privilege" WHERE "Privilege"."objecttable" = 'requesttypes' AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" IN (7, 13, 6, 9, 10, 12) AND "Privilege"."objectid" IS NULL) '
}
),
'Stepinstance' => array(
(int) 0 => 'Steptype',
(int) 1 => 'Stepdatainstance',
(int) 2 => 'Sectioninstance'
),
'Requestdatainstance' => array(),
'Taskinstance' => array()
),
'recursive' => (int) 2
)
As you can see, the condition was correctly added to some of the contained models. However, the executed SQL-query, i.e. for the "Steptype"-Model, is generated without the condition:
SELECT "Steptype"."id" AS "Steptype__id", "Steptype"."name" AS "Steptype__name", "Steptype"."description" AS "Steptype__description", "Steptype"."subscribe" AS "Steptype__subscribe", "RequesttypesSteptype"."id" AS "RequesttypesSteptype__id", "RequesttypesSteptype"."phase" AS "RequesttypesSteptype__phase", "RequesttypesSteptype"."endsphase" AS "RequesttypesSteptype__endsphase", "RequesttypesSteptype"."endsrequest" AS "RequesttypesSteptype__endsrequest", "RequesttypesSteptype"."usertype_id" AS "RequesttypesSteptype__usertype_id", "RequesttypesSteptype"."requesttype_id" AS "RequesttypesSteptype__requesttype_id", "RequesttypesSteptype"."steptype_id" AS "RequesttypesSteptype__steptype_id" FROM "core"."steptypes" AS "Steptype" JOIN "core"."requesttypes_steptypes" AS "RequesttypesSteptype" ON ("RequesttypesSteptype"."requesttype_id" = 6 AND "RequesttypesSteptype"."steptype_id" = "Steptype"."id") ORDER BY "RequesttypesSteptype"."phase" ASC
Direct use of the buildStatement does not work either
I also tried to use the statement itself directly, without building an expression from it. This actually creates exactly the SQL-query I want to have, but does not add the quotes of the table alias in the FROM-clause correctly and therefore causes postgreSQL to throw an error:
SELECT "Requestinstance"."id" AS "Requestinstance__id", "Requestinstance"."user_id" AS "Requestinstance__user_id", "Requestinstance"."created" AS "Requestinstance__created", "Requestinstance"."requesttype_id" AS "Requestinstance__requesttype_id", "Requestinstance"."currentphase" AS "Requestinstance__currentphase", "Requestinstance"."selfsolving" AS "Requestinstance__selfsolving", "User"."username" AS "User__username", "User"."id" AS "User__id", "User"."company_id" AS "User__company_id", "User"."usertype_id" AS "User__usertype_id", "Requesttype"."id" AS "Requesttype__id", "Requesttype"."name" AS "Requesttype__name", "Requesttype"."subtitle" AS "Requesttype__subtitle", "Requesttype"."description" AS "Requesttype__description", "Requesttype"."order" AS "Requesttype__order", "Requesttype"."selfsolving" AS "Requesttype__selfsolving" FROM "core"."requestinstances" AS "Requestinstance" LEFT JOIN "core"."users" AS "User" ON ("Requestinstance"."user_id" = "User"."id") LEFT JOIN "core"."requesttypes" AS "Requesttype" ON ("Requestinstance"."requesttype_id" = "Requesttype"."id") WHERE EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS Privilege WHERE "Privilege"."objecttable" = 'requestinstances' AND "Privilege"."objectid" = "Requestinstance"."id" AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" = (8)) OR EXISTS (SELECT "Privilege"."id" FROM "core"."privileges" AS Privilege WHERE "Privilege"."objecttable" = 'requestinstances' AND "Privilege"."read" = 'TRUE' AND "Privilege"."id" IN (7, 13, 6, 9, 10, 12) AND "Privilege"."objectid" IS NULL) LIMIT 1
Adding the quotes manually to the alias-string while building the statement does not help either, since the framework strips the quotes.
So finally my question(s):
Does anybody know, if the containable-behavior supports expressions at all? I already digged into the DboSource, PdoSource and Postgresql-datasource but could not find anything wrong here. The Containable behavior looks pretty straight forward as well. Am I doing something wrong here?
Or is there another way I could acchieve what I want?
I'm glad for any help in this matter!
Thanks in advance!
I finally figured it out!
To formally answer the question:
Yes, the containable behavior does support expression-syntax!
My problem was with the processing order: The framework processes the behaviors the configured order, I accidently loaded the containable before my custom behavior, thats why it never received my modified conditions...
Working with the correct order, the manipulated condition-string was processed fine by the containable behavior.
To be absolutely sure about the behaviors order, I moved the behavior-loading to the AppModels __construct() method:
// unload any configured Containable behavior
if($this->Behaviors->loaded('Containable')) {
$this->Behaviors->unload('Containable');
}
// load the PrivilegeItem behavior
if($this->alias !== 'Privilege') {
$this->Behaviors->load('PrivilegeItem');
}
// and finally (re-)attach the Containable behavior
$this->Behaviors->load('Containable');
Maybe it helps others avoiding two days of debugging headache...

Standard or convention for DateTime to [A-Z] string conversion?

I like to use DateTime.UtcNow.ToString("yyyyMMddHHmmss") as a unique-enough salt for padding instead of a random string or GUID in tests for easier debugging and sorting. However I can't use it where validation only allows alpha character strings, e.g. a name (where 'Falsehoods Programmers Believe About Names' is ignored).
Is there a standard or a convention to encode a timestamp as a [A-Z]+ string? Preferably something more efficient than roman numerals but still human readable, i.e. not a base64-like lookup-table-based variant but a logic-based one.
Not that I know of, but if you treat A as 0 and J as 9 you can simply replace all numbers from the yyyyMMddHHmmss string.
I ended up with a lookup using a mix of leet speak and calculator spelling forgoing sorting in lieu of readability.
http://www.wikihow.com/Sample/1337-Cheat-Sheet
http://www.wikihow.com/Sample/Calculator-Letter-List
http://www.inversoft.com/blog/2013/08/28/profanity-filtering-101-character-replacements-leet-speak/
var map = new Dictionary<char, char>
{
{ '0', 'O' },
{ '1', 'I' },
{ '2', 'Z' },
{ '3', 'E' },
{ '4', 'A' },
{ '5', 'S' },
{ '6', 'G' },
{ '7', 'T' },
{ '8', 'B' },
{ '9', 'P' }
};
return string.Concat(value.Select(c => map[c]));