Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
At the moment I am taking an online course for python, only about 1/3 the way through and I decided to try and make something with what I've learnt so far. Running into an error now though. I am creating a text-based adventure sort of game in a house. Every room is a seperate function.
EX:
```
def hallway():
hallway_d... | in your definition of the global variables, you define rooms['first\_again'] twice.
Each time you assign a value to an element of a dict:
```
rooms['first_again'] = #something
```
you overwrite what was there previously.
It's saying
```
KeyError: 'torch'
```
because that object no longer has an element called tor... | You've assigned the `rooms['first_again']` twice.
```
rooms['first_again'] = {'torch' : False}
rooms['first_again'] = {'seen' : False}
```
Maybe it should be:
```
rooms['first_aggin'] = {}
rooms['first_again']['torch'] = False
rooms['first_again']['seen'] = False
``` | Python, can't find function | [
"",
"python",
"function",
"dictionary",
"traceback",
""
] |
I am using a python script to automate a process involving batch files. These are batch files that are used for other applications and I am not allowed to edit them.
At the end of the batch file, it prompts the following:
"Press any key to continue ..."
How do I use python to recognize when this prompt appears, and ... | Something like the following should work:
```
p = subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile],
bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while p.poll() is None:
line = p.stdout.readline()
if line.startswith('Press any key to continue'):
p.comm... | You could parse the output of the subprocess and match on the "Press any key to continue" phrase to continue on.
See this thread: [read subprocess stdout line by line](https://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line) especially what he posted as Update2
It might look like this:
```
im... | Python/Batch: Use Python to press any key to continue | [
"",
"python",
"batch-file",
"python-3.x",
"automation",
""
] |
I have a table called `Company` with a single column `CompanyNames`.
I have 17 company names in this column as:
```
Bahria Town Projacs/TPMS Habib Rafique PCA Wilsons MLDB All Orient
Extreme Engineering Prime Engineering Method Rousing co Atlas Pakistan
Bemsol EDL Deep Well Emaad In Situ
```
Now I want to insert a... | ```
insert into Company (CompanyName)
values ('')
``` | create another table with Columns ---CompanyName and row number
```
update Company1 set id=null
WHERE id % 2 = 1;
update Company2 set id=null
WHERE id % 2 != 1;
```
using even odd values to set null
May be this will help if u got what i am saying. | INSERT empty field in a table using sql query | [
"",
"sql",
""
] |
Following [this](http://zguide.zeromq.org/py%3ataskwork) example in the ØMQ docs, I'm trying to create a simple receiver. The example uses infinite loop. Everything works just fine. However, on MS Windows, when I hit CTRL+C to raise KeyboardInterrupt, the loop does not break. It seems that `recv()` method somehow ignor... | A `zmq.Poller` object seems to help:
```
def poll_socket(socket, timetick = 100):
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
# wait up to 100msec
try:
while True:
obj = dict(poller.poll(timetick))
if socket in obj and obj[socket] == zmq.POLLIN:
... | In response to the @Cyclone's request, I suggest the following as a possible solution:
```
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL);
# any pyzmq-related code, such as `reply = socket.recv()`
``` | Stop pyzmq receiver by KeyboardInterrupt | [
"",
"python",
"loops",
"break",
"termination",
"pyzmq",
""
] |
I am doing a speed test with three functions, readFile, prepDict and test. Test is simply prepDict(readFile). I am then running these many times with the timeit module.
When I increase the number of loops by a factor of 10, function prepDict takes ~100 times longer, however function test which uses function prepDict o... | The problem here is that your `prepDict` function expands the inputs. Each time you call it in sequence, it has more data to deal with. And that data grows linearly, so the 10000th run takes about 10000x as long as the first.\*
When you call `test`, it's creating a new dict each time, so the time is constant.
You can... | Your calls to `prepDict` are not happening in an isolated environment. Each call to `prepDict` modifies `tempDict` -- the keys get a little longer each time. So after 10\*\*5 calls to `prepDict` the keys in `prepDict` are rather large strings. You can see this (copiously) if you put a print statement in `prepDict`:
``... | Speed Test causing weird behavior. Multiplying time spent by 100 in one instance, only 10 in another | [
"",
"python",
"performance",
"unit-testing",
""
] |
I'm running a large query in a python script against my postgres database using psycopg2 (I upgraded to version 2.5). After the query is finished, I close the cursor and connection, and even run gc, but the process still consumes a ton of memory (7.3gb to be exact). Am I missing a cleanup step?
```
import psycopg2
con... | I ran into a similar problem and after a couple of hours of blood, sweat and tears, found the answer simply requires the addition of one parameter.
Instead of
```
cursor = conn.cursor()
```
write
```
cursor = conn.cursor(name="my_cursor_name")
```
or simpler yet
```
cursor = conn.cursor("my_cursor_name")
```
The... | Please see the *next answer* by @joeblog for the better solution.
---
First, you shouldn't need all that RAM in the first place. What you should be doing here is fetching *chunks* of the result set. Don't do a `fetchall()`. Instead, use the much more efficient `cursor.fetchmany` method. See [the psycopg2 documentatio... | psycopg2 leaking memory after large query | [
"",
"python",
"postgresql",
"psycopg2",
""
] |
How do I search and replace text in a file using Python 3?
Here is my code:
```
import os
import sys
import fileinput
print("Text to search for:")
textToSearch = input("> ")
print("Text to replace it with:")
textToReplace = input("> ")
print("File to perform Search-Replace on:")
fileToSearch = input("> ")
tempFil... | [`fileinput`](https://docs.python.org/3/library/fileinput.html) already supports inplace editing. It redirects `stdout` to the file in this case:
```
#!/usr/bin/env python3
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_t... | As [pointed out by michaelb958](https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file#comment24808323_17141040), you cannot replace in place with data of a different length because this will put the rest of the sections out of place. I disagree with the other posters suggesting you read ... | How to search and replace text in a file | [
"",
"python",
"python-3.x",
"string",
"file",
"replace",
""
] |
```
if myval == 0:
nyval=1
if myval == 1:
nyval=0
```
Is there a better way to do a toggle in python, like a nyvalue = not myval ? | Use the [`not` boolean operator](http://docs.python.org/2/reference/expressions.html#boolean-operations):
```
nyval = not myval
```
`not` returns a *boolean* value (`True` or `False`):
```
>>> not 1
False
>>> not 0
True
```
If you must have an integer, cast it back:
```
nyval = int(not myval)
```
However, the pyt... | In python, [`not`](http://docs.python.org/3/reference/expressions.html#boolean-operations) is a boolean operator which gets the opposite of a value:
```
>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False
```
And `True == 1` and `False == 0` (if you need to c... | How to "negate" value: if true return false, if false return true? | [
"",
"python",
"boolean",
"negate",
""
] |
I want to use condition in `for` loop in a succinct, clean way. Can I rewrite this
```
>>> for m in (m for m in range(10) if m < 5):
... print m
```
to avoid doubled `for m in ...`, and still have a nice one-line `for`?
```
>>> for m in range(10) if m < 5: print m
File "<stdin>", line 1
for m in range(10) ... | If we assume that you actually meant to do something more complex that would actually require the `if` statement, what you should consider doing is defining a generator to produce the relevant sequence.
e.g. instead of:
```
for m in candidates:
if isvalid(m):
... do something ...
```
Write:
```
def vali... | > This is what I don't want:
```
>>> for m in range(10):
... if m < 5:
... print m
```
That's fine, you could also do something like this:
```
>>> from functools import partial
>>> from operator import gt
>>> for m in filter(partial(gt, 5), range(10)):
print m
0
1
2
3
4
``` | Conditional generator in `for` loop | [
"",
"python",
"python-2.7",
""
] |
What's the difference between:
```
Maand['P_Sanyo_Gesloten']
Out[119]:
Time
2012-08-01 00:00:11 0
2012-08-01 00:05:10 0
2012-08-01 00:10:11 0
2012-08-01 00:20:10 0
2012-08-01 00:25:10 0
2012-08-01 00:30:09 0
2012-08-01 00:40:10 0
2012-08-01 00:50:09 0
2012-08-01 01:05:10 0
2012-08-01 01:10:... | One is a column (aka Series), while the other is a DataFrame:
```
In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [2]: df
Out[2]:
a b
0 1 2
1 3 4
```
The column 'b' (aka Series):
```
In [3]: df['b']
Out[3]:
0 2
1 4
Name: b, dtype: int64
```
The subdataframe with columns (position) in... | Another way is to select a column with the `columns` array:
```
In [5]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [6]: df
Out[6]:
a b
0 1 2
1 3 4
In [7]: df[df.columns[0]]
Out[7]:
0 1
1 3
Name: a, dtype: int64
``` | Get column by number in Pandas | [
"",
"python",
"pandas",
""
] |
I'm using pandas to do an `outer` merge on a set of about ~1000-2000 CSV files. Each CSV file has an identifier column `id` which is shared between all the CSV files, but each file has a unique set of columns of 3-5 columns. There are roughly 20,000 unique `id` rows in each file. All I want to do is merge these togethe... | I think you'll get better performance using a [`concat`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tools.merge.concat.html) (which acts like an outer join):
```
dfs = (pd.read_csv(filename).set_index('id') for filename in filenames)
merged_df = pd.concat(dfs, axis=1)
```
*This means you are doing o... | I met same error in 32-bit pytwhen using read\_csv with 1GB file.
Try 64-bit version and hopefully will solve Memory Error problem | MemoryError on large merges with pandas in Python | [
"",
"python",
"numpy",
"pandas",
"dataframe",
""
] |
i've struggled again and again on this, but can't get it to work. been on these forums for hours now... Data set:
```
Row Date AccountID Column 1
1 21/02/2013 0:30 A0M8FA1003YP .
2 21/02/2013 0:30 A0M8FA1003YP .
3 21/02/2013 0:30 A0M8FA1003YP .
4 24/09... | Query:
**[SQLFIDDLEExample](http://sqlfiddle.com/#!3/2a9e2/1)**
```
SELECT t1.*
FROM Table1 t1
WHERE t1.Date = (SELECT MAX(t2.Date)
FROM Table1 t2
WHERE t2.AccountID = t1.AccountID)
```
Result:
```
| ROW | DATE | ACCOUNTID |
---------------------------... | ```
select * from table where date in (select max(date) from table)
``` | SQL select multiple max rows where ID is same | [
"",
"sql",
""
] |
I am trying string repetition in Python.
```
#!/bin/python
str = 'Hello There'
print str[:5]*2
```
**Output**
> HelloHello
**Required Output**
> Hello Hello
Can anyone please point me in the right direction?
Python version: 2.6.4 | ```
string = 'Hello There'
print ' '.join([string[:5]] * 2)
``` | In case if you want just to repeat any string
```
"Hello world " * 2
``` | How to repeat a string with spaces? | [
"",
"python",
"string",
""
] |
The code is as follows:
```
#coding=utf-8
import re
str = "The output is\n"
str += "1) python\n"
str += "A dynamic language\n"
str += "easy to learn\n"
str += "2) C++\n"
str += "difficult to learn\n"
str += "3244) PHP\n"
str += "eay to learn\n"
pattern = r'^[1-9]+\) .*'
print re.findall(pattern,str,re.M)
```
The ... | ```
>>> import re
>>> strs = 'The output is\n1) python\nA dynamic language\neasy to learn\n2) C++\ndifficult to learn\n3244) PHP\neay to learn\n'
>>> re.findall(r'\d+\)\s[^\d]+',strs)
['1) python\nA dynamic language\neasy to learn\n',
'2) C++\ndifficult to learn\n',
'3244) PHP\neay to learn\n']
``` | you can use this, that allow digits but not followed by a closing parenthesis:
```
re.findall(r'\d+\)\s(?:\D+|\d+(?!\d*\)))*',str)
``` | How to write a regex in python to match this? | [
"",
"python",
"regex",
""
] |
In one of my testing scripts in Python I use this pattern several times:
```
sys.path.insert(0, "somedir")
mod = __import__(mymod)
sys.path.pop(0)
```
Is there a more concise way to temporarily modify the search path? | You could use a simple [context manager](https://docs.python.org/3/reference/datamodel.html#context-managers):
```
import sys
class add_path():
def __init__(self, path):
self.path = path
def __enter__(self):
sys.path.insert(0, self.path)
def __exit__(self, exc_type, exc_value, traceback)... | Appending a value to `sys.path` only modifies it temporarily, i.e for that session only.
Permanent modifications are done by changing `PYTHONPATH` and the default installation directory.
So, if by temporary you meant for current session only then your approach is okay, but you can remove the `pop` part if `somedir` i... | How to temporarily modify sys.path in Python? | [
"",
"python",
"python-import",
""
] |
I'm struggling to do this.
I have created a new database in the terminal called "somedb" using
```
CREATE DATABASE somedb
```
On my desktop I have the SQL dump downloaded from phpMyadmin: somedb.sql
I have tried:
```
somedb < /Users/myname/Desktop/somedb.sql
```
Result: ERROR 1064 (42000): You have an error in yo... | I found an SO post [here](https://stackoverflow.com/questions/4546778/how-can-i-import-a-database-with-mysql-from-terminal).
I used "source" like so:
```
SOURCE /Users/myname/Desktop/somedb.sql;
```
That worked. Great but the internet seemed to want me to use the method like so:
```
mysql -u username -p password da... | Using MAMP Pro, created "uploads" dir in MAMP and put my SQL file in there called "file.sql". Ran the query below in terminal and worked for me.
Make sure to replace brackets and and user info with no spaces after "-u" or "-p"
```
/Applications/MAMP/Library/bin/mysql -u<username> -p<root> <db_name> < /Applications/MA... | Importing a SQL db into mysql using the terminal | [
"",
"mysql",
"sql",
"import",
"terminal",
""
] |
I am reading an [article](http://www.peterbe.com/plog/uniqifiers-benchmark) about python removing duplicate element in a list.
there is a function defined as:
```
def f8(seq): # Dave Kirby
# Order preserving
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)]
```
However, i don't rea... | Firstly list comprehensions are usually easy to read, here is a simple example:
```
[x for x in seq if x != 2]
```
translates to:
```
result = []
for x in seq:
if x != 2:
result.append(x)
```
The reason why you can't read this code is because it is not readable and hacky code as I stated [in this questi... | It is called a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions), they provide a syntactically more compact and more efficient way of writing a normal for-loop based solution.
```
def f8(seq): # Dave Kirby
# Order preserving
seen = set()
return [x for x in seq ... | python list looping technique syntax | [
"",
"python",
"list-comprehension",
""
] |
I am creating a code that requires the program to time how long it runs for and then displays the time. it is basically a timer that runs in the background and I can call upon it to display how long the code has been running for. How do I do this? | You record the start time, then later on calculate the difference between that start time and the current time.
Due to platform differences, for precision you want to use the [`timeit.default_timer` callable](http://docs.python.org/2/library/timeit.html#timeit.default_timer):
```
from timeit import default_timer
sta... | This is easy in python
```
import time
start_time=time.time()
#do something
end_time=time.time()-start_time
```
The resultant `end_time` will be in seconds | How to create a timer on python | [
"",
"python",
""
] |
I read that Private class methods can't be called from outside their class.
If I have a `Car` class with a private method `__reset_odometer()`
can I say:
```
import Car
Car turboCar = Car();
turboCar.__reset_odometer();
```
`__reset_odometer()` is defined inside the Car class.
`turboCar` is an instance of the `Car`... | Calling `turboCar.__reset_odometer()` will raise an exception since, even though the method is being called on a `Car` object, it is still *outside the class definition*. Think of it this way: you aren't inside the class, writing definitions of methods when you instantiate `turboCar = Car()`.
So you can still refer to... | ```
class Car(object):
def __reset_odometer(self):
pass
def reset(self):
self.__reset_odometer() # This is valid.
turbocar = Car()
turbocar.reset()
turbocar.__reset_odometer() # This is invalid. __reset_odometer is only accessible from Car methods.
``` | What does it mean for a private method to be only accessible from its own class in python? | [
"",
"python",
"static",
"private",
""
] |
I have a table as follows:
```
CallID | CompanyID | OutcomeID
----------------------------------
1234 | 3344 | 36
1235 | 3344 | 36
1236 | 3344 | 36
1237 | 3344 | 37
1238 | 3344 | 39
1239 | 6677 | 37
1240 | 6677 | 37
```
I would like to create a ... | You can use a CASE expression with your aggregate to get a total based on the `outcomeId` value:
```
select companyId,
sum(case when outcomeid = 36 then 1 else 0 end) SalesCount,
sum(case when outcomeid <> 36 then 1 else 0 end) NonSalesCount
from yourtable
group by companyId;
```
See [SQL Fiddle with Demo](http:/... | Something like this:
```
SELECT companyId,
COUNT(CASE WHEN outcomeid = 36 THEN 1 END) SalesCount,
COUNT(CASE WHEN outcomeid <> 36 THEN 1 END) NonSalesCount
FROM
yourtable
GROUP BY
companyId
```
should work -- `COUNT()` counts only not null values. | SQL: Count() based on column value | [
"",
"sql",
"count",
""
] |
I searched it on SO, but I couldn't get a right answer.
```
Student
------------------
rollno int PK
name varchar(20)
class varchar(20)
```
The other table is
```
Marks
-----------------
rollno FK
sub1 int
sub2 int
sub3 int
sub4 int
sub5 int
```
`sub1`, `sub2`, etc. contain the marks of subjects. Now I... | ```
select rollno,
case when sub1 < 35 then 0 else 1 end +
case when sub2 < 35 then 0 else 1 end +
case when sub3 < 35 then 0 else 1 end +
case when sub4 < 35 then 0 else 1 end +
case when sub5 < 35 then 0 else 1 end +
end
as [Count]
from student,marks where count > 2
``` | You can use `CASE WHEN` and sum the fields that has more than 35.
```
SELECT s.rollno, s.name, s.class
FROM Student s join Marks m on (s.rollno = m.rollno)
where (CASE WHEN sub1>35 THEN 1 ELSE 0 END +
CASE WHEN sub2>35 THEN 1 ELSE 0 END +
CASE WHEN sub3>35 THEN 1 ELSE 0 END +
CASE WHEN sub4>35 THEN 1 ELSE 0 E... | SQL query to display data from multiple tables | [
"",
"sql",
""
] |
Consider:
```
>>> a = {'foo': {'bar': 3}}
>>> b = {'foo': {'bar': 3}}
>>> a == b
True
```
According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries.
What is actually happening here? Is Python recursively checking each element of the dicti... | Python is recursively checking each element of the dictionaries to ensure equality. See the [C `dict_equal()` implementation](http://hg.python.org/cpython/file/6f535c725b27/Objects/dictobject.c#l1839), which checks each and every key and value (provided the dictionaries are the same length); if dictionary `b` has the s... | From [docs](http://docs.python.org/2/reference/expressions.html#not-in):
> Mappings (dictionaries) compare equal if and only if their sorted
> (key, value) lists compare equal .[[5]](http://docs.python.org/2/reference/expressions.html#id24) Outcomes other than equality are
> resolved consistently, but are not otherwis... | What does the == operator actually do on a Python dictionary? | [
"",
"python",
"dictionary",
""
] |
I know how to create a trigger that checks if a group of columns has one and only one NON NULL for one table but i would like to reuse the code because i will have some other tables with the same requirements. Any recommendations? I was thinking of maybe a trigger that passes it's name of the columns to be checked and ... | > a trigger that checks if a group of columns has one and only one NON
> NULL for one table
This would be a case for a table-level check constraint rather than a trigger.
Example with the constraint on the first 3 columns:
```
CREATE TABLE tablename (
a int,
b int,
c int,
d text,
CHECK ((a is not null and b is ... | That is not a case for a trigger. Just a check constraint:
```
create table t (
a integer,
b text,
c boolean
check ((
(a is not null)::integer
+ (b is not null)::integer
+ (c is not null)::integer
) = 1)
);]
```
In instead of checking every possible combination just use... | Create trigger that ensures there is one and only one NON-NULL in a set of column and reuse it for other tables | [
"",
"sql",
"postgresql",
"plpgsql",
""
] |
I've decided not to waste my summer and start learning python. I figured I'd start learning looping techniques so I wanted to start with a basic list of numbers, aka, write a for loop that will generate the numbers 1 - 10.
This is what I have:
```
def generateNumber(num):
i=0
for i in range(num):
return i
re... | Trying to be consistent with what you first tried, you could do something like this
```
def generateNumber(num):
mylist = []
for i in range(num+1):
mylist.append(i)
return mylist
x = generateNumber(10)
```
but, you could, instead just say,
```
x = range(10+1) # gives a generator that will mak... | It might help to implement this with the ability to specify a range:
```
def generateNumber(low, high):
'''returns a list with integers between low and high inclusive
example: generateNumber(2,10) --> [2,3,4,5,6,7,8,9,10]
'''
return range(low, high+1)
```
This can also be done with the built-in range ... | Python Sequence of Numbers | [
"",
"python",
"list",
"sequence",
""
] |
So I have two dictionaries:
```
dic1 = {1.0: 9.0, 3.0: 33.0, 5.0: 13.0}
dic2 = {1.0: 3.4, 3.0: 88.9, 4.0: 73.0, 5.0: 9.0}
```
The keys in each are the ID number, the values in dic1 are rating and the values in dic2 are cost.
What I want is a way to associated each ID number with both its cost and rating and in the p... | Try this, which will work on old versions of Python (older than 2.7):
```
dic3 = {}
for k in dic1.viewkeys() & dic2.viewkeys():
dic3[k] = (dic1[k], dic2[k])
```
Or this, an approach that will work on recent versions of Python (>= 2.7 but < 3.0), using dictionary comprehensions:
```
dic3 = { k : (dic1[k], dic2[k]... | ```
dic3 = {k : (v1, dic2[k]) for k, v1 in dic1.items() if k in dic2}
``` | Match keys from two dictionaries, and make new dictionary with matched key and two associated values | [
"",
"python",
"python-2.7",
"dictionary",
""
] |
I am writing a very simple function that, given a string as input, parses the string into sentences, reverses the words of each sentence, and returns the reversed sentences but in the given sentence order. I am struggling with the `string.split()` and `string.join()` built-in methods and am getting a TypeError when I r... | Try
```
>> str = 'a1 b2'
>> ' '.join(x[::-1] for x in str.split())
'1a 2b'
```
In function form:
```
def reverseSentences(str):
return ' '.join(x[::-1] for x in str.split())
```
Notice that `x[::-1]` is way faster than `reversed()` ([Reverse a string in Python](https://stackoverflow.com/questions/931092/reverse-a... | `item.split(' ').reverse()` does not return the list, rather it does the reverse in place. So, your join is same as:
```
string.join(None, ' ')
```
Clearly a problem. You should rather use `reversed()` function:
```
string.join(reversed(item.split(' ')), ' ')
```
And rather than `string.join` function, use the meth... | TypeError when using string.join() in Python | [
"",
"python",
"string",
""
] |
I identify Internet **traffic flows** by their **5-tuple** (src IP, dst port, sport, dport, transport protocol number) and I would like turn this 5-tuple into a much more compact **alphanumeric ID** for internal use in my script.
What choices do I have in Python?
I read that the built-in function `hash` is only **con... | Just choose your own hash function:
```
import hashlib
hash = hashlib.md5()
t = (1, 2, 3, 4, 5) # whatever
t_as_string = str(t)
hash.update(t_as_string)
print hash.hexdigest()
```
You can use any of the functions in [hashlib](http://docs.python.org/2/library/hashlib.html). And since this isn't a security issue, it do... | The following Python Hash function, by Ewen Cheslack-Postava, shall remain consistent accross several OS and CPU :
<https://pypi.python.org/pypi/pyhashxx/> | identify 5-tuple flows by hash value in Python | [
"",
"python",
"hash",
""
] |
I'll start by posting my query...
```
SELECT [copyright status],
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
GROUP BY [copyright status]
UNION
SELECT [lw status],
sum(IIF(layer='key info',1,0)) AS [Key In... | The number of columns has to be equal for all parts of the `union`. You could just add a `null` first column for your summary row:
```
SELECT null,
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
``` | You removed `lw status` and didn't select anything:
```
UNION
SELECT 'SUM',
sum(IIF(layer='key info',1,0)) AS [Key Info],
sum(IIF(layer='approaches',1,0)) AS [Approaches],
sum(IIF(layer='research',1,0)) AS [Research]
FROM resources
UNION
<Next Query>
``` | SQL - Sum within UNION query | [
"",
"sql",
"ms-access",
"ms-access-2003",
""
] |
I have a project with multiple package dependencies, the main requirements being listed in `requirements.txt`. When I call `pip freeze` it prints the currently installed packages as plain list. I would prefer to also get their dependency relationships, something like this:
```
Flask==0.9
Jinja2==2.7
Werkzeug==... | You should take a look at [`pipdeptree`](https://pypi.python.org/pypi/pipdeptree):
```
$ pip install pipdeptree
$ pipdeptree -fl
Warning!!! Cyclic dependencies found:
------------------------------------------------------------------------
xlwt==0.7.5
ruamel.ext.rtf==0.1.1
xlrd==0.9.3
openpyxl==2.0.4
- jdcal==1.0
py... | # Warning: py2 only / abandonware
[`yolk`](https://pypi.python.org/pypi/yolk/0.4.3) can display dependencies for packages, provided that they
* were installed via `setuptools`
* came with metadata that includes dependency information
```
$ yolk -d Theano
Theano 0.6.0rc3
scipy>=0.7.2
numpy>=1.5.0
``` | Is there any way to show the dependency trees for pip packages? | [
"",
"python",
"pip",
"requirements.txt",
""
] |
I am trying to follow [this tutorial](http://django-tinymce.readthedocs.org/en/latest/installation.html#testing) on getting tinymce working with django and zinnia. It's not working, so I am attempting to do "Testing" but get this error when I run `django-admin.py syncdb`. How do I fix this?
```
$django-admin.py syncdb... | I found out the django-tinymce documentation is outdated, i.e. partially wrong.
What I discovered is that different versions of tinymce and django-tinymce packages are not compatible.
I solved it adding some variables to my project/settings.py and altering the tinymce directory and file names.
django-tinymce urls.py... | A simple shutdown of the terminal, then restarting the app again fixed it for me (without needing to configure anything extra). I followed the instructions [here](http://django-tinymce.readthedocs.org/en/latest/installation.html):
1. pip install django-tinymce
2. Add `tinymce` to the INSTALLED\_APPS of 'settings.py'
3... | Django-Tinymce Import Error | [
"",
"python",
"django",
"tinymce",
"django-tinymce",
""
] |
I have a `pandas.DataFrame` that I wish to export to a CSV file. However, pandas seems to write some of the values as `float` instead of `int` types. I couldn't not find how to change this behavior.
Building a data frame:
```
df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'], dtype=int)
x = pandas.... | The answer I was looking for was a slight variation of what @Jeff proposed in his answer. The credit goes to him. This is what solved my problem in the end for reference:
```
import pandas
df = pandas.DataFrame(data, columns=['a','b','c','d'], index=['x','y','z'])
df = df.fillna(0)
df = df.astype(int)
df.to_csv('test.... | This is a ["gotcha" in pandas (Support for integer NA)](http://pandas.pydata.org/pandas-docs/stable/gotchas.html#support-for-integer-na), where integer columns with NaNs are converted to floats.
> This trade-off is made largely for memory and performance reasons, and also so that the resulting Series continues to be “... | Python pandas: output dataframe to csv with integers | [
"",
"python",
"csv",
"dataframe",
"pandas",
""
] |
I want to get value from string before I replace the string with other value in Python using regex, but I don't know how to do it.
For example:
Original String:
> This is 123 and that is ABC.
>
> This is 456 and that is OPQ.
I want to extract 123 and 456 and then replace '*This is 123*' and '*This is 456*'to '*That... | Something like this?
```
>>> strs = "This is 123 and that is ABC."
>>> match = re.search(r'.*?(\d+)',strs)
>>> rep = match.group(0)
>>> num = match.group(1)
>>> "{}: {}".format(num, re.sub(rep,'That was XYZ',strs))
'123: That was XYZ and that is ABC.'
>>> strs = 'This is 456 and that is OPQ.'
>>> match = re.search(r'... | ```
string = "This is 123 and that is ABC."
match = re.search("\d+", string).group()
string = match+":"+string.replace(match, "XYZ")
```
Considering the match happens for sure, else you can put an if condition around match | Get value before replace in Python Regex | [
"",
"python",
"regex",
""
] |
i have 3 tables. A, B, C as shown.
```
Table A | Table B | Table C
---------------------- | ------------------------- |--------------------------------
StudentId StudentName | SubjectId SubjectName | StudentId SubjectId Marks
1 Jack | 101 History ... | This [Link](http://sqlfiddle.com/#!3/e6a42/10) will give you what exactly you want. Below is the select Query.
```
select D.StudentName,D.subjectName,Isnull(C.marks,0) as Marks from TableC C
Right Join
(select * from TableA A,TableB B
) D on C.studentID = D.studentID and C.subjectID = D.subjectID
``` | Try:
```
SELECT a.StudentName, b.SubjectName, c.Marks
FROM A
LEFT JOIN C
ON A.StudentID = C.StudentID
LEFT JOIN B
ON B.SubjectID = C.SubjectID
``` | SQL to get all values from look up and corresponding values from master table | [
"",
"sql",
"join",
""
] |
I have this string:
```
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000
```
I want to be able to remove the 'eth0' part from this string, but it may not always be eth0! Its positioning after the "2: " part is consistent though.
Any ideas?
edit:
The overall idea would be to isolate t... | Edit 2: New answer for the updated question.
Use `re.findall(r'\d+: (.*?):', string)`
```
import re
string = """
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 brd 127.255.255.255 scope host lo
2: eth0: <BROADCAST,MUL... | It is not clear if the 2 is a fixed part. You can try variations around that:
```
import re
re.sub("(\d*:)[^:]*:(.*)", "\\1\\2", "2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000")
```
Result:
```
'2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000'
```
**EDIT:*... | I want to be able to isolate a non-specific string from a list using python | [
"",
"python",
"regex",
"string",
""
] |
I have a table with approximately 2.5 million rows that I am thinking about moving into a much larger table, 35 million rows, with a boolean flag set on the original 2.5 million.
If I wanted to run lots of queries against the 2.5 million records in the new larger table, would adding an index be useful / not cause a fu... | Perhaps look at using a [partial index](http://www.postgresql.org/docs/8.0/static/indexes-partial.html).
**From docs**
> A partial index is an index built over a subset of a table; the subset
> is defined by a conditional expression (called the predicate of the
> partial index). The index contains entries for only th... | I would be looking at partitioning, if you have a substantial proportion of the table that you want to access efficiently. | Indexing and performance Implications of moving small table into big table | [
"",
"sql",
"postgresql",
"indexing",
""
] |
I have a table with over 1000 tables (e.g Customers).
I have a query requiring details of a known list of customers (e.g by CustomerID - 1,79,14,100,123)
The IN() function is what I would like to use for the query.
I know to find customers that match the list, I would write:
```
SELECT * FROM Customers
WHERE Custom... | You can use a derived table or temporary table for example to hold the list of `CustomerId` then find the non matching ones with `EXCEPT`.
The below uses a [table value constructor](http://technet.microsoft.com/en-us/library/dd776382.aspx) as a derived table (compatible with SQL Server 2008+)
```
SELECT CustomerId
FR... | In case anyone stumbles upon this question and is wondering how to do this in PostgreSQL
```
VALUES (1),(79),(14),(100),(123) EXCEPT ALL SELECT "CustomerId" from "Customers";
``` | SELECT those not found in IN() list | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Suppose I had a list where each list element was made up of three parts like:
```
[[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0], [0, 0, 4], [0, 1, 3], [0, 2... | You could use the `.count` method.
```
two_zeros = [x for x in lst if x.count(0) == 2]
one_zero = [x for x in lst if x.count(0) == 1]
```
If you wanted to be really clever, you could do the whole thing in a single loop with a collections.defaultdict:
```
d = collections.defaultdict(list)
for sublist in lst:
d[su... | Use `count()`.
From `help`:
```
count(...)
L.count(value) -> integer -- return number of occurrences of value
```
Example Code (Part of your list) -
```
>>> startList = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1]]
>>> for el... | check two values in list element python | [
"",
"python",
""
] |
I'm a little new to the site and have been teaching myself Microsoft SQL over the past week to cover for work and was hoping you guys could help. I have to pull all active patients for a type of group and the only way to tell if patients are active is if there is not a date discharge for the patient. My code is the fol... | try `p.date_discharged IS NULL` you've aliased your table name, and used the alias `a` everywhere except there, as well as used the wrong column name. The `invalid column name` was a good hint. | Try this :
```
select
p.clinic_id,
p.program_id,
p.protocol_id,
p.patient_id,
p.date_discharged
from patient_assignment p
where p.program_id = 'MH'
and p.protocol_id = 'grp'
and date_discharged IS NULL
```
You missed date\_discharged with date\_discharge. | Pulling Null date (Microsoft SQL) | [
"",
"sql",
"sql-server",
"null",
""
] |
I am getting an error when running a python program:
```
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 110, in <module>
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 27, in __init__
File "C:\Program Files... | You are trying to run a Python 2 codebase with Python 3. [`xrange()`](https://docs.python.org/2/library/functions.html#xrange) was renamed to [`range()`](https://docs.python.org/3/library/functions.html#func-range) in Python 3.
Run the game with Python 2 instead. Don't try to port it unless you know what you are doing... | add `xrange=range` in your code :) It works to me. | NameError: global name 'xrange' is not defined in Python 3 | [
"",
"python",
"python-3.x",
"range",
"runtimeexception",
"xrange",
""
] |
So here is a code i have written to find palindromes within a word (To check if there are palindromes within a word including the word itself)
Condition: spaces inbetween characters are counted and not ignored
Example: A but tuba is a palindrome but technically due to spaces involved now it isn't. so that's the criteri... | Your solution seems a bit complicated to me. Just look at all of the possible substrings and check them individually:
```
def palindromes(text):
text = text.lower()
results = []
for i in range(len(text)):
for j in range(0, i):
chunk = text[j:i + 1]
if chunk == chunk[::-1]:... | If you like the recursive solution, I have written a recursive version. It is also intuitive.
```
def palindrome(s):
if len(s) <= 1:
return s
elif s[0] != s[-1]:
beginning_palindrome = palindrome(s[:-1])
ending_palindrome = palindrome(s[1:])
if len(beginning_palindrome) >= len(ending_palindrome):
... | Python: search longest palindromes within a word and palindromes within a word/string | [
"",
"python",
"palindrome",
""
] |
I have a query that returns a few columns and some information. I want to hardcode a list, and have each row returned each value from my list.
So, currently my `SELECT` is returning, for example,
```
ID Name Value
1 Mike 404
2 John 404
```
And lets say, for example, I wish to add a column to my `SELECT... | One way is using `UNION ALL` and [`CROSS APPLY`](https://stackoverflow.com/questions/1139160/when-should-i-use-cross-apply-over-inner-join) to join them with your rows:
```
SELECT p.ID, p.Name ,p.Value, x.Col AS Manager
FROM dbo.Persons p
CROSS APPLY (SELECT Col FROM (SELECT 'Steve' UNION ALL SELECT 'Bill')AS T(Col))X... | This query will give you the exact result as you want
```
select ID,Name,Value, Manager from Test
cross join
(select 'Bill' Manager
union
select 'Steve' Manager) t1
``` | Creating a superset in SQL Server | [
"",
"sql",
"sql-server",
"database",
"sql-server-2005",
"select",
""
] |
I have 10 lineedit widget that design by `qt-designer` and i define signal&slot in my code,
my problem is with repeating same signal&slot 10times in my code,
something like this:
```
self.ui.descCode_lineEdit_1.cursorPositionChanged.connect(lambda: self.Desc(1))
self.ui.Desc_lineEdit_1.editingFinished.connect(lambda: ... | the problem here lies within the lambda, and the i. Later on only the last value of i will be saved. Hence try it like this:
**Minimal *not working* example**:
```
>>> def test(a):
... print a
... x = []
... for i in range(2):
... x.append(lambda: test(i))
... x
14: [<function <lambda> at 0x027FBA30>, <functi... | It's probably easier to use a data structure.
```
fields = [QLineEdit() for x in range(10)]
for i in range(10):
fields[i].cursorPositionChanged.connect(lambda: self.Desc(i+1))
fields[i].editingFinished.connect(lambda:self.DescRate(i+1))
``` | repeated signal and slot for same widets in pyqt4 | [
"",
"python",
"python-3.x",
"pyqt4",
""
] |
I have a MSSQL Database named "Database". Now when I am trying to rename it using query shown below,
```
USE master;
GO
ALTER DATABASE Database
Modify Name = Database01
GO
```
It gives me this error message:
> Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'Database'.
But this query works fine for other d... | If you "quote" the table name it should work. The default quote characters are square brackets [], so:
```
USE master;
GO
ALTER DATABASE [Database]
Modify Name = Database01
GO
``` | Instead of using the the Long code you Can just use the System built-in Stored Procedure -`sp_renamedb'oldDBName','NewDBName'` | How to rename a MSSQL Database that has name "Database"? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2005",
""
] |
I'm trying to run multiple DDLs (around 90) on an SQL Server.
The DDLs don't contain any changes to tables, only view, stored procedures, and functions. The DDLs might have inter-dependencies between them, one STP that calls another, for example.
I don't want to start organizing the files in the correct order, becaus... | We actually do something like this to deploy our database scripts to production. We do this in an application that connects to our databases. To add to the complication, we also have 600 databases that should have the same schema, but don't really. Here's our approach:
1. Merge all our scripts into one big file. Injec... | Organize the files in the correct order, test the procedure on a test environment, have a validation and acceptance test, then run it in production.
While running DDL in a transaction may seem possible, in practice is not. There are many DDL statements that don't mix well with transactions. You must put the applicatio... | SQL Server Multiple DDLs Ignoring Order And in a Single Transaction | [
"",
"sql",
"sql-server",
"t-sql",
"ddl",
""
] |
I have a Table, Table A, and in table A I have Field A. There are values in field A like the following:
```
Street A
Street B
,Street C
Street D
etc
```
I would like to know if there is any SQL that will allow me to either remove the 1st character from Field A where there is a ,.
I have know idea where to start I ca... | ```
UPDATE YourTable
SET YourCol = SUBSTRING(YourCol, 2, 0+0x7fffffff)
WHERE YourCol LIKE ',%'
``` | If you'd rather not care about the length, STUFF is the right candidate :
```
UPDATE YourTable
SET YourCol = STUFF(YourCol, 1, 1, '')
WHERE YourCol LIKE ',%'
``` | How to remove the 1st character from a column in SQL Server | [
"",
"sql",
"sql-server-2008",
""
] |
I need help in inserting a character inside a string, e.g.:
`031613 05:39 AM`
The output should be:
`03/16/13 05:39 AM` | You can use `STUFF`
```
DECLARE @String NVARCHAR(20) = '031613 05:39 AM'
SELECT STUFF(STUFF(@String,3,0,'/'),6,0,'/')
```
[Fiddle](http://sqlfiddle.com/#!3/d41d8/15786) | How about using [SUBSTRING](http://msdn.microsoft.com/en-us/library/ms187748.aspx)?
```
DECLARE @String VARCHAR(50) = '031613 05:39 AM'
SELECT @String,
SUBSTRING(@String,1,2) + '/' + SUBSTRING(@String,3,2) + '/' + SUBSTRING(@String,3,2) + SUBSTRING(@String,7,LEN(@String)-6)
```
## [SQLFiddle DEMO](http://sq... | How to insert character in between a string in SQL Server 2008? | [
"",
"sql",
"sql-server",
"string",
""
] |
I am trying to figure out some ways to accomplish this script. I import an excel sheet and then I need to populate 5 different tables based on this excel sheet. However for this example I just need help with the initial loop then I think I can work through the rest.
```
select distinct Department from IPACS_New_Master... | There are two approaches you can use without a loop.
1) If you have candidate keys in your source (department name) just join your source table back to the table you inserted
e.g.
```
INSERT INTO Department
(Name)
SELECT DISTINCT Dep1
FROM SOURCE;
INSERT INTO Functions
(
Name,
DepartmentID)
SELECT DISTINCT... | Assuming you have tables set up with an IDENTITY field set for the Primary Key, you can populate each successive table's foreign key by joining to the previous table and the source table, something like:
```
INSERT INTO Table1
SELECT DISTINCT Department
FROM SourceTable
GO
INSERT INTO Table2
SELECT DISTINCT b.Deptart... | SQL Loop/Crawler | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
So I came across a problem/question yesterday.
I am building a chat (with AJAX) and use two tables:
`TABLE users -> 'name', 'username', 'password', 'time'`
`TABLE messages -> 'sendFrom', 'sendTo', 'message', 'time'`
So an example message now would be
`'foo' | 'bar' | 'Hey, how are you?' | 130611134427611`
I... | I am answering my own question, since I consider what people might be looking for is a [VIEW](http://www.sqlite.org/lang_createview.html "CREATE VIEW (SQLite)").
First, define that query like this:
```
CREATE VIEW MyViewTable
AS
SELECT ...
FROM ...
...
...;
```
Now you can use that view (which is a seppa... | I am not sure but it does look as if you want a [view](http://www.sqlite.org/lang_createview.html "CREATE VIEW (SQLite)").
Define that query like this:
```
CREATE VIEW MyMessageView
AS
SELECT ...
FROM ...
...
```
Now you can use that view in any context where an ordinary table can be used: in a FROM clause, in a JOI... | Use same alias for union query SQL | [
"",
"sql",
"sqlite",
""
] |
I've got a simple class from which I create two objects. I now want to print the name of the object from within the class. So something like this:
```
class Example:
def printSelf(self):
print self
object1 = Example()
object2 = Example()
object1.printSelf()
object2.printSelf()
```
I need this to print:
... | `object1` is just an identifier(or variable) pointing to an instance object, objects don't have names.
```
>>> class A:
... def foo(self):
... print self
...
>>> a = A()
>>> b = a
>>> c = b
>>> a,b,c #all of them point to the same instance object
(<__main__.A instance at 0xb61ee8ec>, <__ma... | The object does not have a "name". A variable which refers to the object is not a "name" of the object. The object cannot know about any of the variables which refer to it, not least because variables are not a first-class subject of the language.
If you wish to alter the way that object prints, override either `__rep... | How to get the object name from within the class? | [
"",
"python",
"class",
"object",
""
] |
I have to make an `UNION` stament like this more or less:
```
select [table_name], name, address
from Employees
where [my_condition]
UNION
select [table_name], name, address
from Employees_history
where [my_condition]
```
The data retrieved will be in either Employees or Employees\_history but not in both tables.
... | ```
SELECT 'Employees' AS [table_name],
name,
address
FROM Employees
WHERE [my_condition]
UNION ALL
SELECT 'Employees_history' AS [table_name],
name,
address
FROM Employees_history
WHERE [my_condition]
```
I use `UNION ALL` rather than `UNION` as there will be no duplicates across the... | You can append a new field as shown below:
```
select [table_name], name, address, 'Employees'
from Employees
where [my_condition]
UNION
select [table_name], name, address, 'History'
from Employees_history
where [my_condition]
```
You can also use an `alias` as Martin has shown in his answer. | How to get table name within a 'select' statement in SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am very new to Python (and web scraping). Let me ask you a question.
Many website actually do not report its specific URLs in Firefox or other browsers. For example, Social Security Admin shows popular baby names with ranks (since 1880), but the url does not change when I change the year from 1880 to 1881. It is con... | You can still use `urllib`. The button performs a POST to the current url. Using Firefox's [Firebug](https://getfirebug.com/) I took a look at the network traffic and found they're sending 3 parameters: `member`, `top`, and `year`. You can send the same arguments:
```
import urllib
url = 'http://www.ssa.gov/cgi-bin/po... | I recommend using [Scrapy](https://scrapy.readthedocs.org). It's a very powerful and easy-to-use tool for web-scraping. Why it is worth trying:
1. Speed/performance/efficiency
> Scrapy is written with Twisted, a popular event-driven networking
> framework for Python. Thus, it’s implemented using a non-blocking ... | a (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib | [
"",
"python",
"cgi",
"web-scraping",
"firebug",
"urllib",
""
] |
I wanted to match the numeric values of a string:
```
1,000 metric tonnes per contract month
Five cents ($0.05) per tonne
Five cents ($0.05) per tonne
1,000 metric tonnes per contract month
```
My current approach:
```
size = re.findall(r'(\d+(,?\d*).*?)', my_string)
```
What I get with my approach:
```
print size... | Something like this:
```
>>> import re
>>> strs = """1,000 metric tonnes per contract month
Five cents ($0.05) per tonne
Five cents ($0.05) per tonne
1,000 metric tonnes per contract month"""
>>> [m.group(0) for m in re.finditer(r'\$?\d+([,.]\d+)?', strs)]
['1,000', '$0.05', '$0.05', '1,000']
```
Demo : <http://rubu... | `re,findall()` returns a tuple of all the capturing groups for each match, and each set of normal parentheses generates one such group. Write your regex like this:
```
size = re.findall(r'\d{1,3}(?:,\d{3})*(?:\.\d+)?', my_string)
```
**Explanation:**
```
\d{1,3} # One to three digits
(?:,\d{3})* # Optional tho... | Regex for matching string Python | [
"",
"python",
"regex",
""
] |
I am developing an iphone app which uses Sqlite as its backend. I want to implement search functionality in my app and I used sql query for that. I want to implement the searching in a case sensitive manner.I used the following query or fetching data.
```
SELECT data FROM table where data LIKE 'A%' ORDER BY ID ASC
```... | ```
SELECT * FROM a WHERE name glob 'A*'
```
see sql fiddle
<http://sqlfiddle.com/#!7/18215/1> | I'm not sure if you could use a `PRAGMA` statement in your environment, but there is an option as follows:
```
PRAGMA case_sensitive_like = true;
```
> The PRAGMA statement is an SQL extension specific to SQLite and used
> to modify the operation of the SQLite library. When
> case\_sensitive\_like is enabled, case be... | Case sensitive searching | [
"",
"sql",
"sqlite",
"search",
"wildcard",
"nspredicate",
""
] |
I've inherited some `<cough>`ugly`</cough>` code that contains a rather unwieldy SQL statement that hits an Informix database. This code computes various parts of the SQL, and does lots of string concatenation, but I had it spit out what it actually sends to Informix and tried using that in my SQL query tool. It is fun... | The Informix-style OUTER join is not simply a short cut for LEFT OUTER JOIN, but it is a moderate approximation to consider it as such. There are a number of details why it is not that simple.
There's an online explanation for [Informix OUTER Joins](https://web.archive.org/web/20161118035919/http://savage.net.au/SQL/o... | For information on Informix outer syntax:
<http://pic.dhe.ibm.com/infocenter/idshelp/v117/index.jsp?topic=%2Fcom.ibm.sqls.doc%2Fsqls.htm>
IBM's funky documentation does not allow direct links, so search for OUTER in there.
This is for Informix 11.7, not sure what version you are using.
Essentially the outer tables w... | How was `outer` used in Informix-flavored SQL? | [
"",
"sql",
"informix",
""
] |
Is there a method to find all functions that were defined in a python environment?
For instance, if I had
```
def test:
pass
```
`some_command_here` would return `test` | You can use [inspect](http://docs.python.org/2/library/inspect.html) module:
```
import inspect
import sys
def test():
pass
functions = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isfunction)]
print functions
```
prints:
```
['test']
``` | You can use `globals()` to grab everything defined in the global scope of the file, and `inspect` to filter the objects you care about.
```
[ f for f in globals().values() if inspect.isfunction(f) ]
``` | Finding All Defined Functions in Python Environment | [
"",
"python",
"function",
""
] |
When I try to use a link in my Django template from `/appname/index/` to get to `/appname/detail/###` I am instead getting to `/appname/index/detail/###` which is not what I'm trying to get so my app can't find it in the urlconf of course.
First the urls.py line for the detail page
```
url(r'detail/(?P<jobID>\d+)/$',... | Add `/` at start in `href`:
```
<a href="/appname/detail/{{ job.id }}/">{{ job.name }}</a>
```
And for the `url` tag to work you need to do it like this:
```
<a href="{% url 'appname.views.detail' jobID=job.id %}">{{ job.name }}</a>
``` | From my experience, as long as you have defined the url of the page the `href` tag should lead to in `urls.py`, include the absolute path in the format below.
```
Site name: yyyy.com
Url of page to redirect to in urls.py: yyyy.com/signup/
Sample link: <a href="/signup/">Signup</a>
```
You will notice that what goes ... | how to use the href attribute in django templates | [
"",
"python",
"django",
"url",
"href",
""
] |
I have a query in `SQL`, I have to get a date in a format of `dd/mm/yy`
Example: `25/jun/2013`.
How can I `convert` it for `SQL server`? | I'm not sure there is an exact match for the format you want. But you can get close with [`convert()`](http://msdn.microsoft.com/en-us/library/ms187928.aspx) and style `106`. Then, replace the spaces:
```
SELECT replace(convert(NVARCHAR, getdate(), 106), ' ', '/')
``` | There are already [multiple answers and formatting types](https://msdn.microsoft.com/en-us/library/ms187928.aspx) for SQL server 2008. But this method somewhat ambiguous and it would be difficult for you to remember the number with respect to Specific Date Format. That's why in next versions of SQL server there is bett... | Convert Date format into DD/MMM/YYYY format in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012",
""
] |
I Have add some wrong `task` to a `celery` with redis `broker`
but now I want to remove the incorrect `task` and I can't find any way to do this
Is there some commands or some api to do this ? | I know two ways of doing so:
1) Delete queue directly from broker. In your case it's Redis. There are two commands that could help you: **llen** (to find right queue) and **del** (to delete it).
2) Start celery worker with **--purge** or **--discard** options. Here is help:
```
--purge, --discard Purges all waiti... | The simplest way is to use the `celery control revoke [id1 [id2 [... [idN]]]]` (do not forget to pass the `-A project.application` flag too). Where id1 to idN are task IDs. However, it is not guaranteed to succeed every time you run it, for valid reasons...
Sure Celery has API for it. Here is an example how to do it f... | how to remove task from celery with redis broker? | [
"",
"python",
"celery",
"celery-task",
"celeryd",
""
] |
Using the `Twitter API`, I get my rate\_limiting information with the code I've written below:
```
def limit():
twitter = Twitter(auth=OAuth('....'))
g = twitter.application.rate_limit_status()
print g
```
This is great, but I get a big jumble like this:
```
{u'rate_limit_context': {u'access_token': u'....'}, u'reso... | Without knowing the details of the Twitter API, it looks like the `rate_limit_status()` method is returning a `dictionary` of `dictionaries`. So you should be able to get at the data you want by looking up the right keys:
```
>>> g = eval("{u'rate_limit_context': {u'access_token': u'....'}, u'resources': ... ")
>>> g[... | This problem has been frustrating me for the last 72 hours. First, we should clarify here - you are using the Tweepy library, correct? I had some code using the twitter package found at the top of the list in PyPI, but it doesn't appear that they made the upgrade from API 1.0 to API 1.1, nor does the #2 in popularity p... | need specific rate limiting number twitter api python | [
"",
"python",
"twitter",
"tweets",
"rate",
""
] |
I am trying to write a query to get count of the records from my database which has happened in a specific day which is in the table. My query looks like this:
```
SELECT
count(id),
A.status,
YEAR(A.dateRequested),
MONTHNAME(A.dateRequested),
WEEK(A.dateRequested),
DAYNAME(A.dateRequested)
FROM ASSESSMENT ... | You're using `count(id)` without a `group by`. The way MySQL works is that this translates to an empty `group by`. You'll get the `count(id)` for the entire table, and the other fields will be set to one random row.
To list the number of Pending records by weekday:
```
SELECT DAYNAME(A.dateRequested)
, count(i... | 1. Week 16 is the week of the year, not the week of the month.
2. Your query is NOT querying for items happened today. It is looking for items which have a pending status. Change it to something like:
WHERE A.dateRequested = '2013-06-20'
3. You are using COUNT function which will return only one result unless you G... | MySQL query to get a list of records depending on year/month/day | [
"",
"mysql",
"sql",
""
] |
I've got a list of lists containing integers sorted at the moment by the sum of the contents:
```
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0], [0, 0, 4], ... | Is this what you're after...
```
>>> l = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0], [0, 0, 4], [0, 1, 3], [0, 2, 2], [0, 3, 1], [0, 4, 0], [1, 0, 3], [1... | Use your sorting criteria function as `key` in the sorting.
```
input_list = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0], [0, 0, 4], [0, 1, 3], [0, 2, 2],... | Sort a list of lists containing integers | [
"",
"python",
""
] |
I believed that `hash()` function works the same in all python interpreters. But it differs when I run it on my mobile using [python for android](https://code.google.com/p/python-for-android/). I get same hash value for hashing strings and numbers but when I hash built-in data types the hash value differs.
**PC Python... | for old python (at least, my Python 2.7), it seems that
```
hash(<some type>) = id(<type>) / 16
```
and for CPython `id()` is the address in memory - <http://docs.python.org/2/library/functions.html#id>
```
>>> id(int) / hash(int)
16 ... | `hash()` is randomised by default each time you start a new instance of recent versions (Python3.3+) to [prevent dictionary insertion DOS attacks](http://mail.python.org/pipermail/python-announce-list/2012-March/009394.html)
Prior to that, `hash()` was different for 32bit and 64bit builds anyway.
If you want somethin... | Why doesn't Python hash function give the same values when run on Android implementation? | [
"",
"python",
"hash",
"sl4a",
""
] |
Let's say I have:
```
action = '{bond}, {james} {bond}'.format(bond='bond', james='james')
```
this wil output:
```
'bond, james bond'
```
Next we have:
```
action = '{bond}, {james} {bond}'.format(bond='bond')
```
this will output:
```
KeyError: 'james'
```
Is there some workaround to prevent this error to ha... | ## If you are using Python 3.2+, use can use [str.format\_map()](http://docs.python.org/3/library/stdtypes.html#str.format_map).
For `bond, bond`:
```
from collections import defaultdict
'{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond'))
```
Result:
```
'bond, bond'
```
For `bond, {james} bond`:
... | You could use a [template string](http://docs.python.org/2/library/string.html#template-strings) with the `safe_substitute` method.
```
from string import Template
tpl = Template('$bond, $james $bond')
action = tpl.safe_substitute({'bond': 'bond'})
``` | Format string unused named arguments | [
"",
"python",
"string",
"string-formatting",
"missing-data",
"defaultdict",
""
] |
I'm using Python 3.3. I'm getting an email from an IMAP server, then converting it to an instance of an email from the [standard email library](http://docs.python.org/2/library/email.message.html).
I do this:
```
message.get("date")
```
Which gives me this for example:
```
Wed, 23 Jan 2011 12:03:11 -0700
```
I wan... | Do this:
```
import email, email.utils, datetime, time
def dtFormat(s):
dt = email.utils.parsedate_tz(s)
dt = email.utils.mktime_tz(dt)
dt = datetime.datetime.fromtimestamp(dt)
dt = dt.timetuple()
return dt
```
then this:
```
s = message.get("date") # e.g. "Wed, 23 Jan 2011 12:03:11 -0700"
print(ti... | Something like this?
```
>>> import time
>>> s = "Wed, 23 Jan 2011 12:03:11 -0700"
>>> newtime = time.strptime(s, '%a, %d %b %Y %H:%M:%S -0700')
>>> print(time.strftime('Two years ago was %Y', newtime))
Two years ago was 2011 # Or whatever output you wish to receive.
``` | Parse date/time from a string | [
"",
"python",
"python-3.x",
""
] |
Is it possible to modify code below to have printout from 'stdout 'and 'stderr':
* printed on the **terminal** (in real time),
* and finally stored in **outs** and **errs** variables?
The code:
```
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import subprocess
def run_cmd(command, cwd=None):
p = subprocess.Popen... | You could spawn threads to read the stdout and stderr pipes, write to a common queue, and append to lists. Then use a third thread to print items from the queue.
```
import time
import Queue
import sys
import threading
import subprocess
PIPE = subprocess.PIPE
def read_output(pipe, funcs):
for line in iter(pipe.r... | To capture and display at the same time both stdout and stderr from a child process line by line in a single thread, you could use asynchronous I/O:
```
#!/usr/bin/env python3
import asyncio
import os
import sys
from asyncio.subprocess import PIPE
@asyncio.coroutine
def read_stream_and_display(stream, display):
"... | Subprocess.Popen: cloning stdout and stderr both to terminal and variables | [
"",
"python",
"python-3.x",
"subprocess",
"popen",
""
] |
The following code tries to create an integer array filled with `n` times number 1.
```
import sys
def foo(n):
if n == 0:
return []
else:
return foo(n-1).append(1)
if __name__ == '__main__':
foo(5)
```
Executing this program yields in an error:
```
AttributeError: 'NoneType' object has ... | The problem is in your `else`-clause. `append` does not return a new list, but rather adds an element to the list in-place, and then returns `None` (hence your error). Try this instead,
```
return foo(n-1) + [1] # creates a *new* list
``` | Just look at the following code to understand why you are getting the error,
```
>>> x = [].append(1)
>>> x is None
True
```
When you append to a list, the return value is `None`! So you must do something like this,
```
def foo(n):
if n == 0:
return []
else:
return foo(n-1) + [1]
```
Using `... | How to create an integer array within a recursion? | [
"",
"python",
"arrays",
""
] |
So I have no idea how to do this and I've been reading the documentation and searching around but I can't seem to find anything. \d gives me a nice list of all the tables and information on them but I want to be able to send a command to the postgresql database and pipe it into a text file that will contain just the ta... | Run psql with the following switch. It'll show the internal commands psql sends to the catalog to get this kind of information:
> ```
> -E
> --echo-hidden
> ```
>
> Echo the actual queries generated by \d and other backslash commands.
> You can use this to study psql's internal operations. This is
> equivalent to sett... | Alternatively to Denis solution, you might want:
```
select table_name from information_schema.tables;
```
but this is bound to cause problems to lack of schema information. | Show only table names when viewing postgresql tables | [
"",
"sql",
"postgresql",
""
] |
I got a task to replace "O"(capital O) by "0" in a text file by using python. But one condition is that I have to preserve the other words like Over, NATO etc. I have to replace only the words like 9OO to 900, 2OO6 to 2006 and so on. I tried a lot but yet not successful. My code is given below. Please help me any one. ... | `re.sub` can take in a replacement function, so we can pare this down pretty nicely:
```
import re
with open('myfile.txt', 'r') as file:
content = file.read()
with open('myfile.txt', 'w') as file:
file.write(re.sub(r'\d+[\dO]+|[\dO]+\d+', lambda m: m.group().replace('O', '0'), content))
``` | You can probably get away with matching just a leading digit followed by `O`. This won't handle `OO7`, but it will work nicely with `8080` for example. Which none of the answers here matching the trailing digits will. If you want to do that you need to use a lookahead match.
```
re.sub(r'(\d)(O+)', lambda m: m.groups(... | How to replace a character in some specific word in a text file using python | [
"",
"python",
"replace",
""
] |
I have this somewhat complicated command line function in Python (lets call it `myFunction()`), and I am working to integrate it in a graphical interface (using PySide/Qt).
The GUI is used to help select inputs, and display outputs. However, `myFunction` is designed to work as a stand-alone command line function, and ... | you could redirect stdout and restore after. for example:
```
import StringIO
import sys
# somewhere to store output
out = StringIO.StringIO()
# set stdout to our StringIO instance
sys.stdout = out
# print something (nothing will print)
print 'herp derp'
# restore stdout so we can really print (__stdout__ stores t... | Here is a Python 3 pattern using contextmanager that both encapsulates [the monkey-patch technique](https://stackoverflow.com/a/17067799/39396) and also ensures that `sys.stdout` is restored in case of an exception.
```
from io import StringIO
import sys
from contextlib import contextmanager
@contextmanager
def capt... | Intercept python's `print` statement and display in GUI | [
"",
"python",
""
] |
I'm attempting to remove all lines where my regex matches(regex is simply looking for any line that has yahoo in it). Each match is on it's own line, so there's no need for the multiline option.
This is what I have so far...
```
import re
inputfile = open('C:\\temp\\Scripts\\remove.txt','w',encoding="utf8")
inputfil... | Use `fileinput` module if you want to modify the original file:
```
import re
import fileinput
for line in fileinput.input(r'C:\temp\Scripts\remove.txt', inplace = True):
if not re.search(r'\byahoo\b', line):
print(line, end="")
``` | Here's Python 3 variant of [@Ashwini Chaudhary's answer](https://stackoverflow.com/a/17221420/4279), to remove all lines that contain a regex `pattern` from a give `filename`:
```
#!/usr/bin/env python3
"""Usage: remove-pattern <pattern> <file>"""
import fileinput
import re
import sys
def main():
pattern, filenam... | Using Python to Remove All Lines Matching Regex | [
"",
"python",
"regex",
"python-3.x",
""
] |
I'm not a programmer, but would like to use Python for automation of some Administrative purposes.
The first application after "Hello world" I tried to create is interactive ssh client.
I've read some documentation and articles and decided it would be the easiest way to use paramiko module, but unfortunately I'm facing... | Unfortunately I didn't find the way to resolve my issue using paramiko module, but I've found such a module as Exscript.
The simple code is below:
```
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login()
conn = SSH2()
conn.connect('192.168.1.... | Please use for pxssh module this is very useful for your application if work for windows
[Python: How can remote from my local pc to remoteA to remoteb to remote c using Paramiko](https://stackoverflow.com/questions/15818328/python-how-can-remote-from-my-local-pc-to-remotea-to-remoteb-to-remote-c-using/15831027#1583102... | Python interactive ssh client using paramiko | [
"",
"python",
"ssh",
"paramiko",
""
] |
So I have a little script in python and for the help I want to print each method docstring. For example
```
~$ myscript.py help update
```
would print `myClass.update.__doc__` to the screen. The code I was trying to run is this:
```
import sys
class myClass:
def update(self):
""" update method help ""... | Instead of using this:
```
if method == 'update':
help_string = self.update.__doc__
```
you could use more flexible solution:
```
help_string = getattr(self, method).__doc__
```
Just make sure that you catch `AttributeError`s (it will be thrown when there is no method with given name). | This will do it:
```
method = sys.argv[2:3][0] # This is a bit odd; why not sys.argv[2]?
print "Help: " + getattr(self, method).__doc__
``` | Dynamically access instance method | [
"",
"python",
""
] |
I have a 22GB .sql file (100+ tables) and i only need, let's say, 5 of them. I have tried all oracle tools, but none of them is capable of extracting only specific tables.
Is there ANY way to extract only specific tables ? | I just stumpled over a very interesting script that creates a single .sql for each table that exists in the huge main .sql: MYSQLDUMPSPLITTER.sh
<http://kedar.nitty-witty.com/blog/mydumpsplitter-extract-tables-from-mysql-dump-shell-script>
In case the link is 404, please see the github gist [here](https://gist.github... | If you created the file with `mysqldump`, I believe you can use text utilities to extract the CREATE TABLE and INSERT statements.
Specifically, you can use [`sed` addresses](http://www.gnu.org/software/sed/manual/html_node/Addresses.html) to extract all the lines between two regular expressions. It won't have trouble ... | How to extract/split SQL statements in a huge .sql file to get only certain tables? | [
"",
"mysql",
"sql",
""
] |
I am trying to create a dictionary where the name comes from a variable.
Here is the situation since maybe there is a better way:
Im using an API to get attributes of "objects". (Name, Description, X, Y, Z) etc. I want to store this information in a way that keeps the data by "object".
In order to get this info, the ... | I deduce that you are using the [Active Worlds SDK](http://wiki.activeworlds.com/index.php?title=SDK). It would save time to mention that in the first place in future questions.
I guess your goal is to create a top-level dictionary, where each key is the object description. Each value is another dictionary, storing ma... | If the variables are defined in the local scope, it's as simple as:
```
obj_names = {}
while True:
varname = read_name()
if not varname: break
obj_names[varname] = locals()[varname]
``` | How to create a dictionary based on variable value in Python | [
"",
"python",
"variables",
"dictionary",
"activeworlds",
""
] |
I am trying to put the items, scraped by my spider, in a mysql db via a mysql pipeline. Everything is working but i see some odd behaviour. I see that the filling of the database is not in the same order as the website itself. There is like a random order. Probably of the dictionary like list of the items scraped i gue... | Items in a database are have not a special order if you don't impose it. So you should add a timestamp to your table in the database, keep it up-to-date (mysql has a special flag to mark a field as auto-now) and use ORDER BY in your queries. | It's hard to say without the actual code, but in theory..
Scrapy is completely async, you cannot know the order of items that will be parsed and processed through the pipeline.
But, you can control the behavior by "marking" each item with `priority` key. Add a field `priority` to your `Item` class, in the `parse_item... | Scrapy reversed item ordening for preparing in db | [
"",
"python",
"scrapy",
""
] |
I have two tables in a MySQL database. The first one has a list of department names.
```
departments
abbreviation | name
-------------|-------------
ACC | accounting
BUS | business
...
```
The second table has a list of courses with names that contain the department's abbreviatio... | ```
SELECT d.abbreviation, COUNT(*) num
FROM departments d
INNER JOIN courses c ON c.section LIKE CONCAT(d.abbreviation, "%")
GROUP BY d.abbreviation
```
**[Sql Fiddle](http://sqlfiddle.com/#!2/f9e2c/6)** | I quick solution, but not the best, could be:
```
SELECT abbreviation,
(SELECT COUNT(*) FROM courses C WHERE D.abbreviation = SUBSTRING(C.abbreviation, 0, 3)) AS c
FROM departments D;
``` | How to count rows in one table based on another table in mysql | [
"",
"mysql",
"sql",
"select",
"count",
""
] |
I am trying to implement this into python:
<https://dev.twitter.com/docs/api/1.1/get/statuses/retweeters/ids>
here is what I have so far:
```
def reqs():
t = Twitter(auth=OAuth('...'))
tweets = t.statuses.user_timeline.snl()
```
How do I get the user id's of those who retweeted a single tweet from the user's timeli... | use tweeters instead. boom. figured it out on my own
```
t.statuses.retweets(....)
``` | Please see my solution at this post: [difficulty using twitter api command implemention in python](https://stackoverflow.com/questions/17172169/difficulty-using-twitter-api-command-implemention-in-python)
It does use the Twyton API, however. | having difficulty using twitter api command implemention in python | [
"",
"python",
"api",
"twitter",
"encoding",
"implementation",
""
] |
I'm working a linux machine running CentOS. I don't have full sudo powers and theres multiple versions of python already installed on the machine and the whole thing is a bit of a mess, stuff like numpy doesn't work and I need to install modules which rely on that.
I was wondering if its possible to just install pytho... | Try using virtualenv. Of course this assumes that your system already has virtualenv installed.
<https://pypi.python.org/pypi/virtualenv>
Basic usage:
```
virtualenv venv
```
That creates a directory called 'venv' at your current folder. It puts in the appropriate `python` and `pip` binaries.
To go into the virtua... | Make a directory where you install your own software:
```
mkdir -p ~/sw/src
cd ~/sw/src
```
Download and untar Python source into this directory. Configure it to install into `~/sw`, then compile (make sure all the required headers are available, notably those for SSL if you want to open HTTPS urls with `urllib2`):
... | How to install python for one user on centos? | [
"",
"python",
"centos",
""
] |
In Pandas, how can I get a list of indices of a series/dataframe for the entries that satisfy some property?
The following returns a `Series` object
```
my_dataframe.loc[:,'some_column'] == 'some_value'
```
that looks like this:
```
519 True
509 False
826 False
503 False
511 False
512 False
500 ... | ```
In [8]: df = DataFrame(randn(10,2),columns=list('AB'))
In [9]: df
Out[9]:
A B
0 -1.046978 1.561624
1 -0.264645 0.717171
2 0.112354 -2.084449
3 -1.243482 -1.183749
4 1.055667 0.532444
5 -1.295805 2.168225
6 -1.239725 0.969934
7 -0.354017 1.434943
8 -0.867560 0.810315
9 0.097698 -0.03303... | A slight variant on @Jeff's example:
```
In [18]: df
Out[18]:
A B
0 0.319489 1.012319
1 0.494205 -0.918240
2 1.501922 -0.409661
3 -1.593702 0.705407
4 -0.735312 1.037567
5 -0.201132 -0.673124
6 1.237310 -0.877043
7 -0.946714 0.984164
8 -0.923548 0.415094
9 0.135281 -0.199951
In [14] list... | Get indices that satisfy some criteria | [
"",
"python",
"pandas",
""
] |
I want to ensure that all resources are being cleaned correctly. Is this a safe thing to do:
```
try:
closing(open(okFilePath, "w"))
except Exception, exception:
logger.error(exception)
raise
```
**EDIT:**
Infact, thinking about it, do I even need the try/catch as I am raising the exception anyways I can... | To be sure that the file is closed in any case, you can use the [with](http://docs.python.org/release/2.5/whatsnew/pep-343.html) statement. For example:
```
try:
with open(path_to_file, "w+") as f:
# Do whatever with f
except:
# log exception
``` | you can use this to just create a file and close it in one line.
`with open(file_path, 'w') as document: pass` | python - creating an empty file and closing in one line | [
"",
"python",
"file-io",
""
] |
I am trying to make a POST request But getting this error :
```
Traceback (most recent call last):
File "demo.py", line 7, in <module>
r = requests.post(url, data=payload, headers=headers)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 87, in post
return request('post', url, data=data,... | Try this :
```
import requests
url = 'http://www.n-gal.com/index.php?route=openstock/openstock/optionStatus'
payload = 'var=1945&product_id=1126'
headers = {'content-type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=payload, headers=headers)
print r.json()
``` | You have made `payload` a [set](http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset), not a dictionary. You forgot to close the string.
Change:
```
payload = {'var:1945,product_id:1126'}
```
To:
```
payload = {'var':'1945','product_id':'1126'}
```
As it is a set, the request will thus fail. | Make POST request using Python | [
"",
"python",
""
] |
Is there any way I can change this SQL so the terms are defined only once?
[SQLFiddle](http://www.sqlfiddle.com/#!2/b065c/1).
```
SELECT sum(score) score, title
FROM
(
SELECT
score,
title
FROM
(
SELECT 3 score, 'a railway employee' term UNION ALL
SELECT 2 score, 'a railway' term UNION ALL
SELECT 2 score, 'railwa... | Note: I do advise that you put the values into their own table. Just sticking them in the query text is probably not ideal. But the queries I present below will work equally well with a real table as with a hard-coded derived table.
Here's one way:
```
SELECT
sum(score * multiplier) score,
title
FROM
(
SE... | If you don't want to write them out twice, why not just create a table that stores the terms and the scores and then you join on the table:
```
create table terms
(
term varchar(50),
score int
);
insert into terms values
('a railway employee', 3),
('a railway', 2),
('railway employee', 2),
('a', 1),
('railway', 1... | Is there any way I can change this SQL so the terms are defined only once? | [
"",
"mysql",
"sql",
""
] |
Is there any method to replace values with `None` in Pandas in Python?
You can use `df.replace('pre', 'post')` and can replace a value with another, but this can't be done if you want to replace with `None` value, which if you try, you get a strange result.
So here's an example:
```
df = DataFrame(['-',3,2,5,1,-5,-1... | Actually in later versions of pandas this will give a TypeError:
```
df.replace('-', None)
TypeError: If "to_replace" and "value" are both None then regex must be a mapping
```
You can do it by passing either a list or a dictionary:
```
In [11]: df.replace('-', df.replace(['-'], [None]) # or .replace('-', {0: None})... | I prefer the solution using [`replace`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html#pandas-dataframe-replace) with a `dict` because of its simplicity and elegance:
```
df.replace({'-': None})
```
You can also have more replacements:
```
df.replace({'-': None, 'None': None})
`... | Replace invalid values with None in Pandas DataFrame | [
"",
"python",
"pandas",
"dataframe",
"replace",
"nan",
""
] |
I have several records (bills) that are basically duplicates of each other, except for one field, which represents the language that bill is in.
For example:
```
ID,BillID,Account,Name,Amount,Lang
1,0001,abcd,John Smith,10.99,ENG
2,0002,qwer,Jane Doe,9.99,ENG
3,0001,abcd,John Smith,10.99,SPA
4,0003,abcd,John Smith,4.... | Probably the easiest way would be to use `ROW_NUMBER` and `PARTITION BY`
```
SELECT * FROM (
SELECT b.*,
ROW_NUMBER() OVER (PARTITION BY BillID ORDER BY Lang) as num
FROM Bills b
WHERE Account = 'abcd'
) tbl
WHERE num = 1
``` | ```
select
ID,BillID,Account,Name,Amount,max(Lang)
FROM Bills
WHERE Account='abcd'
group by BillID,Account,Name,Amount;
```
Given that you are not giving priority to any specific language if there is same bill in multiple languages. The above query will work perfect.
EDIT : Removed "ID" from group by. @Phil You are ... | Filter duplicate rows based on a field | [
"",
"sql",
"sql-server",
""
] |
I am using python to create a gaussian filter of size 5x5.
I saw this post [here](https://stackoverflow.com/questions/11209115/creating-gaussian-filter-of-required-length-in-python) where they talk about a similar thing but I didn't find the exact way to get equivalent python code to matlab function `fspecial('gaussian... | In general terms if you really care about getting the the exact same result as MATLAB, the easiest way to achieve this is often by looking directly at the source of the MATLAB function.
In this case, `edit fspecial`:
```
...
case 'gaussian' % Gaussian filter
siz = (p2-1)/2;
std = p3;
[x,y] = me... | I found similar solution for this problem:
```
def fspecial_gauss(size, sigma):
"""Function to mimic the 'fspecial' gaussian MATLAB function
"""
x, y = numpy.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]
g = numpy.exp(-((x**2 + y**2)/(2.0*sigma**2)))
return g/g.sum()
``` | How to obtain a gaussian filter in python | [
"",
"python",
"matlab",
"numpy",
"gaussian",
""
] |
This is a slightly weird request but I am looking for a way to write a list to file and then read it back some other time.
I have no way to remake the lists so that they are correctly formed/formatted as the example below shows.
My lists have data like the following:
```
test
data
here
this
is one
group :)
test
dat... | If you don't need it to be human-readable/editable, the easiest solution is to just use `pickle`.
To write:
```
with open(the_filename, 'wb') as f:
pickle.dump(my_list, f)
```
To read:
```
with open(the_filename, 'rb') as f:
my_list = pickle.load(f)
```
---
If you *do* need them to be human-readable, we n... | As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:
```
with open('my_file.txt', 'rU') as in_file:
data = in_file.read().split('\n')
```
That will store your data file as a list of items, one per line. To then put it into a file, you would... | Write and read a list from file | [
"",
"python",
"list",
"python-2.7",
""
] |
My tables as follows
```
name
| id | name |
| 1 | jon |
| 2 | mary |
skill
| id | skill | level |
| 1 | C++ | 3 |
| 1 | Java | 2 |
| 1 | HTML | 5 |
| 1 | CSS | 4 |
| 1 | JS | 5 |
| 2 | PHP | 4 |
| 2 | Ruby | 3 |
| 2 | Perl | 1 |
```
So I want the output to be l... | Since you have mentioned that a `Name` can have a maximum of `5 Skills`, this problem can be done using static query.
```
-- <<== PART 2
SELECT Name,
MAX(CASE WHEN RowNumber = 1 THEN Skill END) Skill_1,
MAX(CASE WHEN RowNumber = 2 THEN Skill END) Skill_2,
MAX(CASE WHEN RowNumber = 3 THEN Skill... | This could also be the possible solution!
**Query**
```
select a.name,
(select skill from skill where skill.id=a.id limit 0,1 ) as skill_1,
(select skill from skill where skill.id=a.id limit 1,1) skill_2,
(select skill from skill where skill.id=a.id limit 2,1 ) skill_3,
(select skill from skill where skill.id=a.i... | Is it possible for SQL to make a SELECT from a "list"? Example inside | [
"",
"mysql",
"sql",
"pivot",
""
] |
I have a python script that runs on aws machines, as well as on other machines.
The functionality of the script depends on whether or not it is on AWS.
Is there a way to programmatically discover whether or not it runs on AWS? (maybe using boto?) | If you want to do that strictly using boto, you could do:
```
import boto.utils
md = boto.utils.get_instance_metadata(timeout=.1, num_retries=0)
```
The `timeout` specifies the how long the HTTP client will wait for a response before timing out. The `num_retries` parameter controls how many times the client will retr... | you can easily use the AWS SDK and check for instance id.
beside of that, you can check the aws ip ranges - check out this link
<https://forums.aws.amazon.com/ann.jspa?annID=1701> | Find out if the current machine is on aws in python | [
"",
"python",
"amazon-web-services",
"boto",
""
] |
I have a table like:
```
ID DATE
01 20.06.13
01 21.06.13
02 13.04.13
03 12.05.13
04 17.05.13
04 19.06.13
```
I need to query so that I have the total amount of distinct ID which have two or more entry in the DATE field. For example in the example table only 01 and 04 have at least two entries so ... | Since your requirement is the *total count* of unique duplicates, not to list the duplicate items themselves, here is the query to do that:
```
SELECT Count(*)
FROM
(
SELECT ID
FROM dbo.YourTable
GROUP BY ID
HAVING Count(*) >= 2
) X
;
```
You could also use some kind of `JOIN` (including... | try this.
```
SELECT DISTINCT ID, COUNT(*) FROM TABLE_NAME GROUP BY ID HAVING COUNT(*) > 1
``` | SQL: number of elements that appear at least twice | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I wish to read in an XML file, find all sentences that contain both the markup `<emotion>` and the markup `<LOCATION>`, then print those entire sentences to a unique line. Here is a sample of the code:
```
import re
text = "Cello is a <emotion> wonderful </emotion> parakeet who lives in <LOCATION> Omaha </LOCATION>. ... | Your problem appears to be that your regex is expecting a space (`\s`) to follow the matching word, as seen with:
```
emotion(?=\s|\.|$)
```
Since when it's part of a tag, it's followed by a `>`, rather than a space, no match is found since that lookahead fails. To fix it, you can just add the `>` after emotion, like... | If I do not understand bad what you are trying to do is remove `<emotion> </emotion> <LOCATION></LOCATION>` ??
Well if is that what you want to do you can do this
```
import re
text = "Cello is a <emotion> wonderful </emotion> parakeet who lives in <LOCATION> Omaha </LOCATION>. He is the <emotion> best </emotion> si... | Python regex to print all sentences that contain two identified classes of markup | [
"",
"python",
"regex",
"pattern-matching",
"markup",
"proximity",
""
] |
I am fairly new to Python and come from a more Matlab point of view.
I am trying to make a series of 2 x 5 panel contourf subplots. My approach so far
has been to convert (to a certain degree) my Matlab code to Python and plot my subplots within a loop. The relavent part of the code looks like this:
```
fig=plt.figure... | Using your code with some random data, this would work:
```
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(10):
axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
axs[i].set_title(str(250+i)... | Basically the same solution as provided by [Rutger Kassies](https://stackoverflow.com/a/17211410), but using a more pythonic syntax:
```
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
data = np.arange(250, 260)
for ax, d in zip(axs.ravel(), d... | Python: subplot within a loop: first panel appears in wrong position | [
"",
"python",
"matplotlib",
"subplot",
""
] |
I have a table that looks something like this. It updates every 5 minutes for each game\_id
```
game_id players date
12 420 2013-06-19 12:30:00
13 345 2013-06-19 12:30:00
14 600 2013-06-19 12:30:00
12 375 2013-06-19 12:25:00
13 475 2013-06-19 12:25:00... | To get the last value, you need a trick of one sort or another. Instead of using a join, this version uses the `substring_index()`/`group_concat()` trick:
```
select game_id, max(players) as MaxPlayers,
substring_index(group_concat(players order by date desc), ',', 1) + 0 as Latest
from players
group by game_id... | <http://www.sqlfiddle.com/#!2/e5157/5>
```
select game_id, max(players) as maximum,
players as current
from tab where date >= '2013-06-19'
group by game_id
``` | How do I query a mysql table to get the current value of a column and the max for the day | [
"",
"mysql",
"sql",
"group-by",
"sql-order-by",
""
] |
I'm currently learning Python.
How do I put this:
```
dates = list()
for entry in some_list:
entry_split = entry.split()
if len(entry_split) >= 3:
date = entry_split[1]
if date not in dates:
dates.append(date)
```
into a one-liner in Python? | Instead of a 1-liner, probably it's easier to understand with a 3-liner.
```
table = (entry.split() for entry in some_list)
raw_dates = (row[1] for row in table if len(row) >= 3)
# Uniquify while keeping order. http://stackoverflow.com/a/17016257
dates = list(collections.OrderedDict.fromkeys(raw_dates))
``` | If the order does not matter:
```
dates = set(split[1] for split in (x.split() for x in some_list) if len(split) >= 3)
```
Of course if you want a list instead of a set, just pass the result into `list()`.
Although I would probably stick with what you have, as it is more readable. | Python List Iteration into One-Liner | [
"",
"python",
"list",
""
] |
I need to figure out the simplest method of grabbing the length of a youtube video programmatically given the url of said video.
Is the youtube API the best method? It looks somewhat complicated and I've never used it before so it's likely to take me a bit to get accommodated, but I really just want the quickest solut... | All you have to do is read the `seconds` attribute in the `yt:duration` element from the XML returned by Youtube API 2.0. You only end up with seconds resolution (no milliseconds yet). Here's an example:
```
from datetime import timedelta
from urllib2 import urlopen
from xml.dom.minidom import parseString
for vid in (... | (I'm not sure what "pre-download" refers to.)
The simplest way to get the length of `VIDEO_ID` is to make an HTTP request for
`http://gdata.youtube.com/feeds/api/videos/VIDEO_ID?v=2&alt=jsonc`
and then look at the value of the `data`->`duration` element that's returned. It will be set to the video's duration in seco... | Getting length of YouTube video (without downloading the video itself) | [
"",
"python",
"youtube-api",
"youtube-dl",
""
] |
Using the following result set:
```
| DATE | BUSINESS | COLLEAGUE | POSITION | HOURS | STANDARDHOURS | COUNTER | OVER16 | OVER32 | OVER48 |
-----------------------------------------------------------------------------------------------------------------
| 2013-01-01 | a | bob jones | analyst | ... | I believe the problem that you are having is the integer divide problem. You want to convert the values to a decimal or floating point format before doing the division. Here is one method:
```
SELECT c.date,
c.business,
CASE
WHEN Sum(c.over16) > 0 THEN ( Sum(c.over16*1.0) / Sum(c.counter) ) *... | You can fix this by using the following in your subquery:
```
SELECT a.date, a.business, a.colleague, a.position, a.hours, b.standardHours,
1 AS counter,
CASE WHEN a.hours >= b.standardHours + 16
THEN 1.0 ELSE 0.0 END AS over16,
CASE WHEN a.hours >= b.standardHours + 32
THEN 1.0 ELSE 0.0 END AS... | calculate percentage of aggregated column | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I want to count the number of 2 or more consecutive week periods that have negative values within a range of weeks.
Example:
```
Week | Value
201301 | 10
201302 | -5 <--| both weeks have negative values and are consecutive
201303 | -6 <--|
Week | Value
201301 | 10
201302 | -5
201303 | 7
201304 | -2 <-- negative b... | you could use a combination of EXISTS.
Assuming you only want to know groups (series of consecutive weeks all negative)
--Find the potential start weeks
```
;WITH starts as (
SELECT [Week]
FROM #ConsecutiveNegativeWeekTestOne AS s
WHERE s.[Value] < 0
AND NOT EXISTS (
SELECT 1
FROM #... | First, would you please share the formula for calculating week number, or provide a real date for each week, or some method to determine if there are 52 or 53 weeks in any particular year? Once you do that, I can make my queries properly skip missing data AND cross year boundaries.
Now to queries: this can be done wit... | SQL to check for 2 or more consecutive negative week values | [
"",
"sql",
"sql-server-2008",
""
] |
I am creating a weather station using a Raspberry Pi. I have a mySQL database setup for the different sensors (temp, humidity, pressure, rain, etc) and am now getting to processing the wind sensors.
I have a python program that watches the GPIO pins for the anemometer and counts the pulses to calculate the wind speed.... | There are multiple cache layers between a Python program and a database. In particular, the Linux disk block cache may keep your database in core depending on patterns of usage. Therefore, you should not assume that writing to a database and reading back is necessarily slower than some home-brew cache that you'd put in... | One option is to use [redis](http://redis.io/) to store your data. It's a key value store that's really good for storing data like what you're talking about. It operates in memory and writes data to disk for persistence, this is [configurable](http://redis.io/topics/persistence "redis persistence") so you could make it... | Python "in memory DB style" data types | [
"",
"python",
"types",
"raspberry-pi",
""
] |
I have searched this question here but couldn't find it, please redirect me if we already have it on the site.
I'm looking for a way to create CTE which uses another CTE as the data to further limit. I have a CTE which creates a report for me , but I would like to narrow this report with another input using the existi... | You can chain 2 (or more) CTE's together.
For example
```
with ObjectsWithA as
(
select * from sys.objects
where name like '%A%'
),
ObjectsWithALessThan100 as
(
select * from ObjectsWithA
where object_id < 100
)
select * from ObjectsWithALessThan100;
```
Or the same example, with more "spelled out" names/ali... | A CTE can refer to previous CTEs:
```
with report as (
<your query here>
),
reportLimited as (
select *
from report
where foo = @bar
)
select *
from reportLimited
```
The only rule is that the references have to be sequential. No forward references. | How to create CTE which uses another CTE as the data to further limit? | [
"",
"sql",
"common-table-expression",
""
] |
I have a script that gets a string in the form of 3/4/2013. How can I convert that to a date that I can then use to determine the age of the date (in months)? I would also like to be able to have the month in decimal form (i.e. 2.8 months old).
I'm not sure what to do at all as far as coding this. I've read about diff... | This is the answer from kzh but with the addition of the decimal that the poster wanted.
```
from datetime import datetime
from dateutil.relativedelta import relativedelta
date = '3/4/2013'
dt = datetime.strptime(date,'%m/%d/%Y')
r = relativedelta(datetime.now(), dt)
months = r.years * 12 + r.months + r.days/30.
pri... | Something like this:
```
>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> dt = datetime.strptime('3/4/2013','%m/%d/%Y')
>>> r = relativedelta(datetime.now(), dt)
>>> months = r.years * 12 + r.months + r.days/30
``` | Given a date in a specific format, how can I determine age in months? | [
"",
"python",
"datetime",
""
] |
```
>>> if 5==5:
print '5'
else: print 'cat'
File "<pyshell#2>", line 3
else: print 'cat'
^
IndentationError: unindent does not match any outer indentation level
```
No matter what the indent is, it still doesn't work. Even if I try to put the `print cat` statement on the next line it gives me syntax... | You want your code to look like this:
```
if 5 == 5:
print '5'
else:
print 'cat'
```
Why? Because Python uses indentation like other languages use brackets: it determines the grouping of statements. [Dive Into Python](http://www.diveintopython.net/getting_to_know_python/indenting_code.html) has an excellent e... | Use proper indentation in python otherwise you'll get such errors.
Use 4 spaces for indentation.
```
if 5 == 5:
print '5'
else:
print 'cat'
```
From [docs](http://docs.python.org/2/reference/lexical_analysis.html#indentation):
> Leading whitespace (spaces and tabs) at the beginning of a logical
> line is us... | python else and elif error | [
"",
"python",
"if-statement",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.