Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am trying to make a function that will do this:
* Make sure there isn't a `.` at the beginning or at the end of a domain.
* Make sure there aren't two `.` in the domain.
* Make sure there is at least one `.` in the domain.
Like blabla@outlook.com, it's suppose to make sure it isn't:
```
.blabla@outlook.com.
blabla... | `.$` should be `\.$`, and `and` should be `or`. The `else` should be `elif`, and you should add a final `else` clause to handle domains with no dots at all.
```
if re.search(r'^\.|\.$', domain) or re.search(r'\.\.', domain):
return False
elif re.search(r'\.', domain):
return True
else:
return False
```
I ... | This is easy enough to do without a regex:
```
(domain[0] != '.' != domain[-1] and
'..' not in domain and
'.' in domain)
```
If you want to exclude cases with two or more periods in general you can try:
```
domain[0] != '.' != domain[-1] and domain.count('.') == 1
``` | Python regex for finding dots in email address | [
"",
"python",
"regex",
""
] |
I'm very new to programming (obviously) and really advanced computer stuff in general. I've only have basic computer knowledge, so I decided I wanted to learn more. Thus I'm teaching myself (through videos and ebooks) how to program.
Anyways, I'm working on a piece of code that will open a file, print out the contents... | Opening a file in python for reading is easy:
```
f = open('example.txt', 'r')
```
To get everything in the file, just use read()
```
file_contents = f.read()
```
And to print the contents, just do:
```
print (file_contents)
```
Don't forget to close the file when you're done.
```
f.close()
``` | Just do this:
```
>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
... print f.read()
```
This will print the file in the terminal. | How do I print the content of a .txt file in Python? | [
"",
"python",
"ubuntu",
""
] |
Hi how can I insert a `JSON` file into a Cell in `Database`? I don't want to store the File path but want to store the whole `Content` of the `JSON` file into the field.
What can I do? | JSON data stored/transferred in as a string. You can store it in a normal NVARCHAR column. | how large is the json text?, depending on that you should have a varchar field if content is not large or CLOB if is a lot of json text,
json is just text , so you just have something to read the content of the file, maybe some transact-sql script , and insert it in your table | Insert JSON file into SQL Server database | [
"",
"sql",
"sql-server",
"json",
""
] |
I have EMP table its columns as per Scott in Oracle.
I want to show all columns in a single column named 'statement' like below.
ex-FORD IS A ANALYST AND HIS MANAGER IS JONES HAVING SALARY 3000 FROM DEPARTMENT RESEARCH
KING IS A PRESIDENT AND HIS MANAGER IS NONE HAVING SALARY 5000 FROM DEPARTMENT ACCOUNTING | ```
select x.ENAME||' is a ' || x.JOB||' and his manager is '||y.ENAME||' having salary '||x.sal||' from department '||d.DNAME
FROM EMP x, EMP y, dept d
where x.MGR = y.EMPNO(+)
and x.DEPTNO = d.DEPTNO
``` | Try something like this:
```
SELECT emp.ename || ' IS A ' || emp.job || ' AND HIS MANAGER IS ' || mgr.ename || ' HAVING SALARY ' || TO_CHAR(emp.sal) || ' FROM DEPARTMENT ' || dept.dname
FROM emp
INNER JOIN emp AS mgr ON emp.mgr = mgr.empno
INNER JOIN dept ON dept.deptno = emp.deptno
``` | Sql query to show all column values as a single statement adding some strings related to each other | [
"",
"sql",
"oracle",
""
] |
Here is an example from a simple list
```
mylist = [2,5,9,12,50]
```
I want to add the first element, in this case 2, to the element next to it. It's the number 5. The outcome (2+5=7) should be added to the next element, number 9 in my example. The outcome should be added to the next element etc...
I have this snipp... | If you wanna write it to specific positions in a file, try this:
Let's say you have a `numbers.txt` file, with 10 lines, like so:
```
0
0
0
0
0
0
0
0
0
0
```
Then use this:
```
original_list = [1, 3, 5, 7, 9]
lines_to_write = [2, 4, 6, 8, 10] # Lines you want to write the results in
total = 0
sum_list = list()
# ... | You can do something simple like this:
```
>>> mylist = [2,5,9,12,50]
>>>
>>> total = 0 # initialize a running total to 0
>>> for i in mylist: # for each i in mylist
... total += i # add i to the running total
... print total # print the running total
...
2
7
16
28
78
```
---
[`numpy`](http://www.numpy... | Adding one element from a list to next,after that to next etc | [
"",
"python",
"list",
""
] |
I have a login screen dialog written using pyqt and python and it shows a dialog pup up when it runs and you can type in a certin username and password to unlock it basicly. It's just something simple I made in learning pyqt. I'm trying to take and use it somewhere else but need to know if there is a way to prevent som... | Bad news first, it is *not possible* to remove the close button from the window, based on the [Riverbank mailing system](http://www.riverbankcomputing.com/pipermail/pyqt/2008-September/020479.html)
> You can't remove/disable close button because its handled by the
> window manager, Qt can't do anything there.
Good ne... | You **can** disable the window buttons in PyQt5.
The key is to combine it with "CustomizeWindowHint",
and **exclude the ones you want to be disabled**.
**Example:**
```
#exclude "QtCore.Qt.WindowCloseButtonHint" or any other window button
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint... | QDialog - Prevent Closing in Python and PyQt | [
"",
"python",
"pyqt",
""
] |
I would like to get the links to all of the elements in the first column in this page (<http://en.wikipedia.org/wiki/List_of_school_districts_in_Alabama>).
I am comfortable using BeautifulSoup, but it seems less well-suited to this task (I've been trying to access the first child of the contents of each tr but that ha... | Here's the example on how you can get all of the links from the first column:
```
from lxml import etree
import requests
URL = "http://en.wikipedia.org/wiki/List_of_school_districts_in_Alabama"
response = requests.get(URL)
parser = etree.HTMLParser()
tree = etree.fromstring(response.text, parser)
for row in tree.xp... | This should work:
```
from lxml import html
urls = []
parser = html.parse("http://url/to/parse")
for element in parser.xpath(your_xpath_query):
urls.append(element.attrib['href'])
```
You could also access the `href` attribute in the XPath query directly, e.g.:
```
for href in parser.xpath("//a/@href"):
ur... | Access element using xpath? | [
"",
"python",
"html",
"xpath",
"html-parsing",
"lxml",
""
] |
I have 2 tables
```
Emp1
ID | Name
1 | X
2 | Y
3 | Z
Emp2
ID | Salary
1 | 10
2 | 20
```
I want to show the `ID`s from Emp1 which are not present in Emp2 with out using `NOT IN`
so the result should be like this
```
ID
3
```
now what i have done is this :
```
select e1.ID
from Emp1 e1 left join Emp2 e2
on ... | Try `left join` with `is null` condition as below
```
select e1.id
from emp1 e1
left join emp2 e2 on e2.id = e1.id
where e2.id is null
```
or `not exists` condition as below
```
select e1.id
from emp1 e1
where not exists
(
select 1
from emp2 e2
where e2.id = e1.id
)
``` | Use this
```
select id from emp1
except
select id from emp2;
```
[**SQL Fiddle**](http://sqlfiddle.com/#!3/db2f7/3) | How to select data from two table with out using "NOT IN" in sql server? | [
"",
"sql",
"sql-server",
""
] |
# Short question
How can matplotlib 2D patches be transformed to 3D with arbitrary normals?
# Long question
I would like to plot [Patches](http://matplotlib.org/api/artist_api.html) in axes with 3d projection. However, the methods provided by [mpl\_toolkits.mplot3d.art3d](http://matplotlib.org/mpl_toolkits/mplot3d/a... | # Short answer
Copy the code below into your project and use the method
```
def pathpatch_2d_to_3d(pathpatch, z = 0, normal = 'z'):
"""
Transforms a 2D Patch to a 3D patch using the given normal vector.
The patch is projected into they XY plane, rotated about the origin
and finally translated by z.
... | Very useful piece of code, but there is a small caveat: it cannot handle normals pointing downwards because it uses only the sine of the angle.
You need to use also the cosine:
```
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d import art3d
from mpl_toolkits.mplot3d import proj3d
import numpy as np... | How can matplotlib 2D patches be transformed to 3D with arbitrary normals? | [
"",
"python",
"matplotlib",
"matplotlib-3d",
""
] |
I am building a simple Python web application and I want it to run stand alone like SABNZBD or Couch Patato. These applications are self contained web applications. What do these products use to serve up the web interface?
The application im building will do a lookup of images albums (folders) and when selected, prese... | why don't you use **flask** in python ?
take a look at this
<http://flask.pocoo.org/>
```
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
``` | There are many options and they're all very easy to pick up in a couple of days. Which one you choose is completely up to you.
Here are a few worth mentioning:
**[Tornado](http://www.tornadoweb.org/): a Python web framework and asynchronous networking library, originally developed at FriendFeed.**
```
import tornado... | Options for building a python web based application | [
"",
"python",
"web",
""
] |
I am looking for a way to do this in Python without much boiler plate code.
Assume I have a list:
```
[(a,4),(b,4),(a,5),(b,3)]
```
I am trying to find a function that will allow me to sort by the first tuple value, and merge the list values together like so:
```
[(a,[4,3]),(b,[4,5])]
```
I know I can do this the ... | Use `collections.defaultdict(list)`:
```
from collections import defaultdict
lst = [("a",4), ("b",4), ("a",5), ("b",3)]
result = defaultdict(list)
for a, b in lst:
result[a].append(b)
print sorted(result.items())
# prints: [('a', [4, 5]), ('b', [4, 3])]
```
Before the sort the algorithm has `O(n)` complexity;... | Assuming that 'a' is your initial list an 'b' is the expected result, the following code will work:
```
d = {}
for k, v in a:
if k in d:
d[k].append(v)
else:
d[k] = [v]
b = d.items()
``` | Filter operation in Python | [
"",
"python",
"python-2.7",
"dictionary",
"reduce",
""
] |
I have an oracle table that store transaction and a date column. If I need to select records for one year say 2013 I do Like this:
```
select *
from sales_table
where tran_date >= '01-JAN-2013'
and tran_date <= '31-DEC-2013'
```
But I need a Straight-forward way of selecting records for one year say pass the P... | You can use **to\_date** function
<http://psoug.org/reference/date_func.html>
```
select *
from sales_table
where tran_date >= to_date('1.1.' || 2013, 'DD.MM.YYYY') and
tran_date < to_date('1.1.' || (2013 + 1), 'DD.MM.YYYY')
```
solution with explicit comparisons `(tran_date >= ... and tran_date < ...)` i... | Use the [extract](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm) function to pull the year from the date:
```
select * from sales_table
where extract(YEAR from tran_date) = 2013
``` | Select records for a certain year Oracle | [
"",
"sql",
"oracle11g",
""
] |
I'm having issues querying XML data stored in a SQL Server 2012 database. The node tree I wish to query is in the following format -
```
<eForm>
<page id="equalities" visited="true" complete="true">
<Belief>
<item selected="True" value="Christian">Christian</item>
<item selected="False" valu... | [**DEMO**](http://sqlfiddle.com/#!6/a9a16/5)
```
SELECT [value].query('data(eForm/page/Belief/item[@selected="True"]/@value)')
FROM test
``` | ```
select
Value.value('(eForm/page/Belief/item[@selected="True"])[1]/@value', 'nvarchar(max)')
from test
```
[**sql fiddle demo**](http://sqlfiddle.com/#!6/a9a16/9) | Using SQL to query an XML data column | [
"",
"sql",
"xml",
"sql-server-2012",
"sqlxml",
""
] |
I came across some code with this `*=` operator in a `WHERE` clause and I have only found one thing that described it as some sort of join operator for Sybase DB. It didn't really seem to apply. I thought it was some sort of bitwise thing (which I do not know much about) but it isn't contained in [this reference](http:... | Kill the deprecated syntax if you can, but:
```
*= (LEFT JOIN)
=* (RIGHT JOIN)
``` | That would be the "old school" equivalent of a [LEFT JOIN](http://www.w3schools.com/sql/sql_join_left.asp). | SQL Server *= operator | [
"",
"sql",
"operators",
"sql-server-2000",
""
] |
Apologies for the rather basic question.
I have an error string that is built dynamically. The data in the string is passed by various third parties so I don't have any control, nor do I know the ultimate size of the string.
I have a transaction table that currently logs details and I want to include the string so th... | If you want to store non unicode text, you can use:
```
varchar(max) or nvarchar(max)
```
Maximum length is 2GB.
Other alternatives are:
```
binary or varbinary
```
Drawbacks: you can't search into these fields and index and order them
and the maximum size : 2GB.
There are TEXT and NTEXT, but they will be depreca... | You can use SQL Server `nvarchar(MAX)`.
Check out [this](http://msdn.microsoft.com/en-us/library/ms187993.aspx) too. | What is the best SQL type to use for a large string variable? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Is there any way to make from string:
```
"I like Python!!!"
```
a list like
```
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']
``` | Use a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions):
```
>>> mystr = "I like Python!!!"
>>> [c for c in mystr if c != " "]
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']
>>> [c for c in mystr if not c.isspace()] # alternately
['I', 'l', 'i', 'k'... | Looks like you don't want any spaces in the resulting list, so try:
```
>>> s = "I like Python!!!"
>>> list(s.replace(' ',''))
['I', 'l', 'i', 'k', 'e', 'P', 'y', 't', 'h', 'o', 'n', '!', '!', '!']
```
But are you *sure* you need a list here? Bear in mind that in most contexts, strings can be treated just like lists:... | How can I make a list from the string | [
"",
"python",
"string",
"list",
"python-2.7",
""
] |
Basically I have 2 tables but the problem is I would like to insert data from table A column A to table B column C.
But when I try to this I get an error
My subquery is:
```
SELECT TOP 1 [Id]
From [A]
Where [B] = 'ValueCon'
```
And here is my insert query
```
INSERT INTO [B]
([BA]
,[BB]
)
VAL... | May be if you use a declared param, you can use it to the INSERT
```
DECLARE @theInsertedId INT;
SELECT TOP 1 @theInsertedId=[Id]
From [A]
Where [B] = 'ValueCon'
INSERT INTO [B]
([BA]
,[BB]
)
VALUES
('TestData'
,@theInsertedId
)
```
Sorry for by bad english! Hope this hel... | [Read up on the proper syntax for `INSERT`](http://technet.microsoft.com/en-us/library/ms174335%28v=sql.90%29.aspx)! It's all very well documented in the SQL Server Books Online ....
**Either** you have `INSERT` and `VALUES` and you provide **atomic** values (variables, literal values), e.g.
```
INSERT INTO [B] ([BA]... | SQL Server 2005 - Insert with Select for 1 Value | [
"",
"sql",
"sql-server-2005",
"sql-insert",
""
] |
I'm trying to make a function that will take an arbritrary number of dictionary inputs and create a new dictionary with all inputs included. If two keys are the same, the value should be a list with both values in it. I've succeded in doing this-- however, I'm having problems with the dict() function. If I manually per... | A typical example of why keywords should not be used as variable names. Here `dict(newtlist)` is trying to call the `dict()` builtin python, but there is a conflicting local variable `dict`. Rename that variable to fix the issue.
Something like this:
```
def dictcomb(*dct): #changed the local variable dict to dct and... | You function has a local variable called `dict` that comes from the function arguments and masks the built-in `dict()` function:
```
def dictcomb(*dict):
^
change to something else, (*args is the typical name)
``` | Issue with dict() in Python, TypeError:'tuple' object is not callable | [
"",
"python",
"function",
"dictionary",
"tuples",
"typeerror",
""
] |
I have some strings like : `'I go to by everyday'` and `'I go to school by bus everyday'` and `'you go to home by bus everyday'` in python. I want to know that is it possible to convert the first one to the other ones **only by inserting** some characters ? if yes get the characters and where they must to insert! I use... | Let's restate the problem and say we are checking to see if s1 (e.g. "I go to by everyday") can become s2 (e.g. "I go to school by bus everyday") with *just* inserts. This problem is very simple if we were to look at the strings as ordered sets. Essentially we are asking if s1 is a subset of s2.
To solve this problem ... | You could walk over both strings in parallel, maintaining an index into each string. For each equal character, you increment both indices - for each unequal character you just increase the index into the string to test against:
```
def f(s, t):
"""Yields True if 's' can be transformed into 't' just by inserting char... | converting a string to another only by insert in python | [
"",
"python",
"string",
""
] |
I have a table that looks something like this:
```
+--------+-------+-------+
|TestName|TestRun|OutCome|
+--------+-------+-------+
| Test1 | 1 | Fail |
+--------+-------+-------+
| Test1 | 2 | Fail |
+--------+-------+-------+
| Test2 | 1 | Fail |
+--------+-------+-------+
| Test2 | 2 | Pass ... | A bit ugly but it works.
```
create table dbo.tests
(
TestName nvarchar(10) not null
, TestRun int not null
, OutCome nvarchar(10) not null
)
insert into dbo.tests
select 'Test1', 1, 'Fail'
union all
select 'Test1', 3, 'Fail'
union all
select 'Test2', 1, 'Fail'
union all
select 'Test2', 3, 'Pass'
union... | ```
select a.TestName,a.TestRun,a.Outcome From table1 a join
Table1 b on a.TestName=b.testname
and a.Outcome='Fail'
and a.TestRun>b.TestRun
``` | SQL query counting based on successive condition | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008-r2",
""
] |
```
ss = ''
for word in ['this','his','is','s']: # Attach the words
if word not in ss: # if they are not already present
ss = ss + word + ' ' # to ss(substring) AFTER ss.
```
It gives output as:
```
'this '
```
But I want to get:
```
'this his is s '
```
How ... | As explained in all the other answers the problem is that the later "words" are all sub-strings of the first, however I would say that the problem is that you are comparing chalk and cheese or in your case words with a string - if you compare words with words the problem goes away:
```
>>> ss = ''
>>> for word in ['th... | ```
ss = []
for word in ['this', 'his', 'is', 's']:
if word not in ss:
ss.append(word)
ss = ' '.join(ss)
``` | How to use 'in' in Python with length constraint | [
"",
"python",
""
] |
My search for suggested files works fine. However, I would like to exclude one file from this search, but don't know how to add it to this query:
```
$query = mysqli_query($con, "
SELECT *, MATCH(file_name_keyword) AGAINST('$file_name_keyword')
FROM `uploaded`
WHERE MATCH(file_name_keyword) AGAINST('$file_name_keywo... | Just put your existing criteria in parentheses and then add the `NOT IN` at the end of the `WHERE` clause.
```
SELECT *,MATCH(file_name_keyword) AGAINST('$file_name_keyword')
FROM `uploaded`
WHERE (MATCH(file_name_keyword) AGAINST('$file_name_keyword') OR file_name_keyword REGEXP '.*($file_name_keyword).*' )
AND id ... | ```
$query = mysqli_query($con, "
SELECT *, MATCH(file_name_keyword) AGAINST('$file_name_keyword') FROM `uploaded`
WHERE
(MATCH(file_name_keyword) AGAINST('$file_name_keyword')
OR file_name_keyword REGEXP '.*($file_name_keyword).*')
AND id NOT IN (57)
LIMIT 8
");
```
You need to use parenthesis around the OR ... | Mysql query NOT IN | [
"",
"mysql",
"sql",
""
] |
I have made a program to allow users to input the largest possible hypotenuse of a right-angled triangle and my program will list down a list of all possible sides of the triangles. Problem is, the program takes forever to run when I input a value such as 10000. Any suggestions on how to improve the efficiency of the p... | like this?
```
hypothenuse=10000
thesets=[]
for x in xrange(1, hypothenuse):
a=math.sqrt(hypothenuse**2-x**2)
if(int(a)==a):
thesets.append([x,a])
print "amount of sets: ", len(thesets)
for i in range(len(thesets)):
print thesets[i][0],thesets[i][1], math.sqrt(thesets[i][0]**2+ thesets[i][1]**2)
``... | Here's a quick attempt using pre-calculated squares and cached square-roots. There are probably many mathematical optimisations.
```
def find_tri(h_max=10):
squares = set()
sq2root = {}
sq_list = []
for i in xrange(1,h_max+1):
sq = i*i
squares.add(sq)
sq2root[sq] = i
sq_list.append(sq)
#
tr... | Extremely inefficient python code | [
"",
"python",
"geometry",
""
] |
I asked this before, but I'm still stuck. This script will end up being run as a cron job.
Previous question : [Importing CSV to Django and settings not recognised](https://stackoverflow.com/questions/17979597/importing-csv-to-django-and-settings-not-recognised)
I've skipped the actual code that imports the csvs, as... | Someone upvoted this question today, which was nice, and I thought I'd come back to it with the benefit of hindsight, because the answers above didn't help me. This is largely because I couldn't adequately explain what I was trying to do; thanks to those who tried to help me.
For other noobs coming to it, there were t... | ```
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'yoursite.settings'
import django
django.setup()
```
Then you can use your models.
```
from my_app.models import MyModel
all_objects = MyModel.objects.all()
``` | Django settings for standalone | [
"",
"python",
"django",
"django-models",
""
] |
I have a file that has a list of bands and the album and year it was produced.
I need to write a function that will go through this file and find the different names of the bands and count how many times each of those bands appear in this file.
The way the file looks is like this:
```
Beatles - Revolver (1966)
Nirvan... | You are right, there is an easier way, with [`Counter`](http://docs.python.org/2/library/collections.html#collections.Counter):
```
from collections import Counter
with open('bandfile.txt') as f:
counts = Counter(line.split('-')[0].strip() for line in f if line)
for band, count in counts.most_common():
print(... | If you're looking for conciseness, use a "defaultdict" and "sorted"
```
from collections import defaultdict
bands = defaultdict(int)
with open('tmp.txt') as f:
for line in f.xreadlines():
band = line.split(' - ')[0]
bands[band] += 1
for band, count in sorted(bands.items(), key=lambda t: t[1], reverse=... | Take certain words and print the frequency of each phrase/word? | [
"",
"python",
"dictionary",
""
] |
I have a counter. With the counter, I do a `counter.most_common()`
However, all I really need from this counter is the top, say, five elements. Would there be a way to retrieve from it by index rather than by key? ie, `counter[0]` for the top element
Is this possible? | `most_common(...)` takes in an argument.
```
>>> a = collections.Counter('abcdababc')
>>> a.most_common()
[('a', 3), ('b', 3), ('c', 2), ('d', 1)]
>>> a.most_common(2)
[('a', 3), ('b', 3)]
``` | [`most_common`](http://docs.python.org/2/library/collections.html#collections.Counter) already does this. `counter.most_common(5)` is the top five elements and their counts. | retrieving dictionary elements by index rather than key | [
"",
"python",
"python-2.7",
""
] |
I have a large file which I need to read in and make a dictionary from. I would like this to be as fast as possible. However my code in python is too slow. Here is a minimal example that shows the problem.
First make some fake data
```
paste <(seq 20000000) <(seq 2 20000001) > largefile.txt
```
Now here is a minima... | If you want the thing you said in the comment, then you can do it easily in pandas:
Let's say you have a file with the same layout but the entries get duplicated, since in your example you add all the duplicates into a list:
```
1 1
2 2
1 3
3 4
1 5
5 6
```
Then you can read and manipulate the data:
```
In [1]: df = ... | Here are a few quick performance improvements I managed to get:
Using a plain `dict` instead of `defaultdict`, and changing `d[parts[0]].append(parts[1])` to `d[parts[0]] = d.get(parts[0], []) + [parts[1]]`, cut the time by 10%. I don't know whether it's eliminating all those calls to a Python `__missing__` function, ... | Read in large file and make dictionary | [
"",
"python",
"c",
"performance",
"pandas",
"cython",
""
] |
I'm currently struggling with a query and need some help with it.
I've got two tables:
```
messages {
ts_send,
message,
conversations_id
}
conversations {
id
}
```
I want to select the messages having the latest ts\_send from each conversation.
So if I got 3 conversations, I would end up with 3 messages... | ```
SELECT c.id, m.message, m.ts_send
FROM conversations c LEFT JOIN messages m
ON c.id = m.conversations_id
WHERE m.ts_send =
(SELECT MAX(m2.ts_send)
FROM messages m2
WHERE m2.conversations_id = m.conversations_id)
```
The LEFT JOIN ensures that you have a row for each conversation, whether it has... | MySql optimises JOINs much better than correlated subqueries, so I'll walk through the join approach.
The first step is to get the maximum `ts_send` per conversation:
```
SELECT conversations_id, MAX(ts_send) AS ts_send
FROM messages
GROUP BY conversations_id;
```
You then need to `JOIN` this back to the message... | Selecting values from column defined by aggregate function | [
"",
"mysql",
"sql",
""
] |
I have a table with a clob column. Searching based on the clob column content needs to be performed. However
`select * from aTable where aClobColumn = 'value';`
fails but
```
select * from aTable where aClobColumn like 'value';
```
seems to workfine. How does oracle handle filtering on a clob column. Does it suppor... | Yes, it's not allowed (this restriction does not affect `CLOB`s comparison in PL/SQL)
to use comparison operators like `=`, `!=`, `<>` and so on in SQL statements, when trying
to compare two `CLOB` columns or `CLOB` column and a character literal, like you do. To be
able to do such comparison in SQL statements, [dbms\_... | how about
```
select * from table_name where to_char(clob_column) ="test_string"
``` | Querying oracle clob column | [
"",
"sql",
"database",
"oracle",
"hibernate",
"jpa",
""
] |
I am using a select case statement to compare two columns. One value is returned from a table valued function and the other is a database column. If the first value of Preferred First Name is null then I need to show the value of FirstName from a view as a aliased column.
I dont know if my syntax is right. Can someone ... | you can use [isnull](http://technet.microsoft.com/en-us/library/ms184325.aspx) function here:
```
select isnull(.. Massive subquery here..., FirstName)
``` | You must use `IS NULL` instead of `= NULL` when comparing with `NULL`.
But in your case you should use `ISNULL` like so:
```
SELECT
ISNULL(
SELECT ASSTRING
FROM dbo.GetCustomFieldValue('Preferred First Name', view_Attendance_Employees.FileKey),
view_Attendance_Employees.FirstName
) AS ... | Using a select case statement to compare field values | [
"",
"sql",
"t-sql",
""
] |
I have written a function to convert pandas datetime dates to month-end:
```
import pandas
import numpy
import datetime
from pandas.tseries.offsets import Day, MonthEnd
def get_month_end(d):
month_end = d - Day() + MonthEnd()
if month_end.month == d.month:
return month_end # 31/March + MonthEnd() ret... | Revised, converting to period and then back to timestamp does the trick
```
In [104]: df = DataFrame(dict(date = [Timestamp('20130101'),Timestamp('20130131'),Timestamp('20130331'),Timestamp('20130330')],value=randn(4))).set_index('date')
In [105]: df
Out[105]:
value
date
2013-01-01 -0.... | If the date column is in datetime format and is set to starting day of the month, this will add one month of time to it:
```
df['date1']=df['date'] + pd.offsets.MonthEnd(0)
``` | pandas: convert datetime to end-of-month | [
"",
"python",
"pandas",
""
] |
I am trying to write a Python script that will calculate how many business days are in the current month. For instance if `month = August` then `businessDays = 22`.
Here is my code for discovering the month:
```
def numToMonth( num ):
months = ["January", "February", "March", "April", "May", "June", "July", "Augus... | This is a long-winded way, but at least it works and doesn't require anything other than the standard modules.
```
import datetime
now = datetime.datetime.now()
holidays = {datetime.date(now.year, 8, 14)} # you can add more here
businessdays = 0
for i in range(1, 32):
try:
thisdate = datetime.date(now.yea... | I would simply use built-in module [calendar](http://docs.python.org/2/library/calendar.html):
```
import calendar
weekday_count = 0
cal = calendar.Calendar()
for week in cal.monthdayscalendar(2013, 8):
for i, day in enumerate(week):
# not this month's day or a weekend
if day == 0 or i >= 5:
... | Using Python to count the number of business days in a month? | [
"",
"python",
"date",
""
] |
I am trying to iterate through two lists one with 76 files and the other with 76 variables to read the files to.
I figured I can iterate through them with zip(list1, list2) but for some reason it is not working.
Here is what I am doing:
```
list1=['file1', 'file2', 'file3']
list2=['v1','v2','v3']
for i,j in zip(list1,... | ```
j=pyfits.getdata(i)
```
This line doesn't store the data to the variable whose name is stored in `j`. Rather, it stores the data to the variable `j`. What you want is instead to make a list of the data:
```
data = [pyfits.getdata(filename) for filename in list1]
```
This will create a list where `data[0]` is the... | I assume you're trying to assign the strings in `list2` to the array that `pyfits.getdata()` returns. However, `list2` contains strings, and you can't assign an array to a string this way. There are some hacky ways to do it, but it's not good practice in Python. I'd recommend using a dictionary, where the strings in `l... | use zip with two lists | [
"",
"python",
"list",
"zip",
"iteration",
""
] |
Assume I have an n-dimensional matrix in Python represented as lists of lists. I want to be able to use an n-tuple to index into the matrix. Is this possible? How?
Thank you! | Here is one way:
```
matrx = [ [1,2,3], [4,5,6] ]
def LookupByTuple(tupl):
answer = matrx
for i in tupl:
answer = answer[i]
return answer
print LookupByTuple( (1,2) )
``` | Using
```
>>> matrix = [[1, 2, 3], [4, 5, 6]]
```
You can do:
```
>>> array_ = numpy.asarray(matrix)
>>> array_[(1,2)]
6
```
Or without numpy:
```
>>> position = (1,2)
>>> matrix[position[0]][position[1]]
6
``` | Use tuples/lists as array indices (Python) | [
"",
"python",
"matrix",
""
] |
I was used VirtualBox manual setups with virtualenvs inside them to run Django projects on my local machine. Recently I discovered Vagrant and decided to switch to it, because it seems very easy and useful.
But I can not figure - do I need still use virtualenv Vagrant VM, is it encouraged practice or forbidden? | If you run one vagrant VM per project, then there is no direct reason to use virtualenv.
If other contributors do not use vagrant, but do use virtualenv, then you might want to use it and support it to make their lives easier. | As [Devin stated](https://stackoverflow.com/a/18271644/41747), it is not necessary to use `virtualenv` when you deploy to a vagrant machine as long as you are the sole user of the machine. However, I would still enable the use of a `virtualenv`, *setup.py*, etc. even if you do not use it for development or deployment.
... | Do I need to use virtualenv with Vagrant? | [
"",
"python",
"django",
"virtual-machine",
"virtualenv",
"vagrant",
""
] |
So I'm trying to clean some phone records in a database table.
I've found out how to find exact matches in 2 fields using:
```
/* DUPLICATE first & last names */
SELECT
`First Name`,
`Last Name`,
COUNT(*) c
FROM phone.contacts
GROUP BY
`Last Name`,
`First Name`
HAVING c > 1;
```
Wow, g... | The first thing you should do shoot the person that named your columns with spaces in them.
Now then, try this:
```
SELECT DISTINCT
c.id,
c.`first name`,
c.`last name`,
c.`general mobile`,
c.`general phone`,
c.`business phone`
from contacts_test c
join contacts_test c2
on (c.`general mobile... | In my experience, when cleaning up data, it's much better to have a comprehending view of the data, and a simple way to manage it, than to have a big and bulky query that does all the analysis at once.
You can also, (more-or-less) renormalize the database, using something like:
```
Create view VContactsWithPhones
as
... | Deduping database records comparing values in numerous fields | [
"",
"mysql",
"sql",
"deduplication",
""
] |
I tried to compile my python work with pyinstaller, with command:
```
pyinstaller.py -F zchat_server.py
```
and got error msg:
F:\workplace\Python\network-study\zchat\dist>zchat\_server.exe
```
Traceback (most recent call last):
File "<string>", line 2, in <module>
File "D:\pyinstaller-2.0\PyInstaller\loader\iu... | I did some research on this - it seems like there are problems with PyInstaller and Zope.
Here are some reference links:
[Problems finding module Zope](http://www.pyinstaller.org/ticket/615)
[PyInstaller fails to find module Zope](http://www.pyinstaller.org/ticket/502) - This link also speaks of a potential solution... | `zope.interface` is a dependency of Twisted. Does pyinstaller have a configuration file somewhere where you need to declare that dependency? | importError with pyinstaller using Twisted | [
"",
"python",
"twisted",
"pyinstaller",
""
] |
This is what I am trying to do. Basically I have some columns deliberately left blank in table `Staging_X` and to be updated later. I would like to update those columns using the `case` conditions below. I want to implement this in a stored procedure.
```
UPDATE Staging_X
SET Staging_X.[NoMaterial]
(SELECT (... | ```
UPDATE Staging_X
SET [NoMaterial] =
case when [Up]+[Test]+[Mon]+[Down_percentage]=0
then 168 else [Lost]*1.68 end
WHERE [NoMaterial] is null
``` | If I understand you correctly, you dont need a selected like that as the values are all in the same row.
So try something like
```
UPDATE Staging_X
SET Staging_X.[NoMaterial] =
case
when ((([Up]+[Test])+[Mon])+[Down_percentage])*(1.68)=(0)
then (168)
else [Los... | Update Multiple Rows using CASE statement | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
So I am designing a program which needs to index a nested list, using a stored list of coordinates:
e.g
```
coordinate = [2,1]
```
For a function which returns the element in the nested list, I use
```
return room[coordinate[0]][coordinate[1]]
```
My programming instincts tell me that this seems overly long, and t... | You can unpack the coordinates into more than one variable.
```
i, j = [2, 1]
return room[i][j]
```
or
```
coordinates = [2, 1]
### do stuff with coordinates
i, j = coordinates
return room[i][j]
``` | The `numpy` module has convenient indexing. It would work well if your `room` is very large.
```
>>> import numpy as np
>>> room = np.arange(12).reshape(3,4)
>>> room
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> coords = (2, 1) # it's important this is a tuple
>>> room[coords]
9
```
... | More pythonic method of indexing with a list of coordinates | [
"",
"python",
"list",
"coordinates",
""
] |
I am facing a problem in finding the sum of values stored in a column,
I have a table like this:
```
gs_cycle_no | from_time | to_time | total_hours(varchar) ...
GSC-334/2012 | 13:00 | 7:00 | 42:00
GSC-334/2012 | 8:30 | 3:45 | 6:00
.
.
.
```
What i need to find is the `Sum(total_hour... | if you have no minutes and only hours, then you can do something like:
```
select
cast(sum(cast(replace(total_hours, ':', '') as int) / 100) as nvarchar(max)) + ':00'
from Table1
group by gs_cycle_no
```
if you don't, try this:
```
with cte as
(
select
gs_cycle_no,
sum(cast(left(total_hours, ... | This will work:
```
;with times as (
select gs_cycle_no = 'GSC-334/2012', total_hours = '8:35'
union all SELECT gs_cycle_no = 'GSC-334/2012', '5:00'
union all SELECT gs_cycle_no = 'GSC-334/2012', '16:50'
union all SELECT gs_cycle_no = 'GSC-334/2012', '42:00'
union all SELECT gs_cycle_no = 'GSC-335/... | How to get sum of time field in SQL server 2008 | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Here's what I have:
```
from pprint import pprint
Names = {}
Prices = {}
Exposure = {}
def AddName():
company_name = input("Please enter company name: ")
return company_name
def AddSymbol(company_name):
stock_symbol = input("Please enter a stock symbol: ")
Names[stock_symbol] = company_name
retu... | In `AddSymbol(company_name)` you return the entire `Names` dictionary. This entire dictionary is then passed into the `AddPrices` function. `AddPrices` is meant to have a stock symbol passed into it (a `str`) but you're passing a `dict`. You could modify `AddSymbol` to return `stock_symbol` instead of `Names`.
I would... | Your `AddSymbol` returns `Names`, which is dictionary. Dictionary can't be used as dictionary key.
Just use `return stock_symbol` in `AddSymbol`. | Using the same key in two dictionaries (Python) | [
"",
"python",
"hash",
"dictionary",
"key",
""
] |
Can somebody explain this odd behavior of [**`regexp_matches()`**](http://www.postgresql.org/docs/current/interactive/functions-string.html#FUNCTIONS-STRING-OTHER) in PostgreSQL 9.2.4 (same result in 9.1.9):
```
db=# SELECT regexp_matches('test string', '$') AS end_of_string;
end_of_string
---------------
{""}
(1 ro... | It looks like it was a bug in PostgreSQL. I verified for sure it is fixed in 9.3.8. Looking at the release notes, I see possible references in:
## 9.3.4
> * Allow regular-expression operators to be terminated early by query
> cancel requests (Tom Lane)
>
> This prevents scenarios wherein a pathological regular ex... | I am not sure about what I am going to say because I don't use PostgreSQL so this is just me thinking out loud.
Since you are trying to match the end of string/line `$`, then in the first situation the outcome is expected, but when you turn on global match modifier `g` and because matching the end of line character do... | regexp_matches() returns two matches for $ (end of string) | [
"",
"sql",
"regex",
"postgresql",
""
] |
In Python we can get the index of a value in an array by using `.index()`.
But with a NumPy array, when I try to do:
```
decoding.index(i)
```
I get:
> AttributeError: 'numpy.ndarray' object has no attribute 'index'
How could I do this on a NumPy array? | Use `np.where` to get the indices where a given condition is `True`.
Examples:
For a 2D `np.ndarray` called `a`:
```
i, j = np.where(a == value) # when comparing arrays of integers
i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays
```
For a 1D array:
```
i, = np.where(a == value) # inte... | **You can convert a numpy array to list and get its index .**
for example:
```
tmp = [1,2,3,4,5] #python list
a = numpy.array(tmp) #numpy array
i = list(a).index(2) # i will return index of 2, which is 1
```
this is just what you wanted. | Index of element in NumPy array | [
"",
"python",
"arrays",
"numpy",
"indexing",
"indexof",
""
] |
I would like to add together the values from a dictionary in Python, if their keys begin with the same letter..
For example, if I have this dictionary: `{'apples': 3, 'oranges': 5, 'grapes': 4, 'apricots': 2, 'grapefruit': 9}`
The result would be: `{'A': 5,'G': 13, 'O': 5}`
I only got this far and I'm stuck:
```
fo... | Take the first character of each key, call `.upper()` on that and sum your values by that uppercased letter. The following loop
```
out = {}
for key, value in original.iteritems():
out[key[0].upper()] = out.get(key[0].upper(), 0) + value
```
should do it.
You can also use a [`collections.defaultdict()` object](h... | You can use a [`defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict) here:
```
from collections import defaultdict
new_d = defaultdict(int)
for k, v in d.iteritems():
new_d[k[0].upper()] += v
print new_d
```
Prints:
```
defaultdict(<type 'int'>, {'A': 5, 'O': 5, 'G': 13})
``` | How to add in a dictionary the values that have similar keys? | [
"",
"python",
""
] |
How can I convert `VARCHAR` data like `'20130120161643730'` to `DATETIME` ?
`CONVERT(DATETIME, '20130120161643730')` does not work.
However, `CONVERT (DATETIME, '20130120 16:16:43:730')` works. I guess it needs data in correct format.
Is there a valid way that can be used to convert to `DATETIME` directly from unfor... | You can make it a little more compact by not forcing the dashes, and using `STUFF` instead of `SUBSTRING`:
```
DECLARE @Var VARCHAR(100) = '20130120161643730';
SET @Var = LEFT(@Var, 8) + ' '
+ STUFF(STUFF(STUFF(RIGHT(@Var, 9),3,0,':'),6,0,':'),9,0,'.');
SELECT [string] = @Var, [datetime] = CONVERT(DATETIME, @Var)... | ```
DECLARE @var VARCHAR(100) = '20130120161643730'
SELECT convert(datetime,(LEFT(@var,8)+' '+SUBSTRING(@var,9,2)+':'+SUBSTRING(@var,11,2)+':'+SUBSTRING(@var,13,2)+':'+RIGHT(@var,3)))
```
The only possible way to convert this type of string to date time is to break it and then convert it to DateTime. Also, Concat does... | Convert varchar data to datetime in SQL server when source data is w/o format | [
"",
"sql",
"sql-server",
"datetime",
"type-conversion",
"varchar",
""
] |
I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:
```
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
```
Is there any better way to do it? someth... | You can use [`operator.itemgetter`](https://docs.python.org/3/library/operator.html#operator.itemgetter):
```
from operator import itemgetter
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)
```
Or you can use [numpy](http://www.numpy.org/):
```
import numpy as np
a = np.array([... | Alternatives:
```
>>> map(a.__getitem__, b)
[1, 5, 5]
```
---
```
>>> import operator
>>> operator.itemgetter(*b)(a)
(1, 5, 5)
``` | Access multiple elements of list knowing their index | [
"",
"python",
"python-3.x",
"list",
"indexing",
"element",
""
] |
I just want to minify the rows of the code. I have two loops with the only difference two lines. Is it possible (functions or classes) to change the lines in each occasion? The two loops are:
```
cursor = ''
while True:
data = API_like_query(id,cursor)
#more code
for i in data['data']:
ids_likes +... | You can create a function quite easily:
```
def do_stuff(api_func, get_data_func):
cursor = ''
while True:
data = api_func(id, cursor)
#more code
for i in data['data']:
ids_likes += get_data_func(i) + ', '
#more code
```
Then the first loop can be reproduced with:
... | `joinedquery=izip(API_like_query(id,cursor),API_com_query(id,cursor))` if query length the same. then `for i1,i2 in joinedquery:` | Slightly different loops in python / Minimize code | [
"",
"python",
"optimization",
""
] |
I have this schema, it's one of my first:
```
CREATE TABLE location (
id INT AUTO_INCREMENT PRIMARY KEY,
locality VARCHAR(20),
administrative_area_level_1 VARCHAR(20),
administrative_area_level_2 VARCHAR(20),
administrative_area_level_3 VARCHAR(20),
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17),
updated TIMESTAMP ON UPD... | Your code should be as follows:
```
CREATE TABLE location (
id INT AUTO_INCREMENT PRIMARY KEY,
locality VARCHAR(20),
administrative_area_level_1 VARCHAR(20),
administrative_area_level_2 VARCHAR(20),
administrative_area_level_3 VARCHAR(20),
loc VARCHAR (17) NOT NULL,
rad VARCHAR (17),
updated T... | Your second table creation is failed since you're using wrong brackets (`{..}` instead of `(..)`)
As for foreign key - all explanation could be found in manual pages ([here](http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html) and [here](http://dev.mysql.com/doc/refman/5.6/en/create-table-foreig... | Linking tables in MYSQL - Do I need a foreign key | [
"",
"mysql",
"sql",
"database",
""
] |
Let's say I have a table similar to the following:
```
Item Description Time
----- ----------- -----
ItemA1 descript 08-16-2013 00:00:00
ItemA2 descript 08-16-2013 00:00:00
ItemA3 descript 08-16-2013 00:00:00
.
.
ItemAN ... | You can try something like:
```
SELECT MAX(Time)
FROM yourTable
WHERE Time < (SELECT MAX(Time) FROM yourTable)
```
[**`SQLFiddle Demo`**](http://sqlfiddle.com/#!2/e7b29/1) | One approach:
```
SELECT t.*
FROM mytable t
JOIN ( SELECT l.time
FROM mytable l
GROUP BY l.time
ORDER BY l.time DESC
LIMIT 1,1
) m
ON m.time = t.time
```
This uses an inline view (assigned an alias of m) to return the second "greatest" time value. The GROUP BY gets us ... | SELECT rows with the second highest value in a column | [
"",
"mysql",
"sql",
"database",
"select",
""
] |
Is their any other way or `sql` query to find the database table names with a particular column than shown below,
```
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'NameID'
``` | In SQL Server, you can query [`sys.columns`](http://technet.microsoft.com/en-us/library/ms176106.aspx).
Something like:
```
SELECT
t.name
FROM
sys.columns c
inner join
sys.tables t
on
c.object_id = t.object_id
WHERE
c.name = 'NameID'
```
You might want an additional ... | you can run this query
```
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%Column%' -- write the column you search here
ORDER BY schema_name, table_name;
``` | find sql table name with a particular column | [
"",
"sql",
"sql-server",
""
] |
I am having trouble changing a column called `end_date` in a table called `key_request` from time with time zone to `timestamp` in my Postgres database . I have tried using the following code:
```
alter table key_request alter column end_date type timestamp with time zone using end_date::timestamp with time zone
```
... | I woul do this in a series of steps
1. Alter the table, adding a new column `end_date1` as `time with time zone`
2. Copy the date from `end_date`(old) to `end_date1`
3. Alter the table, droping the old `end_date` column
4. Alter the table,reaming `end_date1` to `end_date` | you can do something like this:
```
alter table key_request
alter column end_date type timestamp with time zone using date('20130101') + end_date;
```
`sql fiddle demo` | alter column from time with time zone to timestamp | [
"",
"sql",
"postgresql",
"timestamp",
"postgresql-9.2",
"alter",
""
] |
How will you find the sum of numbers in between two numbers. For example, the sum of numbers between 1 and 5 is 9 which is 2 + 3 + 4. | Since the sum of integers from 1 to N equals N\*(N+1) / 2, it's pretty straightforward:
```
create function sumBetween(@p_Lower integer, @p_Upper integer) returns int
as
begin
return ((@p_Upper-1) * @p_Upper)/2 - (@p_Lower * (@p_Lower+1))/2
end
select dbo.sumBetween(1,5)
```
[SQL Fiddle](http://www.sqlfiddle.com/#... | Mathematical formula:
((a + b)\*n/2) - a - b
where n is the count of digits between a and b including a and b
If a = 2 and b = 5 then
((2 + 5)\*4/2) - 2 - 5 = 7 | How will you find the sum of numbers in between two numbers. | [
"",
"sql",
"sql-server",
""
] |
In python you can create a tempfile as follows:
```
tempfile.TemporaryFile()
```
And then you can write to it. Where is the file written in a GNU/Linux system? I can't seem to find it in the /tmp directory or any other directory.
Thank you, | Looking at `.name` on a file handle is indeed one way to see where the file exists. In the case of [`TemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.TemporaryFile) (on \*NIX systems), you'll see `<fdopen>`, indicating an open file handle, but no corresponding directory entry. You'll need to use ... | Call the [`tempfile.gettempdir()` function](http://docs.python.org/2/library/tempfile.html#tempfile.gettempdir):
> Return the directory currently selected to create temporary files in.
You can change where temporary files are created by setting the [`tempfile.tempdir` value](http://docs.python.org/2/library/tempfile.... | Where does python tempfile writes its files? | [
"",
"python",
"linux",
"temporary-files",
""
] |
say I have this list of list
```
listlist = [[0,0,0,1],[0,0,1,1],[1,0,1,1]]
```
and a empty dict()
```
answer = dict()
```
and say I want to find the leftmost non-zero in each list such that I can save the index of that non-zero number into a dictionary like:
```
for list in listlist: #(this is how the first itera... | Assuming only `0`s and `1`s this should work
```
i = 0
for mylist in listlist:
answer[i] = mylist.index(1)
i += 1
```
I recommend that you do not name your list `list`, that overrides some functionality. I prefer to default to the variable name `mylist` | If it's only ever `0`s and `1`s just do something like,
```
>>> answer = {i: lst.index(1) for i, lst in enumerate(listlist)}
>>> answer
{0: 3, 1: 2, 2: 0}
```
Also, don't use `list` as a variable name since it will mask `list` built-in. | Python: finding leftmost non-zero in list of lists | [
"",
"python",
"python-3.x",
""
] |
I want to use the excellent [line\_profiler](http://pythonhosted.org/line_profiler), but only some of the time. To make it work I add
```
@profile
```
before every function call, e.g.
```
@profile
def myFunc(args):
blah
return
```
and execute
```
kernprof.py -l -v mycode.py args
```
But I don't want to ha... | Instead of *removing* the `@profile` decorator lines, provide your own pass-through no-op version.
You can add the following code to your project somewhere:
```
try:
# Python 2
import __builtin__ as builtins
except ImportError:
# Python 3
import builtins
try:
builtins.profile
except AttributeErro... | You don't need to import `__builtins__`/`builtins` or `LineProfiler` at all, you can simply rely on a `NameError` when trying to lookup `profile`:
```
try:
profile
except NameError:
profile = lambda x: x
```
However this needs to be included in every file that uses `profile`, but it doesn't (permanently) alte... | Python profiling using line_profiler - clever way to remove @profile statements on-the-fly? | [
"",
"python",
"profiling",
"decorator",
"python-decorators",
""
] |
I have a PostgreSQL table of the following format:
```
uid | defaults | settings
-------------------------------
abc | ab, bc | -
| |
pqr | pq, ab | -
| |
xyz | xy, pq | -
```
I am trying to list all the uids which contain ab in the `defaults`... | It's not really about bash but you can call your query command using psql. You can try this format:
```
psql -U username -d database_name -c "SELECT uid FROM table_name WHERE defaults LIKE 'ab, %' OR defaults LIKE '%, ab'
```
Or maybe simply
```
psql -U username -d database_name -c "SELECT uid FROM table_name WHERE ... | [@user000001 already provided the bash part](https://stackoverflow.com/a/18229746/939860). And the query could be:
```
SELECT uid
FROM tbl1
WHERE defaults LIKE '%ab%'
```
But this is inherently **unreliable**, since this would also find 'fab' or 'abz'. It is also hard to create a fast index.
Consider **normalizin... | Looping through a PostgreSQL table in bash | [
"",
"sql",
"bash",
"postgresql",
""
] |
I've got a search function for news articles that looks like this (contains more than 5 search items):
```
SELECT TOP 5 *
FROM NewsArticles
WHERE (headline LIKE '% sustainable %'OR
headline LIKE '% sustainability %' OR
headline LIKE '% conservation %' OR
headline LIKE '% environmental % OR
headline LIKE '% environment... | Since you get multiple hits on multiple words, you can use the selected ID's as a filter for the actual selection of the articles:
```
Select TOP 5 *
from NewsArticles
where ID in (SELECT ID
FROM NewsArticles as n
JOIN #SearchItem as s
ON n.headline COLLATE DATABASE_DEFAULT LIKE '% ' + s.Search + ' %' OR... | If you are doing these types of searches, you should use full text search. You need to read up in BOL about how to set this up as it is complicated. However when you have a wildcard as the first character, then SQL server cannot use indexes which is why this is slow. | T-SQL - How can I make a SELECT query with multiple LIKE clauses quicker? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Having some trouble with an `if/else` command in which only part of it is working. When the script is run it will complete the `if` portion if the `name == check_file`, but if it is false it just skips the `else` statement and moves to the next task. Here is the portion of the code that isn't functioning properly:
```... | If the first `if` is evaluating to true (i.e., to reach the inner `if` at all), then the second one automatically will also evaluate to true, since it's the exact same condition.
You'll want to remove the outer `if`, as an `else: pass` at the end of a loop doesn't do anything. The iteration would just finish executing... | You want to take one action for a set of files and a different action for the rest? Try one if that handles all of the cases.
(edit: change selection criteria)
```
copy_this = {sz_check_file:'sales.xls', sc_check_file:'cosales.xls'}
for name in zip_file_names:
copy_to = copy_this.get(name)
if copy_to is not ... | Python If/Else Completing If function but not Else | [
"",
"python",
"python-2.7",
""
] |
I stumbled upon a situation that shutters my understanding of Pythons variable scope.
Here is the code:
```
transaction_id = None
def parseFileContent(hostID,marketID, content, writeToDB=False):
features = _buildObjects(StringIO.StringIO(content))
for feature in features:
featureID = adapter.addFe... | The Python compiler marks a name as local to a function *if you assign to it*. Your last line assigns to `transaction_id` so it is seen as a local name, not a global.
You need to tell the compiler *explicitly* that `transaction_id` is a global, by using the `global` keyword inside the function:
```
def parseFileConte... | Since Python doesn't have variable declarations, it needs another way to tell what's local to what scope. It does so by defining that anything a function assigns to is local to that function unless overridden by a `global` declaration. Thus, assigning to `transaction_id` makes it a local, and the `print` tries to print... | Another UnboundLocalError: local variable referenced before assignment Issue | [
"",
"python",
"python-2.7",
""
] |
I have a table named `Report`, the columns in `Report` as followed:
```
Id(char)
Name(char)
ParentId(char)
Sequence(int)
SortBy(char)
```
The table has some hierarchies. Each row's `ParentId` is another row's `Id`(the top hierarchy's `ParentId` is NULL). The `SortBy` filed is either `"Name"` or `"... | You can use a `CASE` in the order by to dynamically sort by the parent. The only tricky issue with your case is that the columns you can sort by are different data types. In that case you have to cast them to a common data type.
## Query
The query is simple. Left join to the parent and use the parent to determine the... | ```
select r.*
from Report r
left join Report p on p.ID = r.ParentID
order by r.ParentID,
case p.SortBy
when 'Sequence' then right('0000000000' + cast(r.Sequence as varchar(10)), 10)
else r.Name
end
``` | Dynamic Order By using parent value and mixed column types | [
"",
"sql",
"sql-server",
"t-sql",
"sql-order-by",
""
] |
I am trying to create a python dictionary which is to be used as a java script var inside a html file for visualization purposes. As a requisite, I am in need of creating the dictionary with all names inside double quotes instead of default single quotes which Python uses. Is there an easy and elegant way to achieve th... | You can construct your own version of a dict with special printing using `json.dumps()`:
```
>>> import json
>>> class mydict(dict):
def __str__(self):
return json.dumps(self)
>>> couples = [['jack', 'ilena'],
['arun', 'maya'],
['hari', 'aradhana'],
... | `json.dumps()` is what you want here, if you use `print(json.dumps(pairs))` you will get your expected output:
```
>>> pairs = {'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}
>>> print(pairs)
{'arun': 'maya', 'bill': 'samantha', 'jack': 'ilena', 'hari': 'aradhana'}
>>> import json
>>> print(j... | How to create a Python dictionary with double quotes as default quote format? | [
"",
"python",
"python-2.7",
"dictionary",
"python-3.x",
""
] |
Is there a good way to store configuration settings for a web2py app?
I have written a little app that includes a script which looks up user attributes (names, email addresses, etc) from LDAP. Our corporate LDAP server requires a bind, before it allows a search for user details.
I want to share my app from a GitHub r... | There are different options, but one approach is just to put the settings in a module and import. In /yourapp/modules/ldap\_settings.py:
```
ldap_host = 'example.com'
ldap_port = 389
...
```
And then in your function:
```
def user_info(username):
from ldap_settings import *
...
``` | I believe the proper web2py method is to use AppConfig module. Take a look at it in the web2py reference manual here:
<http://web2py.com/books/default/chapter/29/13/deployment-recipes#AppConfig-module> | web2py application configuration file | [
"",
"python",
"configuration",
"ldap",
"web2py",
""
] |
I have a piece of code below that creates a few threads to perform a task, which works perfectly well on its own. However I'm struggling to understand why the print statements I call in my function do not execute until all threads complete and the `print 'finished'` statement is called. I would expect them to be called... | This happens due to stdout buffering. You still can flush the buffers:
```
import sys
print 'starting'
sys.stdout.flush()
```
You can find more info on this issue [here](https://stackoverflow.com/questions/107705/python-output-buffering) and [here](https://stackoverflow.com/questions/230751/how-to-flush-output-of-py... | **For python 3** you can now use the `flush` param like that:
`print('Your text', flush=True)` | Python multithreaded print statements delayed until all threads complete execution | [
"",
"python",
"multithreading",
""
] |
I run into the following problem when writing scientific code with Python:
* Usually you write the code iteratively, as a script which perform some computation.
* Finally, it works; now you wish to run it with multiple inputs and parameters and find it takes too much time.
* Recalling you work for a fine academic inst... | First of all, I would like to stress that the problem that Uri described in his question is indeed faced by many people doing scientific computing. It may be not easy to see if you work with a developed code base that has a well defined scope - things do not change as fast as in scientific computing or data analysis. [... | I might be wrong, but simply using GNU command line utilities, like [`parallel`](http://www.gnu.org/software/parallel), or even `xargs`, seems appropriate to me for this case. Usage might look like this:
```
cat inputs | parallel ./job.py --pipe > results 2> exceptions
```
This will execute `job.py` for every line of... | Harvesting the power of highly-parallel computers with python scientific code | [
"",
"python",
"concurrency",
"parallel-processing",
"multiprocessing",
"scientific-computing",
""
] |
Im writing a VB app that is scrubbing some data inside a DB2 database. In a few tables i want to update entire columns. For example an account number column. I am changing all account numbers to start at 1, and increment as I go down the list. Id like to be able to return both the old account number, and the new one so... | DB2 has a really [nifty feature](https://www.ibm.com/docs/en/db2/11.5?topic=statement-result-sets-from-sql-data-changes) where you can select data from a "data change statement". This was tested on DB2 for Linux/Unix/Windows, but I think that it should also work on at least [DB2 for z/OS](https://www.ibm.com/docs/en/db... | A possible solution is to add an additional column (let's call it `oldaccntnum`) and assign old values to that column as you do your update.
Then drop it when you no longer need it. | Update a table and return both the old and new values | [
"",
"sql",
"db2",
""
] |
i am fairly new to development, so sorry if my question is silly.
I have joined many columns together, and it has a join between a one to many relationships table too.
Anyways the output that i am getting now is
```
Patient_Name episode_id DOB primary_insu sec_insur patient_id
name, ... | You can use `MAX()` to combine the rows:
```
SELECT LTRIM(RTRIM(isnull(pat.LNAME, ''))) + ', ' + LTRIM(RTRIM(isnull(pat.FNAME, ''))) + ', ' + LTRIM(RTRIM(isnull(pat.MNAME, ''))) AS Patient_Name,
pat.episode_id,
CONVERT (VARCHAR (11), pat.dob, 110) AS DOB,
MAX(CASE
WHEN covh.copay_priority ... | You would join to the table twice once to get the primary and once to get the secondary. Use a left join because not all patients will have insureance. Example follows. You will need to adjust it for your actual table strucuture and any other joins you need to get other information.
```
SELECT p.Patient_name, i1.insu... | How to join when multiple records are returned which are the same? | [
"",
"sql",
"join",
""
] |
For some reason my code is not catching an exception when I throw it. I have
```
def trim_rad(rad):
...
if not modrad.shape[0]:
raise IndexError("Couldn't find main chunk")
return modrad, thetas
```
Then later I call that function:
```
try:
modrad, thetas = trim_rad(rad)
except IndexError("C... | You gave `except` an instance of an `IndexError`. Do this instead:
```
try:
modrad, thetas = trim_rad(rad)
except IndexError:
print "Couldn't find main chunk"
return 0
```
Here is an example:
```
>>> try:
... [1][1]
... except IndexError('no'):
... pass
...
Traceback (most recent call last):
Fi... | Catch just the `IndexError`.
```
try:
raise IndexError('abc')
except IndexError('abc'):
print 'a'
Traceback (most recent call last):
File "<pyshell#22>", line 2, in <module>
raise IndexError('abc')
IndexError: abc
try:
raise IndexError('abc')
except IndexError:
print 'a'
a # Output
```
**S... | Python not catching exception | [
"",
"python",
""
] |
I currently have a `DataFrame` laid out as:
```
Jan Feb Mar Apr ...
2001 1 12 12 19
2002 9 ...
2003 ...
```
and I would like to "unpivot" the data to look like:
```
Date Value
Jan 2001 1
Feb 2001 1
Mar 2001 12
...
Jan 2002 9
```
What is the best way to accomplish this using p... | You just have to do `df.unstack()` and that will create a MultiIndexed Series with month as a first level and the year as the second level index. If you want them to be columns then just call `reset_index()` after that.
```
>>> df
Jan Feb
2001 3 4
2002 2 7
>>> df.unstack()
Jan 2001 3
2002 ... | Another solution would be to use `pandas.melt` to avoid unnecessary creation of a `MultiIndex`, though this isn't *that* expensive if your frame is small and with my solution you still have to create a temporary for the "molten" data. The guts of `melt` suggest that both `id_vars` and `value` are copied since `id_vars`... | Unpivot Pandas Data | [
"",
"python",
"pandas",
"numpy",
"dataframe",
""
] |
Per the below record set, I have three columns and need to return the max CaseId value for every set of PersonIds.
```
ID PersonId CaseId
66 30 410
1681 30 3508
226 31 958
856 31 2213
1023 31 2400
```
For example, I would like to return a recordset such as:
```
ID P... | You can also use a subquery to find max CaseId value for each set of PersonIds.
```
SELECT *
FROM dbo.Employee t
JOIN (
SELECT PersonId, MAX(CaseId) AS CaseId
FROM dbo.Employee
GROUP BY PersonId
) t2 ON t.PersonId = t2.PersonId AND t.CaseId = t2.CaseId
```
For improving performance u... | You had it almost right:
```
WITH latestRecord
AS
(
SELECT CaseId,
PersonId,
ID,
RN=ROW_NUMBER() OVER (PARTITION BY PersonId ORDER BY CaseId DESC)
FROM Employee
)
SELECT CaseId,
PersonId,
ID
FROM latestRecord
WHERE RN = 1
ORDER BY CaseId
``` | Get max value from record set with common columns | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm using an object-oriented approach with inheritance to solve a problem, and I'm wondering how to apply 'Duck Typing' principles to this problem.
I have a class `BoxOfShapes` which would be instantiated with a list of `Shapes` ( `Circle`, `Square` and `Rectangle`)
```
import numpy as np
class Shape(object):
de... | This isn't really about duck typing, but about inheritance generally (you could ask exactly the same question about Java, which has no concept of duck typing, for example).
What you want to do is simply to create a dictionary mapping types to list of instances. It's fairly easy to do that dynamically:
```
from collec... | You've already paved the way to use inheritance effectively. You define a `type` method for each shape. Simply create a dictionary that maps the type to a list of elements of that type in your `BoxOfShapes` implementation.
As others have suggested, use the built-in `type()` function. If you want a string representatio... | How to use duck typing effectively with inheritance | [
"",
"python",
"oop",
"duck-typing",
""
] |
stackoverflow,
I have a matrix containing complex numbers (ex. -2.2982235934153075E-11+2.1179547211742553E-9i) that I need to import to a numpy array. I've been using `genfromtext(file)` to parse all my other, real values, but I'm getting a `nan` for all complex values. Any ideas?
```
self.raw = (genfromtxt(self.loc,... | The way I ended up having to do this was to first `replace('i', 'j')` for all cells in the original .csv file and save the new, corrected file. Afterwards, reading the .csv with `dtype=str` caused errors in subsequent calculations, but it turns out you can parse the .csv with `dtype=complex128`, which solved all my pro... | You can do:
```
import numpy as np
a = np.genfromtxt(filename, converters={0: lambda x: x.replace('i','j')},
dtype=str)
a = np.complex_(a)
```
Note that the `converters` parameter was required because your text file is using `i` to denote the imaginary part.
It may be easier to convert your text fi... | numpy read .csv with complex number | [
"",
"python",
"csv",
"file-io",
"numpy",
"complex-numbers",
""
] |
I am concerned about the order of files and directories given by `os.walk()`. If I have these directories, `1`, `10`, `11`, `12`, `2`, `20`, `21`, `22`, `3`, `30`, `31`, `32`, what is the order of the output list?
Is it sorted by numeric values?
```
1 2 3 10 20 30 11 21 31 12 22 32
```
Or sorted by ASCII values, lik... | `os.walk` uses `os.listdir`. Here is the docstring for `os.listdir`:
> listdir(path) -> list\_of\_strings
>
> Return a list containing the names of the entries in the directory.
>
> ```
> path: path of directory to list
> ```
>
> **The list is in arbitrary order**. It does not include the special
> entries '.' and '..... | `os.walk()` yields in each step what it will do in the next steps. You can in each step influence the order of the next steps by sorting the lists the way you want them. Quoting [the 2.7 manual](http://docs.python.org/2/library/os.html#os.walk):
> When topdown is True, the caller can modify the dirnames list in-place ... | In what order does os.walk iterates iterate? | [
"",
"python",
"sorting",
"os.walk",
""
] |
With python's argparse, how do I make a subcommand a required argument? I want to do this because I want argparse to error out if a subcommand is not specified. I override the error method to print help instead. I have 3-deep nested subcommands, so it's not a matter of simply handling zero arguments at the top level.
... | There was a change in 3.3 in the error message for required arguments, and subcommands got lost in the dust.
<http://bugs.python.org/issue9253#msg186387>
There I suggest this work around, setting the `required` attribute after the `subparsers` is defined.
```
parser = ArgumentParser(prog='test')
subparsers = parser.... | In addition to [hpaulj's answer](https://stackoverflow.com/a/18283730/4137828): you can also use the `required` keyword argument with [`ArgumentParser.add_subparsers()`](https://docs.python.org/3.7/library/argparse.html#argparse.ArgumentParser.add_subparsers) since **Python 3.7**. You also need to pass `dest` as argume... | argparse with required subcommands | [
"",
"python",
"argparse",
""
] |
I am trying to find the ***most recently modified*** (from here on out 'newest') file of a specific type in Python. I can currently get the newest, but it doesn't matter what type. I would like to only get the newest MP3 file.
Currently I have:
```
import os
newest = max(os.listdir('.'), key = os.path.getctime)
pr... | Use [glob.glob](http://docs.python.org/2/library/glob#glob.glob):
```
import os
import glob
newest = max(glob.iglob('*.[Mm][Pp]3'), key=os.path.getctime)
``` | Assuming you have imported os and defined your path, this will work:
```
dated_files = [(os.path.getmtime(fn), os.path.basename(fn))
for fn in os.listdir(path) if fn.lower().endswith('.mp3')]
dated_files.sort()
dated_files.reverse()
newest = dated_files[0][1]
print(newest)
``` | How to find newest file with .MP3 extension in directory? | [
"",
"python",
"file-io",
""
] |
I'd like to get the sums for two different values in a list. For example:
```
sample = [(1,3), (4,5), (8,2)]
```
I'd like the output to be
```
13, 10
```
I could do it in a couple of different ways. Here's how I have it currently:
```
t1 = 0
t2 = 0
for item1, item2 in sample:
t1 += item1
t2 += item2
```
W... | You can try this:
```
from itertools import izip
sample = [(1,3), (4,5), (8,2)]
t1, t2 = map(sum, izip(*sample))
```
You can also use a list comprehension instead of `map`.
```
from itertools import izip
sample = [(1,3), (4,5), (8,2)]
t1, t2 = [sum(t) for t in izip(*sample)]
```
And you can deal with more than two ... | A functoinal approach:
```
from operator import add
from functools import partial
sample = [(1,3), (4,5), (8,2)]
result = reduce(partial(map, add), sample)
```
`result` will be the list `[13, 10]` after running this code. | Two sums from one list | [
"",
"python",
"list",
""
] |
Here is the question:
Given two words with the same number of letters in each, work out how many letters need to be changed to get from the first word to the second. A more complex version of edit distance is commonly used in spelling auto-correct algorithms on phones and word processors to find candidate corrections.... | You can try something like:
```
sum(c1 != c2 for c1,c2 in zip(w1,w2))
```
`zip(w1,w2)` creates a generator that returns tuples consisting of corresponding letters of `w1` and `w2`. i.e.:
```
>>> list(zip(w1,w2))
[('h', 'j'), ('e', 'e'), ('l', 'l'), ('l', 'l'), ('o', 'y')]
```
We iterate over these tuples (`c1` gets... | Using [difflib](http://docs.python.org/2/library/difflib.html):
```
>>> import difflib
>>> w1, w2 = 'hello', 'jelly'
>>> matcher = difflib.SequenceMatcher(None, w1, w2)
>>> m = sum(size for start, end, size in matcher.get_matching_blocks())
>>> n = max(map(len, (w1, w2))) # n = len(w1)
>>> n - m
2
``` | Comparing two strings in python? | [
"",
"python",
"python-3.x",
""
] |
I have an SQL query I'm trying to convert to AREL. It starts out:
```
SELECT COUNT(id) > 0 AS exists...
```
So far, I have:
```
Arel::Table.new(:products)[:id].count.gt(0).as(:exists)
```
but I get:
```
NoMethodError - undefined method `as' for #<Arel::Nodes::GreaterThan:0x007fc98c4c58d0>
```
Any ideas? | I'm not sure this is possible: `gt`, `eq`, etc. are expressions used in the WHERE part of the query. What you're trying to do here is operate in the list of fields that is part of the SELECT, which is handled by Arel's `project` method. This is valid:
```
Arel::Table.new(:products).project(product[:id].count.as(:exist... | This should do it, gives you either `0` or `1`.
```
Arel::Table.new(:products)[:id].count.as('exists').gt(0)
```
Test:
```
> Arel::Table.new(:products)[:id].count.as('exists').gt(0).to_sql
=> "COUNT([products].[id]) AS exists > 0"
``` | How do I name a calculated boolean column with AREL? | [
"",
"sql",
"ruby-on-rails",
"arel",
""
] |
Suppose I have a `pandas.DataFrame` called `df`. The columns of `df` represent different individuals and the index axis represents time, so the (i,j) entry is individual j's observation for time period i, and we can assume all data are `float` type possibly with `NaN` values.
In my case, I have about 14,000 columns an... | You can do this, but would need to cythonize (otherwise much slower); however
memory footprint should be better (this gives the number of nan observations, your gives number of valid observations, but easily convertible)
```
l = len(df.columns)
results = np.zeros((l,l))
mask = pd.isnull(df)
for i, ac in enumerate(df):... | You can actually make @Jeff's answer a little faster by only iterating up to (but not including) `i + 1` in the nested loop, and because correlation is symmetric you can assign values at the same time. You can also move the `mask[i]` access outside of the nested loop, which is a tiny optimization but might yield some p... | Fast way to see common observation counts for Python Pandas correlation matrix entries | [
"",
"python",
"numpy",
"pandas",
"missing-data",
""
] |
Ok I have been pondering the idea of dynamic columns, what I mean by this is a table of columns named `January`......`December`.
User at runtime would select a month **range** such as `Feb` to `July`.
What I would normally do is fetch all columns from my code behind then sort the ones I need and ones I don't.
But I ... | There is a way to do this, but involves restructuring your table.
Your problem is that the (month) column names are [meta data](http://en.wikipedia.org/wiki/Metadata), and you want to see them
Instead of
```
year | Jan | feb | Mar | Apr | etc
2013 | 10 | 9 | 11 | 4 | 0
```
as actual data.
What you want to... | And what is the problem with storing data in a normalized form -- a separate row for each month? Then, when you want to fetch a particular range, just use the `where` clause.
SQL Server offers the `pivot` functionality, which makes it pretty easy to put row values into columns. | SQL Server: array of columns | [
"",
"sql",
"sql-server-2008",
""
] |
I have a list of long strings and I'd like to get the indexes of the list elements that match a substring of strings in another list. Checking if a list item contains a a single string inside a list is easy to do with list comprehensions, like [this question](https://stackoverflow.com/questions/4843158/check-if-a-pytho... | You are looking for the `any()` function here:
```
matching = [i for i, x in enumerate(my_list) if any(thing in x for thing in things_to_find)]
```
Demo:
```
>>> my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> things_to_find = ['abc', 'def']
>>> [i for i, x in enumerate(my_list) if any(thing in x for thin... | Maybe something like?:
```
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
things_to_find = ['abc', 'def']
for n, e in enumerate(my_list):
for m in things_to_find:
if m in e:
print '%s is in %s at %s' % (m, e, n)
```
Output:
```
abc is in abc-123 at 0
def is in def-456 at 1
abc is in a... | Find list index of list items within other list items | [
"",
"python",
"python-3.x",
"list-comprehension",
""
] |
I am doing a dice value recognition hobby project that I want to run on a Raspberry Pi. For now, I am just learning OpenCV as that seems like the hardest thing for me. I have gotten this far, where I have dilated, eroded and canny filtered out the dice. This has given me a hierarchy of contours. The image shows the bou... | There could be multiple ways to do it:
1. Use hole filling and then morphological operator to filter circles.
2. Simpler approach would be using white pixel density (% of white pixels). Five dot would have higher white pixel density.
3. Use image moments (mathematical property which represents shape and structure of i... | As Sivam Kalra Said, there are many valid approaches.
I would go with template matching, as it should be robust and relatively easy to implement.
* using your green regions in the canny image, copy each found die face from the original grayscale image into a smaller search image. The search image should be slightly l... | Counting the pips on dice using OpenCV | [
"",
"python",
"opencv",
""
] |
Let's say that I open this file (wordlist.txt):
```
...
14613 bore
14614 borg
14615 boric
14616 boris
14621 born
14622 borne
14623 borneo
14624 boron
...
```
How do I pick the word next to it, if a variable is, for example, 14623? | If you're just doing this once, do it the way falsetru showed.
If you need to look up multiple numbers, store the entries in a dictionary:
```
wordmap = {}
with open('wordlist.txt') as f:
for line in f:
key, value = line.split()
wordmap[key] = value
```
Now you can look up any number like this:
... | Try following:
```
with open('wordlist.txt') as f:
for line in f:
row = line.split()
if row[0] == '14623':
print(row[1])
break
``` | How do I pick a word that's next to a number in a file in Python? | [
"",
"python",
"list",
""
] |
I have this table:
```
create table #tbl
(
dt datetime
)
insert into #tbl values ('2013-01-01 00:00:00')
insert into #tbl values ('2013-02-01 00:00:00')
insert into #tbl values ('2013-02-02 00:00:00')
insert into #tbl values ('2013-03-01 00:00:00')
```
I need to get the start and end of each distinct month... | ```
;with dm as (
select distinct rm = datediff(mm, 0, dt)
from #tbl t
)
select ms.[start], me.[end]
from dm
cross apply (select dateadd(mm, dm.rm, 0)) ms([start])
cross apply (select dateadd(ms, -3, dateadd(month, 1, ms.Value))) me([end])
```
The logic is following. For each date in the table find a n... | Try this:
```
SELECT DISTINCT DATEADD(month, DATEDIFF(month, 0, MyDate), 0) as startOfMonth,
DATEADD(day, -1, DATEADD(month, 1, DATEADD(day, 1 - day(MyDate), MyDate))) as endOfMonth
FROM MyTable
``` | Get start and end of each month between two dates | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I don't understand why the interpreter cannot handle the following:
```
SELECT id
FROM a
INNER JOIN b ON a.id = b.id
```
This query wil result in an error: `Ambiguous column name 'id'`
Which makes sense because the column in defined in multiple tables in my query. However, I clearly stated to only return the rows ... | Let's be clear about a few things. First, it is always a good idea to include table aliases when referring to columns. This makes the SQL easier to understand.
Second, you are assuming that because of the `=` in the `on` condition, the two fields are the *same*. This is not true. The *values* are the same.
For instan... | How do you exepect the interpreter to know which column to use ?
Since it doesn't have a real brain (sadly..!), you need to explicitly specify the table where you want the id from.
In this example it could be :
```
SELECT a.id
FROM a
INNER JOIN b ON a.id=b.id
```
Even if the id values are the same, the column st... | SQL: Ambiguity on key fields | [
"",
"sql",
"relational-database",
""
] |
My requirement is to reduce the size of an image and display in a square box(50 x 50). If the size of the image is less than the size of the square box , the image should be displayed as it is. As an initial attempt I tried with the below code, with the intention to reduce the size of all images with:
```
picSize = Qt... | The following code will achieve your requirement:
```
imgPath = os.path.join(self.imgFolder, img)
actualImage = QtGui.QImage(imgPath)
pixmap = QtGui.QPixmap(imgPath)
pixmap = pixmap.scaled(500, 500, QtCore.Qt.KeepAspectRatio)
lbl = QtGui.QLabel(self)
... | You can use the `scaledToWidth` or scaledToHeight`method on the`QImage` class.
```
img= QtGui.QImage(imgPath)
pixmap = QtGui.QPixmap(img.scaledToWidth(50))
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
``` | Reducing size of an image in PySide | [
"",
"python",
"qt",
"python-2.7",
"pyside",
""
] |
I have table like:

I wanted to get all DeviceID which have key=1 more then 1 time. Like device ID= 3 have two rows with key=1, same as 4. What is the query to get that result?
I tried a lot but couldn't find any solution. It seems not possible with... | You should be able to use `GROUP BY` and `HAVING` to get the `DeviceIds` with more than one row:
```
select deviceid
from yourtable
where key = 1
group by deviceid
having count(key) > 1
```
See [SQL Fiddle with Demo](http://sqlfiddle.com/#!4/275d5/1) | Try something like this:
```
SELECT DeviceID
FROM YourTable
WHERE key = 1
GROUP BY DeviceID
HAVING COUNT(*) > 1
``` | SQL query for rows having one value repeated in more then one column | [
"",
"sql",
"oracle11g",
"duplicates",
""
] |
I want to change a primary key and all table rows which reference to this value.
```
# table master
master_id|name
===============
foo|bar
# table detail
detail_id|master_id|name
========================
1234|foo|blu
```
If I give a script or function
```
table=master, value-old=foo, value-new=abc
```
I want to c... | If you need to change PK you could use [`DEFFERED CONSTRAINTS`](https://www.postgresql.org/docs/current/static/sql-set-constraints.html):
> SET CONSTRAINTS sets the behavior of constraint checking within the current transaction. IMMEDIATE constraints are checked at the end of each statement. **DEFERRED constraints are... | The easiest way to deal with primary key changes - by far - is to `ALTER` your referring foreign key constraints to be `ON UPDATE CASCADE`.
You are then free to update the primary key values, and the changes will cascade to child tables. It can be a very slow process due to all the random I/O, but it will work.
You d... | Generate SQL to update primary key | [
"",
"sql",
"postgresql",
"introspection",
""
] |
If comm is null, I need to update the `comm` value to `salary`, which is `1100`, but it is not getting updated.
My data is:
```
sal comm
9000 800
2975 800
3000 800
1100
3000 800
```
My code is:
```
declare
cursor c3 is select sal,comm,ename from emp where deptno=20
for update of comm;... | This line:
```
update emp set comm=(select c.sal from emp e where e.comm=c.comm )
```
... will not work. You know `c.comm` is null, so you're trying to find a record on `emp` with a matching value, and you can't use an equality test for `null`. This also won't work if there is more than one record where `comm` is `nu... | The following should work:
```
update Employee
set com = sal
where com is null
``` | Update using subquery in plsql block | [
"",
"sql",
"oracle",
""
] |
Suppose I have a Pandas DataFrame like the below and I'm encoding categorical\_1 for training in scikit-learn:
```
data = {'numeric_1':[12.1, 3.2, 5.5, 6.8, 9.9],
'categorical_1':['A', 'B', 'C', 'B', 'B']}
frame = pd.DataFrame(data)
dummy_values = pd.get_dummies(data['categorical_1'])
```
The values for 'cat... | First, if you want pandas to take more values simply add them to the list sent to the `get_dummies` method
```
data = {'numeric_1':[12.1, 3.2, 5.5, 6.8, 9.9],
'categorical_1':['A', 'B', 'C', 'B', 'B']}
frame = pd.DataFrame(data)
dummy_values = pd.get_dummies(data['categorical_1'] + ['D','E'])
```
as in pytho... | I encountered the same problem as yours, that is how to unify the dummy categories between training data and testing data when using `get_dummies()` in Pandas. Then I found a solution when exploring the House Price competition in Kaggle, that is to process training data and testing data at the same time. Suppose you ha... | Specify list of possible values for Pandas get_dummies | [
"",
"python",
"machine-learning",
"pandas",
""
] |
When I run this code, I get this result:
```
15
15
```
I expect the output should be
```
15
17
```
but it is not. The question is: why?
```
def make_adder_and_setter(x):
def setter(n):
x = n
return (lambda y: x + y, setter)
myadder, mysetter = make_adder_and_setter(5)
print myadder(10)
mysetter(7... | Python 2.x has a syntax limitation that doesn't allow to capture a variable in read/write.
The reason is that if a variable is assigned in a function there are only two possibilities:
1. the variable is a global and has been declared so with `global x`
2. the variable is a local of the function
more specifically it'... | You are setting a **local** variable `x` in the `setter()` function. Assignment to a name in a function marks it as a local, unless you specifically tell the Python compiler otherwise.
In Python 3, you can explicitly mark `x` as non-local using the `nonlocal` keyword:
```
def make_adder_and_setter(x):
def setter(... | Closure in python? | [
"",
"python",
"closures",
"python-2.x",
""
] |
```
name salary
----- -----
mohan 500
ram 1000
dinesh 5000
hareesh 6000
mallu 7500
manju 7500
praveen 10000
hari 10000
```
How would I find the nth-highest salary from the aforementioned table using Oracle? | you can use something like this.. this is what i have tested and then pasted here
```
SELECT *
FROM tblname
WHERE salary = (SELECT *
FROM (SELECT *
FROM (SELECT *
FROM (SELECT DISTINCT( salary )
... | ```
select *
from ( select s.*, rank() over (order by salary desc) as rownumber
from salary )
where rownumber = nth
```
pass your salary number in place of "nth" | Find out the nth-highest salary from table | [
"",
"sql",
"oracle11g",
"greatest-n-per-group",
""
] |
How can I write a unit test for a tornado handler that authenticates a user via a secure cookie? Here is the code (and sudo code) for a dummy test that I'd like to make pass. I'm using Tornado 3.1.
```
from tornado.web import Application, RequestHandler
from tornado.escape import to_unicode, json_decode, json_encode
... | Using [mock](https://pypi.python.org/pypi/mock):
```
import mock
...
class UserAPITest(AsyncHTTPTestCase):
def get_app(self):
self.app = Application([('/', MainHandler)],
cookie_secret='asdfasdf')
return self.app
def test_user_profile_annoymous(self):
with mock.pa... | It seems you may try to use a `create_signed_value` function from `tornado.web` module:
```
from tornado.web import create_signed_value
class UserAPITest(AsyncHTTPTestCase):
def get_app(self):
self.app = Application([('/', MainHandler)],
cookie_secret='asdfasdf')
... | How to use a test tornado server handler that authenticates a user via a secure cookie | [
"",
"python",
"unit-testing",
"cookies",
"tornado",
""
] |
I want to pass the first value (number) of the inside list to a dict if the words match
buffer :
```
['from',
'landi',
'stsci',
'edu',
'four'...]
```
list\_1 :
```
[('focus', [-1, -2]),
('four', [-3.3, -1.04]),
...)]
for key in docs_A_rec:
for word, number_1,number_2 in list_1:
if word in buffer:... | there is a bug in your second loop, fix it as the following:
```
for key in docs_A_rec:
for word, (number_1,number_2) in list_1:
if word in buffer:
docs_A_rec[key]['idf'][word] = templist[word][number_1]
```
Hope helps! | should be like this:
```
[('focus', [-1, -2]),
('four', [-3.3, -1.04]),
...)]
for key in docs_A_rec:
for word, (number_1,number_2) in list_1:
if word in buffer:
docs_A_rec[key]['idf'][word] = list_1[word][number_1]
``` | passing values from a strange list in python | [
"",
"python",
"list",
"variables",
""
] |
Can someone tell me why, after I run the code below, these are the values the variables refer to now:
```
x = [1, 2, 3, 5]
x1 = [1, 2, 3, 5]
x2 = [1, 2, 3]
y = [1, 2, 3]
y1 = [1, 2, 3]
y2 = [1, 2, 3]
```
Why isn't `y = [1, 2, 3, 5]` ?
And why isn't `x1 = [1, 2, 3]`?
Because, following this logic:
```
a = 1
b ... | The statement:
```
x1 = x
```
creates a copy of reference to the same list as pointed to by `x`. Now you are passing `x` to the function, where you append a value to `x`:
```
x.append(5)
```
this will affect the list pointed to by the original `x` outside the function, and eventually also reflect the modification f... | Simple. Mutable objects (such as lists) pass by reference, whereas immutable (such as integers) pass by value.
When you do `x1 = x`, `x1` refers to `x`; so any change to `x` also applies to `x1`, because **they refer to the same object**. `x.append(5)` changes the original `x`, and thus `x1` by reference.
However, wh... | Python: Why is this the output when executed? | [
"",
"python",
"list",
"copy",
""
] |
say I have a dict like this :
```
d = {'a': 8.25, 'c': 2.87, 'b': 1.28, 'e': 12.49}
```
and I have a value
```
v = 3.19
```
I want to say something like :
```
x = "the key with the value CLOSEST to v"
```
Which would result in
```
x = 'c'
```
Any hints on how to approach this? | Use [`min(iter, key=...)`](http://docs.python.org/2/library/functions.html#min)
```
target = 3.19
key, value = min(dict.items(), key=lambda (_, v): abs(v - target))
``` | You can do this:
```
diff = float('inf')
for key,value in d.items():
if diff > abs(v-value):
diff = abs(v-value)
x = key
print x
```
which gives `'c'`
You can also use `min` to do the job:
```
x = min(((key, abs(value-v)) for key,value in d.items()), key = lambda(k, v): v)[0]
``` | python dict, find value closest to x | [
"",
"python",
"python-3.x",
""
] |
As the title suggests how do I write a bash script that will execute for example 3 different Python programs as separate processes? And then am I able to gain access to each of these processes to see what is being logged onto the terminal?
Edit: Thanks again. I forgot to mention that I'm aware of appending `&` but I'm... | You can run a job in the background like this:
```
command &
```
This allows you to start multiple jobs in a row without having to wait for the previous one to finish.
If you start multiple background jobs like this, they will all share the same `stdout` (and `stderr`), which means their output is likely to get inte... | Try something like:
```
command1 2>&1 | tee commandlogs/command1.log ;
command2 2>&1 | tee commandlogs/command2.log ;
command3 2>&1 | tee commandlogs/command3.log
...
```
Then you can tail the files as the commands run. Remember, you can tail them all by being in the directory and doing a "tail \*.log"
Alternativel... | Have bash script execute multiple programs as separate processes | [
"",
"python",
"linux",
"bash",
"scripting",
""
] |
```
EquipmentUseId CollectionPointId EmployeeNum ShopOrder StartDateTime
366 69 9999 999999 4/26/13 3:29 PM
373 69 4878 107321 4/26/13 10:19 PM
385 69 4971 107321 4/27/13 7:35 AM
393 ... | ```
with orderedTickets as
(
select ShopOrder, min(StartDateTime) as date
, row_number() over (order by min(StartDateTime)) as rownumber
from table
where ShopOrder is not null
group by ShopOrder
)
select t1.ShopOrder, datediff(ss, t1.StartDateTime, t2.StartDateTime)
from orderedTickets ... | Use CTE, -
```
;with Equipment as
(
select EquipmentUseId, CollectionPointId, EmployeeNum, ShopOrder, StartDateTime, row_number() over (PARTITION BY ShopOrder order by EquipmentUseId) as rownumber
from your_table
),
Equipment2 AS (
select EquipmentUseId, CollectionPointId, EmployeeNum, ShopOrder, StartDateTime, row_... | Calculating differences in time from multiple rows | [
"",
"sql",
"t-sql",
"sql-server-2005",
"datediff",
""
] |
In my *image classification software* there are tables `result` and `image`.
**One result** can contain **many images**.
Each image may be classified as **positive** using value 'P' or **negative** 'N' in the column `image.preclassification`
A result, where more images are positive IS positive.
I want to select only ... | Clever query. But I think you can simplify it:
```
select r.result_id
from result r join
image i
on r.result_id = i.result_id
group by r.result_id
having sum(case when i.preclassification = 'P' then 1 else 0 end) >
sum(case when i.preclassification = 'N' then 1 else 0 end);
```
You can also write thi... | Another way to do it is - just to map "positive" to positive and "negative" to negative :)
```
select r.result_id
from result as r
inner join image as i on r.result_id = i.result_id
group by r.result_id
having sum(case i.preclassification when 'P' then 1 when 'N' then -1 end) > 0
``` | Selecting only rows from master table where subtable rows fulfill a condition | [
"",
"sql",
"postgresql",
""
] |
Is it feasible to use a variable which is also another argument variable when the first argument is not specified in argparse?
So in the following code:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_option('-f', '--file', dest='outputfile')
parser.add_option('-d', '--db', dest='outpufDB')
```
And... | The traditional way to do this (the way people did it going back to old Unix getopt in C) is to give `outputDB` a useless "sentinel" default value. Then, after you do the parse, if `outputDB` matches the sentinel, use `outputfile`'s value instead.
---
See [`default`](http://docs.python.org/dev/library/argparse.html#d... | The simple approach - do your own checking after parse\_args.
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', dest='outputfile')
parser.add_argument('-d', '--db', dest='outpufDB')
args = parser.parse_args()
if args.outpufDB is None:
args.outpufDB = args.outputfile
```
T... | Use another variable when it's not specified in Python's argparse module | [
"",
"python",
"argparse",
""
] |
I have a issue with VIM. I'm trying to install jedi-vim with Vundle plugin, and typing this
"example":
```
import math
math.
```
after dot i get popup with autocomplete. Really not bad, but, i cant choose function/method/class/etc. what i want (arrows somehow doesn't worked, when show popup with autocomplete and pr... | I came across the same problem as you. I am new to vim so I only use a few plugins:
* nerdtree
* jedi-vim
* supertab
* taglist
* vimwiki
* minibufexpl
After trying and error, I found out `jedi-vim` is incompatible with `minibufexpl`. So I deleted `minibufexpl` and everything goes fine. | From [jedi-vim](https://github.com/davidhalter/jedi-vim/blob/master/README.rst) documentation
Note that the python-mode VIM plugin seems to conflict with jedi-vim, therefore you should disable it before enabling jedi-vim. | Jedi-vim doesn't work correctly | [
"",
"python",
"vim",
"autocomplete",
"jedi-vim",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.