Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to read specific lines from file and continue reading after ending the process of each chunk. Let's say, I have 19000 lines in a file. Each time, I will extract first 19 lines,make some calculation with those lines and write the output in another file. Then I will extract again the next 19 lines and do the same processing. So, I tried to extract lines in the following way: ``` n=19 x = defaultdict(list) i=0 fp = open("file") for next_n_lines in izip_longest(*[fp] *n): lines = next_n_lines for i, line in enumerate(lines): do calculation write results ``` Here the code works for first chunk. Could any of you please help me, how can I continue for next n number of chunk ? Thanks a lot in advance!
Your code already extracts lines in groups of 19 lines so I'm not sure what your issue is. I can clean up your solution slightly, but it does the same thing as your code: ``` from itertools import izip_longest # grouping recipe from itertools documentation def grouper(n, iterable, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) def process_chunk(chunk): "Return sequence of result lines. Chunk must be iterable." for i, line in enumerate(chunk): yield 'file-line {1:03d}; chunk-line {0:02d}\n'.format(i, int(line)) yield '----------------------------\n' ``` Here is some test code that demonstrates that every line is visited: ``` from StringIO import StringIO class CtxStringIO(StringIO): def __enter__(self): return self def __exit__(self, *args): return False infile = CtxStringIO(''.join('{}\n'.format(i) for i in xrange(19*10))) outfile = CtxStringIO() # this should be the main loop of your program. # just replace infile and outfile with real file objects with infile as ifp, outfile as ofp: for chunk in grouper(19, ifp, '\n'): ofp.writelines(process_chunk(chunk)) # see what was written to the file print ofp.getvalue() ``` This test case should print lines like this: ``` file-line 000; chunk-line 00 file-line 001; chunk-line 01 file-line 002; chunk-line 02 file-line 003; chunk-line 03 file-line 004; chunk-line 04 ... file-line 016; chunk-line 16 file-line 017; chunk-line 17 file-line 018; chunk-line 18 ---------------------------- file-line 019; chunk-line 00 file-line 020; chunk-line 01 file-line 021; chunk-line 02 ... file-line 186; chunk-line 15 file-line 187; chunk-line 16 file-line 188; chunk-line 17 file-line 189; chunk-line 18 ---------------------------- ```
It's not clear in your question, but I guess the calculations you make depend on all the N lines you extract (19 in your example). So it's better to extract all these lines and then do the work: ``` N = 19 inFile = open('myFile') i = 0 lines = list() for line in inFile: lines.append(line) i += 1 if i == N: # Do calculations and save on output file lines = list() i = 0 ```
python read specific lines from file and continue
[ "", "python", "loops", "readlines", "" ]
I have a structure like this: ``` ['a;1,2,3\n', 'b;abc\n', ...] ``` in other words: it is a `List` with items like this: `'id;element1,element2,...\n'` now I want to check if the List contains a element with the id = `"b"` and if it cotains the item `"b"` I want to return the whole element: ``` 'b;abc\n' ``` how to do this with python? is it possible to do it with a `in` statement?
This will return you a list of all items that match your criteria, I assumed it may have more than one result matching, if there is only 1 result, the result list will have 1 item. ``` >>> input = ['a;1,2,3\n', 'b;abc\n'] >>> filter(lambda item:item.find('b;') == 0 ,input) ['b;abc\n'] ```
``` >>> L = ['a;1,2,3\n', 'b;abc\n'] >>> next((x for x in L if x.partition(';')[0] == 'b'), 'No match') 'b;abc\n' ```
check if item is in list and then return the item
[ "", "python", "" ]
I need to display distinct data between three tables. How to do this requirement. FirstTable: ``` 9999999999 8888888888 7777777777 6666666666 5555555555 ``` SecondTable: ``` 7777777777 9999999999 ``` ThirdTable: ``` 8888888888 ``` i want output in this format. ``` 6666666666 5555555555 ```
Use `LEFT JOIN` ``` SELECT T1."Col" FROM Table1 T1 LEFT JOIN Table2 T2 ON T1."Col" = T2."Col" LEFT JOIN Table3 T3 ON T1."Col" = T3."Col" WHERE T2."Col" IS NULL AND T3."Col" IS NULL ``` Output: ``` | COL | -------------- | 6666666666 | | 5555555555 | ``` ### [See this SQLFiddle](http://sqlfiddle.com/#!4/2981e/4)
For the data you gave us, you can try this: ``` select YourColumn from Table1 minus select Yourcolumn from Table2 minus select YourColumn from Table3 ``` This however wouldn't give you entries that existed in Table 3 but not tables 1 ND 2. I second the suggestion that you improve the question.
How to get data from three or more tables
[ "", "sql", "oracle", "" ]
I have the following code and I am having trouble figuring out how to NOT include these into the group by. Some of the arguments are purely for the case and that is all. I can't include them in the group by. I cam't really group by anything else as I need to get the counts by TransactionTyp only but I keep getting this error: is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Maybe the use of CASE is the wrong way to go about this? But I need to replace some of the values based on other fields. This is in MS SQL too. ``` SELECT Count(*), CASE WHEN a.TransactionTyp IS NOT NULL THEN a.TransactionTyp WHEN a.ClaimStatus = 'Resolved-Deflected' THEN 'Deflected' WHEN a.ClaimStatus = 'Resolved-NoAction' THEN 'Deflected' WHEN a.ClaimStatus = 'Open' AND b.AssignOperator = 'PendClaim.NF_POS_Pinless' THEN 'Affiliate' END As TransactionTyp FROM Table1 a LEFT JOIN Table2 b ON a.ClaimNbr = b.ClaimDisputeNbr AND b.CreateDte = Convert(varchar,GetDate(), 101) WHERE a.ClaimEntryDte = Convert(varchar,GetDate(),101) AND a.ClaimTypCd IN ('DEBS', 'DEBSI', 'DBCIN', 'DBCUS') GROUP BY TransactionTyp ```
One problem might be that you can't refer to aliases in the `group by` clause. Try to repeat the `case` definition in the `group by`: ``` GROUP BY CASE WHEN a.TransactionTyp IS NOT NULL THEN a.TransactionTyp WHEN a.ClaimStatus = 'Resolved-Deflected' THEN 'Deflected' WHEN a.ClaimStatus = 'Resolved-NoAction' THEN 'Deflected' WHEN a.ClaimStatus = 'Open' AND b.AssignOperator = 'PendClaim.NF_POS_Pinless' THEN 'Affiliate' END As TransactionTyp ``` Alternatively, use a subquery to define the alias: ``` select TransactionTyp , count(*) from ( SELECT CASE WHEN a.TransactionTyp IS NOT NULL THEN a.TransactionTyp WHEN a.ClaimStatus = 'Resolved-Deflected' THEN 'Deflected' WHEN a.ClaimStatus = 'Resolved-NoAction' THEN 'Deflected' WHEN a.ClaimStatus = 'Open' AND b.AssignOperator = 'PendClaim.NF_POS_Pinless' THEN 'Affiliate' END As TransactionTyp FROM Table1 a LEFT JOIN Table2 b ON a.ClaimNbr = b.ClaimDisputeNbr AND b.CreateDte = Convert(varchar,GetDate(), 101) WHERE a.ClaimEntryDte = Convert(varchar,GetDate(),101) AND a.ClaimTypCd IN ('DEBS', 'DEBSI', 'DBCIN', 'DBCUS') ) GROUP BY TransactionTyp ```
Without adding create\_on on group by how to get current Date result or current month result ``` select segment_name, cast(SUM(case when t1.create_on=GETDATE()) then actual_total_sale as currentDateData, cast(SUM(case when MONTH(create_on) = MONTH(getDate()) then actual_total_sale as currentMonthData, from PR_DAILY_AOP_TARGET t1 where is_active=1 group by segment_name ```
Using field in CASE without group by
[ "", "sql", "sql-server", "group-by", "" ]
I have the following data from a csv file called temp. ``` Item,Description,Base Price,Available 2000-000-000-300,AC - CF/M Series Green For Black Hood,299.99,3 2000-000-000-380,AC - CF/M Series Green For White Hood,299.99,3 ``` I need to change the headers to read ``` Item Number,Item Description,List Price,QTY Available ``` I have been searching similar questions on here and haven't a solution that I can understand since I am relatively new to python programming. So far I have: ``` import csv import os inputFileName = "temp.csv" outputFileName = os.path.splitext(inputFileName)[0] + "_modified.csv" with open(inputFileName) as inFile, open(outputFileName, "w") as outfile: r = csv.reader(inFile) w = csv.writer(outfile) ``` Which I know only reads the original file and then will write to \_modified. How do I select the current headers and then change them so that they write to the new file?
The headers are just another row of CSV data. Just write them as a new row to the output followed by the rest of the data from the input file. ``` import csv import os inputFileName = "temp.csv" outputFileName = os.path.splitext(inputFileName)[0] + "_modified.csv" with open(inputFileName, 'rb') as inFile, open(outputFileName, 'wb') as outfile: r = csv.reader(inFile) w = csv.writer(outfile) next(r, None) # skip the first row from the reader, the old header # write new header w.writerow(['Item Number', 'Item Description', 'List Price', 'QTY Available']) # copy the rest for row in r: w.writerow(row) ``` For Python 3, use: ``` with open(inputFileName, newline='') as inFile, open(outputFileName, 'w', newline='') as outfile: ``` and you may have to specify an encoding for your data.
Another solution is to use the `fileinput` module to update the file in place: ``` import fileinput for line in fileinput.input('temp', inplace=True): if fileinput.isfirstline(): print 'Item Number,Item Description,List Price,QTY Available' else: print line, ```
Python Edit CSV headers
[ "", "python", "" ]
I'm trying to print the values of a list without line breaks using `sys.stdout.write()`. It works great, but the only problem is that I want to space each value from another. In other words, instead of `123`, I want `1 2 3`. I looked on the website for a solution, but I haven't found something that involves lists. When I add `" "` to `sys.stdout.write(list[i])`, like this: `sys.stdout.write(list[i], " ")`, it doesn't print at all. Any suggestions how to fix that? Here's my code: ``` import random import sys list = [] length = input("Please enter the number of elements to be sorted: ") randomNums = input("Please enter the number of random integers to be created: ") showList = raw_input("Would you like to see the unsorted and sorted list? y/n: ") for i in range(length): list.append(random.randint(1,randomNums)) if(showList == "y"): for i in range(length): sys.stdout.write(list[i], " ") ```
Try ``` sys.stdout.write(" ".join(list)) ``` The above will only work if `list` contains strings. To make it work for any list: ``` sys.stdout.write(" ".join(str(x) for x in list)) ``` Here we use a [generator expression](http://www.python.org/dev/peps/pep-0289/) to convert each item in the list to a string. If your list is large and you'd like to avoid allocating the whole string for it, the following approach will also work: ``` for item in list[:-1]: sys.stdout.write(str(item)) sys.stdout.write(" ") if len(list) > 0: sys.stdout.write(list[-1]) ``` And as mentioned in the other answer, don't call your variable `list`. You're actually shadowing the built-in type with the same name.
You can do: ``` sys.stdout.write(" ".join(my_list)) ``` Also, it's better not to name your variable `list` as Python already has a built-in type called `list`. Hence, that's why I've renamed your variable to `my_list`.
Printing a list without line breaks (but with spaces) in Python
[ "", "python", "python-2.7", "" ]
I'm stuck with a script in Python 3. I want to append additional text to already existing label in tkinter. I attempted this: ``` def labelConfig(string,append=False): if append: label.configure(text+=string) else: label.configure(text=string) ``` But it won't compile... How can I do this properly?
This isn't a tkinter problem, this applies to all of python. You cannot use `+=` when setting a positional argument in a function call. Instead, you must get the value, modify it however you want, then assign the new value to the widget. For example: ``` def labelConfig(string,append=False): if append: text = label.cget("text") + string label.configure(text=text) else: label.configure(text=string) ```
Apart from Bryan Oakley's answer, it also possible to use `+=` if you access the text of the label as a value from a dictionary: ``` def labelConfig(string,append=False): if append: label['text'] += string else: label['text'] = string ``` All options that can be getted or setted with `configure` have the equivalent syntax `widget['option'] = value`, which can be used in situations like this one.
Appending text to label tkinter
[ "", "python", "string", "tkinter", "label", "append", "" ]
I have a Table such that looks like the following: ``` ID TID TNAME CID CNAME SEQUENCE ----------------------------------------------------------- 200649 6125 Schalke 356954 Mirko 1 200749 6125 Schalke 356954 Mirko 1 200849 6125 Schalke 439386 Fred 1 200849 6125 Schalke 356954 Mirko 1 200849 6125 Schalke 495881 Michael 1 200949 6125 Schalke 401312 Felix 1 200949 6125 Schalke 495881 Michael 2 ``` I would like to query this table so it only returns if ID and SEQUENCE are duplicated. i.e. it should only return: ``` 200849 6125 Schalke 439386 Fred 1 200849 6125 Schalke 356954 Mirko 1 200849 6125 Schalke 495881 Michael 1 ``` I have used `having count(ID) > 1` but it will not return anything since CIDs are all unique. Thanks for your help!
I think this is a way to do it: ``` select a.* from yourTable as a inner join ( select id, sequence from yourTable group by id, sequence having count(id)>1) as b on a.id = b.id and a.sequence=b.sequence ```
Something like this? ``` SELECT b.id, b.tid, b.tname, b.cid, b.cname, b.sequence FROM (SELECT id, sequence, Count(*) CNT FROM table1 GROUP BY id, sequence HAVING Count(*) > 1) a LEFT JOIN table1 b ON b.id = a.id AND b.sequence = a.sequence ``` **Result** ``` | ID | TID | TNAME | CID | CNAME | SEQUENCE | --------------------------------------------------------- | 200849 | 6125 | Schalke | 439386 | Fred | 1 | | 200849 | 6125 | Schalke | 356954 | Mirko | 1 | | 200849 | 6125 | Schalke | 495881 | Michael | 1 | ``` [See the demo](http://sqlfiddle.com/#!2/fc2a7/1)
Table has unique rows, however how can I find duplicates of certain columns?
[ "", "sql", "oracle", "" ]
i'm getting python error: **TypeError: join() takes exactly one argument (2 given)** in line 139, of set\_Xpress method, which looks like this: ``` from os import path from json import load ... def set_Xpress(Xpress_number, special_ts, disk, platform, testcase): ... with open("{0}:\\BBT2\\Configuration\\temporary.tmp".format(disk), "r") as test_conf_file_r: test_conf_vocab = load(test_conf_file_r) report = path.join(test_conf_vocab["report_dir"], test_conf_vocab["report_name"]) ... ``` Please, help me understand what cause it. Python shell executes it with no problems, and the same stroke executed fine in another method with this tmp file. Thanks in advance.
`path` is not the `os.path` module, it's a string. You redefined it somewhere. ``` from os import path # path is a module, path.join takes many arguments ... path = '/some/path' # path is now a string, path.join is a totally # different method, takes a single iterable ... report = path.join(one, two) # TypeError, str.join takes one argument ```
[`os.path.join()`](http://docs.python.org/2/library/os.path.html#os.path.join) takes any number of arguments. Are you sure your `path.join` is actually calling `os.path.join`?
os.path.join() takes exactly one argument (2 given)
[ "", "python", "os.path", "" ]
I'm trying to build a search system, and I want to search by multiple fields`name, state, city,` in my django models. I wrote the below code, yet I've been unable to figure out how to go about it. Models: ``` class Finhall(models.Model): user=models.ForeignKey(User) name=models.CharField(max_length=250, unique=True) address=models.CharField(max_length=200) city=models.CharField(max_length=200) state=models.CharField(max_length=200) def __unicode__(self): return u'%s' % (self.name) ``` Views.py ``` def hup_find(request): if ('q' in request.GET) and request.GET['q'].strip(): query_string=request.GET.get('q') seens=Finhall.objects.filter(name__icontains=query_string) else: seens=None return render_to_response('find.html',{'seens':seens},context_instance=RequestContext(request)) ``` Template: ``` {% block content %} <body> <form action="" method="GET"> <input type="text" name="q" /> <button type="submit">search</button> </form> {% for seen in seens %} <p> {{seen.name}}</p> {% empty %} <p> no search </p> {% endfor %} </body> {% endblock %} ``` How can I go about this? I don't want to use haysatck due to some personal reasons.
you can use django [`Q`](https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects) objects to do `OR` query, or if you want to `AND`your queries together just use the current lookups as kwargs ``` seens = Finhall.objects.filter( name__icontains=query_string, address__icontains=query_string ) ``` You should really consider full text search or `haystack` (which makes search easy) because `icontains` issues a `%LIKE%` which is not remotely scalable
EDIT: Just noticed it is Postgres only Apparently in django 1.10 [SearchVector](https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/search/#searchvector) class was added. Usage from the docs: > Searching against a single field is great but rather limiting. The Entry instances we’re searching belong to a Blog, which has a tagline field. To query against both fields, use a SearchVector: ``` >>> from django.contrib.postgres.search import SearchVector >>> Entry.objects.annotate( ... search=SearchVector('body_text', 'blog__tagline'), ... ).filter(search='Cheese') [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>] ```
Search through multiple fields in Django
[ "", "python", "django", "django-views", "" ]
So I have a project with work to try and teach my boss to start using prepared SQL statements, but he could care less and says it's not a big deal. I want to know how to prove to him it is a big deal, but I just can't figure out how to inject a drop table command on the development test server we have set up. I developed an application for a company that is in its testing phase and I want to take it down (have back up) to present to him the issue, as I am using his SQL code. I am trying to get the company to get in habit of using prepared statements, but I seem to be the only one wanting change and they don't. Can someone help me "crack" this database with SQL injection? Thanks!! There is a comment box on the form to be submitted and when it sees an apostrophe it throws the error: Unable to Make Query:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's";', '100', '100')' at line 78 I've tried ``` foo'); DROP TABLE cabletypes;-- ``` but gives same error. How can I make it inject successfully when I am typing in the textarea prior to form submission? The textarea submits to the 'comments' column and value. SQL ``` $sql="INSERT INTO cabletypes (cable_type, sample_no, sample_date, section_lg, wet_dry, avgofppf, sheath_type, plastic_wt, inner_sheath, inner_al_wt, inner_steel_wt, cable_guard, guard_al_wt, guard_steel_wt, guard_other_wt, total_pairs_a, pair_count_gauge_a, copper_wt_a, total_pairs_b, pair_count_gauge_b, copper_wt_b, total_pairs_c, pair_count_gauge_c, copper_wt_c, total_pairs_d, pair_count_gauge_d, copper_wt_d, sum_pairs, copper_wt, copper_percent, lead_wt, lead_percent, contains_lead, waste_wt, sampler, supervisor, comments, cable_no, section_no) VALUES ( '$cable_type', '$sample_no', '$sample_date', '$section_lg', '$wet_dry', '$avgofppf', '$sheath_type', '$plastic_wt', '$inner_sheath', '$inner_al_wt', '$inner_steel_wt', '$cable_guard', '$guard_al_wt', '$guard_steel_wt', '$guard_other_wt', '$total_pairs_a', '$pair_count_gauge_a', '$copper_wt_a', '$total_pairs_b', '$pair_count_gauge_b', '$copper_wt_b', '$total_pairs_c', '$pair_count_gauge_c', '$copper_wt_c', '$total_pairs_d', '$pair_count_gauge_d', '$copper_wt_d', '$sum_pairs', '$copper_wt', '$copper_percent', '$lead_wt', '$lead_percent', 0, '$waste_wt', '$sampler', '$supervisor', '$comments', '$cable_no', '$section_no')"; } mysql_query($sql) or die ("Unable to Make Query:" . mysql_error()); print("Sample Sheet Submitted Successfully!"); ```
You can't issue multi-query SQL in PHP's [ext/mysql](http://php.net/manual/en/book.mysql.php) interface. So you can't do the `; DROP TABLE Students` trick at all. This one of the few points in favor of the deprecated mysql extension. Ironically, PDO supports multi-query by default for all queries. And Mysqli supports it only if you explicitly call [mysqli::multi\_query()](http://php.net/manual/en/mysqli.multi-query.php). But DROP TABLE is not the only illicit thing an attacker may try to do with SQL injection. In fact, an attack that does DROP TABLE is malicious, but gains the attacker nothing of value. Most SQL injection attacks are more methodical. I can think of an exploit for your example INSERT statement: ``` http://yourapp.example.com/cable_types.php?supervisor=jflay',(SELECT GROUP_CONCAT(CONCAT(table_name,'.',column_name)) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema=DATABASE()), NULL, NULL) -- ``` Voilà! I have just created a cable type whose comment tells me all the tables and columns in your database. I can then use this knowledge in subsequent attempts to exploit other pages in your site. (Actually, this may not be a sure example, because GROUP\_CONCAT has a length limit of 1024 characters by default, and your full set of columns is probably longer than that. You can use this exploit to get the same information but perhaps it'll take several INSERT queries.) Anyway, your boss *really* should use parameterized queries for the sake of security, and also for the sake of supporting strings containing apostrophes, but also ease of coding and for performance. Tell him that [prepared statements perform 14% faster](http://www.mysqlperformanceblog.com/2006/08/02/mysql-prepared-statements/) than non-prepared statements.
Send him the old story of [Exploits of a Mom](http://xkcd.com/327/): ![enter image description here](https://i.stack.imgur.com/R6WxZ.png) There's a nice example of numerous MySQL injection attacks here: <http://www.rackspace.com/knowledge_center/article/sql-injection-in-mysql> (Modern?) PHP prevents multiple statements being issued qith mysql\_query, which helps stop some types of SQL injection: <https://stackoverflow.com/a/10663100/74585> The old book [CGI Programming with Perl, 2nd Edition](http://shop.oreilly.com/product/9781565924192.do) is worth a read, even if you don't use CGI or perl, as its [security chapter](http://books.google.com.au/books?id=qAtJv3a49XMC&lpg=PP1&pg=PA194#v=onepage&q&f=false) brilliantly demonstrates that the essence of avoiding things like SQL injection attacks is to **never trust input from the user**.
Demonstrating SQL injection attacks to my boss
[ "", "sql", "code-injection", "" ]
I am trying to deploy a dacpac on tenant using sqlpackage.exe. Currently I am giving SysAdmin or db\_owner permission to the account which will deploy this and it works fine. But in production, if the target tenant database is of some other application, I might not get these permissions, so would like to know the minimal permission that is required for this.
From here: [Upgrade a Data-tier Application](http://msdn.microsoft.com/en-us/library/ee634742.aspx#Permissions) > Permissions > > A DAC can only be upgraded by members of the sysadmin or serveradmin fixed server roles, or by logins that are in the dbcreator fixed server role and have ALTER ANY LOGIN permissions. The login must be the owner of the existing database. The built-in SQL Server system administrator account named sa can also upgrade a DAC.
To update an existing database, you may need to disable the "Deploy database properties" advanced option if deploying in Visual Studio or "/p:ScriptDatabaseOptions=False" when deploying using SQLPACKAGE.EXE.
Permission required for deploy a dacpac
[ "", "sql", "deployment", "" ]
I'm learning python and I want to make sure I am organizing "if" statements in a correct way. The situation that I keep running a lot into is the following : ``` if x == 0: dostuff_A if y == 0: dostuff_B else: dostuff_B ``` As you can see I keep repeating "dostuff\_B" a lot and have to contantly be changing code twice. I know I could have a function instead "dostuff\_B" but my question is regarding the if design. Another workaround that I found is doing the following but then i duplicate the if statement. ``` if x == 0: dostuff_A if x != 0 or y == 0: dostuff_B ``` Any ideas? Thanks in advance! UPDATE : Removed spaces before colon. Also updated my workaround because didn't make sense. Original version was : ``` if x == 0: dostuff_A if x == 0 and y == 0: dostuff_B ```
I see some correct answers have been posted already but they do not explain how they got to the solution. One way of simplifying nested `if-else` statements is by using truth tables: ``` x y what you call ----------------------- 0 0 A and B 0 1 A 1 0 B 1 1 B ``` From the table above you can see that you only call A when `x == 0`. Let's put that into code: ``` if x == 0: somestuff_A ``` From the same table you can see that the only time you don't call B is when `x == 0` and `y == 1`. Again, let's put that into code: ``` if x != 0 or y == 0: somestuff_B ``` or: ``` if not x == 0 or y == 0: somestuff_B ``` If you put the two pieces of code together this is what you get: ``` if x == 0: somestuff_A if not x == 0 or y == 0: somestuff_B ```
I don't know if it's more pythonic, but the second style reads more clearly to me (I agree about the space before the colon, and removed it). ``` if x == 0: dostuff_A if x == 0 and y == 0: dostuff_B ``` This would hold up for other languages as well. However, the two examples you have (now that I look at it closer) are not logically equivalent; perhaps you meant this: ``` if x == 0: dostuff_A if x != 0 or y == 0: dostuff_B ```
Python Pythonic way to organize/design if statements
[ "", "python", "design-patterns", "if-statement", "" ]
I have trained a corpus for LDA topic modelling using gensim. Going through the tutorial on the gensim website (this is not the whole code): ``` question = 'Changelog generation from Github issues?'; temp = question.lower() for i in range(len(punctuation_string)): temp = temp.replace(punctuation_string[i], '') words = re.findall(r'\w+', temp, flags = re.UNICODE | re.LOCALE) important_words = [] important_words = filter(lambda x: x not in stoplist, words) print important_words dictionary = corpora.Dictionary.load('questions.dict') ques_vec = [] ques_vec = dictionary.doc2bow(important_words) print dictionary print ques_vec print lda[ques_vec] ``` This is the output that I get: ``` ['changelog', 'generation', 'github', 'issues'] Dictionary(15791 unique tokens) [(514, 1), (3625, 1), (3626, 1), (3627, 1)] [(4, 0.20400000000000032), (11, 0.20400000000000032), (19, 0.20263215848547525), (29, 0.20536784151452539)] ``` I don't know how the last output is going to help me find the possible topic for the `question` !!! Please help!
I have written a function in python that gives the possible topic for a new query: ``` def getTopicForQuery (question): temp = question.lower() for i in range(len(punctuation_string)): temp = temp.replace(punctuation_string[i], '') words = re.findall(r'\w+', temp, flags = re.UNICODE | re.LOCALE) important_words = [] important_words = filter(lambda x: x not in stoplist, words) dictionary = corpora.Dictionary.load('questions.dict') ques_vec = [] ques_vec = dictionary.doc2bow(important_words) topic_vec = [] topic_vec = lda[ques_vec] word_count_array = numpy.empty((len(topic_vec), 2), dtype = numpy.object) for i in range(len(topic_vec)): word_count_array[i, 0] = topic_vec[i][0] word_count_array[i, 1] = topic_vec[i][1] idx = numpy.argsort(word_count_array[:, 1]) idx = idx[::-1] word_count_array = word_count_array[idx] final = [] final = lda.print_topic(word_count_array[0, 0], 1) question_topic = final.split('*') ## as format is like "probability * topic" return question_topic[1] ``` Before going through this do refer [this](https://stackoverflow.com/questions/16254207/can-we-use-a-self-made-corpus-for-training-for-lda-using-gensim) link! In the initial part of the code, the query is being pre-processed so that it can be stripped off stop words and unnecessary punctuations. Then, the dictionary that was made by using our own database is loaded. We, then, we convert the tokens of the new query to bag of words and then the topic probability distribution of the query is calculated by `topic_vec = lda[ques_vec]` where `lda` is the trained model as explained in the link referred above. The distribution is then sorted w.r.t the probabilities of the topics. The topic with the highest probability is then displayed by `question_topic[1]`.
Assuming we just need topic with highest probability following code snippet may be helpful: ``` def findTopic(testObj, dictionary): text_corpus = [] ''' For each query ( document in the test file) , tokenize the query, create a feature vector just like how it was done while training and create text_corpus ''' for query in testObj: temp_doc = tokenize(query.strip()) current_doc = [] for word in range(len(temp_doc)): if temp_doc[word][0] not in stoplist and temp_doc[word][1] == 'NN': current_doc.append(temp_doc[word][0]) text_corpus.append(current_doc) ''' For each feature vector text, lda[doc_bow] gives the topic distribution, which can be sorted in descending order to print the very first topic ''' for text in text_corpus: doc_bow = dictionary.doc2bow(text) print text topics = sorted(lda[doc_bow],key=lambda x:x[1],reverse=True) print(topics) print(topics[0][0]) ``` The tokenize functions removes punctuations/ domain specific characters to filtered and gives the list of tokens. Here dictionary created in training is passed as parameter of the function, but it can also be loaded from a file.
How to predict the topic of a new query using a trained LDA model using gensim?
[ "", "python", "nlp", "lda", "topic-modeling", "gensim", "" ]
I have the following code. ``` message.gateway_message_id = parsed_response['gateway_message_id'].strip() ``` After this is run `message.gateway_message_id` variable contains this: ``` 18271817281-3 ``` **I would now like to take `message.gateway_message_id` and strip the dash and everything after it leaving only 18271817281, how?**
Use [`str.rsplit`](http://docs.python.org/2/library/stdtypes.html#str.rsplit) with the maxsplit parameter: ``` message.gateway_message_id.rsplit('-', 1)[0] '18271817281-3'.rsplit('-', 1)[0] # '18271817281' '1-2-3-4'.rsplit('-', 1)[0] # '1-2-3' '1234'.rsplit('-', 1)[0] # '1234' ```
`str.partition` (or `str.rpartition` depending on which side to strip the dash) was built for this, it will also be the fastest ``` message.gateway_message_id.rpartition('-')[0] ``` --- ``` >>> text = '18271817281-3' >>> text.rpartition('-')[0] '18271817281' ```
Python striping a variable everything after - dash
[ "", "python", "python-2.7", "" ]
In Python i can slice array with "jump-step". Example: ``` In [1]: a = [1,2,3,4,5,6,7,8,9] In [4]: a[1:7:2] # start from index = 1 to index < 7, with step = 2 Out[4]: [2, 4, 6] ``` Can Ruby do it?
``` a = [1,2,3,4,5,6,7,8,9] a.values_at(*(1...7).step(2)) - [nil] #=> [2, 4, 6] ``` Although in the above case the `- [nil]` part is not necessary, it serves just in case your range exceeds the size of the array, otherwise you may get something like this: ``` a = [1,2,3,4,5,6,7,8,9] a.values_at(*(1..23).step(2)) #=> [2, 4, 6, 8, nil, nil, nil, nil, nil, nil, nil, nil] ```
In ruby, to get the same output: ``` a = [1,2,3,4,5,6,7,8,9] (1...7).step(2).map { |i| a[i] } => [2, 4, 6] ```
split array to sub array by step in Ruby
[ "", "python", "ruby", "" ]
I am trying to use function `np.random.curve_fit(x,a,b,c,...,z)` with a big but fixed number of fitting parameters. Is it possible to use tuples or lists here for shortness, like `np.random.curve_fit(x,P)`, where `P=(a,b,c,...,z)`?
Well, to convert your example, you would use `np.random.normal(x, *P)`. However, `np.random.normal(x,a,b,c,...,z)` wouldn't actually work. Maybe you meant another function?
Yes, like this: ``` np.random.normal(x, *P) ``` The asterisk says "take the remaining arguments from this sequence." See [4.7.4. Unpacking Argument Lists](http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists).
list instead of separated arguments in python
[ "", "python", "" ]
How to do this in pandas: I have a function `extract_text_features` on a single text column, returning multiple output columns. Specifically, the function returns 6 values. The function works, however there doesn't seem to be any proper return type (pandas DataFrame/ numpy array/ Python list) such that the output can get correctly assigned `df.ix[: ,10:16] = df.textcol.map(extract_text_features)` So I think I need to drop back to iterating with `df.iterrows()`, as per [this](https://stackoverflow.com/questions/7837722/what-is-the-most-efficient-way-to-loop-through-dataframes-with-pandas)? UPDATE: Iterating with `df.iterrows()` is at least 20x slower, so I surrendered and split out the function into six distinct `.map(lambda ...)` calls. UPDATE 2: this question was asked back around [v0.11.0](https://github.com/pandas-dev/pandas/releases?after=v0.13.0_ahl1), before the useability `df.apply` was improved or [`df.assign()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.assign.html) was [added in v0.16](https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.16.0.html?highlight=assign). Hence much of the question and answers are not too relevant.
Building off of user1827356 's answer, you can do the assignment in one pass using `df.merge`: ``` df.merge(df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1})), left_index=True, right_index=True) textcol feature1 feature2 0 0.772692 1.772692 -0.227308 1 0.857210 1.857210 -0.142790 2 0.065639 1.065639 -0.934361 3 0.819160 1.819160 -0.180840 4 0.088212 1.088212 -0.911788 ``` **EDIT:** Please be aware of the huge memory consumption and low speed: <https://ys-l.github.io/posts/2015/08/28/how-not-to-use-pandas-apply/> !
I usually do this using `zip`: ``` >>> df = pd.DataFrame([[i] for i in range(10)], columns=['num']) >>> df num 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 >>> def powers(x): >>> return x, x**2, x**3, x**4, x**5, x**6 >>> df['p1'], df['p2'], df['p3'], df['p4'], df['p5'], df['p6'] = \ >>> zip(*df['num'].map(powers)) >>> df num p1 p2 p3 p4 p5 p6 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 4 8 16 32 64 3 3 3 9 27 81 243 729 4 4 4 16 64 256 1024 4096 5 5 5 25 125 625 3125 15625 6 6 6 36 216 1296 7776 46656 7 7 7 49 343 2401 16807 117649 8 8 8 64 512 4096 32768 262144 9 9 9 81 729 6561 59049 531441 ```
Apply pandas function to column to create multiple new columns?
[ "", "python", "pandas", "merge", "multiple-columns", "return-type", "" ]
I have a file with about 1,000,000 lines of fixed width data in it. I can read it, parse it, do all that. What I don't know is the best way to put it into a SQL Server database programmatically. I need to do it either via T-SQL or Delphi or C# (in other words, a command line solution isn't what I need...) I know about `BULK INSERT`, but that appears to work with CSV only.....? Should I create a CSV file from my fixed width data and `BULK INSERT` that? By "fastest" I mean "Least amount of processing time in SQL Server". My desire is to automate this so that it is easy for a "clerk" to select the input file and push a button to make it happen. What's the best way to get the huge number of fixed width records into a SQL Server table?
I assume that by "fastest" you mean run-time: The fastest way to do this from compiled code is to use the [SQLBulkCopy methods](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.batchsize.aspx) to insert the data directly into your target table. You will have to write your own code to open and read the source file and then split it into the appropriate columns according to their fixed-width offsets and then feed that to SQLBulkCopy. (I think that I have an example of this somewhere, if you want to go this route) The fastest way to do this from T-SQL would be to shell out to DOS and then use BCP to load the file directly into your target table. You will need to make a BCP Format File that defines the fixed-width columns for this appraoch. The fastest way to do this from T-SQL, *without* using any CLI, is to use BULK INSERT to load the file into a staging table with only one column as `DATA VARCHAR(MAX)` (make that NVARCHAR(MAX) if the file has unicode data in it). Then execute a SQL query you write to split the DATA column into its fixed-width fields and then insert them into your target file. This should only take a single INSERT statement, though it could be a big one. (I have an example of this somewhere as well) Your other 'fastest' option would be to use an SSIS package or the SQL Server Import Wizard (they're actually the same thing, under the hood). SSIS has a pretty steep learning curve, so it's only really worth it if you expect to be doing this (or things like this) for other cases in the future as well. On the other hand, the Wizard is fairly easy to use as a one-off. The Wizard can also make a schedulable job, so if you need to repeat the same thing every night, that's certainly the easiest, as long as it actually works on your case/file/data. If it doesn't then it can be a real headache to get it right, but fixed-width data should not be a problem. The fastest of all of these options has always been (and likely will always be) BCP.
I personally would do this with an SSIS package. It has the flexibility to handle a fixed width defintion. If this is one time load, use the wizard to import the data. If not. create a package yourself and then schedule it to run periodically.
What is the fastest way to get 1,000,000 lines of fixed width text into a SQL Server database?
[ "", "sql", "sql-server", "data-migration", "fixed-width", "" ]
I spent a whole day looking for the simplest possible multithreaded URL fetcher in Python, but most scripts I found are using queues or multiprocessing or complex libraries. Finally I wrote one myself, which I am reporting as an answer. Please feel free to suggest any improvement. I guess other people might have been looking for something similar.
Simplifying your original version as far as possible: ``` import threading import urllib2 import time start = time.time() urls = ["http://www.google.com", "http://www.apple.com", "http://www.microsoft.com", "http://www.amazon.com", "http://www.facebook.com"] def fetch_url(url): urlHandler = urllib2.urlopen(url) html = urlHandler.read() print "'%s\' fetched in %ss" % (url, (time.time() - start)) threads = [threading.Thread(target=fetch_url, args=(url,)) for url in urls] for thread in threads: thread.start() for thread in threads: thread.join() print "Elapsed Time: %s" % (time.time() - start) ``` The only new tricks here are: * Keep track of the threads you create. * Don't bother with a counter of threads if you just want to know when they're all done; `join` already tells you that. * If you don't need any state or external API, you don't need a `Thread` subclass, just a `target` function.
`multiprocessing` has a thread pool that doesn't start other processes: ``` #!/usr/bin/env python from multiprocessing.pool import ThreadPool from time import time as timer from urllib2 import urlopen urls = ["http://www.google.com", "http://www.apple.com", "http://www.microsoft.com", "http://www.amazon.com", "http://www.facebook.com"] def fetch_url(url): try: response = urlopen(url) return url, response.read(), None except Exception as e: return url, None, e start = timer() results = ThreadPool(20).imap_unordered(fetch_url, urls) for url, html, error in results: if error is None: print("%r fetched in %ss" % (url, timer() - start)) else: print("error fetching %r: %s" % (url, error)) print("Elapsed Time: %s" % (timer() - start,)) ``` The advantages compared to `Thread`-based solution: * `ThreadPool` allows to limit the maximum number of concurrent connections (`20` in the code example) * the output is not garbled because all output is in the main thread * errors are logged * the code works on both Python 2 and 3 without changes (assuming `from urllib.request import urlopen` on Python 3).
A very simple multithreading parallel URL fetching (without queue)
[ "", "python", "multithreading", "callback", "python-multithreading", "urlfetch", "" ]
The code I am working with is: ``` fout = open('expenses.0.col', 'w') for line in lines: words = line.split() amount = amountPaid(words) num = nameMonth(words) day = numberDay(words) line1 = amount, num, day fout.write(line1) fout.close() ``` There is a file that you cannot see that the line in lines is pulling from which runs just fine. There are 100 lines within lines. When writing this last bit of code the goal is to get 100 lines of three columns which consist of the values: amount, num, and day. All three of these values are integers. I have seen similar questions asked such as [[python]Writing a data file using numbers 1-10](https://stackoverflow.com/questions/10420931/pythonwriting-a-data-file-using-numbers-1-10), and I get the same error as that example. My problem is applying dataFile.write("%s\n" % line) to my case with three numbers in each line. Should be a quick 1 line of code fix.
In your example, `line1` is a tuple - of numbers (I assume the functions `amountPaid(), nameMonth(), numberDay()` all return an integer or float). You could do one of two things: * have these functions return the numbers as strings values * or cast the return values as string i.e.: `amount = str(amountPaid(words))` Once these values are strings you can simply do: ``` line1 = amount, num, day, '\n' fout.write(''.join(line1)) ``` Hope that helps!
use the print statement/function rather than the write method.
Python: writing a data file with three columns of integers
[ "", "python", "" ]
Given the following model: ``` create table child_parent ( child number(3), parent number(3) ); ``` Given the following data: ``` insert into child_parent values(2,1); insert into child_parent values(3,1); insert into child_parent values(4,2); insert into child_parent values(5,2); insert into child_parent values(6,3); ``` results in the following tree: ``` 1 / \ 2 3 / \ \ 4 5 6 ``` Now i can find the parents of 5 like this: ``` SELECT parent FROM child_parent START WITH child = 5 CONNECT BY NOCYCLE PRIOR parent = child; ``` But how can I get all the nodes (1,2,3,4,5,6) starting from 5?
Oracle's CONNECT BY syntax is intended for traversing hierarchical data: it is uni-directional so not a suitable for representing a graph, which requires bi-directionality. There's no way to go `2 -> 1 -> 3` in one query, which is what you need to do to get all the nodes starting from 5. --- A long timne ago I answered a question on flattening nodes in a hierarchy (AKA transitive closure) i.e. if `1->2->3` is true, `1->3' is true as well. It links to a paper which demonstrates a PL/SQL solution to generate all the edges and store them in a table. A similar solution could be used in this case. But obviously it is only practical if the nodes in the graph don't chnage very often. So perhaps it will only be of limited use. Anyway, [find out more](https://stackoverflow.com/a/3396499/146325).
Finally I came up with a solution similar like this: ``` SELECT child FROM child_parent START WITH parent = ( SELECT DISTINCT parent FROM ( SELECT parent FROM child_parent WHERE CONNECT_BY_ISLEAF = 1 START WITH child = 5 CONNECT BY PRIOR parent = child UNION SELECT parent FROM child_parent WHERE parent = 5 ) ) CONNECT BY NOCYCLE PRIOR child = parent UNION SELECT DISTINCT parent FROM ( SELECT parent FROM child_parent WHERE CONNECT_BY_ISLEAF = 1 START WITH child = 5 CONNECT BY PRIOR parent = child UNION SELECT parent FROM child_parent WHERE parent = 5 ); ``` It works with all nodes for the provided example. But if one of the leafs has a second parent and the starting point is above this node or in a different branch it don't work. But for me it is good enough. A solution to get all nodes in graph could be: implement the opposite of the query above (from top to bottom) and then execute them (bottom to top, top to bottom) vice versa until you find no more new nodes. This would need PL/SQL and I also don't know about the performance.
Find all nodes in an adjacency list model with oracle connect by
[ "", "sql", "oracle", "tree", "adjacency-list", "" ]
What's the easiest way to add an empty column to a pandas DataFrame object? The best I've stumbled upon is something like ``` df['foo'] = df.apply(lambda _: '', axis=1) ``` Is there a less perverse method?
If I understand correctly, assignment should fill: ``` >>> import numpy as np >>> import pandas as pd >>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]}) >>> df A B 0 1 2 1 2 3 2 3 4 >>> df["C"] = "" >>> df["D"] = np.nan >>> df A B C D 0 1 2 NaN 1 2 3 NaN 2 3 4 NaN ```
To add to DSM's answer and building on [this associated question](https://stackoverflow.com/questions/30926670/pandas-add-multiple-empty-columns-to-dataframe), I'd split the approach into two cases: * Adding a single column: Just assign empty values to the new columns, e.g. `df['C'] = np.nan` * Adding multiple columns: I'd suggest using the `.reindex(columns=[...])` [method of pandas](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html) to add the new columns to the dataframe's column index. This also works for adding multiple new rows with `.reindex(rows=[...])`. Note that newer versions of Pandas (v>0.20) allow you to specify an `axis` keyword rather than explicitly assigning to `columns` or `rows`. Here is an example adding multiple columns: ``` mydf = mydf.reindex(columns = mydf.columns.tolist() + ['newcol1','newcol2']) ``` or ``` mydf = mydf.reindex(mydf.columns.tolist() + ['newcol1','newcol2'], axis=1) # version > 0.20.0 ``` You can also always concatenate a new (empty) dataframe to the existing dataframe, but that doesn't feel as pythonic to me :)
How to add an empty column to a dataframe?
[ "", "python", "pandas", "dataframe", "variable-assignment", "" ]
``` create table t(a int, b int); insert into t values (1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3); select * from t; a | b ---------- 1 | 1 1 | 2 1 | 3 2 | 1 2 | 2 2 | 3 3 | 1 3 | 2 3 | 3 select max(case when a = 1 then b else 0 end) as q, max(case when b = 1 then a else 0 end) as c, ( max(case when a = 1 then b else 0 end) + max(case when b = 1 then a else 0 end) ) as x from t ``` Is it possible to do something like this? ``` select max(case when a = 1 then b else 0 end) as q, max(case when b = 1 then a else 0 end) as c, (q + c) as x from t ```
You can't use the `ALIAS` that was given on the same level of the `SELECT` clause. You have two choices: * by using the expression directly query: ``` select max(case when a = 1 then b else 0 end) as q, max(case when b = 1 then a else 0 end) as c, (max(case when a = 1 then b else 0 end) + max(case when b = 1 then a else 0 end)) as x from t ``` * by wrapping in a subquery query: ``` SELECT q, c, q + c as x FROM ( select max(case when a = 1 then b else 0 end) as q, max(case when b = 1 then a else 0 end) as c from t ) d ```
Also in SQLServer2005+ you can use CTE ``` ;WITH cte AS ( select max(case when a = 1 then b else 0 end) as q, max(case when b = 1 then a else 0 end) as c from t ) SELECT q, c, q + c as x FROM cte ```
how to get value x without code duplication
[ "", "sql", "" ]
I am trying to parse transaction letters from my (German) bank. I'd like to extract all the numbers from the following string which turns out to be harder than I thought. Option 2 does almost what I want. I now want to modify it to capture e.g. 80 as well. My first try is option 1 which only returns garbage. Why is it returning so many empty strings? It should always have at least a number from the first \d+, no? Option 3 works (or at least works as expected), so somehow I am answering my own question. I guess I'm mostly banging my head about why option 2 does not work. ``` # -*- coding: utf-8 -*- import re my_str = """ Dividendengutschrift für inländische Wertpapiere Depotinhaber : ME Extag : 18.04.2013 Bruttodividende Zahlungstag : 18.04.2013 pro Stück : 0,9800 EUR Valuta : 18.04.2013 Bruttodividende : 78,40 EUR *Einbeh. Steuer : 20,67 EUR Nettodividende : 78,40 EUR Endbetrag : 57,73 EUR """ print re.findall(r'\d+(,\d+)?', my_str) print re.findall(r'\d+,\d+', my_str) print re.findall(r'[-+]?\d*,\d+|\d+', my_str) ``` Output is ``` ['', '', '', '', '', '', ',98', '', '', '', '', ',40', ',67', ',40', ',73'] ['0,9800', '78,40', '20,67', '78,40', '57,73'] ['18', '04', '2013', '18', '04', '2013', '0,9800', '18', '04', '2013', '78,40', '20,67', '78,40', '57,73'] ```
Option 1 is the most suitable of the regex, but it is not working correctly because `findall` will return what is matched by the capture group `()`, not the complete match. For example, the first three matches in your example will be the `18`, `04` and `2013`, and in each case the capture group will be unmatched so an empty string will be added to the results list. The solution is to make the group non-capturing ``` r'\d+(?:,\d+)?' ``` Option 2 does not work only so far as it won't match sequences that don't contain a comma. Option 3 isn't great because it will match e.g. `+,1`.
> I'd like to extract all the numbers from the following string ... By "numbers", if you mean both the currency amounts AND the dates, I think that this will do what you want: ``` print re.findall(r'[0-9][0-9,.]+', my_str) ``` Output: ``` ['18.04.2013', '18.04.2013', '0,9800', '18.04.2013', '78,40', '20,67', '78,40', '57,73'] ``` If by "numbers" you mean only the currency amounts, then use ``` print re.findall(r'[0-9]+,[0-9]+', my_str) ``` Or perhaps better yet, ``` print re.findall(r'[0-9]+,[0-9]+ EUR', my_str) ```
Python regular expression (regex) match comma separated number - why does this not work?
[ "", "python", "regex", "" ]
I used openerp version 7 & i created a form view.but its only used to display data .not to add / edit data.above 2 selection boxes for query records. my requirement is need to remove **save** button from top left corner ![screen](https://i.stack.imgur.com/Np6ax.png) **EDITED** : Code added for relevant to that area ``` <record model="ir.actions.act_window" id="bpl_worker_summary_action"> <field name="name">Worker Summary</field> <field name="res_model">bpl.worker.summary</field> <field name="view_type">form</field> <field name="view_mode">form</field> </record> <?xml version="1.0" encoding="utf-8"?> <openerp> <data> <record model="ir.ui.view" id="bpl_worker_summary_form"> <field name="name">Worker Summary</field> <field name="model">bpl.worker.summary</field> <field name="arch" type="xml"> <form string='bpl_worker_summary' create="false" edit="false" version='7.0' > <sheet> <group> <group> <field name='bpl_company_id' readonly="1" /> <field name='bpl_estate_id' /> ```
To remove the save button, you can modify the access right for the logged in user that shouldn't be able to save. The access rights rule will be such that the user or preferrably his group wouldn't have "`write`" access to the "`object`"
You can use `create="false"` attribute in `form` tag. It will disable **Create** button from form view. You can use `edit="false"` to disable **Edit** button. If you want to disable button from form view then use this: ``` <form create="false" edit="false"> ``` If you want to disable button from tree view then use this: ``` <tree create="false"> ```
How to remove Save Button from form view
[ "", "python", "xml", "odoo", "" ]
I have a 2D array containing integers (both positive or negative). Each row represents the values over time for a particular spatial site, whereas each column represents values for various spatial sites for a given time. So if the array is like: ``` 1 3 4 2 2 7 5 2 2 1 4 1 3 3 2 2 1 1 ``` The result should be ``` 1 3 2 2 2 1 ``` Note that when there are multiple values for mode, any one (selected randomly) may be set as mode. I can iterate over the columns finding mode one at a time but I was hoping numpy might have some in-built function to do that. Or if there is a trick to find that efficiently without looping.
Check [`scipy.stats.mode()`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mode.html#scipy.stats.mode) (inspired by @tom10's comment): ``` import numpy as np from scipy import stats a = np.array([[1, 3, 4, 2, 2, 7], [5, 2, 2, 1, 4, 1], [3, 3, 2, 2, 1, 1]]) m = stats.mode(a) print(m) ``` Output: ``` ModeResult(mode=array([[1, 3, 2, 2, 1, 1]]), count=array([[1, 2, 2, 2, 1, 2]])) ``` As you can see, it returns both the mode as well as the counts. You can select the modes directly via `m[0]`: ``` print(m[0]) ``` Output: ``` [[1 3 2 2 1 1]] ```
**Update** The `scipy.stats.mode` function has been significantly optimized since this post, and would be the recommended method **Old answer** This is a tricky problem, since there is not much out there to calculate mode along an axis. The solution is straight forward for 1-D arrays, where `numpy.bincount` is handy, along with `numpy.unique` with the `return_counts` arg as `True`. The most common n-dimensional function I see is scipy.stats.mode, although it is prohibitively slow- especially for large arrays with many unique values. As a solution, I've developed this function, and use it heavily: ``` import numpy def mode(ndarray, axis=0): # Check inputs ndarray = numpy.asarray(ndarray) ndim = ndarray.ndim if ndarray.size == 1: return (ndarray[0], 1) elif ndarray.size == 0: raise Exception('Cannot compute mode on empty array') try: axis = range(ndarray.ndim)[axis] except: raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim)) # If array is 1-D and numpy version is > 1.9 numpy.unique will suffice if all([ndim == 1, int(numpy.__version__.split('.')[0]) >= 1, int(numpy.__version__.split('.')[1]) >= 9]): modals, counts = numpy.unique(ndarray, return_counts=True) index = numpy.argmax(counts) return modals[index], counts[index] # Sort array sort = numpy.sort(ndarray, axis=axis) # Create array to transpose along the axis and get padding shape transpose = numpy.roll(numpy.arange(ndim)[::-1], axis) shape = list(sort.shape) shape[axis] = 1 # Create a boolean array along strides of unique values strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'), numpy.diff(sort, axis=axis) == 0, numpy.zeros(shape=shape, dtype='bool')], axis=axis).transpose(transpose).ravel() # Count the stride lengths counts = numpy.cumsum(strides) counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])]) counts[strides] = 0 # Get shape of padded counts and slice to return to the original shape shape = numpy.array(sort.shape) shape[axis] += 1 shape = shape[transpose] slices = [slice(None)] * ndim slices[axis] = slice(1, None) # Reshape and compute final counts counts = counts.reshape(shape).transpose(transpose)[slices] + 1 # Find maximum counts and return modals/counts slices = [slice(None, i) for i in sort.shape] del slices[axis] index = numpy.ogrid[slices] index.insert(axis, numpy.argmax(counts, axis=axis)) return sort[index], counts[index] ``` Result: ``` In [2]: a = numpy.array([[1, 3, 4, 2, 2, 7], [5, 2, 2, 1, 4, 1], [3, 3, 2, 2, 1, 1]]) In [3]: mode(a) Out[3]: (array([1, 3, 2, 2, 1, 1]), array([1, 2, 2, 2, 1, 2])) ``` Some benchmarks: ``` In [4]: import scipy.stats In [5]: a = numpy.random.randint(1,10,(1000,1000)) In [6]: %timeit scipy.stats.mode(a) 10 loops, best of 3: 41.6 ms per loop In [7]: %timeit mode(a) 10 loops, best of 3: 46.7 ms per loop In [8]: a = numpy.random.randint(1,500,(1000,1000)) In [9]: %timeit scipy.stats.mode(a) 1 loops, best of 3: 1.01 s per loop In [10]: %timeit mode(a) 10 loops, best of 3: 80 ms per loop In [11]: a = numpy.random.random((200,200)) In [12]: %timeit scipy.stats.mode(a) 1 loops, best of 3: 3.26 s per loop In [13]: %timeit mode(a) 1000 loops, best of 3: 1.75 ms per loop ``` EDIT: Provided more of a background and modified the approach to be more memory-efficient
Most efficient way to find mode in numpy array
[ "", "python", "numpy", "2d", "mode", "" ]
I would like to split a string by ':' and ' ' characters. However, i would like to ignore two spaces ' ' and two colons '::'. for e.g. ``` text = "s:11011 i:11010 ::110011 :110010 d:11000" ``` should split into ``` [s,11011,i,11010,:,110011, ,110010,d,11000] ``` after following the Regular Expressions HOWTO on the python website, i managed to comeup with the following ``` regx= re.compile('([\s:]|[^\s\s]|[^::])') regx.split(text) ``` However this does not work as intended as it splits on the : and spaces, but it still includes the ':' and ' ' in the split. ``` [s,:,11011, ,i,:,11010, ,:,:,110011, , :,110010, ,d,:,11000] ``` How can I fix this? **EDIT:** In case of a double space, i only want one space to appear
Note this assumes that your data has format like `X:101010`: ``` >>> re.findall(r'(.+?):(.+?)\b ?',text) [('s', '11011'), ('i', '11010'), (':', '110011'), (' ', '110010'), ('d', '11000')] ``` Then `chain` them up: ``` >>> list(itertools.chain(*_)) ['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000'] ```
``` >>> text = "s:11011 i:11010 ::110011 :110010 d:11000" >>> [x for x in re.split(r":(:)?|\s(\s)?", text) if x] ['s', '11011', 'i', '11010', ':', '110011', ' ', '110010', 'd', '11000'] ```
Python split a string using regex
[ "", "python", "regex", "string", "split", "" ]
So I'm trying to pull off a trick I actually first heard about on this site. ``` [i for i in range(0, 10) if True or print(i)] ``` The idea being that you can call an arbitrary function at every step of a listcomp by sticking it inside an "if" statement that will always return True. But that code gives a syntax error. If I wrap the function I want to call like this, though: ``` def f(i): print i [i for i in range(0, 10) if True or f(i)] ``` it produces the desired output. So I was wondering what the difference is, in Python's mind, between the two, because I can't tell what it could be -- both functions return "None", right?
You cannot mix statements (like `print` in Python 2) with a list comprehension. However, you *can* make `print()` a function by adding: ``` from __future__ import print_function ``` at the top of your file. This turns `print()` into a function for the *whole* module. However, you are using the statement `True or something` and that will never evaluate 'something' because Python boolean expressions short-circuit. You want to turn that around: ``` if print(something) or True ``` There is no point in evaluating the right-hand side of a `or` expression if the left-hand side already evaluated to `True`; nothing the right-hand side can come up with will make the whole expression `False`, ever. You really want to *avoid* such side effects in a list comprehension though. Use a proper loop and keep such surprises out of your code, using `if something or True` is really a hack that will confuse future maintainers of your code (including you).
In Python 2.x, print is not a function. It became a function in Python 3.
Calling print in the middle of a python list comprehension
[ "", "python", "python-2.7", "list-comprehension", "" ]
I'm trying to teach myself Python, and doing well for the most part. However, when I try to run the code ``` class Equilateral(object): angle = 60 def __init__(self): self.angle1, self.angle2, self.angle3 = angle tri = Equilateral() ``` I get the following error: ``` Traceback (most recent call last): File "python", line 15, in <module> File "python", line 13, in __init__ NameError: global name 'angle' is not defined ``` There is probably a very simple answer, but why is this happening?
``` self.angle1, self.angle2, self.angle3 = angle ``` should be ``` self.angle1 = self.angle2 = self.angle3 = self.angle ``` just saying `angle` makes python look for a global `angle` variable which doesn't exist. You must reference it through the `self` variable, or since it is a class level variable, you could also say `Equilateral.angle` The other issues is your comma separated `self.angleN`s. When you assign in this way, python is going to look for the same amount of parts on either side of the equals sign. For example: ``` a, b, c = 1, 2, 3 ```
You need to use `self.angle` here because classes are namespaces in itself, and to access an attribute inside a class we use the `self.attr` syntax, or you can also use `Equilateral.angle` here as `angle` is a class variable too. ``` self.angle1, self.angle2, self.angle3 = self.angle ``` Which is still wrong becuase you can't assign a single value to three variables: ``` self.angle1, self.angle2, self.angle3 = [self.angle]*3 ``` Example: ``` In [18]: x,y,z=1 #your version --------------------------------------------------------------------------- TypeError: 'int' object is not iterable #some correct ways: In [21]: x,y,z=1,1,1 #correct because number of values on both sides are equal In [22]: x,y,z=[1,1,1] # in case of an iterable it's length must be equal # to the number elements on LHS In [23]: x,y,z=[1]*3 ```
Python Error: Global Name not Defined
[ "", "python", "class", "" ]
I've come up with 2 methods to generate relatively short random strings- one is much faster and simpler and the other much slower but I *think* more random. Is there a not-super-complicated method or way to measure *how* random the data from each method might be? I've tried compressing the output strings (via zlib) figuring the more truly random the data, the less it will compress but that hasn't proved much.
You are using standard compression as a proxy for the uncomputable [Kolmogorov Complexity](http://en.wikipedia.org/wiki/Kolmogorov_complexity), which is the "right" mathematical framework for quantifying randomness (but, unfortunately, is not computable). You might also try some measure of [entropy](http://en.wikipedia.org/wiki/Entropy_%28information_theory%29) if you are willing to assume some kind of distribution over strings.
An outcome is considered random if it can't be predicted ahead of time with certainty. If it can be predicted with certainty it is considered deterministic. This is a binary categorization, outcomes either are deterministic or random, there aren't degrees of randomness. There are, however, degrees of predictability. One measure of predictability is entropy, as mentioned by EMS. Consider two games. You don't know on any given play whether you're going to win or lose. In game 1, the probability of winning is 1/2, i.e., you win about half the time in the long run. In game 2, the odds of winning are 1/100. Both games are considered random, because the outcome isn't a dead certainty. Game 1 has greater entropy than game 2, because the outcome is less predictable - while there's a chance of winning, you're pretty sure you're going to lose on any given trial. The amount of compression that can be achieved (by a good compression algorithm) for a sequence of values is related to the entropy of the sequence. English has pretty low entropy (lots of redundant info both in the relative frequency of letters and the sequences of words that occur as groups), and hence tends to compress pretty well.
Quantifying randomness
[ "", "python", "random", "" ]
Hi I need to get table of latest known value one for each input. I started with this ``` SELECT [MeterReadingId] ,[TimeStampUtc] ,[Val] ,[MeterReading].[InverterInputId] ,[Status] FROM [Project].[dbo].[MeterReading] inner join InverterInput on [MeterReading].InverterInputId = [InverterInput].InverterInputId inner join Inverter on [InverterInput].InverterId = [Inverter].InverterId where [InverterInput].InputName = 'DayYield' and [Inverter].PlantId = 1 ``` off course now i got all values which belong to inputs of name 'DayYield and plantId =1 My question is how can got table only of those values which have latest [TimeStampUtc] Other words: get all those [Val] which belong to input of name 'DayYield and plantId =1 and are last inserted into table.
For this, you can use the [**ranking functions**](http://msdn.microsoft.com/en-us/library/ms189798.aspx), `ROW_NUMBER()` for example. Something like this: ``` WITH CTE AS ( SELECT [MeterReadingId] ,[TimeStampUtc] ,[Val] ,m.[InverterInputId] ,[Status] ,ROW_NUMBER() OVER(PARTITION BY m.InverterInputId ORDER BY m.[TimeStampUtc] DESC) AS RN FROM [Project].[dbo].[MeterReading] AS m inner join InverterInput AS ii on m.InverterInputId = ii.InverterInputId inner join Inverter AS i on ii.InverterId = i.InverterId where ii.InputName = 'DayYield' and i.PlantId = 1 ) SELECT * FROM CTE WHERE RN = 1; ``` Using `ORDER BY m.[TimeStampUtc] DESC` will give you the latest `[TimeStampUtc]` . **Note that:** I don't know about the tables' structures you are using, but you might need to use another column to group by in the `PARTITION BY` clause instead of `MeterReadingId`.
One option is a `cross apply`, like: ``` select * from Devices d cross apply ( select top 1 * from Measurements m where m.device_id = d.id order by m.timestamp desc ) m ```
SQL inner join with top 1
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have to decode a string of 1's and 0's using a dictionary of characters with corresponding binary codes. The dictionary is set up like this: ``` self.codes = {'a': '00', 'h': '111', 'e': '110', 'l': '01', 'o': '10'} ``` The codes are such that no binary code is the prefix of any other. At the moment I have this function to do the decoding: ``` def decode(self, ciphertext): start = 0 while start < len(ciphertext): for k in self.codes: res = ciphertext.find(self.codes[k], start) if res == start: decoded += k start += len(self.codes[k]) return decoded ``` (Where ciphertext = the text to be decoded, and self.codes = the dictionary representing the coding system) Unsurprisingly, this is really slow. Can anyone point me towards a more efficient algorithm for this kind of thing? [edit] Thanks all for the great suggestions. I'll try implementing them in a couple of hours when I get home.
You could do something like this: ``` def __init__(self, ...): ... self.codes = {'a': '00', 'h': '111', 'e': '110', 'l': '01', 'o': '10'} self.decode_codes = {value: key for key, value in self.codes.items()} def decode(self, ciphertext): result = '' chunk = '' for c in ciphertext: chunk += c if chunk in self.decode_codes: result += self.decode_codes[chunk] chunk = '' return result ``` Since you said that no two codes are contained within the beginning of one another, this approach will work.
Your code will run a lot faster if you flip keys and values: ``` self.codes = {'00': 'a', '111': 'h', '110': 'e', '01': 'l', '10': 'o'} ``` Now you can do pseudocode like this: ciphertext = your ciphertext (e.g. "001111100110") plaintext = "" currenttoken = "" 1) add the current bit of ciphertext onto the end of currenttoken 2) Does self.codes contain currenttoken? 2a) If so, add self.codes[currenttoken] to plaintext, and currenttoken = "" Dictionary access is O(1), O(1) over the length of a string is O(n). If you also need the unflipped keys/values to make ciphering the string very fast, then I suggest you have two dictionaries, one for encoding fast one for decoding fast.
What's a faster way of decoding a string from a dictionary? (Python)
[ "", "python", "string", "decoding", "" ]
Assume you have a list such as `x = [('Edgar',), ('Robert',)]` What would be the most efficient way to get to just the strings `'Edgar'` and `'Robert'`? Don't really want x[0][0], for example.
Easy solution, and the fastest in most cases. ``` [item[0] for item in x] #or [item for (item,) in x] ``` Alternatively if you need a functional interface to index access (but slightly slower): ``` from operator import itemgetter zero_index = itemgetter(0) print map(zero_index, x) ``` Finally, if your sequence is too small to fit in memory, you can do this iteratively. This is much slower on collections but uses only one item's worth of memory. ``` from itertools import chain x = [('Edgar',), ('Robert',)] # list is to materialize the entire sequence. # Normally you would use this in a for loop with no `list()` call. print list(chain.from_iterable(x)) ``` But if all you are going to do is iterate anyway, you can also just use tuple unpacking: ``` for (item,) in x: myfunc(item) ```
This is pretty straightforward with a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions): ``` x = [('Edgar',), ('Robert',)] y = [s for t in x for s in t] ``` This does the same thing as `list(itertools.chain.from_iterable(x))` and is equivalent in behavior to the following code: ``` y = [] for t in x: for s in t: y.append(s) ```
Python list of tuples, need to unpack and clean up
[ "", "python", "python-2.7", "" ]
I'm trying to create a subquery over a many to many with the following code. ``` SELECT e.ep_suragate_pk FROM episode e JOIN ( SELECT n.name FROM actor n JOIN episode_actor ea ON n.act_suragate_pk = ea.act_suragate_pk ) ep_act ON ep_act.ep_suragate_pk = e.ep_suragate_pk; ``` I'm getting an ORA-00904: invalid indentifier error but all the columns exist. ``` episode ------- ep_suragate_pk episode_actor ------------- ep_suragate_pk act_suragate_pk actor ----- act_suragate_pk ``` If someone can help me understand where I'm going wrong it would be appreciated. Thanks.
you don't need all these sub queries ``` select e.ep_suragate_pk from episode e , episode_actor ea , actor n where ea.ref_id = e.ep_suragate_pk and n.act_suragate_pk = ea.act_suragate_pk ```
The subquery needs to select column `ea.ep_suragate_pk` in order to resolve the invalid identifier issue. Not yet sure if that will get the results you want though.
how do I subquery many to many in oracle?
[ "", "sql", "oracle", "" ]
I'm trying to get a bandpass filter with a 128-point Hamming window with cutoff frequencies 0.7-4Hz in python. I get my samples for my signal from images. (1 sample = 1 image). The fps often changes. How can this be done in python? I read this: <http://mpastell.com/2010/01/18/fir-with-scipy/> but I find firwin rather confusing. How can this be done with this variable fps?
Trying to filter data with an inconsistent sample rate is very difficult (impossible?). So what you are going to want to do is this: 1. Create a new signal with a fixed sample rate. The fixed sample rate should be the maximum sample rate or higher. Do this by setting up a new "grid" representing where the new samples should go, and interpolating their values from existing data. A variety of interpolation methods exist depending on how accurate you need to be. Linear interpolation is probably not a bad starting point, but it depends on what you are doing. Ask on <https://dsp.stackexchange.com/> if you are unsure. 2. Once you've done that, you can apply standard signal processing methods to your signal because the samples are evenly placed, such as those described in the post you linked. 3. If necessary, you may need to interpolate again to get your original sample positions back. If you are looking only to analyze your data, you might be interested in the [Lomb Periodigram](http://en.wikipedia.org/wiki/Least-squares_spectral_analysis). Instead of band-passing your data and then analyzing, you would use the Lomb Periodigram, and then only look at the relevant frequencies, or weight the results however you wanted. (see also the numerical recipes series. Chapter 13.8 is called "Spectral analysis of unevenly spaced data", which appears to be a friendlier introduction than that wikipedia page)
You can use the functions [`scipy.signal.firwin`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.firwin.html) or [`scipy.signal.firwin2`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.firwin2.html) to create a bandpass FIR filter. You can also design a FIR filter using [`scipy.signal.remez`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.remez.html) The following code provides some convenience wrappers for creating a bandpass FIR filter. It uses these to create bandpass filters corresponding to the numbers requested in the question. This assumes that the sampling is done uniformly. If the sampling is not uniform, a FIR filter is not appropriate. ``` from scipy.signal import firwin, remez, kaiser_atten, kaiser_beta # Several flavors of bandpass FIR filters. def bandpass_firwin(ntaps, lowcut, highcut, fs, window='hamming'): taps = firwin(ntaps, [lowcut, highcut], fs=fs, pass_zero=False, window=window, scale=False) return taps def bandpass_kaiser(ntaps, lowcut, highcut, fs, width): atten = kaiser_atten(ntaps, width/(0.5*fs)) beta = kaiser_beta(atten) taps = firwin(ntaps, [lowcut, highcut], fs=fs, pass_zero=False, window=('kaiser', beta), scale=False) return taps def bandpass_remez(ntaps, lowcut, highcut, fs, width): delta = 0.5 * width edges = [0, lowcut - delta, lowcut + delta, highcut - delta, highcut + delta, 0.5*fs] taps = remez(ntaps, edges, [0, 1, 0], fs=fs) return taps if __name__ == "__main__": import matplotlib.pyplot as plt from scipy.signal import freqz # Sample rate and desired cutoff frequencies (in Hz). fs = 63.0 lowcut = 0.7 highcut = 4.0 ntaps = 128 taps_hamming = bandpass_firwin(ntaps, lowcut, highcut, fs=fs) taps_kaiser16 = bandpass_kaiser(ntaps, lowcut, highcut, fs=fs, width=1.6) taps_kaiser10 = bandpass_kaiser(ntaps, lowcut, highcut, fs=fs, width=1.0) remez_width = 1.0 taps_remez = bandpass_remez(ntaps, lowcut, highcut, fs=fs, width=remez_width) # Plot the frequency responses of the filters. plt.figure(1, figsize=(12, 9)) plt.clf() # First plot the desired ideal response as a green(ish) rectangle. rect = plt.Rectangle((lowcut, 0), highcut - lowcut, 1.0, facecolor="#60ff60", alpha=0.2) plt.gca().add_patch(rect) # Plot the frequency response of each filter. w, h = freqz(taps_hamming, 1, worN=2000, fs=fs) plt.plot(w, abs(h), label="Hamming window") w, h = freqz(taps_kaiser16, 1, worN=2000, fs=fs) plt.plot(w, abs(h), label="Kaiser window, width=1.6") w, h = freqz(taps_kaiser10, 1, worN=2000, fs=fs) plt.plot(w, abs(h), label="Kaiser window, width=1.0") w, h = freqz(taps_remez, 1, worN=2000, fs=fs) plt.plot(w, abs(h), '--', label="Remez algorithm, width=%.1f" % remez_width) plt.xlim(0, 8.0) plt.ylim(0, 1.1) plt.grid(True) plt.legend(shadow=True, framealpha=1) plt.xlabel('Frequency (Hz)') plt.ylabel('Gain') plt.title('Frequency response of several FIR filters, %d taps' % ntaps) plt.show() # plt.savefig('plot.png') ``` Here's the plot generated by the script. Of course, it is much more useful to run the script locally, so you can zoom in on the details. [![enter image description here](https://i.stack.imgur.com/8qFgE.png)](https://i.stack.imgur.com/8qFgE.png)
Bandpass filter in python
[ "", "python", "scipy", "signal-processing", "" ]
It seems that the standard way of creating a figure in matplotlib doesn't behave as I'd expect in python: by default calling `fig = matplotlib.figure()` in a loop will hold on to all the figures created, and eventually run out of memory. There are [quite](https://stackoverflow.com/q/7101404/915501) [a](https://stackoverflow.com/q/7125710/915501) [few](https://stackoverflow.com/q/2364945/915501) posts which deal with workarounds, but requiring explicit calls to `matplotlib.pyplot.close(fig)` seems a bit hackish. What I'd like is a simple way to make `fig` reference counted, so I won't have to worry about memory leaks. Is there some way to do this?
If you create the figure without using `plt.figure`, then it should be reference counted as you expect. For example (This is using the non-interactive Agg backend, as well.) ``` from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure # The pylab figure manager will be bypassed in this instance. # This means that `fig` will be garbage collected as you'd expect. fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) ```
If you're only going to be saving figures rather than displaying them, you can use: ``` def savefig(*args, **kwargs): plt.savefig(*args, **kwargs) plt.close(plt.gcf()) ``` This is arguably no less hacky, but whatever.
Create a figure that is reference counted
[ "", "python", "memory-management", "matplotlib", "" ]
Interviewer asked me one question, which seems very easy, but I couldn't figure out, how to solve this ``` Name | Gender -------------- A | F B | M C | F D | F E | M ``` From the above data, gender was wrongly entered, which means in place of `F` it should be `M` and in place of `M` it should `F`. How to update whole table with a single line sql query (don't use pl/sql block). Since, if I will update gender column one by one, then possible error would be all rows values of gender column becomes either `F` or `M`. Final output should be ``` Name | Gender -------------- A | M B | F C | M D | M E | F ```
Try this.. ``` Update TableName Set Gender=Case when Gender='M' Then 'F' Else 'M' end ``` On OP request..update using Select... ``` Update TableName T Set Gender=( Select Gender from TableName B where T.Gender!=B.Gender and rownum=1); ``` [SQL FIDDLE DEMO](http://sqlfiddle.com/#!4/91087/15)
``` update table_name set gender = case when gender = 'F' then 'M' when gender = 'M' then 'F' end ``` SQL works on `Set theory` principles, so updates are happening in parallel, you don't need Temporary storage to store the values before overwriting like we do in other programming language while swapping two values.
Interview : update table values using select statement
[ "", "sql", "oracle", "select", "sql-update", "" ]
I couldn't really find anything about this, and i couldn't really figure it out. Anyways, I have created a view which i need to filter using query/QueryRun etc. in x++. The select statement for what i am trying to do looks like this ``` while select salestable order by PtsWebDeliveryDate, salesId where (SalesTable.SalesStatus == SalesStatus::Delivered && !SalesTable.PtsProdNorwood && SalesTable.CustAccount != acc && SalesTable.InvoiceAccount != acc && salestable.PtsWebDeliveryDate >= today() && salestable.PtsWebDeliveryDate <= today()+daysahead) || ( SalesTable.SalesStatus == SalesStatus::Backorder && SalesTable.SalesType == SalesType::Sales && !SalesTable.PtsProdNorwood && SalesTable.CustAccount != acc && SalesTable.InvoiceAccount != acc && ( (salesTable.PtsSalesorderPacked && salestable.PtsWebDeliveryDate >= today() && salestable.PtsWebDeliveryDate <= today()+daysAhead) || (!salesTable.PtsSalesorderPacked && salestable.PtsWebDeliveryDate >= d && salestable.PtsWebDeliveryDate <= today()+daysahead)) ) { //Do stuff } ``` As you can see i have som OR operators which i need to use. i have startet building the query in x++ and this is what i got: ``` q = new Query(); q.addDataSource(TableNum("packlistview")); q.dataSourceNo(1).addSortField(fn[_OrderBy], _direction); q.dataSourceNo(1).addRange(fieldNum(PackListView, SalesStatus)).value(queryValue(SalesStatus::Delivered)); q.dataSourceNo(1).addRange(fieldNum(PackListView, PtsProdnorwood)).value(queryValue(NoYes::No)); q.dataSourceNo(1).addRange(fieldNum(PackListView, CustAccount)).value(queryValue(!acc)); q.dataSourceNo(1).addRange(fieldNum(PackListView, PtsWebDeliveryDate)).value(queryrange(today(),today()+daysahead)); //OR q.dataSourceNo(1).addRange(fieldNum(PackListView, SalesStatus)).value(queryValue(SalesStatus::Backorder)); q.dataSourceNo(1).addRange(fieldNum(PackListView, SalesType)).value(queryValue(SalesType::Sales)); q.dataSourceNo(1).addRange(fieldNum(PackListView, PtsProdnorwood)).value(queryValue(false)); q.dataSourceNo(1).addRange(fieldNum(PackListView, CustAccount)).value(queryValue(!acc)); q.dataSourceNo(1).addRange(fieldNum(PackListView, InvoiceAccount)).value(queryValue(!acc)); q.dataSourceNo(1).addRange(fieldNum(PackListView, PtsSalesorderPacked)).value(queryValue(false)); q.dataSourceNo(1).addRange(fieldNum(PackListView, PtsWebDeliveryDate)).value(queryrange(d, today()+daysahead)); //OR q.dataSourceNo(1).addRange(fieldNum(PackListView, PtsSalesorderPacked)).value(queryValue(false)); q.dataSourceNo(1).addRange(fieldNum(PackListView, PtsWebDeliveryDate)).value(queryrange(d, today()+daysahead)); qr = new queryRun(q); while( qr.next())// && counter < 100 { //Do stuff } ``` So how do I do incorporate the OR operators with this? Cheers guys :)
I decided to make a temporary table out of it, doing all the filtering in a standard select statement, and later i used a x++ querybuilding to add sorting and the different stuff needed. this worked out great and felt more easy to do rather than injecting long string queries into the queryobjects. But thanks for the answers :)
You can generate the querystring with your criteria like this: ``` .value(strfmt("((Field1 == %1 && Field2 == %2) || Field1 != %3)", var1, var2, var3, varX, ...)); ``` May be it's not very smart but its the way the standard does. You can use `queryValue` function with some variables like base enums or dates to get the proper query string for each value.
How to use AND/OR operators when building query in ax 2012 x++
[ "", "sql", "axapta", "x++", "dynamics-ax-2012", "" ]
I am having issues on trying to figure "DoesNotExist Errors", I have tried to find the right way for manage the no answer results, however I continue having issues on "DoesNotExist" or "Object hast not Attribute DoestNotExists" ``` from django.http import HttpResponse from django.contrib.sites.models import Site from django.utils import simplejson from vehicles.models import * from gpstracking.models import * def request_statuses(request): data = [] vehicles = Vehicle.objects.filter() Vehicle.vehicledevice_ for vehicle in vehicles: try: vehicledevice = vehicle.vehicledevice_set.get(is_joined__exact = True) imei = vehicledevice.device.imei try: lastposition = vehicledevice.device.devicetrack_set.latest('date_time_process') altitude = lastposition.altitude latitude = lastposition.latitude longitude = lastposition.longitude date_time_process = lastposition.date_time_process.strftime("%Y-%m-%d %H:%M:%S"), date_time_created = lastposition.created.strftime("%Y-%m-%d %H:%M:%S") except Vehicle.vehicledevice.device.DoesNotExist: lastposition = None altitude = None latitude = None longitude = None date_time_process = None date_time_created = None except Vehicle.DoesNotExist: vehicledevice = None imei = '' item = [ vehicle.vehicle_type.name, imei, altitude, "Lat %s Lng %s" % (latitude, longitude), date_time_process, date_time_created, '', '' ] data.append(item) statuses = { "sEcho": 1, "iTotalRecords": vehicles.count(), "iTotalDisplayRecords": vehicles.count(), "aaData": data } json = simplejson.dumps(statuses) return HttpResponse(json, mimetype='application/json') ```
I have found the solution to this issue using ObjectDoesNotExist on this way ``` from django.core.exceptions import ObjectDoesNotExist ...... try: # try something except ObjectDoesNotExist: # do something ``` After this, my code works as I need Thanks any way, your post help me to solve my issue
This line ``` except Vehicle.vehicledevice.device.DoesNotExist ``` means look for device *instance* for DoesNotExist exception, but there's none, because it's on class level, you want something like ``` except Device.DoesNotExist ```
Django DoesNotExist
[ "", "python", "django", "django-models", "django-views", "" ]
I have two apps installed in my Django project... ``` Contacts Package Models.py - class Contact Homes Package Models.py - class House ``` Class `House` has a model method called `get_contact`, in this method I import Contacts and filter etc *(not important)*. **My question:** House is now dependent on Contacts, meaning I can no longer install the House app without having the Contact app too. Despite this house should be able to exist without a Contact. In Python, (well in the context on the framework Django) **how do you Python people deal with this?** **Is there a better way?**
If the use of the `Contacts` package in `House` is limited to a single method then you put the import inside the method and catch the exception: ``` def foo(self): try: from Contacts.Models import Contact except ImportError: return ... use Contact here ``` Alternatively you can put the import at the top of the module but set it to None in the case where it isn't available: ``` try: from Contacts.Models import Contact except ImportError: Contact = None ... if Contact is not None: ... use Contact ... ``` If you want to go a more pure OOP route, then you could use Zope3 adapters, but that means you've swapped dependency on one package for dependency on a group of others. It is likely to be overkill for the problem you've described, but if you want to investigate this solution see [this blog post](http://www.stereoplex.com/blog/adapters-in-django-and-the-revenge-of-zope). I think the real issue you will hit if you try this is that you'll have to define an interface such as `IContactProvider` that you can fetch for your House class. That interface has to live somewhere and if that somewhere is the Contacts package you still end up requiring that package to be installed. If your need is for some sort of generic `IContactProvider` and several specific implementations then this could be a good way of handling that problem.
Django as signals and ProxyModels (and Python has monkeypatching when there's no better solution). What I usually do to keep apps decoupled (when it makes sense of course) is to have a "main" django app that I use as a project-specific integration layer. In this case - and assuming `House` has no "hardwired" dependency on `Contact` (ie ForeignKey) - I'd define a ProxyModel for `House` where I'd add the `get_contact` method.
Dealing with Class Dependencies in Python
[ "", "python", "django", "" ]
I'm currently working on an artist website containing an agenda for gigs. I want it to list the first upcoming gigs on the beginning (asc), and list the past gigs after the upcoming gigs. My current solution is two different queries, one calling upcoming and one past events, but I think it's neater to figure out a way to merge them. Does anybody know if this is possible, and how? This is how I begin; ``` SELECT * FROM agenda INNER JOIN organizer ON agenda.agenda_organizer=organizer.organizer_id ```
``` SELECT * FROM agenda INNER JOIN organizer ON agenda.agenda_organizer=organizer.organizer_id ORDER BY CASE WHEN yourDateColumn > NOW() THEN 1 WHEN yourDateColumn < NOW() THEN 2 END ASC, yourDateColumn ```
If you use a [UNION](http://www.w3schools.com/sql/sql_union.asp), then you can do the two statements neatly - and because each [ORDER BY](http://www.w3schools.com/sql/sql_orderby.asp) is simply on the date field, you know it will use the [index](http://www.tutorialspoint.com/sql/sql-indexes.htm) to keep your query fast: ``` SELECT * FROM agenda INNER JOIN organizer ON agenda.agenda_organizer=organizer.organizer_id WHERE yourDateColumn > NOW() ORDER BY yourDateColumn ASC UNION ALL SELECT * FROM agenda INNER JOIN organizer ON agenda.agenda_organizer=organizer.organizer_id WHERE yourDateColumn < NOW() ORDER BY yourDateColumn DESC ```
SQL query order date by ASC, but past entries on end?
[ "", "mysql", "sql", "" ]
i have temp table named `"#Test"` which have columns `"T1", "T2", "T3"` with data. I have database table named "TestTbl" which have same columns. I want to insert data from `#Test` table to `TestTbl` with distinct records of `T1` column. Do you have any idea how to insert distinct records in `TestTbl` table?
You Can Try Like this.... ``` INSERT INTO TestTbl (T1,T2,T3) SELECT T1,T2,T3 from ( Select Row_Number() over(Partition By T1 order By T1) as row,* from #Test ) a where a.row=1; ```
``` INSERT INTO TestTbl (T1,T2,T3) SELECT Distinct(T1), T2, T3 FROM #Test ``` EDIT After further explanation ``` INSERT INTO TestTbl ( T1 , T2 , T3 ) SELECT T1 , T2 , T3 FROM ( SELECT T1 , T2 , T3 , Row_Number() OVER ( PARTITION BY T1 ORDER BY T1) AS record -- you need to select the relevant clause here for the order -- do you want first or latest record? FROM #Test ) tmp WHERE tmp.record = 1 ; ```
How to get Distinct Records from Temp table to Sql one database table
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm encountering an error on the item below and I don't understand why. Can anyone shed some light on it for me? ``` CREATE FUNCTION dbo.fn_AcMonthOrder ( @Month varchar(100) ) RETURNS INT AS BEGIN DECLARE @MonthOrder Int SET @MonthOrder = (CASE WHEN @Month IN ('Aug','August',8) THEN 1 WHEN @Month IN ('Sep','September',9) THEN 2 WHEN@Month IN ('Oct','October',10) THEN 3 ... ELSE 0 END) RETURN @MonthOrder END ``` If I attempt to call this function then it works fine for an integer, but not for the varchars. I.e. PRINT @dbo.fn\_AcMonthOrder(8) will return 1 as expected, but PRINT @dbo.fn\_AcMonthOrder('Aug') Or PRINT @dbo.fn\_AcMonthOrder('August') returns the following error: ``` Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value 'Aug' to data type int. ```
When you use different data types in an expression, SQL Server follows [data type precedence](http://msdn.microsoft.com/en-us/library/ms190309.aspx). In this case: ``` 8 IN ('Aug','August', 8) ``` You're mixing `int` with `varchar`. Since `int` has higher precedence, it will convert the `varchar` to `int`. The reason this particular case does not throw an error might be optimization. This does throw an error: ``` 8 IN ('Aug','August',10) ``` And this does not throw an error: ``` 'Aug' IN ('Aug','August',8) ``` But this throws an error again: ``` 'Sept' IN ('Aug','August',8) ``` This confirms that the optimizer first compares the elements that do not require conversion. It only raises an error when it gets to the elements it cannot convert. At the end of the day, the best solution is to make sure all data types are the same. In your case, you could just list the numbers as a string: ``` WHEN @Month IN ('Aug','August','8') THEN 1 ^^^^^ ```
``` WHEN @Month IN ('Aug','August','8') THEN 1 WHEN @Month IN ('Sep','September','9') THEN 2 WHEN@Month IN ('Oct','October','10') THEN 3 ``` Enclose in single quotes month values in numbers eg change 8 to '8' . This is because @Month is of VARCHAR() datatype and IN() clause requires values inside it must have compatible datatype conversion amongst them.
SQL comma separated value in IN clause case statement error
[ "", "sql", "sql-server", "" ]
I have a function that accepts a date and returns the difference in time between then and the current time (in seconds). It works fine for everything less than a day. But when I even enter a date that's a year in the future, it still returns a number around 84,000 seconds (there are around 86,400 seconds in a day). ``` def calc_time(date): future_date = str(date) t_now = str(datetime.utcnow()) t1 = datetime.strptime(t_now, "%Y-%m-%d %H:%M:%S.%f") t2 = datetime.strptime(future_date, "%Y-%m-%d %H:%M:%S.%f") return ((t2-t1).seconds) ``` Even when I run it with a parameter whose date is in 2014, i get a number way too low. Anyone have any insight?
ahh. apparently .seconds will only return the difference of seconds within the range of a day. .seconds will include both hours and minutes, so i needed to add that to .days\*86400 to get total seconds. thanks for the help, everyone! ;D
Reading the [datetime.timedelta](http://docs.python.org/2/library/datetime.html#datetime.timedelta) docs. > All arguments are optional and default to 0. Arguments may be ints, > longs, or floats, and may be positive or negative. > > Only days, seconds and microseconds are stored internally. Arguments > are converted to those units: > > A millisecond is converted to 1000 microseconds. A minute is converted > to 60 seconds. An hour is converted to 3600 seconds. A week is > converted to 7 days. and days, seconds and microseconds are then > normalized so that the representation is unique, with > > 0 <= microseconds < 1000000 0 <= seconds < 3600\*24 (the number of > seconds in one day) > -999999999 <= days <= 999999999 The solution is to use `.total_seconds()` instead of `.seconds`
Calculating difference in seconds between two dates not working above a day
[ "", "python", "datetime", "" ]
I am working on the following code: ``` def numberToName(number): if (number==3): return "Three" elif (number==2): return "Two" elif (number==1): return "One" else: return "Invalid" print numberToName(2) print numberToName(3) print numberToName(1) print numberToName(1) ``` This code runs 100% fine in the following online Python environment - <http://www.codeskulptor.org/#user11_Hh0KVUpNVP_0.py> But when I use `IDLE` it shows a syntax error `Invalid Syntax` in line `print numberToName(2)` My Python version is 3.3.1 I have noticed some issues as well. For an example, in the given URL, I can run `print "hello"` and get the output, but the same generated error in IDLE unless I type `print ("Hello")`. What is the issue here? I am new to Python. (Please note the main question is about the given code snippet).
That is because the IDE is using Python 3.X, and not Python 2.X like in the online environment. In Python 2.X you can use `print("test")` or `print "Text"`. In Python 3.x you need to use `print("test")`. This is because in Python 2.X print is a keyword, and not a function, while in [Python 3 it is a function](http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function). If you change the print functions to this, it will run on both the web application and your IDE. ``` print(numberToName(2)) print(numberToName(3)) print(numberToName(1)) print(numberToName(1)) ```
The online environment is Python 2. Your IDLE install is Python 3. There are many differences, in this case the issue is that `print` is now a function. See also: <http://python3porting.com/>
Code works in one Python environments but has a syntax error in another
[ "", "python", "python-3.x", "python-idle", "" ]
I'm having trouble printing a message after checking if variables are true or false. What I want to do is print variables that are true out of a selecton of variables. There must be an easier way of doing it than the below but this is all I can come up with. I need a better solution or a modification on the below to make it work. Here is my code: ``` if (quirk) and not (minor, creator, nature): print (quirk, item) elif (minor) and not (quirk, creator, nature): print (minor, item) elif (creator) and not (minor, quirk, nature): print (creator, item) elif (nature) and not (minor, quirk, creator): print (item, nature) else: print ("Something went wrong! Properties out of range! Nature =",nature,"Quirk =",quirk,"Minor =",minor,"Creator =",creator) ``` In this case, I always get the error and never any of the prints. The error always shows that one of the variables is true. Thank you in advance!
You are checking if a non-empty tuple is falsish - which is never true. Use [`any`](http://docs.python.org/2/library/functions.html#any) instead. ``` if quirk and not any([minor, creator, nature]): print (quirk, item) # and so on ``` `any([minor, creator, nature])` returns `True` if any of the elements in the collection are `True`, `False` otherwise.
``` (minor, creator, nature) ``` is a tuple. And it always evaluates to `True` in a boolean context, irrespective of the values of `minor`, `creator` and `nature`. This is what the [documentation for Truth Value Testing](http://docs.python.org/3/library/stdtypes.html#truth-value-testing) has to say: > Any object can be tested for truth value, for use in an if or while > condition or as operand of the Boolean operations below. The following > values are considered false: > > * None > * False > * zero of any numeric type, for example, 0, 0.0, 0j. > * any empty sequence, for example, '', (), []. > * any empty mapping, for example, {}. > * instances of user-defined classes, if the class defines a **bool**() or **len**() method, when that method returns the integer zero or bool value False. > > All other values are considered true — so objects of many types are > always true. Your non-empty sequence falls into the *"All other values"* category and so is regarded as being true. --- To express your condition using plain Python logic, you need to write: ``` if quirk and not minor and not creator and not nature: ``` As @Volatility points out, the `any()` utility function can be used to simplify your code and make it read more clearly.
Printing if different variables are True or False Python 3.3
[ "", "python", "python-3.3", "" ]
Is it even possible to set the absolute position of a grid within Tkinter? I am trying to create a GUI that looks like the one below, but I am probably going about it the wrong way. So if it is possible, how do you set the grid position? Target GUI: ![Target GUI](https://i.stack.imgur.com/UjIkc.png) This is how my GUI is turning out, so far: ![My GUI](https://i.stack.imgur.com/ZMCy2.jpg) As you can see, my New Contact needs to be on the right, while the Contact List should be on the left. I understand how to move the Contact List using absolute values, but can I do the same for my grid elements? Or should I use absolute values with all of them, combined with padding? Currently, this is my code: ``` from tkinter import * contacts=['Justin Day'] class Contact_manager (Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Contact Manager") self.pack(fill=BOTH, expand=1) #New contact grid Label (self, text = "New Contact").grid (row=0, columnspan=2) Label (self, text = "First Name:").grid (row=1, sticky=E) Label (self, text = "Last Name:").grid (row=2, sticky=E) Label (self, text = "Phone#").grid (row=3, sticky=E) self.entry1 = Entry(self) self.entry2 = Entry(self) self.entry3 = Entry(self) self.entry1.grid (row=1, column=1) self.entry2.grid (row=2, column=1) self.entry3.grid (row=3, column=1) friend_check = IntVar() self.friend_check = Checkbutton (self, variable = friend_check, command = self.friend_box, text = "Friend") self.friend_check.grid (row=4, columnspan=2) Label (self, text = "Email:").grid (row=5, sticky=E) Label (self, text = "Birthday:").grid (row=6, sticky=E) self.entry4 = Entry(self) self.entry5 = Entry(self) self.entry4.grid (row=5, column=1) self.entry5.grid (row=6, column=1) #Contact listbox Label (self, text = "Contact List").place(x=20, y=190) contact_lb = Listbox(self) for i in contacts: contact_lb.insert(END, i) contact_lb.bind("<<ListboxSelect>>", self.onSelect) contact_lb.place(x=20, y=210) def onSelect(self, val): sender = val.widget idk = sender.curselection() value = sender.get(idx) self.var.set(value) def friend_box(): if friend_check.get() == 1: contacts.append(Friend(f, l, p, e, bd)) else: contacts.append(Person(f, l, p)) def main(): root = Tk() ex = Contact_manager(root) root.geometry('600x700+200+100') root.mainloop() if __name__ == '__main__': main() ```
You should take a divide-and-conquer approach to laying out widgets in a GUI. Don't try to do everything at once or use one geometry manager to coordinate everything in one window. Be methodical, and tackle one small problem at a time. For example, in your target GUI it appears you have four sections: the contact list, a search box and button, a new contact form, and something in the lower right corner (search results?). If I am correct that those are four distinct areas, start by creating four frames. Use grid to place them in the four corners of the main window. Give each frame a distinct color (for debugging purposes). Now, fiddle with options until those four areas grow and shrink in the way that you want. Make sure you give the columns and rows weight so that they all resize properly. Now that you've done that, you have four smaller, more manageable layout problems. Now, it could be that I'm wrong -- maybe you have two areas, left and right. Or maybe you have three -the left, and then the upper right and the lower right. For now we'll assume I'm right but the technique remains the same regardless. It looks like you already have the layout for the contact form, so move those into the upper-right frame. Make sure they all expand and shrink properly when you grown and shrink the window (and thus, you grow and shrink the containing frame). Once you have done that, work on the next section -- put the contact list in the upper left corner. Again, make sure it all resizes properly. At this point you shouldn't have to worry about the widgets on the right because you already have those sorted out. For this section you don't need grid, you can use pack since it's just a couple widgets stacked on top of each other. However, you can use whichever makes the most sense. Continue on this way, working on the remaining two corners of the GUI. Be methodical, and tackle small independent sections one at a time.
I did something similar, check it out: ``` from Tkinter import Tk, N, S, W, E, BOTH, Text, Frame,Label, Button,Checkbutton, IntVar,Entry class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Windows") Label(text="Contact List").grid(row=0,column=0,columnspan=2) Text(width=30,height=15).grid(row=1,rowspan=9, column=0,columnspan=2,padx=20) Button(text="Display Contact").grid(row=10, column=0,columnspan=2,pady=10) Label(text="Last Name:").grid(row=11, column=0,pady=10) Entry().grid(row=11,column=1) Button(text="Search").grid(row=12,column=0,columnspan=2) Label(text="New Contact").grid(row=0,column=2,columnspan=2) Label(text="First Name:").grid(row=1,column=2,sticky=E) Entry().grid(row=1,column=3) Label(text="Last Name:").grid(row=2,column=2,sticky=E) Entry().grid(row=2,column=3) Label(text="Phone #:").grid(row=3,column=2,sticky=E) Entry().grid(row=3,column=3) friend_check = IntVar() Checkbutton(variable=friend_check, command = self.friend_box, text = "Friend").grid(row=4,column=3,sticky=W) #Label(text="Friend").grid(row=4,column=3,padx=20,sticky=W) Label(text="Email:").grid(row=5,column=2,sticky=E) Entry().grid(row=5,column=3) Label(text="Birthday:").grid(row=6,column=2,sticky=E) Entry().grid(row=6,column=3) Button(text="Add Contact").grid(row=7,column=3,sticky=E) def friend_box(self): if friend_check.get() == 1: print '1' else: print '0' def main(): root = Tk() root.geometry("600x450+900+300") root.resizable(0,0) app = Example(root) root.mainloop() if __name__ == '__main__': main() ```
How do you set the position of a grid using Tkinter?
[ "", "python", "tkinter", "python-3.3", "" ]
I am using SQL Server 2008 and Navicat. I need to rename a column in a table using SQL. ``` ALTER TABLE table_name RENAME COLUMN old_name to new_name; ``` This statement doesn't work.
Use `sp_rename` ``` EXEC sp_RENAME 'TableName.OldColumnName' , 'NewColumnName', 'COLUMN' ``` See: [SQL SERVER – How to Rename a Column Name or Table Name](http://blog.sqlauthority.com/2008/08/26/sql-server-how-to-rename-a-column-name-or-table-name/) Documentation: [**sp\_rename** (Transact-SQL)](https://learn.microsoft.com/de-de/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql) For your case it would be: ``` EXEC sp_RENAME 'table_name.old_name', 'new_name', 'COLUMN' ``` Remember to use single quotes to enclose your values.
Alternatively to `SQL`, you can do this in Microsoft SQL Server Management Studio. Here are a few quick ways using the GUI: ### First Way Slow double-click on the column. The column name will become an editable text box. --- ### Second Way Right click on column and choose Rename from the context menu. For example: ![To Rename column name](https://i.stack.imgur.com/zygEz.jpg) --- ### Third Way *This way is preferable for when you need to rename multiple columns in one go.* 1. Right-click on the table that contains the column that needs renaming. 2. Click *Design*. 3. In the table design panel, click and edit the textbox of the column name you want to alter. For example: ![MSSMS Table Design Example](https://i.stack.imgur.com/UwVU4.png) **NOTE:** I know OP specifically asked for SQL solution, thought this might help others :)
Rename column SQL Server 2008
[ "", "sql", "sql-server", "sql-server-2008", "alter-table", "" ]
I'm trying to make a script that gets data out from an sqlite3 database, but I have run in to a problem. The field in the database is of type text and the contains a html formated text. see the text below ``` <html> <head> <title>Yahoo!</title> </head> <body> <style type="text/css"> html {} .yshortcuts {border-bottom:none !important;} .ReadMsgBody {width:100%;} .ExternalClass{width:100%;} </style> <table cellpadding="0" cellspacing="0" bgcolor="#ffffff"> <tr> <td width="550" valign="top" align="left"> <table cellpadding="0" cellspacing="0" width="500"> <tr> <td colspan="3"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/us/logo.gif" width="292" height="51" style="display:block;" border="0" alt="Yahoo! Mail"></td> </tr> <tr> <td rowspan="3" width="1" bgcolor="#c7c4ca"></td> <td width="498" height="1" bgcolor="#c7c4ca"></td> <td rowspan="3" width="1" bgcolor="#c7c4ca"></td> </tr> <tr> <td width="498" valign="top" align="left"> <table cellpadding="0" cellspacing="0"> <tr> <td width="498" bgcolor="#61399d" align="left" valign="top"> <table cellspacing="0" cellpadding="0"><tr><td height="24"></td></tr></table> <div style="font-family:Arial, Helvetica, sans-serif;font-size:23px;line-height:27px;margin-bottom:10px;color:#ffffff;margin-left:15px;"><span style="color:#ffffff;text-decoration:none;font-weight:bold;line-height:27px;">Välkommen till Yahoo! Mail.</span></div> <div style="font-family:Arial, Helvetica, sans-serif;font-size:22px;line-height:26px;margin-bottom:1px;color:#ffffff;margin-left:15px;margin-bottom:7px;margin-right:15px;">Ansluta och dela går snabbt och enkelt och är tillgängligt överallt.</div> </td> </tr> <tr> <td><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/b1.gif" width="498" height="18" style="display:block;" border="0"></td> </tr> </table> <table cellpadding="0" cellspacing="0" width="498"> <tr> <td width="292" valign="top"> <table cellpadding="0" cellspacing="0"> <tr> <td><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/grad.gif" width="292" height="9" style="display:block;"></td> </tr> <tr> <td width="292" bgcolor="#ffffff" align="left" valign="top"> <table cellspacing="0" cellpadding="0"><tr><td height="11"></td></tr></table> <div style="margin-left:15px;"> <div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:18px;color:#333333;margin-bottom:11px;font-weight:bold;">Det är lätt som en plätt att komma igång.</div> <table cellpadding="0" cellspacing="0" width="267"> <tr> <td width="16" align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:16px;color:#61399d;margin-bottom:9px;font-weight:bold;">1. </div></td> <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#61399d;margin-bottom:9px;"><a rel="nofollow" target="_blank" href="http://us-mg999.mail.yahoo.com/neo/launch?action=contacts" style="text-decoration:underline;color:#61399d;"><span>Lägg till alla dina kontakter på en plats</span></a>.</div></td> </tr> <tr> <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:16px;color:#61399d;margin-bottom:9px;font-weight:bold;">2. </div></td> <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#61399d;margin-bottom:9px;"><a rel="nofollow" target="_blank" href="http://mrd.mail.yahoo.com/themes" style="text-decoration:underline;color:#61399d;"><span>Anpassa din nya inkorg</span></a>.</div></td> </tr> <tr> <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:16px;color:#61399d;margin-bottom:9px;font-weight:bold;">3. </div></td> <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#61399d;"><a rel="nofollow" target="_blank" href="http://se.overview.mail.yahoo.com/mobile" style="text-decoration:underline;color:#61399d;"><span>Anslut överallt på dina mobila enheter</span></a>.</div></td> </tr> </table> </div> </td> </tr> <tr><td height="13"></td></tr> </table> </td> <td width="196" valign="top"> <table cellpadding="0" cellspacing="0"> <tr> <td width="1" bgcolor="#fbfbfd" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g1.gif" width="1" height="21" style="display:block;"></td> <td width="1" bgcolor="#f5f6fa" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g2.gif" width="1" height="21" style="display:block;"></td> <td width="1" bgcolor="#e8eaf1" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g3.gif" width="1" height="21" style="display:block;"></td> <td width="1" bgcolor="#d4d4d4"></td> <td width="186" bgcolor="#f0f0f0" align="left" valign="top"> <table cellspacing="0" cellpadding="0"><tr><td height="3"> </td></tr></table> <div style="margin-left:11px;"> <div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#333333;margin-bottom:9px;"><b>Info för dig:</b></div> <div style="font-family:Arial, Helvetica, sans-serif;font-size:12px;color:#43494e;line-height:18px;margin-bottom:10px;"> Yahoo!-ID och e-postadress:<br /> <div style="font-family:Arial, Helvetica, sans-serif;font-size:12px;color:#43494e;line-height:18px;"> Håll ditt konto och inställningar aktuella. <br><a rel="nofollow" target="_blank" href="https://edit.yahoo.com/config/eval_profile" style="text-decoration:underline;color:#61399d;"><span>Mitt konto</span></a> </div> </div> <table cellspacing="0" cellpadding="0"><tr><td height="20"></td></tr></table> </td> <td width="1" bgcolor="#dbdbdb"></td> <td width="1" bgcolor="#ced2de"></td> <td width="1" bgcolor="#dbdfed"></td> <td width="1" bgcolor="#e8ebf3"></td> <td width="1" bgcolor="#f3f4f9"></td> <td width="1" bgcolor="#fafbfc"></td> </tr> <tr> <td colspan="11"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/b2.gif" width="196" height="8" style="display:block;" border="0"></td> </tr> <tr><td height="13"></td></tr> </table> </td> <td width="10"></td> </tr> </table> </td> </tr> <tr> <td width="498" height="1" bgcolor="#c7c4ca"></td> </tr> </table> <table cellpadding="0" cellspacing="0" width="500"> <tr> <td align="center" valign="top"> <table cellspacing="0" cellpadding="0"><tr><td height="10"></td></tr></table> <div style="font-family:Arial, Helvetica, sans-serif;font-size:11px;line-height:18px;margin-bottom:10px;"> <a rel="nofollow" target="_blank" href="http://info.yahoo.com/legal/se/yahoo/utos.html" style="text-decoration:underline;color:#61399d;">Yahoo! Villkor för användning</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a rel="nofollow" target="_blank" href="http://info.yahoo.com/legal/se/yahoo/mail/atos.html" style="text-decoration:underline;color:#61399d;">Yahoo! Mail –Villkor för användning</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a rel="nofollow" target="_blank" href="http://info.yahoo.com/privacy/se/yahoo/details.html" style="text-decoration:underline;color:#61399d;">Yahoo! Sekretesspolicy</a> </div> </td> </tr> <tr> <td align="left" valign="top"> <div style="font-family:Arial, Helvetica, sans-serif;font-size:11px;line-height:14px;color:#545454;margin-left:16px;margin-right:14px;">Var god svara inte på detta meddelande. Detta är ett servicemeddelande som rör din användning av Yahoo! Mail. Om du vill veta mer om Yahoo!s användning av personlig information, inklusive användning av webb-beacons i HTML-baserad e-post, kan du läsa vår Yahoo! Sekretesspolicy. Yahoo!s adress är 701 First Avenue, Sunnyvale, CA 94089, USA.<br /><br />RefID: lp-1037111</div> </td> </tr> </table> </td> </tr> </table> <img width="1" height="1" src="http://pclick.internal.yahoo.com/p/s=2143684696"> </body> </html>` ``` and the python code that try to extract the data is as follows. ``` >>> import sqlite3 >>> conn = sqlite3.connect('C:/temp/Mobils/export/com.yahoo.mobile.client.android.mail/databases/mail.db') >>> c = conn.cursor() >>> conn.row_factory=sqlite3.Row >>> c.execute('select body from messages_1 where _id=7') <sqlite3.Cursor object at 0x0000000001FB78F0> >>> r = c.fetchone() >>> r.keys() ['body'] >>> print(r['body']) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python32\lib\encodings\cp850.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined> >>> ``` Does anybody have any idea of how to print/write this to a file. Yes I know that this is printed to stdout, but I get the same UnicodeEncodeError when I try to write to a file. I tried both write method of a file object and `print(r['body'], file=f)`.
When you open the file you want to write to, open it with a specific encoding that can handle all the characters. ``` with open('filename', 'w', encoding='utf-8') as f: print(r['body'], file=f) ```
Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to `utf-8` or other encoder that can represent your data. Then you can print it to `sys.stdout`. First, run following code in the console: ``` chcp 65001 set PYTHONIOENCODING=utf-8 ``` Then, start `python` do anything you want.
python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>
[ "", "python", "python-3.x", "sqlite", "" ]
This is poor programming practice, yes, I know, but these scripts are purely mine and this technique would ease my coding a lot. Right now, I have an SQLite database containing a set of key-value pairs representing configuration directives for my script. The script itself is a class which I import into other scripts. So, right now, when I want to access a config variable, I call something like: ``` myLib.myClass.getConfigVariable("theItemIWant") ``` This gets really ugly when using config variables in scripts. So I want to simplify the access to these variables. I could use a dictionary, that is pre-populated when the class is loaded and do: ``` myLib.myClass.config['theItemIWant'] ``` But I was thinking even a bit more elegantly. I wrote a separate Config class that I'd like to offer variable-level access to the config entries. So what I want to be able to do is: ``` myLib.Config().theItemIWant ``` Or to instantiate an object in a script like this: ``` def myRoutine(self): cfg = myLib.Config() print cfg.theItemIWant ``` I've read about ugly (using exec) ways to accomplish this, and I'm actually OK with that, but I can't figure out how to set CLASS level variables this way. Most people suggest either using exec or altering either vars or globals, but I am not sure if this will accomplish setting the variables directly on the Config class and not somewhere else. Using exec failed: ``` SyntaxError: unqualified exec is not allowed in function '__init__' it contains a nested function with free variables ``` So the only way I see to do it is to alter vars() but I'm not sure how this applies to classes.
You could simply implement the `__getattr__()` function for your configuration object like ``` def __getattr__(self, name): if name in self.items: return self.items[name] else: raise AttributeError() ``` See [here](http://docs.python.org/2/reference/datamodel.html#object.__getattr__) for the description for `__getattr__()` in the python documentation.
A solution that tries not to reinvent the wheel. Works when you want to only read config once, and its structure is flat. ``` from collections import namedtuple def getConfig(config_source): # read the config_source into a dict # config_source might be a file name or whatnot config_dict = read_somehow(config_source) tuple_class = namedtuple('Config', config_dict.keys()) return tuple_class(**config_dict) ``` The function returns an immutable object with attributes named after config parameter names. ``` # suppose config file is something like: # a = 1 # foo = bar cfg = getConfig(...) print cfg.a # prints 1 print cfg.foo # prints foo print cfg.unknown # raises AttributeError ``` I used to use this approach to read sections from standard `ConfigParser` instances.
Set class (self) variables from variables?
[ "", "python", "variables", "" ]
I'm switching from Ruby to Python for a project. I appreciate the fact that Python has first-class functions and closures, so this question ought to be easy. I just haven't figured out what is idiomatically correct for Python: In Ruby, I could write: ``` def with_quietude(level, &block) begin saved_gval = gval gval = level yield ensure gval = saved_gval end end ``` and call it like this: ``` with_quietude(3) { razz_the_jazz begin_the_beguine } ``` (Note: I'm not asking about Python `try/finally` handling nor about saving and restoring variables -- I just wanted a non-trivial example of wrapping a block inside some other code.) ## update Or, since some of the answers are getting hung up on the global assignments in the previous example when I'm really asking about closures, what if the call was as follows? (Note that this doesn't change the definition of with\_quietude): ``` def frumble(x) with_quietude { razz_the_jazz(x) begin_the_beguine(2 * x) } end ``` How would you implement something similar in Python (and not get laughed at by the Python experts)?
Looking more into ruby's yield, it looks like you want something like [`contextlib.contextmanager`](http://docs.python.org/2/library/contextlib.html#contextlib.contextmanager): ``` from contextlib import contextmanager def razz_the_jazz(): print gval @contextmanager def quietude(level): global gval saved_gval = gval gval = level try: yield finally: gval = saved_gval gval = 1 with quietude(3): razz_the_jazz() razz_the_jazz() ``` This script outputs: ``` 3 1 ``` indicating that our context manager did reset `gval` in the global namespace. Of course, I wouldn't use this context manager since it *only works in the global namespace*. (It won't work with locals in a function) for example. This is basically a limitation of how assignment creates a new reference to an object and that you can never mutate an object by assignment to it directly. (The only way to mutate an object is to assign to one of it's attributes or via `__setitem__` (`a[x] = whatever`))
A word of warning if you are coming from Ruby: All python 'def's are basically the same as ruby 'proc's. Python doesn't have an equivalent for ruby's 'def' You can get very similar behaviour to what you are asking for by defining your own functions in the scope of the calling function ``` def quietude(level, my_func): saved_gval = gval gval = level my_func() def my_func(): razz_the_jazz() begin_the_beguine() quietude(3, my_func) ``` ---- EDIT: Request for further information: ----- Python's lambdas are limited to one line so they are not as flexible as ruby's. To pass functions with arguments around I would recommend **partial functions** see the below code: ``` import functools def run(a, b): print a print b def runner(value, func): func(value) def start(): s = functools.partial(run, 'first') runner('second', s) ``` ---- Edit 2 More information ---- Python functions are only called when the '()' is added to them. This is different from ruby where the '()' are optional. The below code runs 'b\_method' in start() and 'a\_method' in run() ``` def a_method(): print 'a_method is running' return 'a' def b_method(): print 'b_method is running' return 'b' def run(a, b): print a() print b def start(): run(a_method, b_method()) ```
what is the Python equivalent of Ruby's yield?
[ "", "python", "ruby", "closures", "" ]
I want to limit the number of phrases resulting from the following query: ``` SELECT phrase_txt, word_txt FROM phrase_word LEFT JOIN phrase ON phrase.id = phrase_word.phrase_id LEFT JOIN word ON word.id = phrase_word.word_id; | PHRASE_TXT | WORD_TXT | ------------------------- | Iambad | i | | Iambad | am | | Iambad | bad | | Car | car | | tellme | tell | | tellme | me | ``` Expected output: ``` | PHRASE_TXT | WORD_TXT | ------------------------- | Iambad | i | | Iambad | am | | Iambad | bad | | Car | car | ``` Adding *LIMIT 0,2* doesn't help, as it limits the number of words, not phrases. Let's say 2: ``` | PHRASE_TXT | WORD_TXT | ------------------------- | Iambad | i | | Iambad | am | ``` More details in this [SQL Fiddle](http://sqlfiddle.com/#!2/a0e6b/2).
You can place the `LIMIT` in a subquery to limit the number of `phrases` that are returned: ``` SELECT phrase_txt, word_txt FROM ( select phrase_txt, id from phrase order by id limit 2 ) p LEFT JOIN phrase_word ON p.id = phrase_word.phrase_id LEFT JOIN word ON word.id = phrase_word.word_id ``` See [SQL Fiddle with Demo](http://sqlfiddle.com/#!2/a0e6b/4)
Try: ``` SELECT phrase.text AS p, word.text AS w FROM phrase_word JOIN (select * from phrase limit 2) phrase ON phrase.id = phrase_word.phrase_id LEFT JOIN word ON word.id = phrase_word.word_id; ``` SQLFiddle [here](http://sqlfiddle.com/#!2/152cc/5).
Limit based on a column's values (not # of rows)
[ "", "mysql", "sql", "join", "" ]
I need to build a generator and I was looking for a way to shorten this for loop into a single line. I tried enumerate but that did not work. ``` counter=0 for element in string: if function(element): counter+=1 yield counter else: yield counter ```
``` counter=0 for element in string: counter+=bool(function(element)) yield counter ``` (Yes, adding Booleans to ints works exactly as if `True` was `1` and `False` was `0`). The `bool()` call is only necessary if `function()` can have return values other than `True`, `False`, `1`, and `0`.
If you're using Python 3, you can do: ``` from itertools import accumulate yield from accumulate(1 if function(x) else 0 for x in string) ``` Although I'd use [Simeon Visser's answer](https://stackoverflow.com/a/16310487/464744). While this one may be short, it isn't immediately clear what the code does.
Is there any way to shorten this Python generator expression?
[ "", "python", "list", "for-loop", "generator", "list-comprehension", "" ]
I have the following sql statement in MSSQL 2008. ``` use gasnominations INSERT INTO dbo.GasData (readDate,TagName,Value, amendedValue) with emptce as (SELECT timestamp AS Interval, Left(Right(TagName,Len(TagName)-5),Len(TagName)-10) as TagName, CONVERT(decimal(10, 3), ROUND(value, 3)) As Value FROM OPENQUERY(IHISTORIAN,' SET starttime =''yesterday +6h'', endtime =''today +6h'' SELECT timestamp, tagname, value FROM ihRawData WHERE tagname = "UMIS.99FC9051.F_CV" OR tagname = "UMIS.99F851C.F_CV" OR tagname = "UMIS.35GTGAS.F_CV" OR tagname = "UMIS.35HRSGGAS.F_CV" OR tagname = "UMIS.99XXG546.F_CV" OR tagname = "UMIS.99XXG547.F_CV" OR tagname = "UMIS.99F9082.F_CV" OR tagname = "UMIS.99FC20107.F_CV" OR tagname = "UMIS.95FIQ5043.F_CV" OR tagname = "UMIS.99PBGAS.F_CV" OR tagname = "UMIS.99FE1100.F_CV" OR tagname = "UMIS.99FE1200.F_CV" OR tagname = "UMIS.99FC8279.F_CV" OR tagname = "UMIS.35FI8316.F_CV" AND timestamp BETWEEN ''timestamp'' and ''timestamp'' AND SamplingMode =Calculated AND CalculationMode =Average AND IntervalMilliseconds =1h ORDER BY tagname, timestamp')) select emptce.Interval, emptce.TagName, emptce.Value, gasdata.amendedValue from emptce inner join gasdata on emptce.TagName = gasData.tagName COLLATE DATABASE_DEFAULT and emptce.Interval = DATEADD(DAY, 1, readDate) ``` I get the following error 'If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.' I have tried adding a semi colon before the with but it just then errors on the ;
Try this ``` with emptce as (SELECT timestamp AS Interval, Left(Right(TagName,Len(TagName)-5),Len(TagName)-10) as TagName, CONVERT(decimal(10, 3), ROUND(value, 3)) As Value FROM OPENQUERY(IHISTORIAN,' SET starttime =''yesterday +6h'', endtime =''today +6h'' SELECT timestamp, tagname, value FROM ihRawData WHERE tagname = "UMIS.99FC9051.F_CV" OR tagname = "UMIS.99F851C.F_CV" OR tagname = "UMIS.35GTGAS.F_CV" OR tagname = "UMIS.35HRSGGAS.F_CV" OR tagname = "UMIS.99XXG546.F_CV" OR tagname = "UMIS.99XXG547.F_CV" OR tagname = "UMIS.99F9082.F_CV" OR tagname = "UMIS.99FC20107.F_CV" OR tagname = "UMIS.95FIQ5043.F_CV" OR tagname = "UMIS.99PBGAS.F_CV" OR tagname = "UMIS.99FE1100.F_CV" OR tagname = "UMIS.99FE1200.F_CV" OR tagname = "UMIS.99FC8279.F_CV" OR tagname = "UMIS.35FI8316.F_CV" AND timestamp BETWEEN ''timestamp'' and ''timestamp'' AND SamplingMode =Calculated AND CalculationMode =Average AND IntervalMilliseconds =1h ORDER BY tagname, timestamp')) INSERT INTO dbo.GasData (readDate,TagName,Value, amendedValue) select emptce.Interval, emptce.TagName, emptce.Value, gasdata.amendedValue from emptce inner join gasdata on emptce.TagName = gasData.tagName COLLATE DATABASE_DEFAULT and emptce.Interval = DATEADD(DAY, 1, readDate) ```
Terminate the previous statement with a semicolon, and then use `WITH` in advance of `INSERT`. ``` use gasnominations; with emptce as (...) INSERT INTO dbo.GasData (readDate,TagName,Value, amendedValue) select emptce.Interval, emptce.TagName, emptce.Value, gasdata.amendedValue from emptce inner join gasdata on emptce.TagName = gasData.tagName COLLATE DATABASE_DEFAULT and emptce.Interval = DATEADD(DAY, 1, readDate) ```
SQL - using the with clause, getting error
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I want to apply conditions to a numpy array and I feel like there is a better way out there. As a toy example say I want to know where the elements are equal to 2 or 3. ``` import numpy as np a = np.arange(5) ``` one way would be to construct my condition piece by piece with numpy functions like so ``` result = np.logical_or(a == 2, a == 3) ``` One can see how this could get unwieldy with more complicated conditions though. Another option would be to use list comprehensions ``` result = np.array([x for x in a if x == 2 or x==3]) ``` which is nice because now all my conditional logic can live together in one place but feels a little clunky because of the conversion to and from a list. It also doesn't work too well for multidimensional arrays. Is there a better alternative that I am missing?
It's useful to point out that in the first example, you have a logical array, not the array `[2, 3]` (like you get in the second example). To recover the result from the second answer, you'd need ``` result = a[result] ``` However, in this case, since you're using boolean masks (`True`/`False` approximately equivalent to `1`/`0`), you can actually use bitwise or to do the same thing as `logical_or`: ``` result = a[(a==2) | (a==3)] ``` A word of caution here -- Make sure you use parenthesis. Otherwise, operator precedence can be a bit nasty in these expressions (`|` binds tighter than `==`).
you can remove elements form `numpy array` with `delete` ``` np.delete(a,[0,1,4]) ``` or if you want to keep with the complement, ``` np.delete(a,np.delete(a,[2,3])) ```
options for applying conditions to numpy arrays
[ "", "python", "numpy", "" ]
is there a way to say if a @topParam value is passed in use that, if not select all. ``` @topParam select TOP COALESCE ( @topParam, all ) ```
This is not proper solution but temporary its worked for you ``` @topParam select TOP (COALESCE (@topParam, 1000000000)) ``` Think your result set don;t have 1000000000 so it will take all record when @topParam is null. Enjoy Coding..
If I understand correctly I would use `CASE` ``` CASE WHEN @topParam > 0 THEN (SELECT WITH LIMIT) ELSE (SELECT WITHOUT LIMIT) END ```
Is there a way to coalesce the top option value in stored procedure?
[ "", "sql", "sql-server", "t-sql", "" ]
I know this is simple... Please advise on how I can get a result set of rows 1, 9, 18, and 21 (based on the attached image)?? Thanks, Brad ![QueryandResults](https://i.stack.imgur.com/pAehH.png)
If the rows are truly distinct across every column, then you can use `SELECT DISTINCT`. Since you are using SQL Server you can also use `row_number()` to return one row for each `ThreatId`: ``` select ThreatId, ThreatTopClient, ... from ( select ThreatId, ThreatTopClient, ..., row_number() over(partition by ThreatId order by ThreatMLSeq) rn from xThreatCA where ThreatMLSeq <> N'' and ID <> 0 ) d where rn = 1 order by ThreatMLSeq ```
Use `SELECT DISTINCT` instead of `SELECT` ``` SELECT DISTINCT ThreatID, ThreatTopClient, '#' + CONVERT(NVARCHAR(2), ThreatMLSeq) + ' -- ' + ThreatML AS CAMLPad, ThreatMLSeq, ThreatML, ThratDetailClient, ThreatArea, ThreatFinalInherentRisk, ThreatTier21, ThreatControls, AuditID FROM xThreatCA WHERE (ThreatMLSeq <> N'') AND (ID <>0) ORDER BY dbo.xThreatCA.ThreatMLSeq ```
How to query SQL Table and remove duplicate rows from a result set
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table with a `date` field and a `time(7)` field for each record. Once the record is inserted into the database it will have the insertion day's date and the time inserted logged. Now I would like to select all the records from `Table1 INNER JOIN Table2` that are of **today's date with the first occurrence**, because the records can be duplicate. I have tried using the `time(7)` field to select the least time of today's date where `record1 = 'ABC'`, but that does not return any results and I am sure the query should return 1 result since it is logged twice with different times but with today's date. How can I select the first ever occurrence of a product with today's date? **Example:** ``` SELECT ProductName, Description, Quantity, FROM Products INNER JOIN Transactions ON Products.ProductID = Transactions.ProductID WHERE Transactions.ProductID = 'A6612' AND CONVERT(VARCHAR(20), `Transactions.Date_Tracked, 103) = CONVERT(VARCHAR(10), getdate(), 103) AND Time_Tracked = ( SELECT min(Time_Tracked) FROM Transactions ) AND Country = 'United States' ```
Use option with EXISTS operator. Also, you can avoid not an efficient condition(or predicate) using the CAST function instead of CONVERT into VARCHAR data type ``` SELECT p.ProductName, p.Description, p.Quantity FROM Products p INNER JOIN Transactions t ON p.ProductID = t.ProductID WHERE t.ProductID = 'A6612' AND CAST(t.Date_Tracked AS date) = CAST(GETDATE() AS date) AND EXISTS ( SELECT 1 FROM Transactions t2 WHERE t.ProductID = t2.ProductID AND CAST(t2.Date_Tracked AS date) = CAST(GETDATE() AS date) HAVING MIN(t2.Time_Tracked) = t.Time_Tracked ) AND Country = 'United States' ``` If the request return one record, simply use an ORDER BY clause with the TOP clause. ``` SELECT TOP 1 p.ProductName, p.Description, p.Quantity FROM Products p INNER JOIN Transactions t ON p.ProductID = t.ProductID WHERE t.ProductID = 'A6612' AND CAST(t.Date_Tracked AS date) = CAST(GETDATE() AS date) AND p.Country = 'United States' ORDER BY t.Time_Tracked ``` And finally if Date\_Tracked has type datetime, then: ``` SELECT TOP 1 p.ProductName, p.Description, p.Quantity FROM Products p INNER JOIN Transactions t ON p.ProductID = t.ProductID WHERE t.ProductID = 'A6612' AND CAST(t.Date_Tracked AS date) = CAST(GETDATE() AS date) AND p.Country = 'United States' ORDER BY CAST(t.Date_Tracked AS time) ```
Did you try using rowid? ``` SELECT ProductName, Description, Quantity, FROM Products INNER JOIN Transactions ON Products.ProductID = Transactions.ProductID WHERE Transactions.ProductID = 'A6612' AND CONVERT(VARCHAR(20), `Transactions.Date_Tracked, 103) = CONVERT(VARCHAR(10), getdate(), 103) AND Transactions.rowid = (SELECT min(rowid) FROM Transactions group by productid,date) --This will give you the minimum rowid AND Country = 'United States' --grouped by productid and date. ```
Select the first occurrence of records with today's date using time field
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am writing a flask application, and I have found I have have ton of generic utility functions. Here are the examples of the type of functions that I consider generic utility functions: ``` def make_hash(): return defaultdict(make_hash) def file_read(filename): with open(file_name_, 'r') as f: return f.read() def file_write(filename, data): with open(filename, 'w') as f: f.write(data) ``` I was thinking of tossing these functions into a separate module all together. However, I am curious if I have the following concerns: * There are two few unique functions to warrant a separate module all together. i.e. the file\_read, and file\_write functions above could go into a file.py module, however since its two functions, I feel like this might be overkill. * In my application I use these functions 2-3 times per function so I am moving under the guise they creating these utility functions should help me save some lines of code, and hopefully is making me more efficient. Question: - What would be the pythonic way of grouping generic utility functions? Should I create a separate module? Curious what others are doing for organizing this type of code.
I don't think it has much relation to Python, it's more a design decision. For only these lines I would not make a separate module; however, if you use it 2 to 3 times I would not copy the code. If you later want to change something only one change is needed, keeping functionality consistent. Also the methods seem to be very generic, so you could easily use them in other projects later. And I assume you want to make them static (`@static_method`). What I mostly do is group generic utility classes by type, i.e. in your case one file for dictionaries (having 1 method) and one for file (having 2 methods). Later possibly more methods will be added but the functionality is grouped by type/usage.
In python we have something called Package (a usual folder with an empty file called `__init__.py`) this is used to contain all of your modules this way we create somesort of name spacing. your application can access to its own name space using . for example have the following files ``` MyPackage/__init__.py (empty) MyPackage/webapp.py (your web application) MyPackage/utils.py (generic utilities) ``` and in webapp.py you can have something like this ``` from .utils import * ``` or list them one by one ``` from .utils import file_read, file_write ``` pay attention to the dot prefix before utils
Python - Best Place for Generic Functions
[ "", "python", "function", "utility", "" ]
I am having problem on this query. How can I fix this: ``` select (select case top 1 STATUS when 'Inprocess' then 'Processing' when 'Inworkbin' then 'Waiting In Draft' end from ICS_EMAIL_CONNECTIONS_TRX A where A.SESSIONID = B.SESSIONID and STATUS <> 'Completed' order by A.CREATE_DATE desc) as LAST_STATUS ``` I am getting this error: Incorrect syntax near the keyword 'top'. Any suggestions?
Try: ``` select top 1 case STATUS ``` instead of ``` select case top 1 STATUS ```
You don't need the nested select. ``` select top 1 case STATUS when 'Inprocess' then 'Processing' when 'Inworkbin' then 'Waiting In Draft' end LAST_STATUS from ICS_EMAIL_CONNECTIONS_TRX A where A.SESSIONID = B.SESSIONID and STATUS <> 'Completed' order by A.CREATE_DATE desc; ``` Although this can return 0 rows whereas your original form with the TOP 1 written properly will always return one row, even if the value is NULL.
top 1 case in select statement on TSQL
[ "", "sql", "t-sql", "case", "top-n", "" ]
I'm a newbie in Python and I would like to ask you, how can I get images (a lot of images) made by Gnuplot.py with variable in name? I have this function, which creates single image: ``` def printimage(conf, i): filename = str(i) + "out.postscript" g = Gnuplot.Gnuplot() g.title('My Systems Plot') g.xlabel('Date') g.ylabel('Value') g('set term postscript') g('set out filename') databuff = Gnuplot.File(conf, using='1:2',with_='line', title="test") g.plot(databuff) ``` And this function is used in for loop: ``` i = 0 for row in data: config_soubor.write(str(i) + " " + row[22:]) printimage("config_soubor.conf", i) i = i + 1 ``` I still can't get rid of error "undefined variable: filename". Thanks, Majzlik
Right now, your python script is passing ``` set out filename ``` to gnuplot. There 'filename' is part of the command string; the variable `filename` you set in your script is not being passed to gnuplot. You could try replacing ``` g('set out filename') ``` with ``` g('set out "'+filename+'"') ```
Perhaps you can use the [`hardcopy`](http://gnuplot-py.sourceforge.net/doc/Gnuplot/_Gnuplot/Gnuplot.html#hardcopy) method? ### Documentation ``` hardcopy ( self, filename=None, terminal='postscript', **keyw, ) ``` > Create a hardcopy of the current plot. > > Create a postscript hardcopy of the current plot to the default printer > (if configured) or to the specified filename. > > Note that gnuplot remembers the postscript suboptions across terminal > changes. Therefore if you set, for example, color=1 for one hardcopy > then the next hardcopy will also be color unless you explicitly choose > color=0. Alternately you can force all of the options to their defaults > by setting mode=default. I consider this to be a bug in gnuplot. ### Example See [example call](https://www.astro.rug.nl/~onderwys/PYTHON_DOCS/Gnuplot/Gnuplotdemo.html): ``` g.hardcopy('gp_test.ps', enhanced=1, color=1) ```
Using gnuplot to generate a set of numbered images
[ "", "python", "variables", "filenames", "gnuplot", "" ]
i'm using ms sqlserver 2005. i have a query that need to filter according to date. lets say i have a table containing phone numbers and dates. i need to provide a count number of phone numbers in a time frame (begin date and end date). this phone numbers shouldn't be in the result count if they appear in the past. i'm doing something like this : ``` select (phoneNumber) from someTbl where phoneNumber not in (select phoneNumber from someTbl where date<@startDate) ``` This is looking not efficient at all to me (and it is taking too much time to preform resulting with some side effects that maybe should be presented in a different question) i have about 300K rows in someTbl that should be checked. after i'm doing this check i need to check one more thing. i have a past database that contains yet another 30K of phone numbers. so i'm adding ``` and phoneNumber not in (select pastPhoneNumber from somePastTbl) ``` and that really nail the coffin or the last straw that break the camel or what ever phrase you are using to explain fatal state. So i'm looking for a better way to preform this 2 actions. **UPDATE** i have choose to go with Alexander's solution and ended up with this kind of query : ``` SELECT t.number FROM tbl t WHERE t.Date > @startDate --this is a filter for different customers AND t.userId in ( SELECT UserId FROM Customer INNER JOIN UserToCustomer ON Customer.customerId = UserToCustomer.CustomerId Where customerName = @customer ) --this is the filter for past number AND NOT EXISTS ( SELECT 1 FROM pastTbl t2 WHERE t2.Numbers = t.number ) -- this is the filter for checking if the number appeared in the table before startdate AND NOT EXISTS ( SELECT * FROM tbl t3 WHERE t3.Date<@startDate and t.number=t3.number ) ``` Thanks Gilad
One more option ``` SELECT t.phoneNumber FROM SomeTbl t WHERE t.date > @startDate AND NOT EXISTS ( SELECT 1 FROM SomePastTbl t2 WHERE t2.phoneNumber = t.phoneNumber ) ```
Since its a not in just switch the less than to a greater than. ``` select phoneNumber from someTbl where date > @startDate ``` Next to filter out somePastTbl ``` select s1.phoneNumber from someTbl s1 LEFT JOIN somePastTbl s2 on s1.phoneNumber = s2.phonenumber where s1.date > @startDate and s2 IS NULL ``` **UPDATE** As Per comment: Less than month of start date ``` SELECT COUNT(s1.phoneNumber) FROM someTbl s1 LEFT JOIN somePastTbl s2 on s1.phoneNumber = s2.phonenumber where DATEADD(MONTH,-1,@startDate) < s1.date AND s1.date < @startDate and s2 IS NULL ```
SQL Query select optimization
[ "", "sql", "sql-server", "" ]
I'm running into an issue with `cx_Freeze` when running a frozen application (works fine unfrozen). When running the program it results in the following traceback: ``` Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/cx_Freeze/initscripts/Console.py", line 27, in <module> exec code in m.__dict__ File "PythonApp/mainframe.py", line 3, in <module> File "/usr/local/lib/python2.7/site-packages/dbus/__init__.py", line 103, in <module> from dbus._dbus import Bus, SystemBus, SessionBus, StarterBus File "/usr/local/lib/python2.7/site-packages/dbus/_dbus.py", line 39, in <module> from dbus.bus import BusConnection File "/usr/local/lib/python2.7/site-packages/dbus/bus.py", line 39, in <module> from dbus.connection import Connection File "/usr/local/lib/python2.7/site-packages/dbus/connection.py", line 27, in <module> import threading File "/usr/local/lib/python2.7/threading.py", line 44, in <module> module='threading', message='sys.exc_clear') File "/usr/local/lib/python2.7/warnings.py", line 57, in filterwarnings import re File "/usr/local/lib/python2.7/re.py", line 105, in <module> import sre_compile File "/usr/local/lib/python2.7/sre_compile.py", line 14, in <module> import sre_parse File "/usr/local/lib/python2.7/sre_parse.py", line 17, in <module> from sre_constants import * File "/usr/local/lib/python2.7/sre_constants.py", line 18, in <module> from _sre import MAXREPEAT ImportError: cannot import name MAXREPEAT ``` I'm on linux using a version of python 2.7.4 that I built from source, and importing `_sre` from a prompt works and I can access the `MAXREPEAT` constant. This is usually down to `cx_Freeze` not pulling everything into `library.zip` and can be fixed by explicitly naming the module in `cx_Freeze`s setup include list and is the [solution to this similar question](https://stackoverflow.com/questions/2223128/cx-freeze-importerror-cannot-import-name), but that hasn't helped here. This `_sre` module seems weird.. there's no `_sre` file in the `library.zip` generated but from that error it seems like it can find it, however it can't import that symbol? Surely if the module wasn't there it would be a "`No module named _sre`" error. Or possibly a circular import but `_sre` stub doesn't have any imports. What's odd is I can't seem to find the file either - is this module dynamically created when importing somehow? ``` find /usr/local/lib/python2.7 -name "_sre*" ``` doesn't return anything, and the imported `_sre` module doesn't have a `__file__` attribute either, so I've no idea how to make sure it's included as it shows up as a built-in. ``` >>> import _sre >>> _sre.__file__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute '__file__' >>> repr(_sre) "<module '_sre' (built-in)>" ``` This is [similar to this question](https://stackoverflow.com/questions/15984650/python-wont-run-due-to-importerror-cannot-import-maxrepeat) also which was asked recently, but in this case he was getting the error in the regular interpreter, however for me it's just in `cx_Freeze`. ## edit Running `python -v` does seem like it's a built-in, so I'm not sure why `cx_Freeze` can miss it, or how I'd fix it. ``` ... # /usr/local/lib/python2.7/re.pyc matches /usr/local/lib/python2.7/re.py import re # precompiled from /usr/local/lib/python2.7/re.pyc # /usr/local/lib/python2.7/sre_compile.pyc matches /usr/local/lib/python2.7/sre_compile.py import sre_compile # precompiled from /usr/local/lib/python2.7/sre_compile.pyc import _sre # builtin # /usr/local/lib/python2.7/sre_parse.pyc matches /usr/local/lib/python2.7/sre_parse.py import sre_parse # precompiled from /usr/local/lib/python2.7/sre_parse.pyc ... ```
`_sre` is a [built in module](http://docs.python.org/2.7/library/sys#sys.builtin_module_names), so there's no file to include for it, but it doesn't have a MAXREPEAT attribute in Python 2.7.3: ``` >>> import _sre >>> _sre <module '_sre' (built-in)> >>> _sre.MAXREPEAT Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'MAXREPEAT' ``` My best guess is that your frozen copy somehow has the standard library .py modules from Python 2.7.4, but the compiled Python interpreter from 2.7.3 or an earlier version. I see you're working from `/usr/local` - maybe it's picking up an older version from `/usr`.
I encountered this problem when I just upgraded from ubuntu 12.10 to 13.04, and I fixed this by copying the /usr/bin/python to /path/to/my/env/bin/, and it worked just fine `cp /user/bin/python /path/to/my/env/bin/` or, there's a more elegant way to fix this([reference](https://stackoverflow.com/questions/16297892/ubuntu-importerror-cannot-import-name-maxrepeat)): `mkvirtualenv <existing virtualenv name>`
ImportError: cannot import name MAXREPEAT with cx_Freeze
[ "", "python", "python-2.7", "cx-freeze", "" ]
I accidentally replace python binary files located at /usr/local/bin/. Since then, I can't run any python script or even run the interactive mode of python. ``` $ python Traceback (most recent call last): File "/usr/lib/python2.7/site.py", line 562, in <module> main() File "/usr/lib/python2.7/site.py", line 544, in main known_paths = addusersitepackages(known_paths) File "/usr/lib/python2.7/site.py", line 271, in addusersitepackages user_site = getusersitepackages() File "/usr/lib/python2.7/site.py", line 246, in getusersitepackages user_base = getuserbase() # this will also set USER_BASE File "/usr/lib/python2.7/site.py", line 236, in getuserbase USER_BASE = get_config_var('userbase') File "/usr/lib/python2.7/sysconfig.py", line 558, in get_config_var return get_config_vars().get(name) File "/usr/lib/python2.7/sysconfig.py", line 457, in get_config_vars _init_posix(_CONFIG_VARS) File "/usr/lib/python2.7/sysconfig.py", line 303, in _init_posix makefile = _get_makefile_filename() File "/usr/lib/python2.7/sysconfig.py", line 297, in _get_makefile_filename return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config" + (sys.pydebug and "_d" or ""), "Makefile") AttributeError: 'module' object has no attribute 'pydebug' ``` I have see related questions with the "AttributeError: 'module' object has no attribute 'pydebug' " error, but I still can't figure out how to solve this problem. When I try to re-install appears the same error: ``` $ sudo apt-get install python2.7-minimal [sudo] password for : Reading package lists... Done Building dependency tree Reading state information... Done python2.7-minimal is already the newest version. The following packages were automatically installed and are no longer required: libgsasl7 libmailutils2 libntlm0 Use 'apt-get autoremove' to remove them. 0 upgraded, 0 newly installed, 0 to remove and 402 not upgraded. 4 not fully installed or removed. After this operation, 0 B of additional disk space will be used. Do you want to continue [Y/n]? Y Setting up python2.7-minimal (2.7.1-5ubuntu2.2) ... Traceback (most recent call last): File "/usr/lib/python2.7/site.py", line 562, in <module> main() File "/usr/lib/python2.7/site.py", line 544, in main known_paths = addusersitepackages(known_paths) File "/usr/lib/python2.7/site.py", line 271, in addusersitepackages user_site = getusersitepackages() File "/usr/lib/python2.7/site.py", line 246, in getusersitepackages user_base = getuserbase() # this will also set USER_BASE File "/usr/lib/python2.7/site.py", line 236, in getuserbase USER_BASE = get_config_var('userbase') File "/usr/lib/python2.7/sysconfig.py", line 558, in get_config_var return get_config_vars().get(name) File "/usr/lib/python2.7/sysconfig.py", line 457, in get_config_vars _init_posix(_CONFIG_VARS) File "/usr/lib/python2.7/sysconfig.py", line 303, in _init_posix makefile = _get_makefile_filename() File "/usr/lib/python2.7/sysconfig.py", line 297, in _get_makefile_filename return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config" + (sys.pydebug and "_d" or ""), "Makefile") AttributeError: 'module' object has no attribute 'pydebug' dpkg: error processing python2.7-minimal (--configure): subprocess installed post-installation script returned error exit status 1 dpkg: dependency problems prevent configuration of python2.7: python2.7 depends on python2.7-minimal (= 2.7.1-5ubuntu2.2); however: Package python2.7-minimal is not configured yet. dpkg: error processing python2.7 (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of libpython2.7: libpython2.7 depends on python2.7 (= 2.7.1-5ubuntu2.2); however: Package python2.7 is not configured yet. dpkg: error processing libpython2.7 (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of python2.7-dev: python2.7-dev depends on python2.7 (= 2.7.1-5ubuntu2.2); however: Package python2.7 is not configured yet. python2.7-dev depeNo apport report written because the error message indicates its a followup error from a previous failure. No apport report written because the error message indicates its a followup error from a previous failure. No apport report written because MaxReports is reached already nds on libpython2.7 (= 2.7.1-5ubuntu2.2); however: Package libpython2.7 is not configured yet. dpkg: error processing python2.7-dev (--configure): dependency problems - leaving unconfigured Errors were encountered while processing: python2.7-minimal python2.7 libpython2.7 python2.7-dev E: Sub-process /usr/bin/dpkg returned an error code (1) ```
The problem is that you're hitting `/usr/local/bin/python` instead of `/usr/bin/python`. You can either move it out of the way by running something like... ``` mv /usr/local/bin/python /usr/local/bin/python.old ``` ...as root, or if you're sure you don't need it, then just delete it with... ``` rm /usr/local/bin/python ``` If bash still tries to run `/usr/local/bin/python`, and running `type python` prints... ``` python is hashed (/usr/local/bin/python) ``` ...then do `hash -r` to clear the hash table. It's not a good idea to copy `/usr/bin/python` to `/usr/local/bin/python`, otherwise you may get problems the next time you update python with `apt-get upgrade`, i.e. it'll update `/usr/bin/python`, but `/usr/local/bin/python` will still be run by default.
Looks like this has something to do with a Python build made specially for debugging. I'd suggest you reinstall Python with apt-get: ``` sudo apt-get install --reinstall python2.7 ``` Your question seems to be the same like [this SO question about `sys.pydebug`](https://stackoverflow.com/questions/10641201/attributeerror-module-object-has-no-attribute-pydebug)
My python doesn't work
[ "", "python", "" ]
I'm new to python. How is possible to transform an array like this: ``` x=[[0.3], [0.07], [0.06]] ``` into: ``` x=[0.3,0.07, 0.06] ``` ? Thanks in advance.
The following list comprehension may be useful. ``` >>> x=[[0.3], [0.07], [0.06]] >>> y = [a for [a] in x] >>> y [0.3, 0.07, 0.06] ``` Considering that the inner values are of type `list` too. A similar but more readable code, as given by [cdhowie](https://stackoverflow.com/users/501250/cdhowie) is as follows. ``` >>> x=[[0.3], [0.07], [0.06]] >>> y = [a[0] for a in x] >>> y [0.3, 0.07, 0.06] ```
This is a classic use of `itertools.chain.from_iterable` ``` from itertools import chain print list(chain.from_iterable(x)) ``` Where this example really shines is when you have an iterable with arbitrary length iterables inside it: ``` [[0],[12,15],[32,24,101],[42]] ```
Transform list of arrays
[ "", "python", "arrays", "" ]
I'm currently struggling with filtering by regex in Python. I'm executing a command via ssh and i'm catching it in stdout. All goes well here but than the difficult part comes. The output of the file loaded in stdout is the following: > Command get executed successfully. server.jvm.memory.maxheapsize-count-count = 518979584 > > Command get executed successfully. > server.jvm.memory.maxheapsize-count-count = 518979584 (this multiple times). Than I'm going to execute a regular expression: ``` stdin, stdout, stderr = ssh.exec_command('cat ~/Desktop/jvm.log') result = stdout.readlines() result = "".join(result) print(result) line = re.compile(r'\d+\n') rline = "".join(line.findall(result)) print(rline) ``` the print (rline) results in ``` >> 518979584 >> 518979584 >> 518979584 ``` (also multiple times). I only want to print it once. By printing rline[0] I only get the first number of the whole digit. I thought about using $ but this doesn't help, anyone?
your line : ``` rline = "".join(line.findall(result)) ``` is converting the list returned form `findall` into a string which is then resulting in `rline[0]` returning the first character in the string. simply get the element from `line.findall(result)[0]` as shown in the example below ``` >>> d = ''' Command get executed successfully. server.jvm.memory.maxheapsize-count-count = 518979584 ... ... Command get executed successfully. server.jvm.memory.maxheapsize-count-count = 518979584 ... ''' >>> d '\n\n Command get executed successfully. server.jvm.memory.maxheapsize-count-count = 518979584\n\n Command get executed successfully. server.jvm.memory.maxheapsize-count-count = 518979584\n' >>> import re >>> line = re.compile(r'\d+\n') >>> rline = "".join(line.findall(d)) >>> rline '518979584\n518979584\n' >>> line.findall(d) ['518979584\n', '518979584\n'] >>> line.findall(d)[0].strip() # strip() used to remove newline character - may not be needed '518979584' ```
Well this should give you what you want. ``` (\d+)\D*$ ``` Just do a search, and this will give you the last number that occurs. ``` >>> regex = re.compile(r"(\d+)\D*$") >>> string = "100 20gdg0 3gdfgd00gfgd 400" >>> r = regex.search(string) # List the groups found >>> r.groups() (u'400',) ```
Python Regex to find last occurence of digit
[ "", "python", "regex", "" ]
I'm recently working with DB/2 for an AS/400 and I ran across something that I am not really strong at. I have written this SQL Statement to bring back all of the fields that will bring back all the results dated from 4/30/2012 to 4/30/2013 I've hard-coded the values for now: ``` SELECT PPOLNO, PPRMPD FROM PFNTLPYMTH WHERE (PYEAR >=2012 AND PMONTH <=4 AND PDAY >=1) ``` The table has multiple PPOLNO values that are the same, and the same with the PPRMPD field. I'd like to be able to return a single PPOLNO and a sum of all of the dollar amounts. For example: ***PPOLNO | PPRMPD*** ``` 1 | 500.00 1 | 500.00 2 | 250.00 1 | 100.00 3 | 5000.00 ``` I want to write a sql query that will bring back just: ***PPOLNO | PPRMPD*** ``` 1 | 1100.00 2 | 250.00 3 | 5000.00 ``` But I am not sure what to add on to the SQL Statement to make it so. I can get a distinct list of PPOLNO, but I'm not exactly sure how to go about getting the sum in the same query (if it's even possible). Any help would be greatly appreciated. * Josh
Please Try: ``` SELECT PPOLNO, SUM(PPRMPD) PPRMPD FROM PFNTLPYMTH GROUP BY PPOLNO ``` and you can add necessary where conditions for the query.
``` SELECT PPOLNO, SUM(PPRMPD) AS SUM FROM PFNTLPYMTH WHERE (PYEAR >=2012 AND PMONTH <=4 AND PDAY >=1) GROUP BY PPOLNO ``` Should do it
How do I build a SQL Statement that selects multiple rows and sums the amount?
[ "", "sql", "sum", "distinct", "" ]
So for an exam question I've followed this specific pseudo code which basically makes a program which encrypts a number sequence using the same principle as the ceasar cipher. It should work but for some reason it returns the error. ``` TypeError: 'int' object is not iterable ``` Heres the code, i hope you guys can help me, much appreciated ``` plainNum = input("enter a number to encode ") codedNum = ' ' Key = input("enter a key ") for i in plainNum: codedNum = codedNum + str((int(i)+key)%10) print codedNum ```
Use `raw_input` if you expect a string: ``` plainNum = raw_input("enter a number to encode ") ``` `input()` interprets the input as if it is Python code; enter `5` and it'll return an integer, enter `'some text'` (with quotes) and it'll return a string. `raw_input()` on the other hand returns the entered input uninterpreted.
Most dirty fix of all, simply change ``` for i in plainNum: ``` with ``` for i in str(plainNum): ```
Python Encryption
[ "", "python", "encryption", "" ]
I'm trying to remove gridlines from excel worksheet which I created using openpyxl, and it's not working. I'm doing this: ``` wb = Workbook() ws = wb.get_active_sheet() ws.show_gridlines = False print ws.show_gridlines wb.save('file.xlsx') ``` The that code prints the 'False', yet the saved file shows gridlines.
There is a relevant [issue](https://bitbucket.org/ericgazoni/openpyxl/issue/199/hide-gridlines) in `openpyxl` issue tracker. Plus, according to the source code `show_gridlines` is just a worksheet class property that has no affect at all. Just watch the issue to get any update on it. As an alternative solution, try the new and awesome [xlsxwriter](https://xlsxwriter.readthedocs.org/en/latest) module. It has an ability to hide grid lines on a worksheet (see [docs](https://xlsxwriter.readthedocs.org/en/latest/page_setup.html#hide_gridlines)). Here's an example: ``` from xlsxwriter.workbook import Workbook workbook = Workbook('hello_world.xlsx') worksheet = workbook.add_worksheet() worksheet.write('A1', 'Hello world') worksheet.hide_gridlines(2) workbook.close() ```
This was fixed in 2015. Here is the recommended solution (from description of [issue](https://bitbucket.org/openpyxl/openpyxl/issues/199)) ``` from openpyxl import Workbook wb = Workbook() ws = wb.active ws.sheet_view.showGridLines True ws.sheet_view.showGridLines = False wb.save("gridlines.xlsx") ``` Beware that you should type `ws.sheet_view.showGridLines` and not `ws.showGridLines`.
Removing gridlines from excel using python (openpyxl)
[ "", "python", "excel", "python-2.7", "openpyxl", "" ]
I'm running a python script but it won't show the picture. I have an apple.jpg image in a directory with this program and it should show the picture, but it doesn't. Here is the code: ``` #!/usr/bin/env python from PIL import Image Apple = Image.open("apple.jpg") Apple.show() ``` My OS is Ubuntu and this program just gets completed without showing any error.
It works for me on Ubuntu. It displays the image with Imagemagick. Try this: ``` sudo apt-get install imagemagick ```
I know, it's an old question but here is how I fixed it in Ubuntu, in case somebody has the same problem and does not want to install imagemagick (which does not fix the root cause of the problem anyway). The default viewer on Ubuntu can be started using the command "eog" in the terminal. Pillow, by default, searches only for the commands "xv" and "display", the latter one being provided by imagemagick. Therefore, if you install imagemagick, calling "display" will indeed open up the image. But why not use the viewer that we already have? The Python code to open the viewer can be found in lib/python3.4/site-packages/PIL/ImageShow.py (or the equivalent of your Python installation). Scroll down to below line# 155 and find the code block saying: ``` class DisplayViewer(UnixViewer): def get_command_ex(self, file, **options): command = executable = "display" return command, executable if which("display"): register(DisplayViewer) ``` Copy that block and paste it right underneath, changing the "display" command to Ubuntu's "eog" command: ``` class DisplayViewer(UnixViewer): def get_command_ex(self, file, **options): command = executable = "eog" return command, executable if which("eog"): register(DisplayViewer) ``` After saving ImageShow.py, Pillow should correctly show() images in the default viewer.
Image.show() won't display the picture
[ "", "python", "python-imaging-library", "" ]
I am trying to parse psd files and I found these tool [Psd-Tools](https://github.com/kmike/psd-tools). Just so you know, I am new into the python environment. I have followed the following steps and everything went well: ``` pip install psd-tools pip install docopt pip install Pillow pip install packbits ``` I can see them when I write `pip freeze`. But I can't see any of these `modules` in python with this command: ``` >>> help('modules') ``` Obviously, when I try to use it, I get this error: ``` >>> from psd_tools import PSDImage Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named psd_tools ``` I have python-2.7.3 and python3-3.3.0 installed on my mac. Whether I launch `python` or `python3`, none of them find the `psd_tools` module. So my guess was that the module has a different name, but none of these seems to work `"psd-tools"` `'psd-tools'` `psd\-tools`. Maybe I missed a step with `pip`? Or the module name has changed, then how can I see it ? Did anyone already use [Psd-Tools](https://github.com/kmike/psd-tools)?
Try to use install it from the source, from the [GitHub repository](https://github.com/kmike/psd-tools) of the project.
I'd do `python --version` and `pip --version` to see what version of Python each of them are using. It's possible one or both are not what you expect. FWIW, `pip install psd-tools` then `import psd_tools` worked fine for me on OSX on 2.7.
How to use psd-tools with python
[ "", "python", "parsing", "psd", "" ]
I have this ``` d = \ [('a', {'b': 'c1', 'd': 'f1'}), ('a', {'bb': 'c2', 'dd': 'f2'}), ('a', {'bbb': 'c3', 'ddd': 'f3'})] ``` I want the ouput like this ``` ['c1', 'f1', 'f2', 'c2', 'c3', 'f3'] ``` I have tried this ``` In [51]: [a.values() for k,a in d] Out[51]: [['c1', 'f1'], ['f2', 'c2'], ['c3', 'f3']] ``` I want to do that simplest and shortest possible way
``` >>> d = \ [('a', {'b': 'c1', 'd': 'f1'}), ('a', {'bb': 'c2', 'dd': 'f2'}), ('a', {'bbb': 'c3', 'ddd': 'f3'})] >>> [y for x in d for y in x[1].values()] ['c1', 'f1', 'f2', 'c2', 'c3', 'f3'] ```
You can use `itertools.chain`: ``` >>> d=[('a', {'b': 'c1', 'd': 'f1'}), ('a', {'bb': 'c2', 'dd': 'f2'}), ('a', {'bbb': 'c3', 'ddd': 'f3'})] >>> from itertools import chain >>> list(chain.from_iterable( x[1].values() for x in d )) ['c1', 'f1', 'f2', 'c2', 'c3', 'f3'] ```
How can i make the list form list of tuples
[ "", "python", "dictionary", "" ]
I have a column that contains data like this. dashes indicate multi copies of the same invoice and these have to be sorted in ascending order ``` 790711 790109-1 790109-11 790109-2 ``` i have to sort it in increasing order by this number but since this is a varchar field it sorts in alphabetical order like this ``` 790109-1 790109-11 790109-2 790711 ``` in order to fix this i tried replacing the -(dash) with empty and then casting it as a number and then sorting on that ``` select cast(replace(invoiceid,'-','') as decimal) as invoiceSort...............order by invoiceSort asc ``` while this is better and sorts like this ``` invoiceSort 790711 (790711) <-----this is wrong now as it should come later than 790109 790109-1 (7901091) 790109-2 (7901092) 790109-11 (79010911) ``` Someone suggested to me to split invoice id on the - (dash ) and order by on the 2 split parts like=====> `order by split1 asc,split2 asc (790109,1)` which would work i think but how would i split the column. The various split functions on the internet are those that return a table while in this case i would be requiring a scalar function. Are there any other approaches that can be used? The data is shown in grid view and grid view doesn't support sorting on 2 columns by default ( i can implement it though :) ) so if any simpler approaches are there i would be very nice. **EDIT** : thanks for all the answers. While every answer is correct i have chosen the answer which allowed me to incorporate these columns in the GridView Sorting with minimum re factoring of the sql queries.
Judicious use of `REVERSE`, `CHARINDEX`, and `SUBSTRING`, can get us what we want. I have used hopefully-explanatory columns names in my code below to illustrate what's going on. Set up sample data: ``` DECLARE @Invoice TABLE ( InvoiceNumber nvarchar(10) ); INSERT @Invoice VALUES ('790711') ,('790709-1') ,('790709-11') ,('790709-21') ,('790709-212') ,('790709-2') SELECT * FROM @Invoice ``` Sample data: ``` InvoiceNumber ------------- 790711 790709-1 790709-11 790709-21 790709-212 790709-2 ``` And here's the code. I have a nagging feeling the final expressions could be simplified. ``` SELECT InvoiceNumber ,REVERSE(InvoiceNumber) AS Reversed ,CHARINDEX('-',REVERSE(InvoiceNumber)) AS HyphenIndexWithinReversed ,SUBSTRING(REVERSE(InvoiceNumber),1+CHARINDEX('-',REVERSE(InvoiceNumber)),LEN(InvoiceNumber)) AS ReversedWithoutAffix ,SUBSTRING(InvoiceNumber,1+LEN(SUBSTRING(REVERSE(InvoiceNumber),1+CHARINDEX('-',REVERSE(InvoiceNumber)),LEN(InvoiceNumber))),LEN(InvoiceNumber)) AS AffixIncludingHyphen ,SUBSTRING(InvoiceNumber,2+LEN(SUBSTRING(REVERSE(InvoiceNumber),1+CHARINDEX('-',REVERSE(InvoiceNumber)),LEN(InvoiceNumber))),LEN(InvoiceNumber)) AS AffixExcludingHyphen ,CAST( SUBSTRING(InvoiceNumber,2+LEN(SUBSTRING(REVERSE(InvoiceNumber),1+CHARINDEX('-',REVERSE(InvoiceNumber)),LEN(InvoiceNumber))),LEN(InvoiceNumber)) AS int) AS AffixAsInt ,REVERSE(SUBSTRING(REVERSE(InvoiceNumber),1+CHARINDEX('-',REVERSE(InvoiceNumber)),LEN(InvoiceNumber))) AS WithoutAffix FROM @Invoice ORDER BY -- WithoutAffix REVERSE(SUBSTRING(REVERSE(InvoiceNumber),1+CHARINDEX('-',REVERSE(InvoiceNumber)),LEN(InvoiceNumber))) -- AffixAsInt ,CAST( SUBSTRING(InvoiceNumber,2+LEN(SUBSTRING(REVERSE(InvoiceNumber),1+CHARINDEX('-',REVERSE(InvoiceNumber)),LEN(InvoiceNumber))),LEN(InvoiceNumber)) AS int) ``` Output: ``` InvoiceNumber Reversed HyphenIndexWithinReversed ReversedWithoutAffix AffixIncludingHyphen AffixExcludingHyphen AffixAsInt WithoutAffix ------------- ---------- ------------------------- -------------------- -------------------- -------------------- ----------- ------------ 790709-1 1-907097 2 907097 -1 1 1 790709 790709-2 2-907097 2 907097 -2 2 2 790709 790709-11 11-907097 3 907097 -11 11 11 790709 790709-21 12-907097 3 907097 -21 21 21 790709 790709-212 212-907097 4 907097 -212 212 212 790709 790711 117097 0 117097 0 790711 ``` Note that all you actually need is the `ORDER BY` clause, the rest is just to show my working, which goes like this: * Reverse the string, find the hyphen, get the substring after the hyphen, reverse that part: This is the number without any affix * The length of (the number without any affix) tells us how many characters to drop from the start in order to get the affix including the hyphen. Drop an additional character to get just the numeric part, and convert this to `int`. Fortunately we get a break from SQL Server in that this conversion gives zero for an empty string. * Finally, having got these two pieces, we simple `ORDER BY` (the number without any affix) and then by (the numeric value of the affix). This is the final order we seek. The code would be more concise if SQL Server allowed us to say `SUBSTRING(value, start)` to get the string starting at that point, but it doesn't, so we have to say `SUBSTRING(value, start, LEN(value))` a lot.
Try this one - **Query:** ``` DECLARE @Invoice TABLE (InvoiceNumber VARCHAR(10)) INSERT @Invoice VALUES ('790711') , ('790709-1') , ('790709-21') , ('790709-11') , ('790709-211') , ('790709-2') ;WITH cte AS ( SELECT InvoiceNumber , lenght = LEN(InvoiceNumber) , delimeter = CHARINDEX('-', InvoiceNumber) FROM @Invoice ) SELECT InvoiceNumber FROM cte CROSS JOIN ( SELECT repl = MAX(lenght - delimeter) FROM cte WHERE delimeter != 0 ) mx ORDER BY SUBSTRING(InvoiceNumber, 1, ISNULL(NULLIF(delimeter - 1, -1), lenght)) , RIGHT(REPLICATE('0', repl) + SUBSTRING(InvoiceNumber, delimeter + 1, lenght), repl) ``` **Output:** ``` InvoiceNumber ------------- 790709-1 790709-2 790709-11 790709-21 790709-211 790711 ```
Sort string as number in sql server
[ "", "sql", "sorting", "sql-server-2008-r2", "natural-sort", "" ]
I am trying to make 100 lists with names such as: list1, list2, list3, etc. Essentially what I would like to do is below (although I know it doesn't work I am just not sure why). ``` num_lists=100 while i < num_lists: intial_pressure_{}.format(i) = [] centerline_temperature_{}.format(i) = [] ``` And then I want to loop through each list inserting data from a file but I am unsure how I can have the name of the list change in that loop. Since I know this won't work. ``` while i < num_lists: initial_pressure_i[0] = value ``` I'm sure what I'm trying to do is really easy, but my experience with python is only a couple of days. Any help is appreciated. Thanks
Welcome to Python! Reading your comments on what you are trying to do, I suggest ditching your current approach. Select an easier data structure to work with. Suppose you have a list of files: ``` files = ['data1.txt', 'data2.txt',...,'dataN.txt'] ``` Now you can loop over those files in turn: ``` data = {} for file in files: data[file] = {} with open(file,'r') as f: lines=[int(line.strip()) for line in f] data[file]['temps'] = lines[::2] #even lines just read data[file]['pressures'] = lines[1::2] #odd lines ``` Then you will have a dict of dict of lists like so: ``` {'data1.txt': {'temps': [1, 2, 3,...], 'pressures': [1,2,3,...]}, 'data2.txt': {'temps': [x,y,z,...], 'pressures': [...]}, ...} ``` Then you can get your maxes like so: ``` max(data['data1.txt']['temps']) ``` Just so you can see what the data will look like, run this: ``` data = {} for i in range(100): item = 'file' + str(i) data[item] = {} kind_like_file_of_nums = [float(x) for x in range(10)] data[item]['temps'] = kind_like_file_of_nums[0::2] data[item]['pres'] = kind_like_file_of_nums[1::2] print(data) ```
Instead of creating 100 list variables, you can create 100 lists inside of a list. Just do: ``` list_of_lists = [[] for _ in xrange(100)] ``` Then, you can access lists on your list by doing: ``` list_of_lists[0] = some_value # First list list_of_lists[1] = some_other_value # Second list # ... and so on ```
Name of a list changing as I go through a loop
[ "", "python", "list", "" ]
I'm currently writing a web application in Python using the Flask web framework. I'm really getting used to just putting everything in the one file, unlike many other projects I see where they have different directories for classes, views, and stuff. However, the Flask example just stuff everything into the one file, which is what I seem to be going with. Is there any risks or problems in writing the whole web app in the one single file, or is it better to spread out my functions and classes across separate files?
Usually it's not a good practice to keep your app in a single file except that it's trivial or for educational purposes. I don't want to reinvent the wheel, so here's links for sample flask project structures, skeletons and other info on the subject: * [Flask: Large App how-to](https://gist.github.com/cuibonobo/8696392) * <https://github.com/italomaia/flask-empty> * [How to organize a relatively large Flask application?](https://stackoverflow.com/questions/9395587/how-to-organize-a-relatively-large-flask-application?rq=1) * [Flask project structure](https://stackoverflow.com/questions/14298692/flask-project-structure) * [How do I Structure My Flask Applications](https://mattupstate.com/blog/how-i-structure-my-flask-applications/) And, or course, read the awesome flask [mega-tutorial](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) - you'll see how your application will grow and split into logical parts step-by-step.
There is no right or wrong answer to this. One file may be easy to manage if it is a very small project and you probably are the only one working on it. Some of the reasons you split the project into multiple source files however are: * You only change and commit what requires change. What I mean here is if you have a large single file with all your code in it, any change in the file will mean saving/updating the entire file. Imagine if you made a mistake, the entire codebase could get screwed up. * You have a large team possibly with different set of duties and responsibilities. For example, you could have a designer who only takes care of the design/front end (HTML,CSS etc.). If you have all the code in one file, they are exposed to the other stuff that they don't need to worry about. Also, they can independently work on their portion without needing to worry about anything else. You minimize the risk of mistakes by having multiple source files here. * Easier to manage as the codebase gets bigger. Can you imagine looking through 100,000 lines of code in one single file and trying to debug a problem ?
Is it bad practice to write a whole Flask application in one file?
[ "", "python", "flask", "coding-style", "standards", "project-structure", "" ]
How to read a whole file in Python? I would like my script to work however it is called * `script.py log.txt` * `script.py < log2.txt` * `python script.py < log2.txt` * `python -i script.py logs/yesterday.txt` You get the idea. --- I tried ``` import fileinput from bs4 import BeautifulSoup f = fileinput.input() soup = BeautifulSoup(f.read()) ``` But I get ``` Traceback (most recent call last): File "visual-studio-extension-load-times.py", line 5, in <module> soup = BeautifulSoup(f.read()) AttributeError: FileInput instance has no attribute 'read' ```
Instead of using `fileinput`, open the file directly yourself: ``` import sys try: fileobj = open(sys.argv[1], 'r') except IndexError: fileobj = sys.stdin with fileobj: data = fileobj.read() ```
``` f = open('file.txt', 'r') data = f.read() f.close() ``` further more, to open a file passed from the command line you can do: (also, this is a smarter way to open files, instead of `f = open(...)` you can do `with ...`) ``` import sys with open(sys.argv[1], 'r') as f: data = f.read() ``` The reason for `with` being a smarter way to open files, is because it will automaticlly close the file after you leave the indented `with` block. This means you don't have to "worry" about files being open or forgotten for to long (that can cause "to many open filehandles" from your OS) --- Then to `sys.argv` `sys.argv[1]` will be the first parameter on the command line after your python file. `sys.argv[0]` will be your scripts name. for instance: `python myscript.py heeyooo` will be: * `sys.argv[0] == "myscript.py"` * `sys.argv[1] == "heeyooo"` :) Then there's all sorts of modules that will be interesting to you when working with files. For one, `os.path` is a good start because you will most likely want to do as much cross-platform as possible and this gives you the option to convert `\` into `/` on Linux and vice versa. A few good ones are: * os.path.abspath * os.path.isfile * os.path.isdir You also have `os.getcwd()` which might be good :)
How to read a whole file in Python? To work universally in command line
[ "", "python", "beautifulsoup", "" ]
Is there a better (and shorter) way of how to create chessboard like array. Requirements for the board are: * board can be different size (in my example it's 3x3) * bottom left square of the board should always be black * black square is presented by `"B"`, white square is presented by `"W"` **Code that I have:** ``` def isEven(number): return number % 2 == 0 board = [["B" for x in range(3)] for x in range(3)] if isEven(len(board)): for rowIndex, row in enumerate(board): if isEven(rowIndex + 1): for squareIndex, square in enumerate(row): if isEven(squareIndex + 1): board[rowIndex][squareIndex] = "W" else: for squareIndex, square in enumerate(row): if not isEven(squareIndex + 1): board[rowIndex][squareIndex] = "W" else: for rowIndex, row in enumerate(board): if not isEven(rowIndex + 1): for squareIndex, square in enumerate(row): if isEven(squareIndex + 1): board[rowIndex][squareIndex] = "W" else: for squareIndex, square in enumerate(row): if not isEven(squareIndex + 1): board[rowIndex][squareIndex] = "W" for row in board: print row ``` **Output:** ``` ['B', 'W', 'B'] ['W', 'B', 'W'] ['B', 'W', 'B'] ```
How about: ``` >>> n = 3 >>> board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)] >>> print board [['B', 'W', 'B'], ['W', 'B', 'W'], ['B', 'W', 'B']] >>> n = 4 >>> board = [["BW"[(i+j+n%2+1) % 2] for i in range(n)] for j in range(n)] >>> print board [['W', 'B', 'W', 'B'], ['B', 'W', 'B', 'W'], ['W', 'B', 'W', 'B'], ['B', 'W', 'B', 'W']] ```
Kind of a hack but ``` print [["B" if abs(n - row) % 2 == 0 else "W" for n in xrange(3)] for row in xrange(3)][::-1] ``` This seems like requirements creep or something =) ``` def make_board(n): ''' returns an empty list for n <= 0 ''' return [["B" if abs(c - r) % 2 == 0 else "W" for c in xrange(n)] for r in xrange(n)][::-1] ```
Create a black and white chessboard in a two dimensional array
[ "", "python", "" ]
I have a query like this: ``` SELECT * FROM Cases WHERE created_at BETWEEN '2013-05-01' AND '2013-05-01' ``` But this gives no results even though there is data on the 1st. `created_at` looks like `2013-05-01 22:25:19`, I suspect it has to do with the time? How could this be resolved? It works just fine if I do larger date ranges, but it should (inclusive) work with a single date too.
It *is* inclusive. You are comparing datetimes to dates. The second date is interpreted as midnight *when the day starts*. One way to fix this is: ``` SELECT * FROM Cases WHERE cast(created_at as date) BETWEEN '2013-05-01' AND '2013-05-01' ``` Another way to fix it is with explicit binary comparisons ``` SELECT * FROM Cases WHERE created_at >= '2013-05-01' AND created_at < '2013-05-02' ``` Aaron Bertrand has a long blog entry on dates ([here](https://sqlblog.org/2009/10/16/bad-habits-to-kick-mis-handling-date-range-queries)), where he discusses this and other date issues.
It has been assumed that the second date reference in the `BETWEEN` syntax is magically considered to be the "end of the day" but **this is untrue**. i.e. this was expected: ``` SELECT * FROM Cases WHERE created_at BETWEEN the beginning of '2013-05-01' AND the end of '2013-05-01' ``` but what really happen is this: ``` SELECT * FROM Cases WHERE created_at BETWEEN '2013-05-01 00:00:00+00000' AND '2013-05-01 00:00:00+00000' ``` Which becomes the equivalent of: ``` SELECT * FROM Cases WHERE created_at = '2013-05-01 00:00:00+00000' ``` --- The problem is one of perceptions/expectations about `BETWEEN` which **does** include BOTH the lower value and the upper values in the range, but **does not** magically make a date the "beginning of" or "the end of". `BETWEEN` should be avoided when filtering by date ranges. **Always** use the `>= AND <` instead ``` SELECT * FROM Cases WHERE (created_at >= '20130501' AND created_at < '20130502') ``` the parentheses are optional here but can be important in more complex queries.
SQL "between" not inclusive
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "date", "" ]
Whenever I try to print out json from python, it ignores line breaks and prints the literal string "\n" instead of new line characters. I'm generating json using jinja2. Here's my code: ``` print json.dumps(template.render(**self.config['templates'][name])) ``` It prints out everything in the block below (literally - even the quotes and "\n" strings): ``` "{\n \"AWSTemplateFormatVersion\" : \"2010-09-09\",\n \"Description\" : ... ``` (truncated) I get something like this whenever I try to dump anything but a dict. Even if I try json.loads() then dump it again I get garbage. It just strips out all line breaks. What's going wrong?
This is what I use for pretty-printing json-objects: ``` def get_pretty_print(json_object): return json.dumps(json_object, sort_keys=True, indent=4, separators=(',', ': ')) print get_pretty_print(my_json_obj) ``` `json.dumps()` also accepts parameters for encoding, if you need non-ascii support.
`json.dumps()` returns a JSON-encoded string. The JSON standard mandates that newlines are encoded as `\\n`, which is then printed as `\n`: ``` >>> s="""hello ... there""" >>> s 'hello\nthere' >>> json.dumps(s) '"hello\\nthere"' >>> print(json.dumps(s)) "hello\nthere" ``` There's not much you can do to change that if you want to keep a valid JSON string. If you want to print it, the correct way would be to print the JSON *object*, not its string representation: ``` >>> print(s) hello there >>> print(json.loads(json.dumps(s))) # pointless; just for demonstration... hello there ```
Can't pretty print json from python
[ "", "python", "json", "" ]
I have two tables, with each table having a composite primary key. One attribute is in both composite primary keys. How am i supposed to reference the common attribute?? Do i just reference it as a FK in both tables as below? The cust\_id and flight\_id below are each part of the composite key as well and reference primary keys in other tables. (Ignore the third attribute in the erd for the br\_flight table as I choose to use a composite key in the end). ``` CREATE TABLE BOOKING_REFERENCE ( REFERENCE_ID NVARCHAR(10) NOT NULL, CUST_ID NUMBER(10)NOT NULL, STATUS NVARCHAR (1), NOT NULL, PRIMARY KEY(REFERENCE_ID, CUST_ID), FOREIGN KEY(REFERENCE_ID) REFERENCES BR_FLIGHT(REFERENCE_ID): FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(CUST_ID); CREATE TABLE BR_FLIGHT ( REFERENCE_ID NVARCHAR(10) NOT NULL , FLIGHT_ID NVARCHAR (10) NOT NULL, PRIMARY KEY(REFERENCE_ID, FLIGHT_ID), FOREIGN KEY (REFERENCE_ID) REFERENCES BOOKING_REFERENCE(REFERENCE_ID) FOREIGN KEY (FLIGHT_ID) REFERENCES FLIGHT(FLIGHT_ID) ); ``` ![enter image description here](https://i.stack.imgur.com/DH9NE.jpg) Would the above sql work?? Thanks in advance and apologies for the shoddy diagram:)
Foreign keys have to match the primary/unique key they reference column for column. Since the primary key of `BOOKING_REFERENCE` is (`REFERENCE_ID`, `CUST_ID`), that means that the foreign key from `BR_FLIGHT` to `BOOKING_REFERENCE` must consist of 2 columns also. That means you need to add `CUST_ID` to the `BR_FLIGHT` table - either that or your `BOOKING_REFERENCE` primary key is wrong and should just be (`REFERENCE_ID`). That said, it doesn't make sense to have foreign keys defined in both directions as you do. The "child" table should reference the "parent" and not vice versa.
When you reference composite primary key with a foreign key you must reference the whole key. In your case you should alter the BR\_FLIGHT table and add the CUST\_ID column ``` ALTER TABLE BR_FLIGHT ADD ( CUST_ID NUMBER(10)NOT NULL ); ``` And reference the full key as: ``` FOREIGN KEY (REFERENCE_ID, CUST_ID) REFERENCES BOOKING_REFERENCE (REFERENCE_ID, CUST_ID) ``` Now DDL for BR\_FLIGHT table will be: ``` CREATE TABLE BR_FLIGHT ( REFERENCE_ID NVARCHAR(10) NOT NULL , CUST_ID NUMBER(10)NOT NULL, FLIGHT_ID NVARCHAR (10) NOT NULL, PRIMARY KEY(REFERENCE_ID, FLIGHT_ID), FOREIGN KEY (REFERENCE_ID, CUST_ID) REFERENCES BOOKING_REFERENCE (REFERENCE_ID, CUST_ID) ); ``` As Tony Andrews pointed out you don't need the foreign part in the BOOKING\_REFERENCE table. It should look like this: ``` CREATE TABLE BOOKING_REFERENCE ( REFERENCE_ID NVARCHAR(10) NOT NULL, CUST_ID NUMBER(10)NOT NULL, STATUS NVARCHAR (1), NOT NULL, PRIMARY KEY(REFERENCE_ID, CUST_ID) ); ```
Referencing a composite primary key
[ "", "sql", "oracle", "foreign-keys", "primary-key", "composite-primary-key", "" ]
when I do curl to a API call link <http://example.com/passkey=wedsmdjsjmdd> ``` curl 'http://example.com/passkey=wedsmdjsjmdd' ``` I get the employee output data on a csv file format, like: ``` "Steve","421","0","421","2","","","","","","","","","421","0","421","2" ``` how can parse through this using python. I tried: ``` import csv cr = csv.reader(open('http://example.com/passkey=wedsmdjsjmdd',"rb")) for row in cr: print row ``` but it didn't work and I got an error `http://example.com/passkey=wedsmdjsjmdd No such file or directory:` Thanks!
You need to replace `open` with [urllib.urlopen](http://docs.python.org/2/library/urllib.html#urllib.urlopen) or [urllib2.urlopen](http://docs.python.org/2/library/urllib2.html#urllib2.urlopen). e.g. ``` import csv import urllib2 url = 'http://winterolympicsmedals.com/medals.csv' response = urllib2.urlopen(url) cr = csv.reader(response) for row in cr: print row ``` This would output the following ``` Year,City,Sport,Discipline,NOC,Event,Event gender,Medal 1924,Chamonix,Skating,Figure skating,AUT,individual,M,Silver 1924,Chamonix,Skating,Figure skating,AUT,individual,W,Gold ... ``` The original question is tagged "python-2.x", but for a Python 3 implementation (which requires only minor changes) [see below](https://stackoverflow.com/a/62614979/785213).
Using pandas it is very simple to read a csv file directly from a url ``` import pandas as pd data = pd.read_csv('https://example.com/passkey=wedsmdjsjmdd') ``` This will read your data in tabular format, which will be very easy to process
How to read a CSV file from a URL with Python?
[ "", "python", "csv", "curl", "output", "python-2.x", "" ]
Why does this code give a `KeyError`? ``` output_format = """ { "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" } """ print output_format.format(filename='My_file_name', success=True, error_msg='', log_identifier='123') ``` Error message: ``` KeyError: ' "File"' ```
You need to double the outer braces; otherwise Python thinks `{ "File"..` is a reference too: ``` output_format = '{{ "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" }}' ``` Result: ``` >>> print output_format.format(filename='My_file_name', ... success=True, ... error_msg='', ... log_identifier='123') { "File": "My_file_name", "Success": True, "ErrorMessage": "", "LogIdentifier": "123" } ``` If, indicentally, you are producing JSON output, you'd be better off using the [`json` module](http://docs.python.org/library/json.html): ``` >>> import json >>> print json.dumps({'File': 'My_file_name', ... 'Success': True, ... 'ErrorMessage': '', ... 'LogIdentifier': '123'}) {"LogIdentifier": "123", "ErrorMessage": "", "Success": true, "File": "My_file_name"} ``` Note the *lowercase* `true` in the output, as required by the JSON standard.
As mentioned by Tudor in a [comment](https://stackoverflow.com/questions/16356810/string-format-a-json-string-gives-keyerror#comment95949992_51538980) to another answer, the [Template](https://docs.python.org/3/library/string.html#template-strings) class was the solution that worked best for me. I'm dealing with nested dictionaries or list of dictionaries and handling those were not as straightforward. Using Template though the solution is quite simple. I start with a dictionary that is converted into a string. I then replace all instances of `{` with `${` which is the Template identifier to substitute a placeholder. The key point of getting this to work is using the Template method `safe_substitute`. It will replace all valid placeholders like `${user_id}` but ignore any invalid ones that are part of the dictionary structure, like `${'name': 'John', ...`. After the substitution is done I remove any leftovers `$` and convert the string back to a dictionary. In the code bellow, `resolve_placeholders` returns a dictionary where each key matches a placeholder in the payload string and the value is substituted by the Template class. ``` from string import Template . . . payload = json.dumps(payload) payload = payload.replace('{', '${') replace_values = self.resolve_placeholders(payload) if replace_values: string_template = Template(payload) payload = string_template.safe_substitute(replace_values) payload = payload.replace('${', '{') payload = json.loads(payload) ```
String format a JSON string gives KeyError
[ "", "python", "json", "string", "format", "" ]
If I have a table that looks like this ``` begin date end date data 2013-01-01 2013-01-04 7 2013-01-05 2013-01-06 9 ``` How can I make it be returned like this... ``` date data 2013-01-01 7 2013-01-02 7 2013-01-03 7 2013-01-04 7 2013-01-05 9 2013-01-06 9 ``` One thing I was thinking of doing is to have another table that just has all the dates and then join the table with just dates to the above table using `date>=begin date` and `date<=end date` but that seems a little clunky to have to maintain that extra table with nothing but repetitive dates. In some instances I don't have a data range but just an `as of` date which basically looks like my first example but with no `end date`. The `end date` is implied by the next row's 'as of' date (ie end date should be the next row's `as of` -1). I had a "solution" for this that uses the row\_number() function to get the next value but I suspect that methodology, which the way I'm doing it has a bunch of nested self joins, contributes to very long query times.
Using some sample data... ``` create table data (begindate datetime, enddate datetime, data int); insert data select '20130101', '20130104', 7 union all select '20130105', '20130106', 9; ``` **The Query**: (Note: if you already have a numbers/tally table - use it) ``` select dateadd(d,v.number,d.begindate) adate, data from data d join master..spt_values v on v.type='P' and v.number between 0 and datediff(d, begindate, enddate) order by adate; ``` **Results**: ``` | COLUMN_0 | DATA | ----------------------------------------- | January, 01 2013 00:00:00+0000 | 7 | | January, 02 2013 00:00:00+0000 | 7 | | January, 03 2013 00:00:00+0000 | 7 | | January, 04 2013 00:00:00+0000 | 7 | | January, 05 2013 00:00:00+0000 | 9 | | January, 06 2013 00:00:00+0000 | 9 | ``` --- Alternatively you can generate a number table on the fly (0-99) or as many numbers as you need ``` ;WITH Numbers(number) AS ( select top(100) row_number() over (order by (select 0))-1 from sys.columns a cross join sys.columns b cross join sys.columns c cross join sys.columns d ) select dateadd(d,v.number,d.begindate) adate, data from data d join Numbers v on v.number between 0 and datediff(d, begindate, enddate) order by adate; ``` [SQL Fiddle Demo](http://sqlfiddle.com/#!18/954e2/1)
You can use recursive CTE to get all the dates between two dates. Another CTE is to get ROW\_NUMBERs to help you with those missing EndDates. ``` DECLARE @startDate DATE DECLARE @endDate DATE SELECT @startDate = MIN(begindate) FROM Table1 SELECT @endDate = MAX(enddate) FROM Table1 ;WITH CTE_Dates AS ( SELECT @startDate AS DT UNION ALL SELECT DATEADD(DD, 1, DT) FROM CTE_Dates WHERE DATEADD(DD, 1, DT) <= @endDate ) ,CTE_Data AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY BeginDate) AS RN FROM Table1 ) SELECT DT, t1.data FROM CTE_Dates d LEFT JOIN CTE_Data t1 on d.DT BETWEEN t1.[BeginDate] AND COALESCE(t1.EndDate, (SELECT DATEADD(DD,-1,t2.BeginDate) FROM CTE_Data t2 WHERE t1.RN + 1 = t2.RN)) ``` **[SQLFiddle DEMO](http://sqlfiddle.com/#!6/dc4ed/2)**
SQL how to convert row with date range to many rows with each date
[ "", "sql", "sql-server-2008-r2", "" ]
I have a DBF - foxpro query and seems like I have an error, I am using codeIgniter and its feedback is just **Fatal error: Call to a member function execute() on a non-object in D:\xampp\htdocs\accounting\system\database\drivers\pdo\pdo\_driver.php on line 193** and I have encountered this error many times already and it means I have an error in my SQL but I cant figure out where. here are my tables ### GUESTS ### Guest ID | Guest\_Name | Guest\_Seat\_No ``` 1 | John | 24 ``` ### SEATS ### Seat\_No | Room\_Location ``` 24 | 2nd Floor Room 11 ``` --- **HERE IS MY SQL QUERY** ``` SELECT A.Guest_ID, A.Guest_Name, A.Guest_Seat_No, B.Room_Location FROM GUESTS A JOIN SEATS B ON A.Guest_Seat_No = B.Seat_No WHERE A.Guest_ID = '1' ``` It seems there's something wrong in my query, its very difficult to determine the error because it just returns a **fatal error generated by codeIgniter** not the actual **sql syntax error** can someone please help me?
you should define what kind of `JOIN` type you are using, like `INNER , LEFT, OUTER, FULL,`
``` SELECT A.Guest_ID, A.Guest_Name, A.Guest_Seat_No, B.Room_Location FROM GUESTS AS A JOIN SEATS AS B ON A.Guest_Seat_No = B.Seat_No WHERE A.Guest_ID = '1' ```
SQL query seems to have an Error
[ "", "sql", "codeigniter", "foxpro", "dbf", "" ]
Could someone elucidate for me why the following does not work: ``` insert into DrugInteractions(ndc_fk, ndc_pk) (select top 1 ndc from DrugList where drug_name like 'cipro%'), (select top 1 ndc from DrugList where drug_name like 'tizan%') ``` The column `ndc` in `DrugList` is a primary key which uniquely identifies a certain drug. Since you need two things to interact the `DrugInteractions` table has two copies of the `ndc`; these two `ndc`s will be a composite primary key. So say Drug A has an ndc of 1 and Drug B has an ndc of 2, then the row in DrugInteraction would look like: ``` ndc_pk ndc_fk 1 2 ``` Is there a way to populate a table using an insert statement with two queries, one for each column like I'm trying? The error I get is: > Msg 102, Level 15, State 1, Line 2 > Incorrect syntax near ','
You need to use `VALUES` to combine them; ``` insert into DrugInteractions(ndc_fk,ndc_pk) VALUES( (select top 1 ndc from DrugList where drug_name like 'cipro%'), (select top 1 ndc from DrugList where drug_name like 'tizan%') ) ``` [An SQLfiddle to test with](http://sqlfiddle.com/#!6/5db86/2).
``` insert into DrugInteractions(ndc_fk, ndc_pk) select top 1 ndc, newid() from DrugList where drug_name like 'cipro%' union select top 1 ndc, newid() from DrugList where drug_name like 'tizan%' ```
Use two queries to populate table with INSERT statement
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
``` debian@debian:~$ echo $PYTHONPATH /home/qiime/lib/: debian@debian:~$ python Python 2.7.3 (default, Jan 2 2013, 16:53:07) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/usr/local/lib/python2.7/dist-packages/feedparser-5.1.3-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/stripogram-1.5-py2.7.egg', '/home/qiime/lib', '/home/debian', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib- dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7'] ``` How can I get all of `PYTHONPATH` output in bash? Why `echo $PYTHONPATH` can not get all of them?
The environment variable [`PYTHONPATH`](http://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH) is actually only added to the list of locations Python searches for modules. You can print out the full list in the terminal like this: ``` python -c "import sys; print(sys.path)" ``` Or if want the output in the UNIX directory list style (separated by `:`) you can do this: ``` python -c "import sys; print(':'.join(x for x in sys.path if x))" ``` Which will output something like this: ``` /usr/local/lib/python2.7/dist-packages/feedparser-5.1.3-py2.7.egg:/usr/local/lib/ python2.7/dist-packages/stripogram-1.5-py2.7.egg:/home/qiime/lib:/home/debian:/us r/lib/python2.7:/usr/lib/python2.7/plat-linux2:/usr/lib/python2.7/lib-tk:/usr/lib /python2.7/lib-old:/usr/lib/python2.7/lib- dynload:/usr/local/lib/python2.7/dist- packages:/usr/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages/PIL:/u sr/lib/python2.7/dist-packages/gst-0.10:/usr/lib/python2.7/dist-packages/gtk-2.0: /usr/lib/pymodules/python2.7 ```
## Just write: just write `which python` in your terminal and you will see the python path you are using.
How to get the PYTHONPATH in shell?
[ "", "python", "linux", "pythonpath", "" ]
I'm on a linux machine (Redhat) and I have an 11GB text file. Each line in the text file contains data for a single record and the first n characters of the line contains a unique identifier for the record. The file contains a little over 27 million records. I need to verify that there are not multiple records with the same unique identifier in the file. I also need to perform this process on an 80GB text file so any solution that requires loading the entire file into memory would not be practical.
Read the file line-by-line, so you don't have to load it all into memory. For each line (record) create a sha256 hash (32 bytes), unless your identifier is shorter. Store the hashes/identifiers in an `numpy.array`. That is probably the most compact way to store them. 27 million records times 32 bytes/hash is 864 MB. That should fit into the memory of decent machine these days. To speed up access you could use the first e.g. 2 bytes of the hash as the key of a `collections.defaultdict` and put the rest of the hashes in a list in the value. This would in effect create a hash table with 65536 buckets. For 27e6 records, each bucket would contain on average a list of around 400 entries. It would mean faster searching than a numpy array, but it would use more memory. ``` d = collections.defaultdict(list) with open('bigdata.txt', 'r') as datafile: for line in datafile: id = hashlib.sha256(line).digest() # Or id = line[:n] k = id[0:2] v = id[2:] if v in d[k]: print "double found:", id else: d[k].append(v) ```
Rigth tool for the job: put your records into a database. Unless you have a Postgres or MySQL installation handy already, I'd take sqlite. ``` $ sqlite3 uniqueness.sqlite create table chk ( ident char(n), -- n as in first n characters lineno integer -- for convenience ); ^D ``` Then I'd insert the unique identifier and line number into that table, possibly using a Python script like this: ``` import sqlite3 # install pysqlite3 before this n = ... # how many chars are in the key part lineno = 0 conn = sqlite3.connect("uniqueness.sqlite") cur = conn.cursor() with open("giant-file") as input: for line in input: lineno +=1 ident = line[:n] cur.execute("insert into chk(ident, lineno) values(?, ?)", [ident, lineno]) cur.close() conn.close() ``` After this, you can index the table and use SQL: ``` $ sqlite3 uniqueness.sqlite create index x_ident on chk(ident); -- may take a bit of time -- quickly find duplicates, if any select ident, count(ident) as how_many from chk group by ident having count(ident) > 1; -- find lines of specific violations, if needed select lineno from chk where ident = ...; -- insert a duplicate ident ``` Yes, I tried most of this code, it should work :)
Find duplicate records in large text file
[ "", "python", "linux", "bash", "shell", "" ]
I'm trying to query some data to practice and these are the three tables: ``` course assignment assignment_submissions id id id course assignment ``` As you can see the relationships are pretty basic, but I'm just that rusty with plain SQL, that's why I'm practicing. Given a `course 'id'`, how can I find all the `assignment_submission` rows that belong to it? I would need to get the assignments, then for each assignment get each submissions. Here's my attempt, but this fails and returns a MUCH larger dataset than expected. ``` SELECT sub.id, sub.grade, FROM uv_assignment_submissions sub, uv_assignment ass WHERE ass.course = 1245 ```
You would need a `JOIN` all 3 tables, `course`, `assignment` and `assignment_submissions`. I have used a `JOIN` construct assuming you need to display the course details only when some records exists for `assignments` and `assignment_submissions`. The reason why your query fails is because, its currently getting the `Cartesian` product of all records from the `2 tables`, you would need a condition to specify which rows are valid for the current `assignment` by specifying a `JOIN` condition Something like this should work ``` SELECT c.id, asub.id FROM course c JOIN assignment a ON ( c.id = a.course ) JOIN assignment_submissions asub ON ( asub.ID = a.assignment ) WHERE c.id = 10 --your course id goes here OR c.id in (10, 20, 30) -- for multiple IDS ``` More on SQL Joins: <http://dev.mysql.com/doc/refman/5.0/en/join.html>
the problem with your attempt is that you have a cross product of the three tables and are only limiting which rows in uv\_assignment are used. So for course 1245 you are showing every assignment even if not relevant to that course, and so on. However, you were close: ``` SELECT sub.id, sub.grade, FROM uv_assignment_submissions sub, uv_assignment ass WHERE sub.assignment = ass.id and ass.course = course.id and ass.course = 1245 ```
Trouble querying results from three tables
[ "", "mysql", "sql", "" ]
Assuming I have the following table structure ``` CREATE TABLE `calendar` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `date` DATE NOT NULL, PRIMARY KEY (`id`) ) ``` And the following data ``` INSERT INTO `calendar` (`title`, `date`) VALUES ('Day 1 - Event 1', '2013-05-01'), ('Day 2 - Event 1', '2013-05-02'), ('Day 2 - Event 2', '2013-05-02'), ('Day 3 - Event 1', '2013-05-03'); ``` I was hoping to limit the result set to 2 items but not cut the result in between items of the same date. ``` SELECT * FROM `calendar` WHERE `date` >= '2013-05-01' LIMIT 2 ``` Yield ``` ('Day 1 - Event 1', '2013-05-01'), ('Day 2 - Event 1', '2013-05-02'), ('Day 2 - Event 2', '2013-05-02') ``` Instead of just ``` ('Day 1 - Event 1', '2013-05-01'), ('Day 2 - Event 1', '2013-05-02') ``` Any ideas?
Something like this should work putting your desired dates in a subquery: ``` SELECT DISTINCT c.* FROM `calendar` c JOIN ( SELECT `date` FROM `calendar` WHERE `date` >= '2013-05-01' LIMIT 2 ) c2 on c.`date` = c2.`date` ``` [SQL Fiddle Demo](http://sqlfiddle.com/#!2/5481e/1) I would recommend adding an `ORDER BY` date to your query though as you can't guarantee the order of the results without.
If I understand correctly, you want to show the first 2 items but if there is a tie (on the date) on the last item, to include tied results as well. SQL-Server has `TOP (2) WITH TIES` but unfortunately MySQL's `LIMIT` has no equivalent. So, the query has to be more complex: ``` SELECT * FROM calendar WHERE `date` >= '2013-05-01' AND `date` <= COALESCE( ( SELECT `date` FROM calendar WHERE `date` >= '2013-05-01' ORDER BY `date` LIMIT 1 OFFSET 1 -- that's 2 minus 1 ), '9999-12-31' ) ; ``` And another way, similar to @sgeddes's answer: ``` SELECT c.* FROM calendar c JOIN ( SELECT DISTINCT `date` FROM ( SELECT `date` FROM `calendar` WHERE `date` >= '2013-05-01' ORDER BY `date` LIMIT 2 ) AS c2 ) AS cc ON c.`date` = cc.`date` ; ```
MySQL limit by count and return items with same date
[ "", "mysql", "sql", "" ]
I am dealing with pandas DataFrames like this: ``` id x 0 1 10 1 1 20 2 2 100 3 2 200 4 1 NaN 5 2 NaN 6 1 300 7 1 NaN ``` I would like to replace each NAN 'x' with the previous non-NAN 'x' from a row with the same 'id' value: ``` id x 0 1 10 1 1 20 2 2 100 3 2 200 4 1 20 5 2 200 6 1 300 7 1 300 ``` Is there some slick way to do this without manually looping over rows?
You could perform a [groupby/forward-fill](http://pandas.pydata.org/pandas-docs/stable/api.html#id32) operation on each group: ``` import numpy as np import pandas as pd df = pd.DataFrame({'id': [1,1,2,2,1,2,1,1], 'x':[10,20,100,200,np.nan,np.nan,300,np.nan]}) df['x'] = df.groupby(['id'])['x'].ffill() print(df) ``` yields ``` id x 0 1 10.0 1 1 20.0 2 2 100.0 3 2 200.0 4 1 20.0 5 2 200.0 6 1 300.0 7 1 300.0 ```
``` df id val 0 1 23.0 1 1 NaN 2 1 NaN 3 2 NaN 4 2 34.0 5 2 NaN 6 3 2.0 7 3 NaN 8 3 NaN df.sort_values(['id','val']).groupby('id').ffill() id val 0 1 23.0 1 1 23.0 2 1 23.0 4 2 34.0 3 2 34.0 5 2 34.0 6 3 2.0 7 3 2.0 8 3 2.0 ``` use sort\_values, groupby and ffill so that if you have `Nan` value for the first value or set of first values they also get filled.
Fill in missing pandas data with previous non-missing value, grouped by key
[ "", "python", "pandas", "nan", "missing-data", "data-cleaning", "" ]
I am having some problems with my WHERE clause (using SQL 2008) . I have to create a stored procedure that returns a list of results based on 7 parameters, some of which may be null. The ones which are problematic are @elements, @categories and @edu\_id. They can be a list of ids, or they can be null. You can see in my where clause that my particular code works if the parameters are not null. I'm not sure how to code the sql if they are null. The fields are INT in the database. I hope my question is clear enough. Here is my query below. ``` BEGIN DECLARE @elements nvarchar(30) DECLARE @jobtype_id INT DECLARE @edu_id nvarchar(30) DECLARE @categories nvarchar(30) DECLARE @full_part bit DECLARE @in_demand bit DECLARE @lang char(2) SET @jobtype_id = null SET @lang = 'en' SET @full_part = null -- full = 1, part = 0 SET @elements = '1,2,3' SET @categories = '1,2,3' SET @edu_id = '3,4,5' select jobs.name_en, parttime.fulltime_only, jc.cat_id category, je.element_id elem, jt.name_en jobtype, jobs.edu_id minEdu, education.name_en edu from jobs left join job_categories jc on (jobs.job_id = jc.job_id) left join job_elements je on (jobs.job_id = je.job_id) left join job_type jt on (jobs.jobtype_id = jt.jobtype_id) left join education on (jobs.edu_id = education.edu_id) left join (select job_id, case when (jobs.parttime_en IS NULL OR jobs.parttime_en = '') then 1 else 0 end fulltime_only from jobs) as parttime on jobs.job_id = parttime.job_id where [disabled] = 0 and jobs.jobtype_id = isnull(@jobtype_id,jobs.jobtype_id) and fulltime_only = isnull(@full_part,fulltime_only) -- each of the following clauses should be validated to see if the parameter is null -- if it is, the clause should not be used, or the SELECT * FROM ListToInt... should be replaced by -- the field evaluated: ie if @elements is null, je.element_id in (je.element_id) and je.element_id IN (SELECT * FROM ListToInt(@elements,',')) and jc.cat_id IN (SELECT * FROM ListToInt(@categories,',')) and education.edu_id IN (SELECT * FROM ListToInt(@edu_id,',')) order by case when @lang='fr' then jobs.name_fr else jobs.name_en end; END ```
Something like ``` and (@elements IS NULL OR je.element_id IN (SELECT * FROM ListToInt(@elements,','))) and (@categories IS NULL OR jc.cat_id IN (SELECT * FROM ListToInt(@categories,','))) .... ``` should do the trick
``` je.element_id IN (SELECT * FROM ListToInt(@elements,',')) OR @elements IS NULL ``` that way for each one
SQL WHERE ... IN clause with possibly null parameter
[ "", "sql", "where-clause", "conditional-statements", "" ]
I'm developing an API using Python which makes server calls using XML. I am debating on whether to use a library (ex. <http://wiki.python.org/moin/MiniDom>) or if it would be "better" (meaning less overhead and faster) to use string concatenation in order to generate the XML used for each request. Also, the XML I will be generating is going to be quite dynamic so I'm not sure if something that allows me to manage elements dynamically will be a benefit.
I would definitely recommend that you make use of one of the Python libraries; such as [MiniDom](http://docs.python.org/2/library/xml.dom.minidom.html), [ElementTree](http://effbot.org/zone/element-index.htm), [lxml.etree](http://lxml.de/tutorial.html) or [pyxser](http://coder.cl/products/pyxser/). There is no reason to not to, and the potential performance impact will be minimal. Although, personally I prefer using [simplejson](https://code.google.com/p/simplejson/) (or simply [json](http://docs.python.org/2/library/json.html)) instead. ``` my_list = ["Value1", "Value2"] json = simplejson.dumps(my_list) # send json ```
Since you are just using authorize.net, why not use [a library specifically designed for the Authorize.net API](https://github.com/jeffschenck/authorizesauce) and forget about constructing your own XML calls? If you want or need to go your own way with XML, don't use minidom, use something with an `ElementTree` interface such as [`cElementTree`](http://docs.python.org/2/library/xml.etree.elementtree.html) (which is in the standard library). It will be much less painful and [probably much faster](http://effbot.org/zone/celementtree.htm). You will certainly need an XML library to *parse* the XML you produce, so you might as well use the same API for both. It is very unlikely that the overhead of using an XML library will be a problem, and the benefit in clean code and knowing you can't generate invalid XML is very great. If you absolutely, positively need to be as fast as possible, use one of the [extremely fast templating libraries](https://stackoverflow.com/a/1326219/1002469) available for Python. They will probably be much faster than any naive string concatenation you do and will also be safe (i.e do proper escaping).
Generating XML in Python
[ "", "python", "xml", "" ]
I've defined two classes as follows: ``` class ClassModel(object): pass class FunctionModel(object): attr = None def __call__(self): return self.attr ``` The idea is to create several copy of `ClassModel`, each one containing zero or more methods inheriting from `FunctionModel`, which should have each one their own attributes. I'm fine for creating children of `ClassModel` and `FunctionModel`. But I don't succeed to attach the two so that, when the children of `ClassModel` are instanciated, the function-like objects derived from `FunctionModel` which have been attached to them are recognized by Python as their methods. See what happens ``` >>> func = type('func', (FunctionModel,), {'attr': 'someattr'}) >>> func_inst = func() >>> func_inst <__main__.func object at 0x968e4ac> >>> Cls = type('Cls', (ClassModel,), {'func_inst': func_inst}) >>> cls_inst = Cls() >>> cls_inst.func_inst <__main__.func object at 0x968e4ac> ``` How can I go with this ?
I finally figured out how to do this. Class methods are added after the new class object is created (which is not exactly what I wanted), but before it is actually instanciated. Name of methods can be changed dynamically thanks to `setattr`. ``` class ClassModel(object): number = None class FunctionModel(object): number = None def __call__(myself, clsself): return myself.number + clsself.number ``` Define the class and add it attributes: ``` from types import MethodType func1 = type('func1', (FunctionModel,), {'number': 3}) func2 = type('func2', (FunctionModel,), {'number': 5}) func1_inst = func1() func2_inst = func2() Cls = type('Cls', (ClassModel,), {'number': 10}) setattr(Cls, 'func1', MethodType(func1_inst, Cls)) setattr(Cls, 'func2', MethodType(func2_inst, Cls)) ``` And instanciate it: ``` cls_inst = Cls() cls_inst.func1() # 13 cls_inst.func2() # 15 ```
Consider using metaclasses, here an example: ``` class ClassModel(object): attr = None class FunctionModel(object): attr = None def __init__(self,aValue): self.attr = aValue def __call__(self, cls): return self.attr + cls.attr def getFMClasses(aDictOfMethods): class MM(type): def __new__(cls, name, bases, dct): for aName in aDictOfMethods: dct[aName] = classmethod(FunctionModel(aDictOfMethods[aName])) return super(MM, cls).__new__(cls, name, bases, dct) pass pass return MM ``` Once all that is defined, getting new classes is a child game... ``` class NewClass1(ClassModel): __metaclass__ = getFMClasses({'method1':3,'method2':5}) attr = 2 class NewClass2(ClassModel): __metaclass__ = getFMClasses({'method1':6,'DifferentMethod':2,'OneMore':0}) attr = 3 myObj = NewClass1() print myObj.method1() print myObj.method2() myObj = NewClass2() print myObj.method1() print myObj.DifferentMethod() print myObj.OneMore() ```
Attach a method to a class while the class is being created
[ "", "python", "class", "function", "python-3.x", "" ]
I try to read an email from a file, like this: ``` import email with open("xxx.eml") as f: msg = email.message_from_file(f) ``` and I get this error: ``` Traceback (most recent call last): File "I:\fakt\real\maildecode.py", line 53, in <module> main() File "I:\fakt\real\maildecode.py", line 50, in main decode_file(infile, outfile) File "I:\fakt\real\maildecode.py", line 30, in decode_file msg = email.message_from_file(f) #, policy=mypol File "C:\Python33\lib\email\__init__.py", line 56, in message_from_file return Parser(*args, **kws).parse(fp) File "C:\Python33\lib\email\parser.py", line 55, in parse data = fp.read(8192) File "C:\Python33\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 1920: character maps to <undefined> ``` The file contains a multipart email, where the part is encoded in UTF-8. The file's content or encoding might be broken, but I have to handle it anyway. How can I read the file, even if it has Unicode errors? I cannot find the policy object `compat32` and there seems to be no way to handle an exception and let Python continue right where the exception occured. What can I do?
I can't test on your message, so I don't know if this will actually work, but you can do the string decoding yourself: ``` with open("xxx.eml", encoding='utf-8', errors='replace') as f: text = f.read() msg = email.message_from_string(f) ``` That's going to get you a lot of replacement characters if the message isn't actually in UTF-8. But if it's got `\x81` in it, UTF-8 is my guess.
To parse an email message in Python 3 without unicode errors, read the file in binary mode and use the `email.message_from_binary_file(f)` (or `email.message_from_bytes(f.read())`) method to parse the content (see the [documentation of the email.parser module](https://docs.python.org/3/library/email.parser.html#email.message_from_bytes)). Here is code that parses a message in a way that is compatible with Python 2 and 3: ``` import email with open("xxx.eml", "rb") as f: try: msg = email.message_from_binary_file(f) # Python 3 except AttributeError: msg = email.message_from_file(f) # Python 2 ``` (tested with Python 2.7.13 and Python 3.6.0)
How to handle Python 3.x UnicodeDecodeError in Email package?
[ "", "python", "exception", "unicode", "python-3.x", "python-unicode", "" ]
I was trying to convert a date string to a valid date python format, but I got a erroneous date: ``` >from datetime import datetime >mydate = '300413' # is 2013-04-30 >print datetime.strptime(mydate,'%d%m%Y') >0413-02-01 00:00:00 ``` How can I parse to a valid date, this date string?
If you read [`strptime()` and `strftime()` Behavior](http://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) in the docs, `%Y` means: > Year with century as a decimal number [0001,9999] But you're giving it a 2-digit year, with *no* century. That's supposed to raise a `ValueError`. For example, if you try it with 2.5.6, 2.7.2, 3.2.1, or 3.3.0, you get this: > ValueError: time data '300413' does not match format '%d%m%Y' But, thanks to a bug in older versions of Python, you might get garbage instead. If you want a 2-digit year, use `%y`, when means: > Year without century as a decimal number [00,99].
As listed in the [documentation](http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior), `%Y` is the code for a four-digit year. You should be using the code for a two-digit year, `%y`.
Python convert ddmmyy format to valid date
[ "", "python", "date-format", "" ]
I have a database with a few tables of which I am trying to get some data from. but due to the layout (which I can't do anything about), I can't seem to get a normal JOIN to work. I have three tables: * datorer * program * volymlicenser * In the table "datorer" is a number of computers (registered with AD name, room number and a cell for comments). * In the table "program" is different programs that my organization have purchased. * In the table "volymlicenser" is the few licenses owned by the organization that is volume licenses. The cells in here is ID, RegKey and comp\_name. Most programs are OEM licenses and only installed on one computer, hence they never needed to register the program names together with the belonging computer in another table like with the volume licenses. When the database was designed, it was only containing the two last tables, and no join queries was needed. Recently they added the table "datorer" which consists of the said cells above. What I would like to do now, is, preferably by one single query, see if the boolean cell program.VL is set to true. If so, I want to join progran.RegKey on volymlicenser.RegKey, and from there get the contents from volymlicenser.comp\_name. The query I tried with, is the following.. which did not work. ``` SELECT prog.Namn AS Program, prog.comp_name AS Datornamn, pc.room AS Rum, pc.kommentar AS Kommentar FROM program AS prog JOIN datorer AS pc ON prog.comp_name = pc.comp_name JOIN volymlicenser AS vl ON vl.RegKey = prog.RegKey WHERE prog.Namn = "Adobe Production Premium CS6" ``` Hope someone can help me. :) Please do ask if something is not fully clear! The following are example records and desired results: Table `datorer`: ``` | id | comp_name | room | kommentar| |----------------------------------| | 1 | MB-56C5 | 1.1 | NULL | | 2 | MB-569B | 4.1 | NULL | ``` Table `program`: ``` | id | Namn | amount | VL | RegKey | comp_name | leveranotor | purchased | note | Suite | SuiteContents | |-----------------------------------------------------------------------------------------------| | 1 | Adobe Production Premium CS6 | 2 | 1 | THE-ADOBE-SERIAL | NULL | Atea | 2012-11-01 | Purchased 2012 together with new computers | 1 | The contents of this suite | | 2 | Windows 7 PRO retail | 1 | 0 | THE-MS-SERIAL | MB-569B | Atea | 2012-11-01 | Purchased 2012 together with new computers | 0 | NULL | | 3 | Windows 7 PRO retail | 1 | 0 | THE-MS-SERIAL | MB-56C5 | Atea | 2012-11-01 | Purchased 2012 together with new computers | 0 | NULL | ``` Table `volymlicenser`: ``` | id | RegKey | comp_name | |-----------------------------------| | 1 | THE-ADOBE-SERIAL | MB-569B | ``` Desired result according to the SQL select query: ``` | Program | Computer name | Room | Kommentar| |-------------------------------------------| | Adobe Production Premium CS6 | MB-569B | 4.1 | NULL | |-------------------------------------------| ``` Desired result when querying for Windows 7 PRO retail: ``` | Program | Computer name | Room | Kommentar| |-------------------------------------------| | Windows 7 PRO Retail | MB-569B | 4.1 | NULL | | Windows 7 PRO Retail | MB-56C5 | 1.1 | NULL | ``` Desired result if the "WHERE" was changed to "Windows 7 PRO Retail" Simply put, if program.VL is 1, the comp\_name will be found in the volymlicenser.comp\_name column. If program.VL is 0, the comp\_name will be found in program.comp\_name column. Uppon finding the comp\_name, it needs to join comp\_name from any of these tables on datorer.comp\_name to get the room number. I hope that this makes as much sense to you as it does to me.
Take a look at COMP\_NAME in **PROGRAM** -- it's NULL for the Adobe product. In following, the first regular join you wrote cut the Adobe out of the results. So, after the first join, you just ended up with the the Microsoft products. And then the second join using Reg\_Key would have gotten you an empty table because the remaining RegKeys refer solely to "THE-MS-SERIAL". Instead... ``` SELECT prog.namn, coalesce(vl.comp_name, prog.comp_name), pc.room, pc.kommentar FROM program as prog LEFT JOIN volymlicenser as vl ON prog.RegKey = vl.RegKey LEFT JOIN dataorer as pc ON coalesce(vl.comp_name, prog.comp_name) = pc.comp_name ``` The use of left joins will preserve the contents of the tables to the left of the join syntax. This join method is required because the join keys are not consistently filled out through all three tables. And the coalesce function acts like an ifelse function. If the first variable is null then it is replaced with the contents of the next variable. Nifty. By the way, I haven't run this myself.
You're probably better off creating 2 inline tables, one with each of your JOIN configurations, then using a CASE to decide which to select from: ``` SELECT CASE WHEN table1.column1 = "A" THEN table2.column2 ELSE table1.column2 END FROM (SELECT t1.id, t1.column1, t2.column2 FROM t1 INNER JOIN t2 ON t1.x = t2.y) table1 INNER JOIN (SELECT t1.id, t1.column1, t3.column2 FROM t1 INNER JOIN t3 ON t1.x = t2.y) table2 ON table1.id = table2.id; ```
Joining tables depending on value of cell in another table
[ "", "sql", "sqlite", "" ]
I need help, my program is simulating the actions of a dice. I want to an error check to occur checking if the input string is a number and if it isn't I want to ask the question again again until he enters an integer ``` # This progam will simulate a dice with 4, 6 or 12 sides. import random def RollTheDice(): print("Roll The Dice") print() NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: ")) Repeat = True while Repeat == True: if not NumberOfSides.isdigit() or NumberOfSides not in ValidNumbers: print("You have entered an incorrect value") NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides") print() UserScore = random.randint(1,NumberOfSides) print("{0} sided dice thrown, score {1}".format (NumberOfSides,UserScore)) RollAgain = input("Do you want to roll the dice again? ") if RollAgain == "No" or RollAgain == "no": print("Have a nice day") Repeat = False else: NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: ")) ```
As a commenter disliked my first answer with `try:` `except ValueError` and the OP asked about how to use `isdigit`, that's how you can do it: ``` valid_numbers = [4, 6, 12] while repeat: number_of_sides = 0 while number_of_sides not in valid_numbers: number_of_sides_string = input("Please select a dice with 4, 6 or 12 sides: ") if (not number_of_sides_string.strip().isdigit() or int(number_of_sides_string) not in valid_numbers): print ("please enter one of", valid_numbers) else: number_of_sides = int(number_of_sides_string) # do things with number_of_sides ``` the interesting line is `not number_of_sides_string.strip().isdigit()`. Whitespace at both ends of the input string is removed by `strip`, as a convenience. Then, `isdigit()` checks if the full string consists of numbers. In your case, you could simply check ``` if not number_of_sides_string not in ['4', '6', '12']: print('wrong') ``` but the other solution is more general if you want to accept any number. As an aside, the [Python coding style guidelines](http://www.python.org/dev/peps/pep-0008/) recommend lowercase underscore-separated variable names.
Capture the string in a variable, say `text`. Then do `if text.isdigit()`.
Checking input is a number in python
[ "", "python", "" ]
Please help, I can't seem to find a way to do this. I am working on a web science project and this is my third project with python. I need to compare the first item in dictionary with all the other items in the same dictionary, but my other items are dictionaries. For example, I have a dictionary that has the following values: ``` {'25': {'Return of the Jedi (1983)': 5.0}, '42': {'Batman (1989)': 3.0, 'E.T. the Extra-Terrestrial (1982)': 5.0}, '8': {'Return of the Jedi (1983)': 5.0 },'542': {'Alice in Wonderland (1951)': 3.0, 'Blade Runner (1982)': 4.0}, '7': {'Alice in Wonderland (1951)': 3.0,'Blade Runner (1982)': 4.0}} ``` So I need to see if the keys '25' and '42' contain same movie "Return of the Jedi" in this case, then if '25' and '8' have the same movie and so on. I they do, I need to know how many movies overlap. This is an example of the dictionary, the whole dictionary contains 1000 keys and the sub-dictionaries are way bigger also. I tried to iterate, compare dictionaries, make copies, merge, join, but I can´t seem to grasp how I can do this. Help please! The thing is that I still can't compare both subdictionaries because I need to find the keys that have at least 2 of the same movies as a whole.
You can use `collections.Counter`: ``` >>> dic={'25': {'Return of the Jedi (1983)': 5.0}, '42': {'Batman (1989)': 3.0, 'E.T. the Extra-Terrestrial (1982)': 5.0}, '8': {'Return of the Jedi (1983)': 5.0 }} >>> from collections import Counter >>> c=Counter(movie for v in dic.values() for movie in v) >>> [k for k,v in c.items() if v>1] #returns the name of movies repeated more than once ['Return of the Jedi (1983)'] >>> c Counter({'Return of the Jedi (1983)': 2, 'Batman (1989)': 1, 'E.T. the Extra-Terrestrial (1982)': 1}) ``` To get the keys related to each movie you can use `collections.defaultdict`: ``` >>> from collections import defaultdict >>> movie_keys=defaultdict(list) >>> for k,v in dic.items(): for movie in v: movie_keys[movie].append(k) ... >>> movie_keys defaultdict(<type 'list'>, {'Batman (1989)': ['42'], 'Return of the Jedi (1983)': ['25', '8'], 'E.T. the Extra-Terrestrial (1982)': ['42']}) ```
There's not really a "first" item in a dictionary, but you could find all the keys that contain a given movie with something like this: ``` movies = {} for k in data: for movie in data[k]: movies.setdefault(movie, []).append(k) ``` The output movies would look like: ``` {'Return of the Jedi (1983)': [25, 8], 'Batman (1989)': [42], ...} ```
Iterate and compare first item to all items in dictionary
[ "", "python", "loops", "dictionary", "" ]
the python code section are following lines: ``` >>> values = [0, 1, 2] >>> values[1] = values >>> values [0, [...], 2] ``` why the value is `[0,[...],2]`,what is `...`? why the value is not `[0,[0,1,2],2]`?
`[...]` means you self-referenced the variable to itself (cyclic reference): ``` >>> values = [0, 1, 2] >>> sys.getrefcount(values) #two references so far: shell and `values` 2 >>> values[1] = values #created another reference to the same object but a cyclic one >>> sys.getrefcount(values) # references increased to 3 3 >>> values[1] is values # yes both point to the same obejct True ``` Now you can modify the object using either `values` or `values[1]`: ``` >>> values[1].append(4) >>> values [0, [...], 2, 4] #or >>> values[1][1][1].append(5) >>> values [0, [...], 2, 4, 5] ```
You created a recursive reference; you replaced the item at index `1` with a reference to whole list. To display that list now, Python does *not* recurse into the nested reference and instead displays `[...]`. ``` >>> values = [0, 1, 2] >>> values[1] = values >>> values [0, [...], 2] >>> values[1] is values True ``` Referencing `values[1]` is the *same thing* as referencing `values`, and you can do so ad infinitum: ``` >>> values[1] [0, [...], 2] >>> values[1][1] is values True >>> values[1][1] is values[1] True ```
Python:how to understand assignment and reference?
[ "", "python", "variable-assignment", "" ]