Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm pulling data to use in a Pivot table in Excel, but Excel is not recognizing the date format. I'm using.. ``` CONVERT(date, [DateTimeSelected]) AS [Search Date] ``` Which shows as as **2013-08-01** in my query output. When it get to into my Excel pivot table via my SQL Connection it looks the same but the filter...
Is appears that `cast(convert(char(11), Bo.Depart, 113) as datetime)` works..
I found the only answer for me was to set the SQL data as source for a Table, rather than a pivot table, and then build a pivot table from that Table. That was I was able to apply the Number format to the Pivot table Row Labels, and that allowed me to format the date how I wanted on the chart.
SQL Date formatting for Excel pivot tables
[ "", "sql", "excel", "date", "pivot", "pivot-table", "" ]
[Sql fiddle](http://sqlfiddle.com/#!3/25d42/6) ``` CREATE TABLE [Users_Reg] ( [User_ID] [int] IDENTITY (1, 1) NOT NULL CONSTRAINT User_Reg_P_KEY PRIMARY KEY, [Name] [varchar] (50) NOT NULL, [Type] [varchar] (50) NOT NULL /*Technician/Radiologist*/ ) CREATE Table [Study] ( [UID] ...
You will want to JOIN on the `users_reg` table twice to get the result. Once for the radiologist and the another for the technician: ``` select ps.uid, ur1.name rad_name, ur1.type rad_type, ur2.name tech_name, ur2.type tech_type from Patient_Study ps left join Users_Reg ur1 on ur1.User_ID=ps.Radiologist left...
in your case you could use `isnull`: ``` select * from Patient_Study as PS inner join Users_Reg as U on U.User_ID = isnull(nullif(PS.Radiologist, ''), PS.Technician) ``` or two `left outer joins`: ``` select PS.*, isnull(UP.Type, UT.Type) as Type from Patient_Study as PS left outer join Users_Reg as UP on UP....
Sql query getting name column null
[ "", "sql", "sql-server", "t-sql", "" ]
I use python os.walk() to get files and dirs in some directories, but there're files whose names are too long(>300), os.walk() return nothing, use onerror I get '[Error 234] More data is available'. I tried to use yield, but also get nothing and shows 'Traceback: StopIteration'. OS is windows, code is simple. I have t...
In Windows file names (including path) can not be greater than 255 characters, so the error you're seeing comes from Windows, not from Python - because somehow you managed to create such big file names, but now you can't read them. See this [post](https://stackoverflow.com/questions/265769/maximum-filename-length-in-nt...
The only workaround I can think of is to map the the folder to the specific directory. This will make the path way shorter. e.g. z:\myfile.xlsx instead of c:\a\b\c\d\e\f\g\myfile.xlsx
Python's os.walk() fails in Windows when there are long filenames
[ "", "python", "windows", "file", "filenames", "os.walk", "" ]
I need a little help with this, I've been searching for a solution with no results. This are my settings: settings.py: ``` STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DI...
For hours and hours of searching for any solution, finally I found that this problem is a bug: <https://bugzilla.redhat.com/show_bug.cgi?id=962223> I'm not sure if this bug is by Django or Python, My Django version is 1.5.1 and Python is 2.7.5. I would need to proof in previous django and python version to see if bug...
Are you sure your `STATICFILE_DIRS` is correct? If your settings is like at the moment, the `static` folder is supposed to be in same level as `settings.py`. ``` PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # it means settings.py is in PROJECT_ROOT? STATICFILES_DIRS = ( PROJECT_ROOT + '/static/', # <=...
Django 1.5 GET 404 on static files
[ "", "python", "django", "static", "http-status-code-404", "" ]
I am using this command to find the same values in two tables when the tables have 100-200 records. But When the tables have 100000-20000 records, the sql manager, browsers, shortly the computer is freesing. Is there any alternative command for this? ``` SELECT distinct names FROM table1 WHERE names in (SELECT names ...
a simple join will also do it. make sure the column is indexed. ``` select distinct t1.names from table1 t1, table2 t2 where t1.names = t2.names ```
Try with `join` ``` SELECT distinct t1.names FROM table1 t1 join table2 t2 on t2.names = t1.names ```
Looking for an alternative SQL command to find the same values in two tables
[ "", "mysql", "sql", "" ]
I can create a named child logger, so that all the logs output by that logger are marked with it's name. I can use that logger exclusively in my function/class/whatever. However, if that code calls out to functions in another module that makes use of logging using just the logging module functions (that proxy to the r...
This is the solution I've come up with: Using thread local data to store the contextual information, and using a Filter on the root loggers handlers to add this information to LogRecords before they are emitted. ``` context = threading.local() context.name = None ...
This is what logging.handlers (or the handlers in the logging module) is for. In addition to creating your logger, you create one or more handlers to send the logging information to various places and add them to the root logger. Most modules that do logging create a logger that they use for there own purposes but depe...
How can you make logging module functions use a different logger?
[ "", "python", "logging", "" ]
I realize that this question has been asked before([Python Pyplot Bar Plot bars disappear when using log scale](https://stackoverflow.com/questions/14047068/python-pyplot-bar-plot-bars-disapear-when-using-log-scale)), but the answer given did not work for me. I set my pyplot.bar(x\_values, y\_values, etc, log = True) b...
The error is raised due to the `log = True` statement in `ax.bar(...`. I'm unsure if this a matplotlib bug or it is being used in an unintended way. It can easily be fixed by removing the offending argument `log=True`. This can be simply remedied by simply logging the y values yourself. ``` x_values = np.arange(1,8, ...
Are you sure that is all your code does? Where does the code throw the error? During plotting? Because this works for me: ``` In [16]: import numpy as np In [17]: x = np.arange(1,8, 1) In [18]: y = np.exp(x) In [20]: import matplotlib.pyplot as plt In [21]: fig = plt.figure() In [22]: ax = fig.add_subplot(111) In [24...
Barplot with log y-axis program syntax with matplotlib pyplot
[ "", "python", "matplotlib", "typeerror", "bar-chart", "" ]
I need another python script that will execute these 3 scripts.
You probably want the following : ``` import os def include(filename): if os.path.exists(filename): execfile(filename) include('myfile.py') ``` But I think it would be better to refactor your code using functions and use **import** . There already was similar [questio](https://stackoverflow.com/questions/7148...
import - will execute code which you import (once) os.system("scriptname.py") subprocess popen
How to execute three .py files from another python file?
[ "", "python", "" ]
I'm trying to run a for loop. Here's the section of my code I'm having trouble with: ``` aldurstengd_ororka = {(18, 19, 20, 21, 22, 23, 24):1, (25):0.95, (26):0.90, (27):0.85, (28, 29):0.75, (30, 31):0.65, (32, 33):0.55, (34, 35):0.45, (36, 37):0.35, (40, 41, 42, 43, 44, 45):0.15, (46, 47, 48, 49, 50):0.10, ...
If `aldurstengd_ororka` is a dictionary, then this expression: ``` aldurstengd_ororka([age]) ``` is an error. Perhaps you meant something like: ``` aldurstengd_ororka[(age)] ``` EDIT: The error you were seeing is quite interesting, I did reproduce it with this snippet: ``` for age in aldurstengd_ororka.keys(): ...
Your tuple keys that just have a single int in them are being parsed as an int instead of a tuple. So when you try to for item in age - you're trying to iterate through a non-iterable. Use lists `[4]` or use a comma `(4,)`, and it'll do the trick: ``` aldurstengd_ororka = {(18, 19, 20, 21, 22, 23, 24):1, (25):0.95, (2...
"Int" object is not iterable
[ "", "python", "object", "int", "iterable", "" ]
I am trying to understand how the following COBOL cursor works: ``` T43624 EXEC SQL T43624 DECLARE X_CURSOR CURSOR FOR T43624 SELECT T43624 A T43624 ,B T43624 ,C T43624 ,D T43624 ,E T43624 ...
There is no default sort order for results returned from a DB/2 select statement. If you need, or expect, data to be returned in some order then the ordering must be specified using an ORDER BY clause on the SQL predicate. You may find that results appear to be ordered but that ordering is just an artifact of the acce...
There is no **default** ordering. The order the records are returned to the program will be determined by the access method DB2 uses. For example on a single Table query if DB2 does a ``` Full Table Scan Rows most likely in table sequence (small tables) Index Scan Rows most likely in Index sequence (small ta...
Is there a default sort order for cursors in COBOL reading from DB2?
[ "", "sql", "cursor", "db2", "cobol", "" ]
I would like to use Ansible to execute a simple job on several remote nodes concurrently. The actual job involves grepping some log files and then post-processing the results on my local host (which has software not available on the remote nodes). The command line ansible tools don't seem well-suited to this use case ...
Some investigation reveals that ansible is looking for the hosts in my inventory in ~/.ssh/known\_hosts. My configuration has HashKnownHosts enabled. ansible isn't ever able to find the host entries it is looking for because it doesn't understand the hash known hosts entry format. Whenever ansible's ssh transport can'...
Since you have HashKnownHosts enabled, you should upgrade to the latest version of Ansible. Version 1.3 added support for hashed `known_hosts`, see [the bug tracker](https://github.com/ansible/ansible/issues/3716) and [changelog](https://github.com/ansible/ansible/blob/devel/CHANGELOG.md). This should solve your proble...
How do I drive Ansible programmatically and concurrently?
[ "", "python", "concurrency", "parallel-processing", "ansible", "ansible-runner", "" ]
I have this list of lists in Python: ``` [[100,XHS,0], [100,34B,3], [100,42F,1], [101,XHS,2], [101,34B,5], [101,42F,2], [102,XHS,1], [102,34B,2], [102,42F,0], [103,XHS,0], [103,34B,4], [103,42F,2]] ``` and I would like to find the most efficient way (I'm dealing with a lot of data) to create a new list of lists using...
An itertools approach with the building blocks broken out - get last elements, group into threes, convert groups of 3 into a list... ``` from operator import itemgetter from itertools import imap, izip last_element = imap(itemgetter(-1), a) in_threes = izip(*[iter(last_element)] * 3) res = map(list, in_threes) # [[0,...
``` new_list = [] temp_list = [] counter = 1 for x in list: temp_list.extend(x[-1]) if ((counter % 3) == 0): new_list.append(temp_list) temp_list = [] counter += 1 print new_list ```
Using the last element from each list in Python
[ "", "python", "" ]
Can someone please specify what is the difference between `os.path.getmtime(path)` and `os.path.getctime(path)` in unix systems . As per the defnition in python docs: `os.path.getmtime(path)` > Return the time of last modification of path. The return value is a > number giving the number of seconds since the epoch (s...
The mtime refers to last time the file's contents were changed. This can be altered on unix systems in various ways. Often, when you restore files from backup, the mtime is altered to indicate the last time the contents were changed before the backup was made. The ctime indicates the last time the inode was altered. T...
From the man page on stat, which `os.path.getmtime()` and `os.path.getctime()` both use on Unix systems: > The field `st_mtime` is changed by file modifications, for example, by `mknod(2)`, `truncate(2)`, `utime(2)` and `write(2)` (of more than zero bytes). Moreover, `st_mtime` of a directory is changed by the creatio...
Difference between python - getmtime() and getctime() in unix system
[ "", "python", "python-2.6", "" ]
What's the proper way to tell a looping thread to stop looping? I have a fairly simple program that pings a specified host in a separate `threading.Thread` class. In this class it sleeps 60 seconds, the runs again until the application quits. I'd like to implement a 'Stop' button in my `wx.Frame` to ask the looping t...
# Threaded stoppable function Instead of subclassing `threading.Thread`, one can modify the function to allow stopping by a flag. We need an object, accessible to running function, to which we set the flag to stop running. We can use `threading.currentThread()` object. ``` import threading import time def doit(ar...
This has been asked before on Stack. See the following links: * [Is there any way to kill a Thread in Python?](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) * [Stopping a thread after a certain amount of time](https://stackoverflow.com/questions/6524459/stopping-a-thread-pytho...
How to stop a looping thread in Python?
[ "", "python", "multithreading", "wxpython", "" ]
This is my Data ``` Id Name Amt 1 ABC 20 2 XYZ 30 3 ABC 25 4 PQR 50 5 XYZ 75 6 PQR 40 ``` I want the last record by every particular Name like : ``` 3 ABC 25 5 XYZ 75 6 PQR 40 ``` I tried group by, but i am missing some thing. ``` SELECT PatientID, Balance, PReceiptNo FROM tblPaymen...
Something like this should work: ``` SELECT p1.* FROM tblPayment p1 LEFT JOIN tblPayment p2 ON p1.Name = p2.Name AND p1.Id < p2.Id WHERE p2.Id IS NULL; ``` See [this SQLFiddle](http://sqlfiddle.com/#!2/3d8a5/2)
Should be similar to: ``` SELECT id, name, amt FROM myTable mt1 where mt1.id = ( SELECT MAX(id) FROM myTable mt2 WHERE mt2.name = mt1.name ) ```
find the last record by Person
[ "", "sql", "" ]
I have two tables: ``` Table1 has columns A, B, C, D, E, F, G Table2 has columns G, H, I, J, K, L, M, N ``` I want to join those two tables on column G. however, to avoid the duplicate columns(ambiguous G). I have to do the query like below. ``` select t1.*, t2.H, t2.I, t2.J, t2.K, t2.L, t2.M, t2.N from T...
You can use a [*natural join*](http://en.wikipedia.org/wiki/Join_%28SQL%29#Natural_join): > A natural join is a type of equi-join where the join predicate arises > implicitly by comparing all columns in both tables that have the same > column-names in the joined tables. The resulting joined table contains > **only one...
It's usually *strongly discouraged* to use `SELECT * FROM` in anything but ad-hoc queries for testing. The reason is that table schemas change, which can break code that assumes the presence of a certain column, or the order of columns in a table. Even if it makes your query quite long, I'd suggest specifying each an...
SQL all columns except
[ "", "mysql", "sql", "hive", "" ]
Is there a debugger that can debug the Python virtual machine **while it is running Python code**, similar to the way that `GDB` works with C/C++? I have searched online and have come across `pdb`, but this steps through the code executed ***by*** the Python interpreter, not the Python interpreter as its running the pr...
If you're looking to debug Python at the bytecode level, that's exactly what `pdb` does. If you're looking to debug the CPython reference interpreter… as icktoofay's answer says, it's just a C program like any other, so you can debug it the same way as any other C program. (And you can get the source, compile it with ...
The reference implementation of Python, CPython, is written in C. You can use GDB to debug it as you would debug any other program written in C. That said, Python does have a few little helpers for use in GDB [buried under `Misc/gdbinit`](http://hg.python.org/cpython/file/2.7/Misc/gdbinit). It's got comments to descri...
Debugging the python VM
[ "", "python", "debugging", "python-2.7", "" ]
I am having trouble with my small film database tag/category query. My table is: ``` ID(index),Name(film name),category ``` One movie can have multiple categories. ``` SELECT Name FROM categorytable WHERE category ='Action'; ``` Works fine but if I want other tags I get empty cursor: ``` SELECT Name FROM catego...
The reason your query doesn't work is because each row has only one category. Instead, you need to do aggregation. I prefer doing the conditions in the `having` clause, because it is a general approach. ``` SELECT Name FROM categorytable group by Name having sum(case when category ='Action' then 1 else 0 end) > 0 and...
You can use the OR clause, or if you have multiple categories it will probably be easier to use IN So either ``` SELECT Name FROM categorytable WHERE category ='Action' OR category ='Sci-Fi' ``` Or using `IN` ``` SELECT Name FROM categorytable WHERE category IN ('Action', 'Sci-Fi', 'SomeOtherCategory ') ``` Usin...
Select multiple film category
[ "", "sql", "sqlite", "select", "" ]
I'm really new to databases so please bear with me. I have a website where people can go to request tickets to an upcoming concert. Users can request tickets for either New York or Dallas. Similarly, for each of those locales, they can request either a VIP ticket or a regular ticket. I need a database to keep track o...
You should have one column containing a quantity, a column that specifies the type (VIP), and another that specifies the city.
To make it flexible you would do: ``` Table: location Columns: location_id integer description varchar Table type Columns: type_id integer description varchar table purchases columns: purchase_id integer type_id integer location_id integer ``` This way you can a...
Database schema for storing ints
[ "", "mysql", "sql", "database", "schema", "" ]
I am trying to get value form a list in a dict? not sure how it can be accessed? but here's what I did & I'm getting a error as **TypeError: string indices must be integers, not str** ``` lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90....
### question1(How to access the key 'homework' & sum its value in list?) ``` >>> sum(lloyd['homework']) 354.0 ``` ### question2 homework + quizzes + tests ``` def findsum(x): return sum([sum(x['homework']),sum(x['quizzes']),sum(x['tests'])]) >>> findsum(lloyd) 741.0 ``` ### question3) How to access the key 'll...
You are looping over the *keys* of `alice`, not the values. Your keys are strings. Even if you were looping over the values, none of the values in `alice` can be indexed by `'quizzes'`. You could just print `alice['quizzes']`, but that is probably not what you wanted to start with. You want to put all your named dicti...
string indices must be integers not str dictionary
[ "", "python", "python-2.7", "" ]
I am trying to understand how to create a query to filter out some results based on an inner join. Consider the following data: ``` formulation_batch ----- id project_id name 1 1 F1.1 2 1 F1.2 3 1 F1.3 4 1 F1.all formulation_batch_component ----- id formulation_...
One way would be to use `distinct`: ``` SELECT distinct "formulation_batch".* FROM "formulation_batch" INNER JOIN "formulation_batch_component" ON "formulation_batch"."id" = "formulation_batch_component"."formulationBatch_id" WHERE "formulation_batch"."project_id" = 1 AND (("formulation_batch_component"."comp...
In this case it is possible to apply the `distinct` before the `join` possibly making it more performant: ``` select fb.* from formulation_batch fb inner join ( select distinct formulationbatch_id from formulation_batch_component where component_id in (1, 2) ) fbc on fb.id = fb...
how to prevent duplicates with inner join query (Postgres)
[ "", "sql", "postgresql", "inner-join", "" ]
I am making a simple program for fun. This should take input for X amount of files to be filled with Y amount of random 0's and 1's. When I run this I would like to have 2 files both filled with 20 random 0's and 1's in each file. At the moment when I run this only the first file gets filled and the second one is left...
In addition to reseting the value of `s1`, make sure you close your files. Sometimes, the output does not get written to the file if the program ends before the buffer is written to disk. You can guarantee the file is closed by using a [`with` statement](http://effbot.org/zone/python-with-statement.htm). The file will...
You don't reinit `s1` to `0`. So the second time there will be nothing written to the file. ``` import random fileamount = int(raw_input("How many files should I make? > ")) amount = int(raw_input("How many characters in the files? > ")) print "I will now make %r files with %r characters in them!\n" % (fileamount, am...
Nested loop and File io
[ "", "python", "loops", "file-io", "" ]
I've seen a couple similar threads, but attempting to escape characters isn't working for me. In short, I have a list of strings, which I am iterating through, such that I am aiming to build a query that incorporates however many strings are in the list, into a 'Select, Like' query. Here is my code (Python) ``` def ...
First, your problem has nothing to do with SQL. Throw away all the SQL-related code and do this: ``` var = 'foo' " OR tble_tble.var LIKE %'%s'%" % var ``` You'll get the same error. It's because you're trying to do `%`-formatting with a string that has stray `%` signs in it. So, it's trying to figure out what to do w...
You need to escape `%` like this you need to change the quotes to include the both `%` generate proper SQL ``` " OR tble_tble.var LIKE '%%%s%%'" ``` For example: ``` var = "abc" print " OR tble_tble.var LIKE '%%%s%%'" % var ``` It will be translated to: ``` OR tble_tble.var LIKE '%abc%' ```
"ValueError: Unsupported format character ' " ' (0x22) at..." in Python / String
[ "", "python", "regex", "string", "list", "" ]
I have recently had a few problems with my Python installation and as a result I have just reinstalled python and am trying to get all my addons working correctly as well. I’m going to look at virtualenv after to see if I can prevent this from happening again. When I type `which python` into terminal I now get ``` /L...
Since `pip` is an executable and `which` returns path of executables or filenames in environment. It is correct. Pip module is installed in site-packages but the executable is installed in bin.
Modules go in `site-packages` and executables go in your system's executable path. For your environment, this path is `/usr/local/bin/`. To avoid having to deal with this, simply use `easy_install`, `distribute` or `pip`. These tools know which files need to go where.
Python: PIP install path, what is the correct location for this and other addons?
[ "", "python", "python-2.7", "pip", "" ]
What is the correct way to write an SQL Query so I can use the output of a function that I have used in the Select Statement in the Where clause? Data Table: ``` ID Count_ID 111 2 111 2 222 3 222 3 222 3 333 1 ``` Query: ``` Select ID, Count(Table1.ID) As Count_ID From Table1 Where Count_ID = 3 Group...
There's a circular dependency on your filtering. You want to only select records where the count is 3, but you must count them before you can determine this. This means that you need a HAVING clause rather than a WHERE clause (to filter on an aggregate function, you always need a HAVING clause). Furthermore, you can't...
In this case, because you're referencing an aggregate function and a grouping, you have to use a `HAVING` clause. ``` Select ID, Count(Table1.ID) As Count_ID From Table1 Group By ID Having Count(Table1.ID) = 3 ```
Using output of function from select in where clause
[ "", "sql", "" ]
Assume you have a numpy array as `array([[5],[1,2],[5,6,7],[5],[5]])`. Is there a function, such as `np.where`, that can be used to return all row indices where `[5]` is the row value? For example, in the array above, the returned values should be `[0, 3, 4]` indicating the `[5]` row numbers. Please note that each row...
This should do it: ``` [i[0] for i,v in np.ndenumerate(ar) if v == [5]] => [0, 3, 4] ```
If you check `ndim` of your array you will see that it is actually not a multi-dimensional array, but a `1d` array of list objects. You can use the following list comprehension to get the indices where 5 appears: ``` [i[0] for i,v in np.ndenumerate(a) if 5 in v] #[0, 2, 3, 4] ``` Or the following list comprehension ...
np.where equivalent for multi-dimensional numpy arrays
[ "", "python", "arrays", "numpy", "" ]
Working with Python 2.7, I'm wondering what real advantage there is in using the type `unicode` instead of `str`, as both of them seem to be able to hold Unicode strings. Is there any special reason apart from being able to set Unicode codes in `unicode` strings using the escape char `\`?: Executing a module with: ``...
`unicode` is meant to handle *text*. Text is a sequence of **code points** which *may be bigger than a single byte*. Text can be *encoded* in a specific encoding to represent the text as raw bytes(e.g. `utf-8`, `latin-1`...). Note that `unicode` *is not encoded*! The internal representation used by python is an implem...
Unicode and encodings are completely different, unrelated things. # Unicode Assigns a numeric ID to each character: * 0x41 → A * 0xE1 → á * 0x414 → Д So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to Д. Even the little arrow → I used has its Unicode number, it's 0x2192. And even emojis have their U...
Python str vs unicode types
[ "", "python", "string", "unicode", "" ]
I need to query for rows from a table where one of columns matches a string whose defining characteristic is an alphanumeric string of specific length (say 4) followed by a ":" followed by an integer. * pattern : alphanumericstring : integer * example1: 1234:someint * example2: abcd:someotherint I tried the following...
You can use a combination of `charindex`, `substring` and `isnumeric` ``` CREATE TABLE MyTable ( col1 varchar(20), col2 varchar(50) ) INSERT INTO MyTable VALUES ('ABCD:123', 'Value 123'), ('1234:1234', 'Value 1234'), ('xyz:1234', 'should not be selected'), ('cdef:abcd', 'should not be sel...
SQL Server doesn't directly support regular expressions (if you search around, you can probably find some tutorials for adding them via user-defined functions). `LIKE` doesn't support quantifiers, but it does have wildcards and lightweight character classes. An underscore will match any character: ``` SELECT col1 FR...
pattern matching for a string of specific length in sql
[ "", "sql", "sql-server", "" ]
I'm doing a simple lookup ``` if xo.st in sts: #... ``` If the condition is met I need to get the index of the element in sts (sts is a list or a tuple). This needs to be fast (it is a big list). What is the best solution for this?
What about: ``` if xo.st in sts: print sts.index(xo.st) ``` This will return the first index of `xo.st` in`sts`
First thing that comes to mind is ``` list.index(xo.st) ```
Python: Get index if in statement evaluates true
[ "", "python", "performance", "indexing", "" ]
I have created table as bellow ``` create table T1(num varchar2(20)) ``` then I inserted 3 lac numbers in above table so now it looks like below ``` num 1 2 3 . . 300000 ``` Now if I do ``` select * from T1 ``` then it takes 1min 15sec to completely fetch the records and as I created index on column `num` and if ...
The index does not improve the retrieval process when you are trying to fetch all rows. The index makes it possible to find a subset of rows much more quickly.
An index can help if you want to retrieve a few rows from a large table. But since you retrieve all rows and since your index contains all the columns of your table, it won't speed up the query. Furthermore, you don't tell us what tool you use to retrieve the data. I guess you use SQL Developer or Toad. So what you me...
Index Created but doesn't speed-up on retrieval process
[ "", "sql", "oracle", "oracle10g", "" ]
I have a table like this ``` ItemsWithQuantity ================= ID Quantity --------------- x 4 y 7 ``` I want to built a view or query that turns it into this ``` ID x x x x y y y y y y y ``` To basically un-count them, and get a unique row for every quantity. What's the best way to do this d...
Simplest way: ``` SELECT iq.ID FROM ItemsWithQuantity iq INNER JOIN master..spt_values n ON iq.Quantity > n.number AND n.type = 'p' ``` **[SQLFiddle DEMO](http://sqlfiddle.com/#!6/d24bd/1)** This is using `master..spt_values` system table for numbers, which is a pretty safe but still *undocumented* feature. If you a...
Create a numbers table first (`(ID INT NOT NULL PRIMARY KEY)`) with numbers from 1 to 1m). Then the query becomes more easy: ``` SELECT tab.ID FROM ItemsWithQuantity tab CROSS APPLY ( SELECT ID FROM Numbers WHERE ID BETWEEN 1 AND Quantity ) x ORDER BY tab.ID ``` `CROSS APPLY` reads like "for each outer row, join th...
Take a table with a quantity field, or a count of items, and make unique rows for each, dynamically
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "" ]
I am using the PyQt library to take a screenshot of a webpage, then reading through a CSV file of different URLs. I am keeping a variable feed that incremements everytime a URL is processed and therefore should increment to the number of URLs. Here's code: ``` webpage = QWebPage() fo = open("C:/Users/Romi/Desktop/res...
When Python parses the body of a function definition and encounters an assignment such as ``` feed = ... ``` Python interprets `feed` as a local variable by default. If you do not wish for it to be a local variable, you must put ``` global feed ``` in the function definition. The global statement does not have to b...
Put a global statement at the top of your function and you should be good: ``` def onLoadFinished(result): global feed ... ``` To demonstrate what I mean, look at this little test: ``` x = 0 def t(): x += 1 t() ``` this blows up with your exact same error where as: ``` x = 0 def t(): global x x...
Local variable referenced before assignment?
[ "", "python", "python-2.7", "python-3.x", "variable-assignment", "" ]
I am trying to find the last entry for a specific **user** for each **location**. I also need to ignore any rows where the **balance** is zero. Sample table: ``` ID location user balance -- -------- ---- ------- 1 GLA A 10.21 2 GLA A 0.00 3 GLA B 45.68 4 GLA B ...
You should be able to use `row_number()` to get the result: ``` select id, location, [user], balance from ( select id, location, [user], balance, row_number() over(partition by location, [user] order by id desc) seq from yourtable ) d where seq = 1 and balance <> 0 order by id; ``` ...
``` Select A.ID , A.location, A.[user] , A.balance from TABLE1 A inner join ( Select Max(Id) AS Id from TABLE1 group by location,[user] ) B on A.ID=B.ID WHERE A.Balance>0 ``` [**Sql Fiddle Demo**](http://sqlfiddle.com/#!...
Find the last entry for specific user id
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
I am self learning Python from the MIT open courseware website. I am having trouble completing this assignment using only the information learned in the lectures. The last thing I learned was iterations using the "While" and "For" loops. I have not learned functions yet. Is it possible to write a program that computes ...
Your code has a few problems which I’ll try to point out: ``` count = 0 prime = [] # this is obviously meant to collect all primes candidate = [] # what is this supposed to do then though? x = 2 y = 1 # never used while count < 1000: # you start at `count = 0` but never increase the count ...
Without doing the whole thing for you, as has been said you are building up a list of primes, in `prime` so you could use that instead of hardcoding things to check. ``` prime = [] x = 2 while len(prime) < 1000: if *** check here *** prime.append(x) x = x + 1 ```
Trouble finding the 1000th prime using python
[ "", "python", "python-2.7", "" ]
Hello I have browsed the forum for a while and am asking my first question here. I'm in a bit of a bind and was wondering if I could get some help out. I am using Access 2007 and have not found a good answer to the question on the Net yet. My data is Diagnostic Codes and CustomerID's and what I am looking for is a why...
I'm not expert in MS Access and it is quite a long time last time I have written anything for it, but this maybe will work: ``` SELECT cd.DiagCode, Count(cd.CustomerID) FROM (select distinct DiagCode, CustomerID from CustomerTable) as cd Group By cd.DiagCode; ```
I had the same question and found a link (now defunct) by the Access Team at Microsoft to have a nice working example of how to accomplish this; which I will also include here below. --- **Data:** ``` Color Value Red 5 Green 2 Blue 8 Orange 1 Red 8 Green 6 Blue 2 ``` To get a count of the numbe...
Count Distinct in a Group By aggregate function in Access 2007 SQL
[ "", "sql", "ms-access-2007", "" ]
I have to insert some data in oracle DB, without previously checking if it already exist. Does exist any way, transiction on oracle to catch the exception inside the query and handle it to don't return any exception? It would be perfect something in mysql's style like ``` insert .... on duplicate key a=a ```
You can use [`MERGE`](http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm). The syntax is a bit different from a regular insert though; ``` MERGE INTO test USING ( SELECT 1 AS id, 'Test#1' AS value FROM DUAL -- your row to insert here ) t ON (test.id = t.id) -- dupli...
If you can use PL/SQL, and you have a unique index on the columns where you don't want any duplicates, then you can catch the exception and ignore it: ``` begin insert into your_table (your_col) values (your_value); exception when dup_val_on_index then null; end; ```
Oracle DB insert and do nothing on duplicate key
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
Subject: Issues and their tasks. Environment: SQL Server 2008 or above Database tables: Issues, Tasks, and IssuesTasks Let's say I have a single input screen that deals with a single issue and their associated tasks. We're dealing with Issue1 and there are 7 tasks listed to check off. The user checks 3 of the 7 task...
Use SQL server build in `PIVOT` function: ``` SELECT <non-pivoted column>, [first pivoted column] AS <column name>, [second pivoted column] AS <column name>, ... [last pivoted column] AS <column name> FROM (<SELECT query that produces the data>) AS <alias for the source query> PIVOT ( <aggr...
Please excuse me if this isn't kosher; I'm still getting acclimated with the rules around here (long time reader of stackoverflow, first day posting). I actually just wrote an article on this on my new blog, and I sincerely think it would help. Basically, you can dynamically build your pivoted column values and pass th...
sql turn dynamic rows into columns
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I am making a formset in python/django and need to dynamically add more fields to a formset as a button is clicked. The form I'm working on is for my school asking students who they would like to disclose certain academic information to, and the button here allows them to add more fields for entering family members/peo...
I've had trouble with dynamically adding fields in Django before and this stackoverflow question helped me: [dynamically add field to a form](https://stackoverflow.com/questions/6142025/dynamically-add-field-to-a-form) To be honest, I'm not entirely sure what you mean by "persistent" in your case - are the values of y...
A coworker of mine finally figured it out. Here is the revised views.py: ``` from django.shortcuts import render from django.http import HttpResponse from form import ModelForm, Parent from models import Form, ParentForm, Contact from django.http import HttpResponseRedirect from django.forms.formsets import formset_fa...
Can a django formset that dynamically adds fields have persistent data?
[ "", "python", "database", "django", "django-forms", "" ]
How do I get the index column name in Python's pandas? Here's an example dataframe: ``` Column 1 Index Title Apples 1 Oranges 2 Puppies 3 Ducks 4 ``` What I'm trying to do is get/set the dataframe's index title. Here is what I tried: ``` impor...
You can just get/set the index via its `name` property ``` In [7]: df.index.name Out[7]: 'Index Title' In [8]: df.index.name = 'foo' In [9]: df.index.name Out[9]: 'foo' In [10]: df Out[10]: Column 1 foo Apples 1 Oranges 2 Puppies 3 Ducks 4 ```
You can use [`rename_axis`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename_axis.html), for removing set to `None`: ``` d = {'Index Title': ['Apples', 'Oranges', 'Puppies', 'Ducks'],'Column 1': [1.0, 2.0, 3.0, 4.0]} df = pd.DataFrame(d).set_index('Index Title') print (df) Col...
How to get/set a pandas index column title or name?
[ "", "python", "pandas", "dataframe", "" ]
I'm trying to create a powerset in Python 3. I found a reference to the `itertools` module, and I've used the powerset code provided on that page. The problem: the code returns a reference to an `itertools.chain` object, whereas I want access to the elements in the powerset. My question: how to accomplish this? Many t...
`itertools` functions return [*iterators*](https://docs.python.org/3/glossary.html#term-iterator), objects that produce results lazily, on demand. You could either loop over the object with a `for` loop, or turn the result into a list by calling `list()` on it: ``` from itertools import chain, combinations def power...
Here's a solution using a generator: ``` from itertools import combinations def all_combos(s): n = len(s) for r in range(1, n+1): for combo in combinations(s, r): yield combo ```
Powersets in Python using itertools
[ "", "python", "python-3.x", "python-itertools", "" ]
I am reading JSON from the database and parsing it using python. ``` cur1.execute("Select JSON from t1") dataJSON = cur1.fetchall() for row in dataJSON: jsonparse = json.loads(row) ``` The problem is some JSON's that I'm reading is broken. I would like my program to skip the json if its not a valid json and if it is...
**Update** You're getting an expecting string or buffer - you need to be using row[0] as the results will be 1-tuples... and you wish to take the first and only column. **If you did want to check for bad json** You can put a try/except around it: ``` for row in dataJSON: try: jsonparse = json.loads(row)...
If you just want to silently ignore errors, you can wrap `json.loads` in a try..except block: ``` try: jsonparse = json.loads(row) except: pass ```
Skipping broken jsons python
[ "", "python", "json", "" ]
I am doing a task for my work and unfortunately the tables are designed horribly and I can't do too much as far as modifying the structure (one of our major programs here has been based off these outdated tables for years). That being said, I need to find a way to use SQL Server (TSQL) to count the number of distinct c...
One way to do this is by unpivoting the data and then subsequently grouping it again. This gives you the ability to use `count(distinct)`: ``` select name, count(distinct val) from t unpivot (val for col in (FieldA, FieldB, FieldC, FieldD)) unpvt group by name; ``` However, the most efficient way to do this is to kee...
``` DECLARE @x TABLE ( Name VARCHAR(32), A VARCHAR(32), B VARCHAR(32), C VARCHAR(32), D VARCHAR(32) ); INSERT @x VALUES ('Jim', 1,3,4,6), ('John',1,1,1,2), ('Jane',2,2,3,3); SELECT Name, NumCols = COUNT(DISTINCT x) FROM @x AS x UNPIVOT (x FOR y IN (A,B,C,D)) AS up GROUP BY Name ORDER BY NumCols DESC; ```
Count Number of Distinct Columns in a Row with tSQL
[ "", "sql", "sql-server", "t-sql", "" ]
I want to render a Jinja2 Template using a custom object implementing the `__getitem__` interface. The object implements a lazy variable look up because it is impossible to create a dictionary from it (the number of available variables is almost infinite, value retrieval works dynamically on the queried key). Is it po...
I now figured out this (extremely hacky and ugly) solution. ``` t = CustomTemplate(source) t.set_custom_context(Context()) print t.render() ``` Using the following replacements: ``` from jinja2.environment import Template as JinjaTemplate from jinja2.runtime import Context as JinjaContext class CustomContextWrapper...
It looks like you have a function, `get_customer()` which returns a dictionary, or is an object? Why not just pass that to the template? ``` from jinja2 import Template t = Template('Dear {{ customer.first }},\n') t.render(customer=get_customer()) ``` IIRC, Jinja is pretty forgiving of keys that don't exist, so `cus...
Lazy variable lookup in Jinja templates
[ "", "python", "templates", "jinja2", "" ]
I have a very large list called 'data' and I need to answer queries equivalent to ``` if (x in data[a:b]): ``` for different values of a, b and x. Is it possible to preprocess data to make these queries fast
# idea you may create a `dict`. For every element store the sorted list of positions where it occurs. To answer query: binary search first element that greater or equal `a`, check if it exists and less than `b` # Pseudocode Preprocessing: ``` from collections import defaultdict byvalue = defaultdict(list) for i,...
Yes, you could preprocess those slices into sets, thereby making membership lookup `O(1)` instead of `O(n)`: ``` check = set(data[a:b]) if x in check: # do something if y in check: # do something else ```
Fast membership in slices of lists
[ "", "python", "performance", "" ]
I have the following matrix which I believe is sparse. I tried converting to dense using the x.dense format but it never worked. Any suggestions as to how to do this?, thanks. ``` mx=[[(0, 2), (1, 1), (2, 1), (3, 1), (4, 1), (5, 3), (6, 4), (7, 2), (8, 5), (9, 1)], [(10, 1), (11, 5), (12, 2), (13, 1), (21, 1), (22, 1...
List comprehension is the easiest way: ``` new_list = [[b for _,b in sub] for sub in mx] ``` Result: ``` >>> new_list [[2, 1, 1, 1, 1, 3, 4, 2, 5, 1], [1, 5, 2, 1, 1, 1, 1, 1, 1, 2], [2, 1, 1, 1, 2, 1, 1, 1, 1, 1]] ```
Your source data do not really match any of the built-in formats supported by sparse matrices in SciPy (see <http://docs.scipy.org/doc/scipy/reference/sparse.html> and <http://en.wikipedia.org/wiki/Sparse_matrix>), so using `.todense()` will not really be productive here. In particular, if you have something like: ```...
How to convert sparse matrix to dense form using python
[ "", "python", "numpy", "matrix", "scipy", "word-frequency", "" ]
My select looks like this and it returns the fields from the biggest id... ``` SELECT * FROM Pontos WHERE IdPonto = (SELECT MAX(IdPonto) FROM Pontos) ``` But now I want to select just the fields from the second biggest.
`SELECT * FROM Pontos WHERE IdPonto = (SELECT IdPonto FROM Pontos ORDER BY IdPonto DESC LIMIT 1,1)` should work.
This would be one way to do it: ``` SELECT * FROM Pontos ORDER BY Id DESC LIMIT 1 OFFSET 1 ``` (Not quite certain about sqlite syntax, but read this SO thread for more info: [Sqlite LIMIT / OFFSET query](https://stackoverflow.com/questions/3325515/sqlite-limit-offset-query-doubt)) edit: I do not think it is necessar...
SQL: SELECT All the fields from the SECOND BIGGEST ID
[ "", "android", "sql", "performance", "sqlite", "select", "" ]
I have a variable which may or may not get a value in the instance: ``` class EC(): __init__(self, a=False): ... if a: self.__var = ... ``` Later I want to check if the **\_\_var** exists in the instance. Because prepending **\_\_** to the name changes the internal name to **\_EC\_\_var** the checking code b...
You've forgotten the [EAFP principle](https://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python): ``` try: value = self.__var except AttributeError: # do something else ``` If you're determined to use a sentinel, you can combine it with a class variable: ``` class EC(): __var = ob...
Just use hasattr(self, '\_var') to see if it exists - it may be set to None but it will exist if hasattr says it does. E.g.: ``` >>> class a(): ... def __init__(self): ... self.a = 3 ... self._a_ = 4 ... self.__a__ = 'Fred' ... >>> A=a() >>> hasattr(a, 'a') False >>> hasattr(A, 'a') True >>> hasattr(...
What's the best way to check if class instance variable is set in Python?
[ "", "python", "" ]
I want to read huge text file line by line (and stop if a line with "str" found). How to check, if file-end is reached? ``` fn = 't.log' f = open(fn, 'r') while not _is_eof(f): ## how to check that end is reached? s = f.readline() print s if "str" in s: break ```
There's no need to check for EOF in python, simply do: ``` with open('t.ini') as f: for line in f: # For Python3, use print(line) print line if 'str' in line: break ``` [Why the `with` statement](http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects): > It is go...
Just iterate over each line in the file. Python automatically checks for the End of file and closes the file for you (using the `with` syntax). ``` with open('fileName', 'r') as f: for line in f: if 'str' in line: break ```
Python: read all text file lines in loop
[ "", "python", "file", "" ]
With same keys in dictionaries, I have found [this answer](https://stackoverflow.com/questions/13975021/merge-join-lists-of-dictionaries-based-on-a-common-value-in-python) However I want to merge the previous example's dictionaries as if I had these two: ``` list_a = {'data' : [{'user__name': u'Joe', 'user__id': 1}, ...
In that case you'd have to use a dictionary to map ids to dictionaries first: ``` result = {d['user__id': d for d in list_a} for d in list_b: if d['user_num'] in result: result[d['user_num']].update(d) ```
``` >>> res = {d["user_num"]: d for d in list_b["data"]} >>> for a in list_a["data"]: ... res[a["user__id"]]["user__name"] = a["user__name"] >>> list_c = {"data" : res.values()} ``` However, it will raise KeyError if there's no user in list\_b for user in list\_a
Join two Python dictionaries based on same value but different key name (like SQL's JOIN)
[ "", "python", "dictionary", "key", "" ]
This query is giving me error so whats wrong with this query? ``` SELECT recipes.recipeId as recipeId, recipes.title as title, recipes.cookingtime as cookingtime, recipes.serving as serving, schedule.catId as catId, images.imagePath AS imagePath FROM recipes INNER JOIN sched...
You are thinking correct. `GROUP BY` should come after `WHERE` clause and before `ORDER BY` clause. ``` SELECT recipes.recipeId as recipeId, recipes.title as title, recipes.cookingtime as cookingtime, recipes.serving as serving, schedule.catId as catId, images.imagePath AS imageP...
should be like that, where then group by , then order ``` WHERE schedule.day = 'saturday' GROUP BY recipeId ORDER BY catId ASC ```
Whats wrong with this SQL query
[ "", "mysql", "sql", "" ]
I have a database and its structure looks like this: 1. The table is called `Values` 2. The columns of that table are: `Key, Attribute, Value` 3. An `object` is a series of rows that share the same `Key`. For example: ``` ROWID Key Attribute Value ***** *********************...
``` select t1.key from Table1 t1 inner join Table1 t2 on t1.key = t2.key where t1.Attribute = 'CreatedAt' and t2.Attribute = 'UpdatedAt' and t1.value < t2.value ``` * see it working live in an [sqlfiddle](http://sqlfiddle.com/#!2/7bc8c/1/0)
Here's my version: ``` SELECT Key, MAX(CASE WHEN Attribute = 'FirstName' THEN Value END) As "First_Name", MAX(CASE WHEN Attribute = 'CreatedAt' THEN Value END) As "Created_At", MAX(CASE WHEN Attribute = 'UpdatedAt' THEN Value END) As "Updated_At" FROM Value GROUP BY Key HAVING Created_At < Updat...
Multiple column match across rows
[ "", "sql", "sqlite", "" ]
Here's the schema: ``` CREATE TABLE `employees` ( `employee_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `department_id` int(11) DEFAULT NULL, `boss_id` int(11) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `salary` varchar(255) DEFAULT NULL, PRIMARY KEY (`employee_id`) ); CREATE TABLE `departments` ( ...
It's doing exactly what you think it's doing. The problem is that your data isn't what you think it is. The department\_id for all entries in the `employees` table are the same, `1`. So you are getting one value per department, the problem is that only one department is represented. Here's a [SQLfiddle](http://sqlfidd...
``` SELECT d.name, e.name, e.salary FROM employees e INNER join departments d on e.department_id=d.department_id INNER JOIN ( SELECT d.department_id, max(e.salary) as salary from departments d left join employees e on e.department_id=d.department_id group by d.department_id ) x ON x.salary = e....
SQL Query only returns one row
[ "", "mysql", "sql", "" ]
Ok so I'm defining a function that takes a variable number of inputs and clamps each of them ``` def clamp(*args): return [ max(min(arg, 0.8), 0.2) for arg in args] ``` I like the readability of this function: ``` a = 0.12 b = 0.45 c = 0.992 A,B,C = clamp(a,b,c) print A,B,C >> 0.2, 0.45, 0.8 ``` This takes a...
I'm not very conviced but here is an alternative solution ``` >>> clam = lambda a: max(min(a, 0.8), 0.2) >>> def clamp(a, *args): ... if args: ... return [ clam(arg) for arg in (a,)+args] ... else: ... return clam(a) ... >>> clamp(123, 123) [0.8, 0.8] >>> clamp(123) 0.8 ```
You can force it to unpack a single element by adding a comma after the name. Not ideal but here you go: ``` A, = clamp(a) ```
Unpacking variable length list returned from function
[ "", "python", "" ]
I have two SQLite tables like this: ``` AuthorId | AuthorName ---------------------- 1 | Alice 2 | Bob 3 | Carol ... | .... BookId | AuthorId | Title ---------------------------------- 1 | 1 | aaa1 2 | 1 | aaa2 3 | 1 | aaa3 4 | 2 | d...
You can do the counting using a correlated subquery: ``` SELECT b.BookId, a.AuthorId, a.AuthorName, b.Title FROM Author a join Book b on a.AuthorId = b.AuthorId where (select count(*) from book b2 where b2.bookId <= b.BookId and b2.AuthorId = b.AuthorId ) <= 2; ``` For a small database t...
There is alternative variant: ``` SELECT * FROM ( SELECT * FROM BOOK, AUTHOR WHERE BOOK.AUTHORID = AUTHOR.AUTHORID ) T1 WHERE T1.BOOKID IN ( SELECT T2.BOOKID FROM BOOK T2 WHERE T2.AUTHORID = T1.AUTHORID ORDER BY T2.BOOKTITLE LIMIT 2 ) ORDER BY T1.BOOKTITLE ```
How to select the first N rows of each group?
[ "", "sql", "sqlite", "greatest-n-per-group", "limit-per-group", "" ]
I have a select statement where I want to order by different criteria based on a CASE expression, but I'm having trouble with syntax when I want to order by multiple criteria. I would like it to be similar to the following code, but I get syntax errors. ``` SELECT * FROM Table1 ORDER BY CASE WHEN @OrderBy = 1 THEN Col...
Although a `case` only returns one value, you can repeat the case: ``` SELECT * FROM Table1 ORDER BY (CASE WHEN @OrderBy = 1 THEN Column1 WHEN @OrderBy = 2 THEN Column3 end), (CASE WHEN @OrderBy = 1 THEN Column2 END) ``` This gives the secondary sort on `Column2` for `@OrderBy = 1`. ...
`CASE` is an *expression* which returns *exactly* one result, and cannot be used for control-of-flow logic like in some other languages. I have no idea what your data types are so I'm guessing you want this: ``` CASE WHEN @OrderBy = 1 THEN Column1 END, CASE WHEN @OrderBy = 2 THEN Column3 END, Column2; ``` If Column1 ...
ORDER BY with two criteria in a CASE expression
[ "", "sql", "sql-server", "select", "sql-order-by", "switch-statement", "" ]
Looking for elegant (or any) solution to convert columns to rows. Here is an example: I have a table with the following schema: ``` [ID] [EntityID] [Indicator1] [Indicator2] [Indicator3] ... [Indicator150] ``` Here is what I want to get as the result: ``` [ID] [EntityId] [IndicatorName] [IndicatorValue] ``` And th...
You can use the [UNPIVOT](http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx) function to convert the columns into rows: ``` select id, entityId, indicatorname, indicatorvalue from yourtable unpivot ( indicatorvalue for indicatorname in (Indicator1, Indicator2, Indicator3) ) unpiv; ``` Note,...
well If you have 150 columns then I think that UNPIVOT is not an option. So you could use xml trick ``` ;with CTE1 as ( select ID, EntityID, (select t.* for xml raw('row'), type) as Data from temp1 as t ), CTE2 as ( select C.id, C.EntityID, F.C.value('local-name(.)', 'nvarchar(128)') as I...
SQL Server : Columns to Rows
[ "", "sql", "sql-server", "t-sql", "unpivot", "" ]
I have a table with columns: `ID` (Int), `Date` (Date) and `Price` (Decimal). `Date` column is in format 2013-04-14: ## Table Example ``` ID Date Price 1 2012/05/02 23.5 1 2012/05/03 25.2 1 2012/05/04 22.5 1 2012/05/05 22.2 1 2012/05/06 26.5 2 ...
Try the following. ``` CREATE TABLE #temp ( Date date, x money, y money ) ; SELECT Date, MAX(CASE WHEN id=1 THEN price END) AS x, MAX(CASE WHEN id=3 THEN price END) AS y FROM Top40 WHERE Date BETWEEN '2012-05-02' AND '2012-05-04' GROUP BY Date ; ``` See [SQL Fiddle](http://sqlfiddle.com/#!6/5f2f0/4) for...
The simplest way to do it in code (although it may not perform well with large data sets) is to do something like: ``` SELECT [Date], x = MAX(CASE WHEN ID = 1 THEN PRICE END) , y = MAX(CASE WHEN ID = 3 THEN PRICE END) INTO #tmp FROM Top40 GROUP BY [Date] ```
Insert data into temp table, multiple columns from one Table
[ "", "sql", "sql-server-2012", "" ]
I have a set I want to make into a sorted list. I run: ``` sorted_list=list(my_set).sort() ``` but this returns `none`, even when both `list(my_set)` and `my_set` are both nonempty. On the other hand this: ``` sorted_list=list(my_set) sorted_list.sort() ``` works just fine. Why is this happening? Does python not a...
`.sort()` sorts the list in place and returns `None`. You need to use the `sorted()` function here. ``` >>> a = [3, 2, 1] >>> print a.sort() None >>> a [1, 2, 3] >>> sorted(a) [1, 2, 3] ```
It's simple: * `sort()` makes sorting in place and returns `None` * `sorted()` returns a sorted copy Here's a quote from [How To/Sorting - Python Wiki](http://wiki.python.org/moin/HowTo/Sorting/): > Python lists have a built-in sort() method that modifies the list > in-place and a sorted() built-in function that bui...
Why can't I sort a list right after I make it?
[ "", "python", "list", "python-3.x", "" ]
I'm a total noob trying to create a blank MS Access database using VBA in Excel. I want to name the new database "tblImport". This is the code I´m using: ``` Sub makedb() Dim accessApp As Access.Application Set accessApp = New Access.Application accessApp.DBEngine.CreateDatabase "C:\tblImport.accdb", dbLan...
The name of the locale constant in the CreateDatabase method is wrong: This: `accessApp.DBEngine.CreateDatabase "C:\tblImport.accdb", dbLangGenera` Should be: `accessApp.DBEngine.CreateDatabase "D:\tblImport.accdb", DB_LANG_GENERAL` Change that and your code should work. (It does for me at least).
Old Question. Here are my two cents. You have a typo... `dbLangGenera` should be `dbLangGeneral` More about it in [Workspace.CreateDatabase Method (DAO)](https://msdn.microsoft.com/en-us/library/office/ff822832.aspx) Voting to close this question as per [Dealing with questions with obvious replies](https://meta.stac...
How can a blank MS Access database be created using VBA?
[ "", "sql", "excel", "vba", "ms-access", "" ]
I am new to Mock and am writing a unit test for this function: ``` # utils.py import requests def some_function(user): payload = {'Email': user.email} url = 'http://api.example.com' response = requests.get(url, params=payload) if response.status_code == 200: return response.json() ...
Patch `json` method instead of `content`. (`content` is not used in `some_function`) Try following code. ``` import unittest from mock import Mock, patch import utils class UtilsTestCase(unittest.TestCase): def test_some_function(self): user = self.user = Mock() user.email = 'user@example.com' ...
Another pattern I like to use that is a little more reusable would be to start the patcher in your unit test's `setUp` method. It's also important to check that mock request was called with the expected parameters: ``` class UtilsTestCase(TestCase): def setUp(self): self.user = Mock(id=123, email='foo@bar...
Django unittest and mocking the requests module
[ "", "python", "unit-testing", "mocking", "python-requests", "" ]
I am using the `ttk.Progressbar` in my app. I have scoured the net for an answer but no avail. I have the following code which is working well. But I want to change the thickness of the bar. ``` progressbar = ttk.Progressbar(myGui, orient=HORIZONTAL, length=400, mode="determinate", ...
The [ttk progress bar](http://docs.python.org/3.1/library/tkinter.ttk.html#progressbar) appears to lack the width option in Python. Using a work around ([here](https://stackoverflow.com/a/11981214/1663352)) for an issue with a Tkinter Button. From this I have been able to create a working solution. The key to solving...
If you *must* use the xpnative theme or themes like it, then you will likely not have the option to change the thickness the conventional way. However if you use the default theme, you can configure the thickness with a style. There are likely other themes that let you do this as well, and if you're going to be playing...
tkinter.ttk.Progressbar: How to change thickness of a horizontal bar
[ "", "python", "python-3.x", "tkinter", "ttk", "" ]
I'm doing an exercise that asks for a function that approximates the value of pi using Leibniz' formula. These are the explanations on Wikipedia: ![enter image description here](https://i.stack.imgur.com/BmZlF.png) ![enter image description here](https://i.stack.imgur.com/Tihza.png) Logical thinking comes to me easi...
The capital sigma here is [sigma notation](http://en.wikipedia.org/wiki/Summation#Capital-sigma_notation). It is notation used to represent a summation in concise form. So your sum is actually an infinite sum. The first term, for n=0, is: ``` (-1)**0/(2*0+1) ``` This is added to ``` (-1)**1/(2*1+1) ``` and then to...
The Leibniz formula translates directly into Python with no muss or fuss: ``` >>> steps = 1000000 >>> sum((-1.0)**n / (2.0*n+1.0) for n in reversed(range(steps))) * 4 3.1415916535897934 ```
Leibniz formula for π - Is this any good? (Python)
[ "", "python", "python-3.x", "" ]
Ok, most possibly I am doing something wrong, but following the advice of a user here I run this query: ``` SELECT id, item, (SELECT COUNT(item) FROM Table1 WHERE id=a.id AND item=a.item) cnt FROM (SELECT DISTINCT a.id,b.item FROM Table1 a, Table1 b) a ORDER BY id, item; ``` on this table: ``` ID ITEM --...
Your query is quite convoluted. I think you just want to count the combinations of `id` and `item`. If so, this is a simple aggregation: ``` select id, item, count(*) from Table1 a group by id, item; ``` If you want all ids and items to appear, then use a driver table: ``` select driver.id, driver.item, coalesce(cou...
If the only thing you want to achieve is a a count grouped by `id` and `item`, why don't you just : ``` SELECT ID, Item, COUNT(1) FROM Table 1 GROUP BY ID, Item ``` It's as simple as that!
Count query is taking too long - over 24 hours have passed
[ "", "mysql", "sql", "database", "" ]
I want to create a stored procedure to insert random data in 'Video' table. I have already generated 30,000 record data for UserProfile table. Note: The username is FK element in Video table. ``` CREATE TABLE UserProfile ( Username VARCHAR(45) NOT NULL , UserPassword VARCHAR(45) NOT NULL , Email VARCHAR(45...
It's not too difficult to generate random data, even in SQL For example, to get a random username from your userprofile table. ``` BEGIN -- get a random row from a table DECLARE @username VARCHAR(50) SELECT @username = [Username] FROM ( SELECT ROW_NUMBER() OVER(ORDER BY [Username]) [row], [Username] FROM [Use...
As Aaron already suggested in his comment – I wouldn’t really reinvent the wheel. Just go and find some of the already available tools for this. [Here](http://www.mssqltips.com/sqlservertip/2190/generating-sql-server-test-data-with-visual-studio-2010/) is an article on how to do this in VS and thread here on StackOve...
How to generate random data in SQL server
[ "", "sql", "sql-server", "database", "sql-server-2008", "stored-procedures", "" ]
I want to implement an algorithm that gets the index of letter changes. I have the below list, here I want to find the beginning of every letter changes and put a result list except the first one. Because, for the first one, we should get the last index of occurrence of it. Let me give you an example: ``` letters=['A'...
Here's my suggestion. It has three steps. 1. Fist, find all the starting indexes for each run of letters. 2. Replace the index in the first non-X run with the index of the end of its run, which will be one less than the start of the following run. 3. Filter out all X runs. The code: ``` def letter_runs(letters): ...
Now that you've explained you want the first index of every letter after the first, here's a one-liner: ``` letters=['A','A','A','A','A','A','A','A','A','A','A','A','B','C','C','X','D','X','B','B','A','A','A','A'] [(n+1, b) for (n, (a,b)) in enumerate(zip(letters,letters[1:])) if a!=b and b!='X'] #=> [(12, 'B'), (13, ...
An algorithm to find transitions in Python
[ "", "python", "algorithm", "" ]
Here is an example of my table: ``` ID Name ClickLink1 ClickLink2 ClickLink3 -- ---- ---------- ---------- ---------- 1 John Landing ThankYou 2 Abby ThankYou Landing Landing 3 Chris ThankYou 4 Sam Land...
I think this would do it below, and should be an agnostic solution since you didn't provide the DBMS flavor. ``` SELECT ClickLink1 as Page, 'ClickLink1' as Link, Count(ID) as Count FROM myTable GROUP BY ClickLink1 UNION SELECT ClickLink2 as Page, 'ClickLink2' as Link, Count(ID) as Count FROM myTable GROUP BY ClickLink...
The main issue is that your current table is denormalized so you need to count across the columns. One way to do this would be to unpivot the data from multiple columns into multiple rows. There are a few different ways that you can do this. You can use a UNION ALL to converts the columns into rows and then count the ...
SQL Query counting appearances in multiple columns
[ "", "sql", "sql-server", "" ]
ok, so I have a list of lists ``` list = [['a','b','c'], ['1','2','3'], ['x','y','z']] ``` and I want to edit the first item of each list so it has a symbol before it. A "?" in this example. I figure I can use list comprehension to do this. Something similar to this: ``` list = ['?'+x for x in i[0] for i in list] ``...
Do ``` l = [['?' + i[0]] + i[1:] for i in l] (l is the list you pass in) ```
First of all, don't name a variable `list`; you are now masking the [built-in `list()` type](http://docs.python.org/2/library/functions.html#list), and can easily lead to bugs if you expect `list()` to still be that type elsewhere in your code. To prepend a string to the first element of each nested list, use a simple...
List comprehension for a list of lists
[ "", "python", "list-comprehension", "" ]
Often, some of the answers mention that a given solution is **linear**, or that another one is **quadratic**. How to make the difference / identify what is what? Can someone explain this, the easiest possible way, for the ones like me who still don't know?
A method is linear when the time it takes increases linearly with the number of elements involved. For example, a for loop which prints the elements of an array is roughly linear: ``` for x in range(10): print x ``` because if we print range(100) instead of range(10), the time it will take to run it is 10 times l...
They must be referring to run-time complexity also known as Big O notation. This is an extremely large topic to tackle. I would start with the article on wikipedia: <https://en.wikipedia.org/wiki/Big_O_notation> When I was researching this topic one of the things I learned to do is graph the runtime of my algorithm wi...
Linear time v.s. Quadratic time
[ "", "python", "big-o", "complexity-theory", "time-complexity", "" ]
I am trying to get a list of players who are logged into an online game (DayZ). The backend database is MySQL and the way to determine if a user is logged in is not exectly straight forward. Is is building this query that I could use help with. Basically there is a table named `player_login` that makes a new entry eve...
The following query yields the most recent logout time for each player: ``` SELECT PlayerUID, MAX(DateStamp) AS MostRecentLogout FROM player_login WHERE Action = 0 GROUP BY PlayerUID ``` A similar query with `Action = 2` yields all most-recent login times. Combining these lets you compare them: ``` SELECT plin.Playe...
try this ``` SELECT PlayerUID, Action FROM player_login WHERE `Action` = 0 GROUP BY PlayerUID ORDER BY Datestamp DESC ```
SQL query to determine which users are online
[ "", "mysql", "sql", "" ]
a simple database design question has been bugging me for a while, thought I'll ask it here. Suppose I have a database table, `"Loan"` with the following fields, ``` StudentIdentification, LoanDate, ReturnDate ``` This table is used track every student who has loaned something (not in the database). Since every stud...
I would create a single table, and then have a filtered index (SQL Server 2008+) or indexed view (SQL Server 2005-) to enforce that there is only a single row for each student with a `NULL` return date: ``` CREATE TABLE Loans ( StudentID int not null, LoanDate datetime not null, ReturnDate datetime null, ...
You can use a simple SCD (slowly changing dimension) structure and use one table to store both current and historical data. ``` StudentIdentification, CreationDate, LoanDate, ReturnDate ``` the first two columns are the PK. You can also add an amount to indicate a loan or a return. You might find [this question](ht...
Storing all loan (insert loan date, update return date) records in one table or 2 tables (with history) is better?
[ "", "sql", "sql-server", "database", "oracle", "" ]
This is extracted from Learning Python 4th edition. Its function is to subclass set using list. But I don't understand line 5 `list.__init__([])`, please help. The code works even when I commented out this line of code. Why? ``` ### file: setsubclass.py class Set(list): def __init__(self, value = []): # Cons...
The code in the book contains an error. I've submitted an errata to O'Reilly books, which you can read along with the authors response on [this page](http://oreilly.com/catalog/errata.csp?isbn=0636920028154) (search for 982). Here's a small snippet of his response: > This code line has apparently been present in the b...
You mean this line? ``` list.__init__([]) ``` When you override the `__init__` method of any type, it's good practice to always call the inherited `__init__` method; that is, the `__init__` method of the base class. This way you perform initialization of the parent class, and add initialization code specific to t...
Extending Types by Subclassing in Python
[ "", "python", "" ]
I have two tables with the following structure: ``` DECLARE @Table1 TABLE ( IdColumn INT, DateColumn DATETIME ) DECLARE @Table2 TABLE ( IdColumn INT, DateColumn DATETIME, Value NUMERIC(18,2) ) ``` What i want to do is get the latest value from table2 having a less or equal date in table1. This ...
I would do this with a correlated subquery: ``` select t1.*, (select top 1 value from @table2 t2 where t2.idColumn = t1.idColumn and t2.dateColumn <= t1.dateColumn order by t2.dateColumn desc ) t2value from @table1 t1; ```
I am just posting Gordon's Answer with correct syntax : ``` select t1.*, (select top 1 value from @table2 t2 where t2.IdColumn = t1.IdColumn and t2.DateColumn <= t1.DateColumn order by t2.DateColumn desc ) t2value from @table1 t1 ```
Get the latest value on each date
[ "", "sql", "sql-server", "" ]
I have two tables: ``` FirstField | SecondField | ThirdField FirstValue SecondValue ThirdValues ---------------------------------------------- FirstField | SecondField | ThirdField OtherValue1 OtherValue2 OtherValue3 ``` What I need it to add those two tables together into one SQL query. They can no...
Try `UNION ALL`: ``` SELECT FirstField ,SecondField ,ThirdField FROM Table1 UNION ALL SELECT FirstField ,SecondField ,ThirdField FROM Table2 ``` If you want to remove duplicate rows use `UNION` instead. ``` SELECT FirstField ,SecondField ,ThirdField FROM Table1 UNION SELECT FirstField ,SecondField ,ThirdF...
Have a lok at using a [UNION/UNION ALL](http://technet.microsoft.com/en-us/library/ms180026.aspx) > Combines the results of two or more queries into a single result set > that includes all the rows that belong to all queries in the union. > The UNION operation is different from using joins that combine columns > from ...
Multiple SQL tables added together without a JOIN
[ "", "sql", "" ]
I have a python dictionary of the form : ``` a1 = { 'SFP_1': ['cat', '3'], 'SFP_0': ['cat', '5', 'bat', '1'] } ``` The end result I need is a dictionary of the form : ``` {'bat': '1', 'cat': '8'} ``` I am currently doing this: ``` b1 = list(itertools.chain(*a1.values())) c1 = dict(itertools.i...
Using [defaultdict](http://docs.python.org/2/library/collections.html#collections.defaultdict): ``` import itertools from collections import defaultdict a1 = {u'SFP_1': [u'cat', u'3'], u'SFP_0': [u'cat', u'5', u'bat', u'1']} b1 = itertools.chain.from_iterable(a1.itervalues()) c1 = defaultdict(int) for animal, count ...
``` In [8]: a1 = { 'SFP_1': ['cat', '3'], 'SFP_0': ['cat', '5', 'bat', '1'] } In [9]: answer = collections.defaultdict(int) In [10]: for L in a1.values(): for k,v in itertools.izip(itertools.islice(L, 0, len(L), 2), ...
Convert list into dictionary in python
[ "", "python", "" ]
I am trying to make a numpy array that looks like this: ``` [a b c ] [ a b c ] [ a b c ] [ a b c ] ``` So this involves updating the main diagonal and the two diagonals above it. What would be an efficient way of doing this?
This is an example of a [Toeplitz matrix](https://en.wikipedia.org/wiki/Toeplitz_matrix) - you can construct it using [`scipy.linalg.toeplitz`](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.toeplitz.html): ``` import numpy as np from scipy.linalg import toeplitz first_row = np.array([1, 2, 3...
You can use `np.indices` to get the indices of your array and then assign the values where you want. ``` a = np.zeros((5,10)) i,j = np.indices(a.shape) ``` `i,j` are the line and column indices, respectively. ``` a[i==j] = 1. a[i==j-1] = 2. a[i==j-2] = 3. ``` will result in: ``` array([[ 1., 2., 3., 0., 0., 0...
Make special diagonal matrix in Numpy
[ "", "python", "arrays", "numpy", "matrix", "toeplitz", "" ]
I am learning about reading/writing strings, lists, etc to txt/dat files. I wanted to add a comment in my code so I can refer back to what the access keys are. So this is what I did. ``` # Mode Description # rb Read from a binary file. If the file doesn’t exist, Python will complain with an error. # wb Write...
Replace all the `’` by `'`. It's complaining because you didn't add the encoding type to the beginning of the file. The default encoding is `utf-8`, in which those characters are not allowed. Instead of replacing, you can add this line to the beginning (before the comments): `# coding: iso-8859-1` (Or another encodi...
Replace the smart quotes `’` with the regular quote `'` in your comments.
Python - Error when trying to add comments
[ "", "python", "python-3.x", "syntax-error", "" ]
I have been trying to return a variable in a function in a variable and use it outside of it: ``` test = 0 def testing(): test = 1 return test testing() print(test) ``` But when I run it, the result is 0. How could I fix this problem?
You are messing up a bit the scopes and/or assignment. Try this: ``` def testing(): test = 1 return test test = testing() print(test) ``` Explanation: The `test` inside `testing` is different to the `test` inside the module. You have to assign it on module-level to get the expected result.
Because you declare `test` in the function, it is not a global variable, thus, you can not access the variable `test` you created in the function outside of it as they are different scopes If you want to `return test` to a variable, you have to do ``` result = testing() print(result) ``` Or, you can also add a `glob...
Returning Variables in Functions Python Not Working Right
[ "", "python", "variables", "return-value", "" ]
My table scheme is as follows: (Bold column name is primary key) Table 1: **id1** - id2 Table 2: **id2** - name2 Table 3: **id3** - name3 Table 4: id1 - Id3 What I want to do is have sql code that : 1. Select data in id1 and id3 columns for which name2=input=name3 2. Insert into table 4 3. Only insert into 4 if i...
Here the query you need ``` insert into table4(id1, id3) select t1.id1, t3.id3 from table2 as t2 inner join table1 as t1 on t1.id2 = t2.id2 inner join table3 as t2 on t2.name2 = t3.name3 where t2.name2 like 'input' and not exists ( select * from table4 as t4 where t4.id1 = t1.id1 and...
I think you are looking for this ``` INSERT INTO table4( id1, id3) SELECT id1, id3 FROM table2 INNER JOIN table1 ON table1.id2 = table2.id2 Left JOIN table3 ON table2.name2 = table3.name3 WHERE name2 LIKE 'input' and table3.name3 is null ``` or something similar. Left (outer join) gets all the records in table2 whe...
Select data from one table and insert into another existing table, which doesn't exist in the table
[ "", "mysql", "sql", "" ]
Just wanted to see if there is a way to output a result that is not stored based on the addition of up to 4 fields? Have a table that holds the count of passengers on a service for different categories, Adult, Child Infant and staff, and I want to try and out put a number based on the result of these fields that is no...
You can do this with a query on the data: ``` select t.*, (case when Adult + Child + Infant + staff > 15 then 45 when Adult + Child + Infant + staff > 9 then 35 end) as CoachSize from t; ``` You can also do this using a `view` so it is available as if it were a table: ``` create view vw_t...
Depending on what SQL program you're using, most offer the `CASE WHEN` statement (see this [SQL Fiddle example](http://sqlfiddle.com/#!6/e416c/1)) ``` CREATE TABLE CaseValues( Value INT ) INSERT INTO CaseValues VALUES (1) , (16) , (9) SELECT CASE WHEN Value > 15 THEN 45 WHEN Value BETWEEN 6 AND 14 THEN 35 ...
Is there anything like an Excel IF Statement in SQL
[ "", "sql", "" ]
Given two lists, I want to merge them so that all elements from the first list are even-indexed (preserving their order) and all elements from second list are odd-indexed (also preserving their order). Example below: ``` x = [0,1,2] y = [3,4] result = [0,3,1,4,2] ``` I can do it using for loop. But I guess there cou...
You can simply do: ``` for i,v in enumerate(y): x.insert(2*i+1,v) ``` this takes the advantage that insert will use the last index when it is overpassed. One example: ``` x = [0,1,2,3,4,5] y = [100, 11,22,33,44,55,66,77] print x # [0, 100, 1, 11, 2, 22, 3, 33, 4, 44, 5, 55, 66, 77] ```
Here's something you can use. (Use `list(izip_longest(...))` for Py2x) ``` >>> from itertools import chain >>> from itertools import zip_longest >>> list(filter(lambda x: x != '', chain.from_iterable(zip_longest(x, y, fillvalue = '')))) [0, 3, 1, 4, 2] ``` This works for arbitrary length lists like follows - ``` >>>...
python merge two lists (even/odd elements)
[ "", "python", "list", "merge", "" ]
``` Select convert(varchar(8), max(checkdate),1) lastcheckdate from table where status = 'processed' and not status in ('delivered', 'scheduled') Select convert(varchar(8), max(checkdate),1) as nextcheckdate from table where status = 'scheduled' and not status in ('delivered', 'processed') ``` What I'm looking f...
Formally, I think the following returns the two values. ``` select convert(varchar(8), max(case when status = 'processed' then checkdate end), 1 ) as lastcheckdate, convert(varchar(8), max(case when status = 'scheduled' then checkdate end), 1 ) as nextcheckdate from table; ``` Howev...
Your WHERE clauses are redundant. ``` Select convert(varchar(8), max(checkdate),1) lastcheckdate from table where status = 'processed' and not status in ('delivered', 'scheduled') ``` For any row searched, if status = 'processed', then status is neither 'delivered', nor 'scheduled'. They are exclusive. Therefore,...
Is it possible to have these 2 queries in one?
[ "", "sql", "sql-server", "" ]
As I did a bit test, a python dict of int=>int (different value) of 30 million items can easily eats >2G memory on my mac. Since I work with only int to int dict, is there any better solution than using python dict? Some requirements I need are, 1. more memory efficient at holding tens of million level of int to int ...
Judy-array based solution seems the option I should look into. I'm still looking for a good implementation that can be used by Python. Will update later. Update, finally I'm experimenting a Judy array wrapper at <http://code.google.com/p/py-judy/> . Seems no any document there but I tried to find its methods simply b...
There are at least two possibilities: **arrays** You could try using two arrays. One for the keys, and one for the values so that index(key) == index(value) **Updated 2017-01-05:** use 4-byte integers in array. An array would use less memory. On a 64-bit FreeBSD machine with python compiled with clang, an array of ...
efficient way to hold and process a big dict in memory in python
[ "", "python", "dictionary", "" ]
I have a dictionary D where: ``` D = {'foo':{'meow':1.23,'mix':2.34}, 'bar':{'meow':4.56, 'mix':None}, 'baz':{'meow':None,'mix':None}} ``` I wrote this code to write it to a text file: ``` def dict2txt(D, writefile, column1='-', delim='\t', width=20, order=['mix','meow']): import csv with open( writefile, 'w' ) ...
Now, an alternate, easier and more efficient way of doing this, by using the wonderful [Pandas](http://pandas.pydata.org/) library ``` import pandas as pd order=['mix', 'meow'] D = {'foo':{'meow':1.23,'mix':2.34}, 'bar':{'meow':4.56, 'mix':None}, 'baz':{'meow':None,'mix':None}} df = pd.DataFrame(D).T.reindex(columns...
Take advantage of your "order" variable to drive some generators: ``` def dict2txt(D, writefile, column1='-', delim='\t', width=20, order=['mix','meow']): import csv # simplify formatting for clarity fmt = lambda s: '{!s:{}}'.format(s, width) with open(writefile, 'w') as f: writer = csv.writer(...
Python: Write dictionary to text file with ordered columns
[ "", "python", "text", "dictionary", "" ]
I have read through some somewhat related questions, but did not find the specifics related to my question. If I have a stable application that is not going to be changed and it has been thoroughly tested and used in the wild... one might consider removing referential integrity / foreign key constraints in the databas...
From my experience with Oracle: Foreign Keys provide information to the optimizer ("you're going to find exactly one match on this join"), so removing those might result in (not so) funny things happening to your execution plans. Foreign Keys do perform checks, which costs performance. I have seen those to use up a b...
The benefits (however small) with be insignificant to the cons. If performance is a problem check the indexes. Throw more hardware its way. There are a host of techniques to improve performance. I know you said not to mention the cons - but you should consider them. The data is a very valuable asset and ensuring its ...
Removing Referential Integrity on Stable Application
[ "", "sql", "database", "" ]
`traceback.format_exc()` can get it with raising an exception. `traceback.print_stack()` prints the stack without an exception needed, but it does not return a string. There doesn't seem to be a way to get the stack trace string without raising an exception in python?
It's `traceback.extract_stack()` if you want convenient access to module and function names and line numbers, or `''.join(traceback.format_stack())` if you just want a string that looks like the `traceback.print_stack()` output.
How about [traceback.format\_stack?](http://docs.python.org/2/library/traceback.html#traceback.format_stack)
How to get stack trace string without raising exception in python?
[ "", "python", "stack-trace", "" ]
I want to print an enumerated list in user specified columns. ``` import random lst = random.sample(range(100), 30) counter = 0 for pos, num in enumerate(sorted(lst)): if counter % 2 == 0: print '(%s) %s' %(pos, num), counter = counter + 1 else: print '(%s) %s'.rjust(16) %(pos, num) ...
The "user specified" part of your question is tricky. How does the user specify what they want in each column? Can they specify more than two columns? etc. However, if you know you have 30 items, and you know that you want the 1st 15 in the first column and the next 15 in the 2nd column I believe the following will do...
``` def print_table(seq, columns=2): table = '' col_height = len(seq) / columns for x in xrange(col_height): for col in xrange(columns): pos = (x * columns) + col num = seq[x + (col_height * col)] table += ('(%s) %s' % (pos, num)).ljust(16) table += '\n' ...
print an enumerated list in multiple columns
[ "", "python", "multiple-columns", "enumerate", "" ]
Consider this list here: ``` example=[] ``` And another: ``` python=["hi","bye","hello","yes","no"] ``` If I decide to add one of the elements from python to example, will a duplicate of that element b created or will the variable python lose an element. ``` example+=[python[0]] ``` So would the string "hi" be du...
No, there will be no "transfer". This is easy enough to check, by just printing the values after the operation. Instead, the list example will have appended to it the elements of the first string: ``` >>> f = [] >>> f+= ["hi", "there"][0] >>> f ['h', 'i'] ``` This happens because `a += b` is conceptually\* equivalen...
The string "hi" will be split into chars and assigned to `example` when you do `example+=python[0]` So `example` in this case will contain `['h','i']`. Also, the list `python` will not lose an element.
In python, what happens, will the length of a list decrease if I add part of the list to another list?
[ "", "python", "python-3.x", "" ]
I use the following code to tokenize a string,read from stdin. ``` d=[] cur = '' for i in sys.stdin.readline(): if i in ' .': if cur not in d and (cur != ''): d.append(cur) cur = '' else: cur = cur + i.lower() ``` This gives me a array of non repeating words.However, in...
Try this ``` d=[] cur = '' for i in sys.stdin.readline(): if i in ' .': if cur not in d and (cur != ''): d.append(cur) cur = '' # note the different indentation else: cur = cur + i.lower() ```
Try this: ``` for line in sys.stdin.readline(): res = set(word.lower() for word in line[:-1].split(" ")) print res ``` Example: ``` line = "Dan went to the north pole to lead an expedition during summer." res = set(word.lower() for word in line[:-1].split(" ")) print res set(['north', 'lead', 'expedition', ...
Tokenizing a string gives some words merged
[ "", "python", "stdin", "" ]
The new version of Pandas uses [the following interface](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.excel.read_excel.html#pandas.io.excel.read_excel) to load Excel files: ``` read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA']) ``` but what if I don't know the sheets that are a...
You can still use the [ExcelFile](http://pandas.pydata.org/pandas-docs/dev/io.html#excel-files) class (and the `sheet_names` attribute): ``` xl = pd.ExcelFile('foo.xls') xl.sheet_names # see all sheet names xl.parse(sheet_name) # read a specific sheet to DataFrame ``` *see [docs for parse](http://pandas.pydata.or...
You should explicitly specify the second parameter (sheetname) as None. like this: ``` df = pandas.read_excel("/yourPath/FileName.xlsx", None); ``` "df" are all sheets as a dictionary of DataFrames, you can verify it by run this: ``` df.keys() ``` result like this: ``` [u'201610', u'201601', u'201701', u'201702',...
Pandas: Looking up the list of sheets in an excel file
[ "", "python", "excel", "pandas", "openpyxl", "xlrd", "" ]
In scipy, the error occurs quite often. ``` >>> import scipy >>> scipy.integrate.trapz(gyroSeries, timeSeries) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'integrate' >>> ``` **I figure out how to solve this problem by doing the following:*...
Most possibly because scipy is a library (package) that contains modules and to import a specific module from the scipy library, you need to specify it and import the module itself. As it's a separate module (sub-package), once you import it, it's attributes are available to you by using the regular scipy.module.attrib...
In order to fix the error, add the following line at the top of your script ``` from scipy import integrate ```
AttributeError: 'module' object (scipy) has no attribute *** Why does this error occur?
[ "", "python", "scipy", "" ]
I have a counter that looks a bit like this: ``` Counter: {('A': 10), ('C':5), ('H':4)} ``` I want to sort on keys specifically in an alphabetical order, NOT by `counter.most_common()` is there any way to achieve this?
Just use [sorted](http://docs.python.org/2/library/functions.html#sorted): ``` >>> from collections import Counter >>> counter = Counter({'A': 10, 'C': 5, 'H': 7}) >>> counter.most_common() [('A', 10), ('H', 7), ('C', 5)] >>> sorted(counter.items()) [('A', 10), ('C', 5), ('H', 7)] ```
``` >>> from operator import itemgetter >>> from collections import Counter >>> c = Counter({'A': 10, 'C':5, 'H':4}) >>> sorted(c.items(), key=itemgetter(0)) [('A', 10), ('C', 5), ('H', 4)] ```
sorting a counter in python by keys
[ "", "python", "python-2.7", "dictionary", "" ]
It can be like this form? I try select case but error always occur. if there is any help i'll be thankful. ``` CREATE PROCEDURE searchStatement ( @word1 varchar(50), @word2 varchar(50), @word3 varchar(50) ) as select * from words where 1=1 if @word1 <> '-1' and word1 =@word1 if @word2 <> '-1' a...
You can check the condition via `if` statement and form a `string query` as like below then you can execute the string `query` through `exec` command. ``` declare @resultSet nvarchar(max) set @resultSet = 'select *from searchStatement where 1= 1 ' if @word1 <> '-1' begin set @resultSet = @resultSet + ' and word1 =...
you could use this: ``` select *. from word where (@word1 = '-1' or word = @word1) and (@word2 = '-1' or word = @word2) and (@word3 = '-1' or word = @word3) ``` BTW, if you want to give an empty parameter into procedures, it's better to use null instead of -1
I try to create stored procedure that received 3 parameters, if any param its value equal "-1" it'll not be included in the select statement
[ "", "sql", "sql-server", "" ]
The strings in Python are immutable and support the buffer interface. It could be efficient to return not the new strings, but the buffers pointing to the parts of the old string when using slices or the `.split()` method. However, a new string object is constructed each time. Why? The single reason I see is that it ca...
The underlying string representation is **null-terminated**, even though it keeps track of the length, hence you *cannot* have a string object that references a sub-string that isn't a suffix. This already limits the usefulness of your proposal since it would add a lot of complications to deal differently with suffices...
That's how slices work. Slices always perform a shallow copy, allowing you to do things like ``` >>> x = [1,2,3] >>> y = x[:] ``` Now it would be possible to make an exception for strings, but is it really worth it? [Eric Lippert blogged about his decision not to do that for .NET](http://blogs.msdn.com/b/ericlippert/...
Python's immutable strings and their slices
[ "", "python", "string", "garbage-collection", "" ]
I am having a problem with installing Django. It seems that Python will not recognize it once it is installed. Below are the steps I have taken. I'm using Mac OS 10.7.5 Python 2.7 and Django 1.5.1 I am not using virtualenv What am I doing wrong? Is there any reason Python will not recognize it? How can I fix this? H...
It is likely that your pip installation is pointing to a different python than your python version installed at `opt/local/bin/python`. It is likely that your `pip` is talking to the system installed python and not the version you installed. You can consider uninstalling python and re-installing in the correct path or...
try using pip as the superuser : ``` sudo pip install -U django ``` worked for me ...
Python not recognising Django Installation. (ImportError: No module named django)
[ "", "python", "django", "python-2.7", "" ]
I have a huge data file (~2 G) that needs to be splitted into odd and even lines, processed separately and written into two files, I don't want to read the whole file into RAM, so I think a generator should be a suitable choice. In short I want do something like this: ``` lines = (l.strip() for l in open(inputfn)) odd...
``` def oddlines(fileobj): return (line for index,line in enumerate(fileobj) if index % 2) def evenlines(fileobj): return (line for index,line in enumerate(fileobj) if not index % 2) ``` Note that this will require scanning the file twice, since these aren't designed to run in parallel. It does, however, lead...
Use `itertools.islice` to slice an iterator: ``` from itertools import islice with open('filename') as f1, open('evens.txt', 'w') as f2: for line in islice(f1, 0, None, 2): f2.write(line) with open('filename') as f1, open('odds.txt', 'w') as f2: for line in islice(f1, 1, None, 2): f2.write(lin...
Separate odd and even lines in a generator with python
[ "", "python", "data-manipulation", "" ]
Lets say I have two tables: Table1 ``` Id Name 1 Joe 2 Greg 3 Susan 4 Max ``` Table2 ``` Uid comment 2 Good customer 4 Great guy ``` What I want to do is list all elements of Table 1, and if Table1.Id = Table2.Uid I want to select this comment. If comment does not exist give blank field. Result should be: ...
Try to use `left join` it shows you all data from `table1` ``` select t1.Id, t1.Name, t2.comment from table1 t1 left join table2 t2 on t1.id=t2.Uid ``` **NOTE**: Good practice is to use aliases as above. Code is more readable.
``` select table1.Id, table1.Name, table2.comment from table1 left outer join table2 on table1.id=table2.Uid ```
SQL optional parameter?
[ "", "mysql", "sql", "" ]
Say I have a table structured like this: ``` id dt val a 1/1/2012 23 a 2/1/2012 24 a 6/1/2013 12 a 7/1/2013 56 b 1/1/2009 34 b 3/1/2009 78 ``` Every `id` has a `dt` in the form of a month, and a value. There may be months missing, but there will never be duplicate months...
Just use a subquery as the expression: ``` SELECT id, dt, val, ( SELECT SUM(val)/12 FROM mytable t2 WHERE t2.id = t.id AND t2.dt > DATEADD(mm, -12, t.dt) AND t2.dt < t.dt ) val12MonthAvg FROM mytable t ``` However with millions or rows it'...
Assumptions: * Your date format is m/d/yyyy (I used format mm/dd/yyyy)* id on this table is an FK to some other entity where id is the PK* you are meant to take the date of the chosen row, and look for that row and all rows less than 12 months older for that id, and sum the val's in those rows I'll write this in Orac...
Ways to Calculate rolling subtotal
[ "", "sql", "" ]
I want to produce a list of possible websites from two lists: ``` strings = ["string1", "string2", "string3"] tlds = ["com', "net", "org"] ``` to produce the following output: ``` string1.com string1.net string1.org string2.com string2.net string2.org ``` I've got to this: ``` for i in strings: print...
One very simple way to write this is the same as in most other languages. ``` for s in strings: for t in tlds: print s + '.' + t ```
`itertools.product` is designed for this purpose. ``` url_tuples = itertools.product(strings, tlds) urls = ['.'.join(url_tuple) for url_tuple in url_tuples] print(urls) ```
concatenate all items from two lists in Python
[ "", "python", "" ]
[Project Euler Problem 10](http://projecteuler.net/problem=10): > The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. > > Find the sum of all the primes below two million. I don't think there is any errors in my code. But it takes really a lot of time to give the answer. I've tried using PyPy because I've heard its...
The right data structure for a prime sieve is a bitset, indexed by integer value. Python doesn't have one of those built-in, but since your limit is small (only 2 million), a regular list of integers should fit in memory even though its wasteful by a factor of 30 or more (it will take about 9 MB where the equivalent bi...
The problem is this: ``` primes.remove(i*j) ``` `.remove()` is very inefficient when called on large lists, because it first has to iterate through the entire list to determine where, if any, the value is present, and then it has to iterate through a portion of the list again to shift all of the elements after the re...
Trying to solve of Project Euler #10, but code takes *a lot* of time to display output
[ "", "python", "python-2.7", "pypy", "" ]
Why does `dict(k=4, z=2).update(dict(l=1))` return `None`? It seems as if it should return `dict(k=4, z=2, l=1)`? I'm using Python 2.7 should that matter.
The `.update()` method alters the dictionary *in place* and returns `None`. The dictionary *itself* is altered, no altered dictionary needs to be returned. Assign the dictionary first: ``` a_dict = dict(k=4, z=2) a_dict.update(dict(l=1)) print a_dict ``` This is clearly documented, see the [`dict.update()` method do...
[`dict.update()`](http://docs.python.org/2/library/stdtypes.html#dict.update) method does update in place. It does not return the modified dict, but `None`. The doc says it in first line: > Update the dictionary with the key/value pairs from other, overwriting existing keys. **Return None.**
Why does dict(k=4, z=2).update(dict(l=1)) return None in Python?
[ "", "python", "python-2.7", "dictionary", "" ]