Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I run that code in python shell 3.3.2, but it gives me `SyntaxError: invalid syntax`.
```
class Animal(object):
"""Makes cute animals."""
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
print self.name #error occurs in that l... | [`print` is a function in Python 3](http://docs.python.org/3.0/whatsnew/3.0.html), not a keyword as it was in earlier versions. You have to enclose the arguments in parentheses.
```
def description(self):
print(self.name)
print(self.age)
``` | `print` is a function ([see the docs](http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function)):
You want:
```
...
def description(self):
print(self.name)
print(self.age)
...
``` | Python:Why invalid syntax here? | [
"",
"python",
"syntax",
""
] |
So I have a function that takes the following: `times` = a list of datetime objects, `start` = a datetime object, and `end` = a datetime object. and returns a list that are the datetime objects **between** start and end
```
def func(times,start,end):
return times[start:end],(times.index(start),times.index(end))
``... | You can use bisect
```
import bisect
def func(times, start, end):
bucket = [start, end]
out = [x for x in times if bisect.bisect(bucket, x) is 1 or x in bucket]
return out, (times.index(out[0]), times.index(out[-1]))
``` | A naive approach for this question:
```
def func(times, start, end):
s = 0
e = len(times)-1
while s < len(times) and times[s]< start:
s+=1
while e >= 0 and times[e] > end:
e-=1
if (e < 0 or s >= len(times) or s > e):
return None
return times[s:e+1], (s,e)
``` | index estimation for a list of datetimes in python | [
"",
"python",
"function",
"datetime",
""
] |
I am writing a simple command-line program that shows the current time and let user set the alarm. However, the alarm did not ring as the raw\_input was blocking it. I have even implement multithreading but it didn't work as well. Here's the full code:
```
import datetime, time, thread, os
program_running = True
now ... | I find the implementation with globals and only a single thread for alarms a little strange. This way you can always only have set one alarm at a time and there will always be an alarm thread running even without any alarm being set. Also your now is never being updated to the alarm shouldn't run at all.
Maybe consider... | 2 Things
1. In the while loop of thread, put a sleep
2. Just before the inner if of thread, do
now = datetime.datetime.now() | Command line multithreading | [
"",
"python",
"multithreading",
"python-multithreading",
"raw-input",
""
] |
My mind has gone totally blank this morning. I'm creating a proc and need it to pull results with a date-related WHERE clause. The WHERE clause should state that the report should look back two months from `GetDate()`.
This is using T-SQL in SQL Server 2012. The column containing the date for the clause is called `[De... | If `[Delivery Date]` has both date and time and want to consider time as well? then try
```
SELECT *
FROM tableName
WHERE [Delivery Date] >= DATEADD(month, -2, GETDATE())
```
If `[Delivery Date]` is only a date or ignore the time part? then try
```
SELECT *
FROM tableName
WHERE [Delivery Date] >= CONVERT(date, DAT... | Try this
```
SELECT *
FROM tableName
WHERE [Delivery Date] < DATEADD(month, -2, GETDATE())
```
MSDN Link for [DATEADD](http://msdn.microsoft.com/en-us/library/ms186819.aspx)
Similar Question: [Stackoverflow link](https://stackoverflow.com/questions/5425627/sql-query-for-todays-date-minus-two-months) | GetDate() Function in T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to get the datestamp on the file in mm/dd/yyyy format
```
time.ctime(os.path.getmtime(file))
```
gives me detailed time stamp `Fri Jun 07 16:54:31 2013`
How can I display the output as `06/07/2013` | You want to use [`time.strftime()`](http://docs.python.org/2/library/time.html#time.strftime) to format the timestamp; convert it to a time tuple first using either [`time.gmtime()`](http://docs.python.org/2/library/time.html#time.gmtime) or [`time.localtime()`](http://docs.python.org/2/library/time.html#time.localtime... | ```
from datetime import datetime
from os.path import getmtime
datetime.fromtimestamp(getmtime(file)).strftime('%m/%d/%Y')
``` | python get time stamp on file in mm/dd/yyyy format | [
"",
"python",
"date",
"unix-timestamp",
""
] |
When I create a `unittest.TestCase`, I can define a `setUp()` function that will run before every test in that test case. Is it possible to skip the `setUp()` for a single specific test?
It's possible that wanting to skip `setUp()` for a given test is not a good practice. I'm fairly new to unit testing and any suggest... | From the [docs](http://docs.python.org/2/library/unittest.html#unittest.TestCase.setUp) (italics mine):
> `unittest.TestCase.setUp()`
>
> Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by
> this method will be considered an error rather than a... | You can use Django's @tag decorator as a criteria to be used in the setUp method to skip if necessary.
```
# import tag decorator
from django.test.utils import tag
# The test which you want to skip setUp
@tag('skip_setup')
def test_mytest(self):
assert True
def setUp(self):
method = getattr(self,self._testMe... | Is it possible to skip setUp() for a specific test in python's unittest? | [
"",
"python",
"unit-testing",
"testing",
"python-unittest",
""
] |
I have a variable and I need to know if it is a datetime object.
So far I have been using the following hack in the function to detect datetime object:
```
if 'datetime.datetime' in str(type(variable)):
print('yes')
```
But there really should be a way to detect what type of object something is. Just like I can... | You need `isinstance(variable, datetime.datetime)`:
```
>>> import datetime
>>> now = datetime.datetime.now()
>>> isinstance(now, datetime.datetime)
True
```
**Update**
As noticed by Davos, `datetime.datetime` is a subclass of `datetime.date`, which means that the following would also work:
```
>>> isinstance(now, ... | Use `isinstance`.
```
if isinstance(variable,datetime.datetime):
print "Yay!"
``` | Detect if a variable is a datetime object | [
"",
"python",
"datetime",
""
] |
Is there a function in Access VBA that works like the `IN` function in SQL?
I'm looking for something like:
```
if StringValue IN(strA, strB, strC) Then
``` | While sgedded's answer is correct, here's another way that I think is a little cleaner code.
```
Select Case stringValue
Case strA, strB, strC
'is true statements
End Select
```
<http://msdn.microsoft.com/en-us/library/gg278665(v=office.14).aspx> | You should be able to use the `Instr` function:
```
If Instr("," & strA & "," & strB & "," & strC & ",", "," & stringValue & ",") > 0 Then
```
This places commas around each element to make sure the search is exact.
<http://office.microsoft.com/en-us/access-help/instr-function-HA001228857.aspx> | IN Function for Access VBA | [
"",
"sql",
"ms-access",
"vba",
"ms-access-2003",
""
] |
I had previously learnd that in cherrypy you have to expose a method to make it a view target and this is also spread all over the documentation:
```
import cherrypy
@cherrypy.expose
def index():
return "hello world"
```
But I have inherited a cherrypy application which seems to work without exposing anythi... | Because it relies on the routes dispatcher which works slightly differently. Mainly, it doesn't need the `exposed` attribute that the `expose` decorator sets because the URLs are explicitly described (as you can see with the `connect(...)` method). On the other hand, the default CherryPy dispatcher doesn't provide an e... | I have read this page: <http://docs.cherrypy.org/stable/concepts/dispatching.html>
I am not sure but maybe the dispatching replaces the necessity for exposing. | How come this cherrypy application does not use `expose`decorators? | [
"",
"python",
"decorator",
"cherrypy",
"web-frameworks",
""
] |
I save 'haystack' in a temporary variable, but when I modify 'haystack', the temporary variable change too. Why? Help please? it's normal? in PHP I didn't have this problem.
```
# -*- coding:utf-8 -*-
haystack = [1,'Two',3]
tempList = haystack
print 'TempList='
print tempList
iterable = 'hello'
haystac... | You are not creating a copy of the list; you merely create a second reference to it.
If you wanted to create a temporary (shallow) copy, do so explicitly:
```
tempList = list(haystack)
```
or use the full-list slice:
```
tempList = haystack[:]
```
You modify the mutable list in-place when calling `.extend()` on th... | `tempList` and `haystack` are just two names that you bind to the same `list`.
Make a copy:
```
tempList = list(haystack) # shallow copy
``` | How to use a temporary variable in Python 2.7 - memory | [
"",
"python",
"variables",
"memory",
""
] |
First of, I've searched this topic here and elsewhere online, and found numorous articles and answers, but none of which did this...
I have a `table` with ratings, and you should be able to update your rating, but not create a new row.
My table contains: `productId`, `rating`, `userId`
If a row with `productId` and ... | First add a `UNIQUE` constraint:
```
ALTER TABLE tableX
ADD CONSTRAINT productId_userId_UQ
UNIQUE (productId, userId) ;
```
Then you can use the `INSERT ... ON DUPLICATE KEY UPDATE` construction:
```
INSERT INTO tableX
(productId, userId, rating)
VALUES
(101, 42, 5),
(102, 42, 6),
(103, 42, 0)
ON DUPLI... | You are missing something or need to provide more information. Your program has to perform a SQL query (a SELECT statement) to find out if the table contains a row with a given productId and userId, then perform a UPDATE statement to update the rating, otherwise perform a INSERT to insert the new row. These are separat... | SQL `update` if combination of keys exists in row - else create new row | [
"",
"mysql",
"sql",
""
] |
I have the following table:
```
ItemID Price
1 10
2 20
3 12
4 10
5 11
```
I need to find the second lowest price. So far, I have a query that works, but i am not sure it is the most efficient query:
```
select min(price)
from table
where itemid not in
(select itemid
from table
where pr... | ```
select price from table where price in (
select
distinct price
from
(select t.price,rownumber() over () as rownum from table t) as x
where x.rownum = 2 --or 3, 4, 5, etc
)
``` | ```
SELECT MIN( price )
FROM table
WHERE price > ( SELECT MIN( price )
FROM table )
``` | SQL. Is there any efficient way to find second lowest value? | [
"",
"sql",
"db2",
"subquery",
""
] |
In Matplotlib, it's not too tough to make a legend (`example_legend()`, below), but I think it's better style to put labels right on the curves being plotted (as in `example_inline()`, below). This can be very fiddly, because I have to specify coordinates by hand, and, if I re-format the plot, I probably have to reposi... | Nice question, a while ago I've experimented a bit with this, but haven't used it a lot because it's still not bulletproof. I divided the plot area into a 32x32 grid and calculated a 'potential field' for the best position of a label for each line according the following rules:
* white space is a good place for a labe... | **Update:** User [cphyc](https://stackoverflow.com/users/2601223/cphyc) has kindly created a Github repository for the code in this answer (see [here](https://github.com/cphyc/matplotlib-label-lines)), and bundled the code into a package which may be installed using `pip install matplotlib-label-lines`.
---
Pretty Pi... | How to place inline labels in a line plot | [
"",
"python",
"matplotlib",
"line-plot",
"plot-annotations",
"labellines",
""
] |
I am trying to find a temp directory ,
but when i am trying to get the directory using
```
tempfile.gettempdir()
```
it's giving me error of
```
File "/usr/lib/python2.6/tempfile.py", line 254, in gettempdir
tempdir = _get_default_tempdir()
File "/usr/lib/python2.6/tempfile.py", line 201, in _get_default_temp... | This kind of error occured in two case
1. permission(should be drwxrwxrwt and owened by root)
2. space
To check space(disk usage)just run the command on terminal
```
df -h
```
Will list the disk usage on unix and get the output like
```
Filesystem Size Used Avail Use% Mounted on
/dev/sda5 28G 15G ... | Problem can also occur if **inode** are full.
You can type `df -i`
```
# df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
udev 253841 322 253519 1% /dev
tmpfs 255838 430 255408 1% /run
/dev/xvda1 5120000 5120000 0 100% /
tmpfs 255838 1 255837 ... | No usable temporary directory found | [
"",
"python",
"odoo",
""
] |
I have a table of following/followers that has 3 fields:
`id , FollowingUserName,FollowedUserName`
And I have a table with posts:
```
id,Post,PublishingUsername
```
And I need a query which returns certain fields from post
but the "where" will be where:
* The `PublishingUsernam` From The Posts Will Match The `Fol... | To just get posts:
```
select p.* from posts p where p.PublishingUsername in
(select FollowedUsername from followers)
and p.PublishingUsername = LOGGEDINUSER
```
Or you could use a join:
```
select p.* from posts p
left join followers f on f.PublishingUsername = p.PublishingUsername
and p.publishingUsername = LOGGE... | You're looking to do a [JOIN](http://dev.mysql.com/doc/refman/5.0/en/join.html) it looks like. Basically, you want to select from your post table where the publishing username = followed user name, and where followingusername = loggedin name.
Just taking a stab (since I don't have an SQL server here right now), but it... | "WHERE" Statement From Another Table | [
"",
"sql",
""
] |
I have a data frame with alpha-numeric keys which I want to save as a csv and read back later. For various reasons I need to explicitly read this key column as a string format, I have keys which are strictly numeric or even worse, things like: 1234E5 which Pandas interprets as a float. This obviously makes the key comp... | *Update: this has [been fixed](https://github.com/pydata/pandas/issues/3795): from 0.11.1 you passing `str`/`np.str` will be equivalent to using `object`.*
Use the object dtype:
```
In [11]: pd.read_csv('a', dtype=object, index_col=0)
Out[11]:
A B
1A 0.35633069074776547 ... | Nowadays, (pandas==1.0.5) it just works.
`pd.read_csv(f, dtype=str)` will read everything as string Except for NAN values.
Here is the list of values that will be parse to NAN : [empty string, ‘#N/A’, ‘#N/A N/A’, ‘#NA’, ‘-1.#IND’, ‘-1.#QNAN’, ‘-NaN’, ‘-nan’,
‘1.#IND’, ‘1.#QNAN’, ‘’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘n/a’,... | Pandas reading csv as string type | [
"",
"python",
"pandas",
"casting",
"type-conversion",
"dtype",
""
] |
I am trying to implement a function `primeFac()` that takes as input a positive integer `n` and returns a list containing all the numbers in the prime factorization of `n`.
I have gotten this far but I think it would be better to use recursion here, not sure how to create a recursive code here, what would be the base ... | A simple trial division:
```
def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d) # supposing you want multiple factors repeated
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
```
with `O(sqrt(n))` comple... | The [primefac module](https://pypi.python.org/pypi/primefac) does factorizations with all the fancy techniques mathematicians have developed over the centuries:
```
#!python
import primefac
import sys
n = int( sys.argv[1] )
factors = list( primefac.primefac(n) )
print '\n'.join(map(str, factors))
``` | Prime factorization - list | [
"",
"python",
"python-3.x",
"prime-factoring",
""
] |
I'm running a **Python** code that reads a list of URLs and opens each one of them individually with **urlopen**. Some URLs are repeated in the list. An example of the list would be something like:
* www.example.com/page1
* www.example.com/page1
* www.example.com/page2
* www.example.com/page2
* www.example.com/page2
*... | Use a `collections.defaultdict()` object:
```
from collections import defaultdict
urls = defaultdict(int)
for url in url_source:
print '{}: {}'.format(url, urls[url])
# process
urls[url] += 1
``` | Using `ioStringIO` for simplicity:
```
import io
fin = io.StringIO("""www.example.com/page1
www.example.com/page1
www.example.com/page2
www.example.com/page2
www.example.com/page2
www.example.com/page3
www.example.com/page4
www.example.com/page4""")
```
We use `collections.Counter`
```
from collections import Counte... | How to count the number of time a unique URL is open in python? | [
"",
"python",
"counter",
"urlopen",
""
] |
I'm doing some calculation using (+ operations), but i saw that i have some null result, i checked the data base, and i found myself doing something like `number+number+nul+number+null+number...=null` . and this a problem for me.
there is any suggestion for my problem? how to solve this king for problems ?
thanks | My preference is to use ANSI standard constructs:
```
select coalesce(n1, 0) + coalesce(n2, 0) + coalesce(n3, 0) + . . .
```
`NVL()` is specific to Oracle. `COALESCE()` is ANSI standard and available in almost all databases. | You need to make those values 0 if they are null, you could use [nvl](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions105.htm) function, like
```
SELECT NVL(null, 0) + NVL(1, 0) from dual;
```
where the first argument of NVL would be your column. | Oracle SQL null plus number give a null value | [
"",
"sql",
"oracle10g",
""
] |
I'm nearing what I think is the end of development for a Django application I'm building. The key view in this application is a user dashboard to display metrics of some kind. Basically I don't want users to be able to see the dashboards of other users. Right now my view looks like this:
```
@login_required
@permissio... | Just pull `request.user` and make sure this List is theirs.
You haven't described your model, but it should be straight forward.
Perhaps you have a user ID stored in your List model? In that case,
```
if not request.user == user_list.user:
response = http.HttpResponse()
response.status_code = 403
return ... | I solve similiar situations with a reusable mixin. You can add login\_required by means of a method decorator for dispatch method or in urlpatterns for the view.
```
class OwnershipMixin(object):
"""
Mixin providing a dispatch overload that checks object ownership. is_staff and is_supervisor
are considered... | Django -- Allowing Users To Only View Their Own Page | [
"",
"python",
"django",
"django-views",
"django-urls",
""
] |
Given a set or a list (assume its ordered)
```
myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
```
I want to find out how many numbers appear in a range.
say my range is 10. Then given the list above, I have two sets of 10.
I want the function to return `[10,10]`
if my range was 15. Then I should get `... | With the right key function, the`groupby`method in the `itertools`module makes doing this fairly simple:
```
from itertools import groupby
def ranger(values, range_size):
def keyfunc(n):
key = n/(range_size+1) + 1
print '{} in {}'.format(n, key)
return key
return [len(list(g)) for k, ... | You want to use simple division and the remainder; the [`divmod()` function](http://docs.python.org/2/library/functions.html#divmod) gives you both:
```
def chunks(lst, size):
count, remainder = divmod(len(lst), size)
return [size] * count + ([remainder] if remainder else [])
```
To create your desired output... | Grouping list of integers in a range into chunks | [
"",
"python",
""
] |
I'm looking for an elegant and pythonic way to get the date of the end of the previous quarter.
Something like this:
```
def previous_quarter(reference_date):
...
>>> previous_quarter(datetime.date(2013, 5, 31))
datetime.date(2013, 3, 31)
>>> previous_quarter(datetime.date(2013, 2, 1))
datetime.date(2012, 12, 3... | You can do it the "hard way" by just looking at the month you receive:
```
def previous_quarter(ref):
if ref.month < 4:
return datetime.date(ref.year - 1, 12, 31)
elif ref.month < 7:
return datetime.date(ref.year, 3, 31)
elif ref.month < 10:
return datetime.date(ref.year, 6, 30)
... | Using [dateutil](http://niemeyer.net/python-dateutil):
```
import datetime as DT
import dateutil.rrule as rrule
def previous_quarter(date):
date = DT.datetime(date.year, date.month, date.day)
rr = rrule.rrule(
rrule.DAILY,
bymonth=(3,6,9,12), # the month must be one of these
bymonth... | Calculate the end of the previous quarter | [
"",
"python",
""
] |
```
create table people(
id_pers int,
nom_pers char(25),
d_nais date,
d_mort date,
primary key(id_pers)
);
create table event(
id_evn int,
primary key(id_evn)
);
create table assisted_to(
id_pers int,
id_evn int,
foreign key (id_pers) references people(id_pers),
foreign key (id_evn) references e... | Try this:
```
select distint ae.id_evn,
p1.nom_pers personA, p2.nom_pers PersonB
from assieted_to ae
Join people p1
On p1.id_pers = ae.id_pers
Join people p2
On p2.id_pers = ae.id_pers
And p2.id_pers > p1.id_pers
```
This generates all pairs of people [couples] who assis... | You select two persons, so you need to select two `assisted_event` rows as well, because each person has its own assignment row in the `assisted_event` table. The idea is to build a link between `p1` and `p2` through a pair of `assisted_event` rows sharing the same `id_evn`
```
select p1.id_pers, p2.id_pers
from peopl... | SQL: couple people who assisted to the same event | [
"",
"sql",
"postgresql",
""
] |
I have a problem with mysql alias.
I have this query:
```
SELECT (`number_of_rooms`) AS total, id_room_type,
COUNT( fk_room_type ) AS reservation ,
SUM(number_of_rooms - reservation) AS result
FROM room_type
LEFT JOIN room_type_reservation
ON id_room_type = fk_room_type
WHERE result > 10
GR... | Not 100% but to the best of my knowledge you cant use aliases in your declarations, and thats why you are getting the column issue. Try this:
```
SELECT (`number_of_rooms`) AS total, id_room_type,
COUNT( fk_room_type ) AS reservation ,
SUM(number_of_rooms - COUNT( fk_room_type ) ) AS result
FROM room_type... | To apply a predicate (filter condition) on the result of an aggregate function, you use a Having clause. Where clause expressions are only applicable to intermediate result sets created prior to any aggregation.
```
SELECT (`number_of_rooms`) AS total, id_room_type,
COUNT( fk_room_type ) AS reservation ,
S... | MySql SUM ALIAS | [
"",
"mysql",
"sql",
"sum",
"alias",
""
] |
I have always been using JOINS but today I saw a simple code that was like that:
```
SELECT Name FROM customers c, orders d WHERE c.ID=d.ID
```
It is just the old way? | There is no difference, the execution plan will be the same using that method or `JOIN` | These 2 queries are semantically identical. With an join, predicates can be specified in either the JOIN or WHERE clauses. | What is difference between JOIN and a.ID=b.ID | [
"",
"sql",
"oracle",
""
] |
I know this is a simple fix, but can't seem to find an answer for it:
I am trying to create a batch file that takes all files in a folder downloaded daily from an ftp server, combine them into a separate folder, and then make new files out of the combined file based on the column of the file (this is the part giving m... | I didn't tested it, but this could work:
```
with open('your/file') as file:
line = file.readline()
while line:
rows = line.split('|')
with open(rows[1].strip() + '.txt', 'a') as out:
out.write(line)
line = file.readline()
``` | ```
@ECHO OFF
SETLOCAL enabledelayedexpansion
DEL noderesult*.txt 2>nul
FOR /f "skip=1tokens=1,2*delims=|" %%i IN (logfile.txt) DO (
SET node=%%j
SET node=!node: =!
>>noderesult!node!.txt ECHO(%%i^|%%j^|%%k
)
```
Should do the job, producing `noderesult?.txt` - caution - the `DEL` line deletes all existing `noderes... | Automate text file editing with batch, python, whatever | [
"",
"python",
"text",
"batch-file",
"automation",
""
] |
Is there a possibility to obtain letters (like A,B) instead of numbers (1,2) e.g. as a result of Dense\_Rank function call(in MS Sql) ? | Try this:
```
SELECT
Letters = Char(64 + T.Num),
T.Col1,
T.Col2
FROM
dbo.YourTable T
;
```
Just be aware that when you get to 27 (past `Z`), things are going to get interesting, and not useful.
If you wanted to start doubling up letters, as in `... X, Y, Z, AA, AB, AC, AD ...` then it's going to get a bi... | hint: try this in your SQL Enterprise manager
```
select char(65), char(66), char(67)
```
a full solution, for ranks up to 17,500 (or three letters, up to ZZZ) is:
```
select
case When rnk < 703 Then ''
else Char(64 + ((rnk-26) / 26 / 26)) End +
case When rnk < 27 Then ''
When rnk < 703 Then Char(64 ... | SQL: Is there a possibility to convert numbers (1,2,3,4...) to letters (A,B,C,D...) | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Specs: Ubuntu 13.04, Python 3.3.1
Background: total beginner to Python, came across this "manual sorting" problem.
What I was asked to do: "Have the user enter 3 numeric values and store them in 3 different variables. Without using lists or sorting algorithms, manually sort these 3 numbers from smallest to largest."
... | For three items, you could use `max` and `min` to sort them:
```
a, b, c = 3, 1, 8
x = min(a, b, c) # Smallest of the three
z = max(a, b, c) # Largest of the three
y = (a + b + c) - (x + z) # Since you have two of the three, you can solve for
# the third
print(a, b, c)
print(x, y, z)
``... | Using the Bubble Sort Algorithm:
```
num1=input("Enter a number: ")
num2=input("Enter another number: ")
num3=input("One more! ")
if num1<num2:
temp=0
temp=num1
num1=num2
num2=temp
if num1<num3:
temp=0
temp=num1
num1=num3
num3=temp
if num2<num3:
temp=0
temp=num2
num2=num3
... | How to manually sort a list of numbers in Python? | [
"",
"python",
"list",
"sorting",
"python-3.x",
"manual",
""
] |
I am a Python beginning self-learner, running on MacOS.
I'm making a program with a text parser GUI in tkinter, where you type a command in a `Entry` widget, and hit a `Button` widget, which triggers my `parse()` funct, ect, printing the results to a `Text` widget, text-adventure style.
> > Circumvent the button
>
> ... | Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.
```
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def f... | Another alternative is to use a lambda:
```
ent.bind("<Return>", (lambda event: name_of_function()))
```
Full code:
```
from tkinter import *
from tkinter.messagebox import showinfo
def reply(name):
showinfo(title="Reply", message = "Hello %s!" % name)
top = Tk()
top.title("Echo")
Label(top, text="Enter your... | How do I bind the enter key to a function in tkinter? | [
"",
"python",
"python-3.x",
"tkinter",
"key-bindings",
""
] |
I have list:
```
myList = ['qwer', 'tyu', 'iop12', '3456789']
```
How to check if none of elements in list contains searched substring,
* for string `'wer'` result should be False (exist element containing substring)
* for string `'123'` result should be True (none of element contain such substring) | ```
not any(search in s for s in myList)
```
Or alternatively:
```
all(search not in s for s in myList)
```
For example:
```
>>> myList = ['qwer', 'tyu', 'iop12', '3456789']
>>> not any('wer' in s for s in myList)
False
>>> not any('123' in s for s in myList)
True
``` | The built-in `any` and `all` functions are very useful.
```
not any(substring in element for element in myList)
```
Test runs show that
```
>>> myList = ['qwer', 'tyu', 'iop12', '3456789']
>>> substring = 'wer'
>>> not any(substring in element for element in myList)
False
>>> substring = '123'
>>> not any(substring ... | Check if none of list elements contain searched substring | [
"",
"python",
"list",
"substring",
""
] |
We are super excited about App Engine's support for [Google Cloud Endpoints](https://developers.google.com/appengine/docs/python/endpoints/).
That said we don't use OAuth2 yet and usually authenticate users with username/password
so we can support customers that don't have Google accounts.
We want to migrate our API ... | I'm using webapp2 Authentication system for my entire application. So I tried to reuse this for Google Cloud Authentication and I get it!
webapp2\_extras.auth uses webapp2\_extras.sessions to store auth information. And it this session could be stored in 3 different formats: securecookie, datastore or memcache.
Secur... | I wrote a custom python authentication library called Authtopus that may be of interest to anyone looking for a solution to this problem: <https://github.com/rggibson/Authtopus>
Authtopus supports basic username and password registrations and logins, as well as social logins via Facebook or Google (more social provide... | Custom Authentication for Google Cloud Endpoints (instead of OAuth2) | [
"",
"python",
"google-app-engine",
"google-cloud-endpoints",
""
] |
Just wondering how to write the following SQL in LINQ syntax
```
select U.Id, U.FirstName, U.Surname,
(select COUNT(COESNo) from COESDetails where InspectorId = U.Id) as Count
from UserDetails U
where U.AppearOnReport = 1
```
either Fluent or Query Expression, or Both
Thanks | The fluent syntax is
```
db.UserDetails.Where(ud => ud.AppearOnReport).Select(ud =>
new {
ud.Id,
ud.FirstName,
ud.Surname,
Count = db.COESDetails.Count(c => c.InspectorId == ud.Id)
});
``` | ```
from u in db.UserDetails
join c in db.COESDetails on u.Id equals c.InspectorId into uc
where u.AppearOnReport == 1
select new {
u.Id,
u.FirstName,
u.Surname,
Count = uc.Count()
}
``` | how to write the following in LINQ syntax | [
"",
"sql",
"linq",
""
] |
This topic is in response to a problem I've been having getting Pygame to be set up correctly on my computer. I have Windows 7, Python 3.3 and "64-bit" Windows (now I know what a bit and a byte are, but I don't really understand the implications of having a "64-bit" computer) I'm proficient in Python but know nothing a... | To save yourself pain, just use 32bit python, and 32bit pygame. If you mix 32 and 64 bit, it will not run correctly. That's probably the problem you're having.
Since you have python 3.3, you would use <https://bitbucket.org/pygame/pygame/downloads/pygame-1.9.2a0.win32-py3.3.msi>
You shouldn't have to edit the registr... | As mentioned previously, tkinter would offer a solution. For example, this was created in tkinter (<http://www.youtube.com/watch?v=RHxLkNryOzI>) | Python game design without Pygame | [
"",
"python",
"pygame",
"python-3.3",
""
] |
The file names are dynamic and I need to extract the file extension. The file names look like this:
parallels-workstation-parallels-en\_US-6.0.13976.769982.run.sh
```
20090209.02s1.1_sequence.txt
SRR002321.fastq.bz2
hello.tar.gz
ok.txt
```
For the first one I want to extract `txt`, for the second one I want to extrac... | ```
import os
def splitext(path):
for ext in ['.tar.gz', '.tar.bz2']:
if path.endswith(ext):
return path[:-len(ext)], path[-len(ext):]
return os.path.splitext(path)
assert splitext('20090209.02s1.1_sequence.txt')[1] == '.txt'
assert splitext('SRR002321.fastq.bz2')[1] == '.bz2'
assert split... | Your rules are arbitrary, how is the computer supposed to guess when it's ok for the extension to have a `.` in it?
At best you'll have to have a set of exceptional extensions, eg `{'.bz2', '.gz'}` and add some extra logic yourself
```
>>> paths = """20090209.02s1.1_sequence.txt
... SRR002321.fastq.bz2
... hello.tar.... | What's the way to extract file extension from file name in Python? | [
"",
"python",
"string",
""
] |
I'm trying to interact with an NCURSES program.
As an example I'm using GNU Screen and run aptitude inside. (you could try it with mc instead.)
The program below starts a screen session with -x to connect to my session.
I want to navigate by pressing Arrow-down and Arrow-up.
If I send 'q' for quit I see a box pop u... | > I've changed TERM=xterm to TERM=ansi which fixes it. Why xterm doesn't
> work still puzzles me.
Using Ubuntu 13.04, it looks like the `ansi` and `xterm` control codes aren't quite the same.
```
$ infocmp ansi | grep cud
cr=^M, cub=\E[%p1%dD, cub1=\E[D, cud=\E[%p1%dB, cud1=\E[B,
kcud1=\E[B, kcuf1=\E[... | A good method to obtain codes for particular terminal functions is using the `tput` command, for some particular terminal type with `-T` option.
In Python, use the `curses` module to obtain correct codes:
```
from curses import *
setupterm('xterm')
key_up = tigetstr("kcuul")
key_down = tigetstr("kcudl")
```
You can... | How do I interact with a child process pretending to be a terminal? | [
"",
"python",
"twisted",
""
] |
i have following question regarding GROUP\_CONCAT():
My table has simplified following format:
```
| userId | visitTime | position |
1 TIME1 A
1 TIME2 B
1 TIME3 B
1 TIME4 B
1 TIME5 A
1 TIME6 C
```
With m... | First of all, to implement this you will need a unique id to show you the order of records (otherwise your request is impossible to implement). So I'm going to add an `id` column to your table like this:
```
| id | userId | visitTime | position |
1 1 TIME1 A
2 1 TIME2 B
3 ... | Here is the syntax:
```
Select group_concat(distinct position order by position)
from Table
where userId=1
``` | Group_Concat internal Group by order | [
"",
"mysql",
"sql",
""
] |
Is it possible to get the IP Address of the server programmaticaly in a bottle request?
I need to return a link to a file on the server inside a request and need to know the IP. Bottle will be started on a server with different IPs and all of these IPs will be serve requests.
currently i looks like this:
```
from bo... | If your servers aren't behind a load balancer, just use the `Host` HTTP header.
```
@route('/file')
def getAFileLink():
host = bottle.request.get_header('host')
return {'url': 'http://{}/some/file.abc'.format(host)}
``` | Give a try to `bottle.request.url` ([docs](http://bottlepy.org/docs/dev/api.html#bottle.BaseRequest.url)).
In case you need only scheme and hostname, use [urlparse](http://docs.python.org/2/library/urlparse.html) to get it. | get server address from bottle | [
"",
"python",
"bottle",
""
] |
I am trying to translate every element of a `numpy.array` according to a given key:
For example:
```
a = np.array([[1,2,3],
[3,2,4]])
my_dict = {1:23, 2:34, 3:36, 4:45}
```
I want to get:
```
array([[ 23., 34., 36.],
[ 36., 34., 45.]])
```
I can see how to do it with a loop:
```
def loop... | I don't know about efficient, but you could use `np.vectorize` on the `.get` method of dictionaries:
```
>>> a = np.array([[1,2,3],
[3,2,4]])
>>> my_dict = {1:23, 2:34, 3:36, 4:45}
>>> np.vectorize(my_dict.get)(a)
array([[23, 34, 36],
[36, 34, 45]])
``` | Here's another approach, using [`numpy.unique`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html#numpy.unique):
```
>>> a = np.array([[1,2,3],[3,2,1]])
>>> a
array([[1, 2, 3],
[3, 2, 1]])
>>> d = {1 : 11, 2 : 22, 3 : 33}
>>> u,inv = np.unique(a,return_inverse = True)
>>> np.array([d[x] for ... | Translate every element in numpy array according to key | [
"",
"python",
"numpy",
""
] |
Hi this is a piece of code that is supposed to create a function that returns the absolute value of the inputted integer or float.
Can't seem to figure out what's wrong with it, here's the code and the error. Any help is appreciated!
here is the code for the function:
```
import math
def distance_from_zero(num):
... | [`abs()`](http://docs.python.org/2/library/functions.html#abs) is a built-in function, so just replace all occurrences of `math.abs` with `abs`.
You should also use the [`isinstance()`](http://docs.python.org/2/library/functions.html#isinstance) function for type checking instead of using `type()` and comparing, for e... | As others pointed out, `abs` is builtin so it isn't imported from the `math` module.
I wanted to comment on your type checking. Another way that is the most "pythonic" is to use a `try: except:` block to check the type:
```
def distance_from_zero(num):
try:
return abs(num)
except ValueError:
r... | Python math module doesn't have abs | [
"",
"python",
""
] |
Rubyist writing Python here. I've got some code that looks kinda like this:
```
result = database.Query('complicated sql with an id: %s' % id)
```
`database.Query` is mocked out, and I want to test that the ID gets injected in correctly without hardcoding the entire SQL statement into my test. In Ruby/RR, I would hav... | ```
import mock
class AnyStringWith(str):
def __eq__(self, other):
return self in other
...
result = database.Query('complicated sql with an id: %s' % id)
database.Query.assert_called_once_with(AnyStringWith(id))
...
```
**Preemptively requires a matching string**
```
def arg_should_contain(x):
def ... | You can just use `unittest.mock.ANY` :)
```
from unittest.mock import Mock, ANY
def foo(some_string):
print(some_string)
foo = Mock()
foo("bla")
foo.assert_called_with(ANY)
```
As described here -
<https://docs.python.org/3/library/unittest.mock.html#any> | unittest.mock: asserting partial match for method argument | [
"",
"python",
"unit-testing",
"mocking",
""
] |
I'm currently writing validation code for a tool parameter in ArcMap 10 (updateMessages) and need to prevent users from using non-alphanumeric characters within a string as it will be used to name a newly created field in a feature class.
I have so far used 'str.isalnum()' however this of course excludes underscores. ... | ```
import re
if re.match(r'^\w+$', text):
``` | Try regular expressions:
```
import re
if re.match(r'^[A-Za-z0-9_]+$', text):
# do stuff
``` | Only accept alphanumeric characters and underscores for a string in python | [
"",
"python",
"arcpy",
"parameters",
"field",
"validation",
""
] |
i have a list of words in the file "temp":
```
1. the
2. of
3. to
4. and
5. bank
```
and so on
how do i improve its readability?
```
import itertools
f = open("temp.txt","r")
lines = f.readlines()
pairs = list(itertools.permutations(lines, 2))
print(pairs)
```
I am lost, please help. | I am assuming that your problem is creating all the possible pair of words defined in the `temp` file. This is called [permutation](http://en.wikipedia.org/wiki/Permutation) and you are already using the `itertools.permutations` function
If you need to actually write the output to a file your code should be the follow... | ```
import itertools
with open("temp.txt", "r") as f:
words = [item.split(' ')[-1].strip() for item in f]
pairs = list(itertools.permutations(words, 2))
print(pairs)
```
Prints (using `pprint` for readability):
```
[('the', 'of'),
('the', 'to'),
('the', 'and'),
('the', 'bank'),
('of', 'the'),
('of', 'to'),... | how to create a list of word pairs from a list | [
"",
"python",
"list",
""
] |
I'm going through the free Python class Google has available ([Link if interested)](https://developers.google.com/edu/python/regular-expressions) and I'm stuck on one of the exercises.
Goal:
Consider dividing a string into two halves.
If the length is even, the front and back halves are the same length.
If the length ... | Simpler method:
```
def front_back(a, b):
hlena, hlenb = (len(a) + 1)/2, (len(b) + 1)/2
return a[:hlena] + b[:hlenb] + a[hlena:] + b[hlenb:]
```
No need for `if` clause to handle empty string case. Order of operations for slice calculation was not correct in your code.
Tip: Defore diving in and coding, play ... | Your problem is that you're not treating a and b as separate cases. Consider the case where a has length 4 and b has length 5. In that case you would always take the first branch, which would treat b incorrectly.
```
def front_back(a, b):
if len(a)%2 == 0:
firstpart , secondpart = a[:len(a)/2] , a[len(a)/2... | Python divide odd length string and combine | [
"",
"python",
""
] |
First of all I'm glad to be here, I read you lately and i found useful answers here.
This is my first post so please be kind with me, I'm a newbie in programming.
So, I'm writing my 1st web application in Django - a todo app and I don't know how to write the function that does this this. I found something in Django ... | ```
#edit_task.html
{% block content %}
<form action="/edit_task/{{task.id}}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock content %}
```
Notice how I added `{{task.id}}` expression in `<form action="/edit_task/{{task.id}}" method="post">`
**IMPORTA... | Just add name space to your url and according update your template.
```
#urls.py
url(r'^edit_task/(?P<task_id>\w+)/$', 'todo.views.edit_task', name= "edit_task")
#edit_task.html
{% block content %}
<form action="{% url 'edit_task' task_id %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit"... | Unable to update CharField - Django | [
"",
"python",
"django",
"forms",
"edit",
""
] |
I am trying to make a UI for my game and there are some curves to the UI. Now I can detect collision between two surfaces. I can detect by pixel between two sprites, but it seems mouse detection by pixel is alluding me. Basically I want to detect when the mouse is over the UI and then ignore everything below that while... | Okay I am thinking of this as the best option rather then some of the alternatives. Will keep everyone up to date if this works or not.
global click variable to store data in a dict
Objects have layer variable ranging from 1 to ? from lowest to greatest layer(similar to html zIndex)
1. Primary Loop
1. reset the gl... | You could create a mask of the UI (this would be easiest if the UI is contained in one surface which is then applied to the screen surface), and set the threshold of the mask to the appropriate value so that your transparent pixels are set to `0` in the mask.
<http://www.pygame.org/docs/ref/mask.html#pygame.mask.from_... | Python pygame Detect if mouse is over non transparent part of surface | [
"",
"python",
"opengl",
"python-2.7",
"pygame",
""
] |
I am using the terrific [Python Requests](http://www.python-requests.org/) library. I notice that the [fine documentation](http://www.python-requests.org/en/latest/user/quickstart/) has many examples of *how* to do something without explaining the *why*. For instance, both `r.text` and `r.content` are shown as examples... | The `requests.Response` class [documentation](https://requests.readthedocs.io/en/master/api/#requests.Response.text) has more details:
`r.text` is the content of the response in Unicode, and `r.content` is the content of the response in bytes. | It seems clear from the documentation is that r.content
```
You can also access the response body as bytes, for non-text requests:
>>> r.content
```
If you read further down the page it addresses for example an image file | What is the difference between 'content' and 'text' | [
"",
"python",
"python-requests",
""
] |
Lets say we have to 2 identical tables with millions of rows and they have business transactions, both tables have the exact same information. One column specifies if the row is a "Sale" or "Order", other columns specify names(commonly repeated), date, amount, tax etc....
Data in the tables are not organized so obviou... | Every index is pure redundancy that:
* costs storage space,
* occupies cache space that could otherwise be occupied by something else
* must be maintained on INSERT / UPDATE / DELETE.
If the index can be utilized by a query, the speedup usually vastly outweighs the factors listed above. Conversely, if the index is no... | When you are querying with conditions on columns which don't have indexes on them, theoretically you should get pretty much the same performance regardless of presence/absence of PK. However, in practice it depends on RDMS implementation. From my experience I can tell for sure that in SQLServer you will see worse overa... | Are indexed tables faster than non indexed table while querying? | [
"",
"sql",
"database",
""
] |
I need to make a program that receives a integer and stores it on a file. When it has 15 (or 20, the exact number doesn't matter) it will overwrite the first one that it wrote. They may be on the same line or each one in a new line.
This program reads temperature from a sensor and then i will show that on a site with a... | I think what you want is something like this:
```
import sys
fileTemps = 'temps'
with open(fileTemps, 'rw') as fd:
temps = fd.readlines()
if temps.__len__() >= 15:
temps.pop(0)
temps.append(' '.join(sys.argv[1:]) + '\n')
with open(fileTemps, 'w') as fd:
for l in temps:
fd.write(l)
```
First ... | You want something like
```
values = open(target_file, "r").read().split("\n")
# ^ this solves your original problem as readline() will keep the \n in returned list items
if len(values) >= 15:
# keep the values at 15
values.pop()
values.insert(0, new_value)
# push new value at the start of the list
tmp_fd, tmp... | Store 15 last values on a file on Python | [
"",
"python",
"file",
"list",
""
] |
I have a lot of records in postgresql database sample table s\_attrs attribute like
```
sex = female, age = 32 years, disease = hepatitis B:DOID:2043
sex = male, age = 35 years, disease = hepatitis B:DOID:2043
sex = male, age = 34 years, disease = hepatitis B:DOID:2043
sex = male, age = 55 years, disease = hepatitis B... | Assuming that you have an id column in your table your base query may look like this
```
WITH attr_explode AS
(
SELECT id, unnest(string_to_array(s_attrs, ',')) attr
FROM Table1
)
SELECT id, array_to_string(array_agg(concat(trim(split_part(attr, '=', 1)), '="', trim(split_part(attr, '=', 2)), '"')), ',') s_att... | below is the sample replace statement
select replace(
replace('sex = female, age = 32 years, disease = hepatitis B:DOID:2043',' = ','="')
, ', ','",') + '"'; | database sql replace statement update records | [
"",
"sql",
"database",
"postgresql",
""
] |
Normally I would use R and do merge.by, but this file seems to be too big for any of the computers in the department to deal with this! (Additional info for anyone working in genetics) Essentially, imputation seems to remove the rs numbers for snp IDs, and I am left with Chromosome:Position information in its place. So... | Simple with `awk`:
```
$ awk 'FNR==NR{a[$5]=$2;next}$3 in a{$3=a[$3]}1' file2 file1
1111 1111 rs58108140 G G
1112 1112 rs58108140 G G
1113 1113 rs58108140 G G
1114 1114 rs58108140 G G
1115 1115 rs58108140 G G
``` | `join` and `awk` can do that. You can also use `cut` instead of `awk`, but you'd have to reorder the fields afterwards in some other way.
```
join -1 3 -2 5 file1 file2 | awk '{print $2, $3, $7, $4, $5}'
```
Warning: as mentioned by sudo\_O, this will work only if the files are sorted - I'm assuming they are, based o... | If column A in file 1 = column A in file 2, replace with column B from file 2 | [
"",
"python",
"linux",
"awk",
""
] |
I am trying to convert a 'fastq' file in to a tab-delimited file using python3.
Here is the input: (line 1-4 is one record that i require to print as tab separated format). Here, I am trying to read in each record in to a list object:
```
@SEQ_ID
GATTTGGGGTT
+
!''*((((***
@SEQ_ID
GATTTGGGGTT
+
!''*((((***
```
using t... | When you replace `@` with `,@`, you put a comma at the beginning of the string (since it starts with `@`). Then when you split on commas, there is nothing before the first comma, so this gives you an empty string in the split. What happens is basically like this:
```
>>> print ',x'.split(',')
['', 'x']
```
If you kno... | You can also go line-by-line without all the replacing:
```
fobj = io.StringIO("""@SEQ_ID
GATTTGGGGTT
+
!''*((((***
@SEQ_ID
GATTTGGGGTT
+
!''*((((***""")
data = []
entry = []
for raw_line in fobj:
line = raw_line.strip()
if line.startswith('@'):
if entry:
data.append(entry)
entry =... | .split() creating a blank line in python3 | [
"",
"python",
"blank-line",
"fastq",
""
] |
Is there a way to check if the table(s) have Cascade Delete turned on? I'm looking at the script of the table (from SQL Server) and I don't see any indication of Cascade Delete. | Please use `sys.foreign_keys` for foreign key relations.
The column - `delete_referential_action` helps you know if there is a delete on cascade.
<http://technet.microsoft.com/en-us/library/ms189807.aspx>
Below View help with similar works:
```
sys.default_constraints for default constraints on columns
sys.check_co... | You can use INFORMATION\_SCHEMA for standard approach, ex.
```
select * from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
where DELETE_RULE ='CASCADE'
``` | Cascade Delete turned on? | [
"",
"sql",
"sql-server",
""
] |
Here's my problem. I'm trying to request a url from the rotten tomatoes API. Now the thing is that they require you to have your movie titles contain + signs where ever there should be spaces. However I'm not sure how to implement this on the app engine side, because whenever I try doing the same thing on app engine, I... | I haven't found a way to handle the plus signs, because appengine seems to infer that these are new variables/values. However, using a regex other than '+' is a viable solution to the problem as a whole, as long as the application accessing the URL is able to replace [space]s with [regex] rather than the normal '+'. Se... | This does not directly answer your question, but have you tried using the [url fetch service](https://developers.google.com/appengine/docs/python/urlfetch/), directly:
eg:
```
from google.appengine.api import urlfetch
title = self.request.get("title")
site = "http://api.rottentomatoes.com/api/public/v1.0/movies.json... | How to handle urls in python urllib2 appengine with plus signs? | [
"",
"python",
"google-app-engine",
"urllib2",
""
] |
I have two tables on different databases. I am trying to find the differences in the number of records. So far I have tried:
```
select COUNT(*)
from tabel1 a1
where not exists
(
select *
from db2.table1 a2
where a1.id = a2.id
);
```
Which returns `31298`. But if I run the count on the tables by them selve... | There are records in table2 that don't have any corresponding entries in table1.
Your inner query only select values in table2 that also correspond to table1.
So if table1 has IDs
```
1
3
5
```
and table 2 has IDs
```
1
3
7
```
you would see count of 1 (id 5) because rows 1 and 3 match, but 7 doesn't match anythi... | How about this:
```
SELECT (SELECT COUNT(*) FROM Table1) - (SELECT COUNT(*) FROM db2.Table1)
``` | Count not showing correctly? | [
"",
"mysql",
"sql",
""
] |
I am trying to design and test code similar to the following in a good object oriented way? (Or a pythonic way?)
Here is a factory class which decides whether a person's name is long or short:
```
class NameLengthEvaluator(object):
def __init__(self, cutoff=10)
self.cutoff = cutoff
def evaluate(self,... | ## Unit Testing
> Does the Person method name\_length\_opinion() deserve a unit test, and if so what would it look like?
Do you want to make sure it does what you think it does and makes sure it doesn't break in the future? If so, write a unit test for it.
> and that the test would just exist to confirm that nobody ... | It really depends on the lifecycle of that code. It's obvious that, in its current state, the method is obviously correct, and the unit test is more of a specification for how it should behave. If you plan on making changes in the future (reimplementing `NameLengthEvaluator` somehow differently, for instance), having u... | Unit testing simple methods... a sound OOP / pythonic solution? | [
"",
"python",
"oop",
"unit-testing",
""
] |
I have been wondering for a while if there is easier way to assign class attributes to method local namespace. For example, in `dosomething` method, I explicitly make references to `self.a` and `self.b`:
```
class test:
def __init__(self):
self.a = 10
self.b = 20
def dosomething(self):
... | > Q. Is there any way to do this more compact way?
**1.** If the variables are read-only, it would be reasonably Pythonic to factor-out a multi-variable accessor method:
```
class Test:
def __init__(self):
self.a = 10
self.b = 20
self.c = 30
def _read_vars(self):
return self.... | You can easily solve this problem with a tradeoff, by storing the variables in a dictionary.
```
data = {}
copy_to_local_variables = ["a", "b", "c", "d"]
for var_name in copy_to_local_variables:
data[var_name] = getattr(self, var_name)
```
(Though I am unable to understand why you need to copy class attributes to... | Python importing class attributes into method local namespace | [
"",
"python",
"class",
"namespaces",
""
] |
I need help on a query, or a link to an answer that covers it:
I have two tables: `STOCK_ITEMS` and `STOCK_LOC_INFO`
`STOCK_ITEMS` has many fields, but the two of interest are `STOCKCODE` and `STOCK_CLASSIFICATION`
`STOCK_LOC_INFO` contains a record for every stock location (11 locations) against every `STOCKCODE`
... | Using Oracle you could do like this:
```
select COUNT(SOH.STOCKCODE)
from dbo.STOCK_ITEMS SOH
WHERE SOH.STOCKCODE IN (
SELECT SLI.STOCKCODE
FROM STOCK_LOC_INFO SLI
where SLI.QTY > 0
and SLI.LOCATION in(1,2,3,9,11)
)
``` | Do you just want the count of distinct stockcodes that meet your criteria?
If so:
```
SELECT COUNT(DISTINCT SOH.STOCKCODE)
FROM STOCK_ITEMS SOH
INNER JOIN STOCK_LOC_INFO SLI
ON SOH.STOCKCODE = SLI.STOCKCODE
WHERE SLI.QTY > 0 AND SLI.LOCATION IN(1,2,3,9,11)
```
You could also limit the SLI table before joining:
```
S... | How do I get a count of results from a query? | [
"",
"sql",
"count",
"inner-join",
""
] |
Years ago a conversion from MSSQL 6.5 to MSSQL 2000 has been done and they realized just this week that the conversion failed to convert some datetime columns. It is now my task to fix that and I've been scratching my head on how I could preserve some pieces of information I know is accurate. Here is the structure of o... | I believe you want to only update `DateTimeField1` & `DateTimeField2` when they are less than `'20000101'`. `CASE` Statement will take care of not updating wrong field.
Try single query `UPDATE` -
**SQL SERVER 2008 AND LATER -**
```
UPDATE Table1
SET DateTimeField1 = (CASE WHEN (DateTimeField1 < '20000101')
... | If one field is always 1900-01-01 but with the correct time, and the other field is 12:00:00 AM but with the correct date, you can just add them together.
```
UPDATE Test
SET
DateTimeField1 = DateTimeField1 + DateTimeField3,
DateTimeField2 = DateTimeField2 + DateTimeField3
WHERE (DateTimeField1 < '20000101') OR (D... | Update datetime fields date only | [
"",
"sql",
"sql-server",
""
] |
I am new to python. I am given a folder with around 2000 text files. I am supposed to output each word and the number of times it occurs (without repetition in a file). For example, the sentence: "i am what i am" must include only one occurrence of "i" in a file.
I am able to do this for a single file, but how do I do... | You can get a list of files by using the `glob()` or `iglob()` function in the [`glob`](http://docs.python.org/2/library/glob.html?highlight=glob#glob) module. I noted that you weren't using the `Counter` object efficiently. It would be much better to just call its `update()` method and pass it the list of words. Here'... | See `os.listdir()`, it will give you a list of all entries in in a directory.
<http://docs.python.org/2/library/os.html#os.listdir> | unique word frequency in multiple files | [
"",
"python",
"data-mining",
""
] |
I am using inner join with the like clause ..
My tried sql is
```
SELECT tbl_songs.id AS sid,
tbl_songs.name AS sname,
tbl_albums.id AS aid,
tbl_albums.name AS aname
FROM tbl_songs
INNER JOIN tbl_albums
ON tbl_songs.albums LIKE '%' + tbl_albums.name + '%';
```
... | you have to form the clause using concat ...
```
...LIKE CONCAT('%',tbl_albums.name, '%');
```
there is no `+` operator like this in mysql | ```
You can use below format in oracle sql:
SELECT tbl_songs.id AS sid,
tbl_songs.name AS sname,
tbl_albums.id AS aid,
tbl_albums.name AS aname
FROM tbl_songs
INNER JOIN tbl_albums
ON tbl_songs.albums LIKE ('%'||tbl_albums.name||'%');
``... | Inner join with like clause | [
"",
"mysql",
"sql",
""
] |
I have two tables:
### CATEGORY
```
category_id int(10) UNSIGNED AUTO_INCREMENT
category_title varchar(255)
```
### PRODUCT
```
product_id int(10) UNSIGNED AUTO_INCREMENT
product_category int(10) UNSIGNED
product_title varchar(255)
```
---
Column `produ... | Your table does not define any indexes. It is easily remedied though, by adding the indexes using the following statememts:
```
ALTER TABLE `product` ADD INDEX `product_category` (`product_category`);
ALTER TABLE `category` ADD PRIMARY KEY(category_id);
```
Now if you run your query again, the `DESC` should show you ... | ```
SELECT ws_shop_category.*, count(ws_shop_product.product_category) as products_count
from ws_shop_category
left join ws_shop_product
on (ws_shop_category.category_id = ws_shop_product.product_category)
group by
ws_shop_category.category_id
order by
ws_shop_category.category_title asc
``` | How to count number of rows which is related to another table | [
"",
"mysql",
"sql",
"performance",
""
] |
I am using pdfminer to extract data from pdf files using python. I would like to extract all the data present in pdf irrespective of wheather it is an image or text or whatever it is. Can we do that in a single line(or two if needed, without much work). Any help is appreciated. Thanks in advance | > Can we do that in a single line(or two if needed, without much work).
No, you cannot. Pdfminer is powerful but it's rather low-level.
Unfortunately, the documentation is not exactly exhaustive. I was able to find my way around it thanks to some code by Denis Papathanasiou. The code is discussed in [his blog](http:/... | For Python 3:
> pip install pdfminer.six
```
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
def convert_pdf_to_txt(path, codec='utf-8'):
rsrcmgr = ... | Extracting entire pdf data with python pdfminer | [
"",
"python",
"pdf-reader",
""
] |
I am trying to find if any of the sublists in `list1` has a repeated value, so i need to be told if a number in list1[0] is the same number in list[1] (which 20 is repeated)
the numbers represent coords and the coords of each item in list1 cannot over lap, if they do then i have a module that reruns a make a new list1... | How about something like:
```
is_dup = sum(1 for l in list1 if len(set(l)) < len(l))
if is_dup > 0:
print ("repeat found")
else:
print ("no repeat found")
```
Another example using [`any`](http://docs.python.org/2/library/functions.html#any):
```
any(len(set(l)) < len(l) for l in list1)
```
To check if only one... | ## Solution for the updated question
```
def has_duplicates(iterable):
"""Searching for duplicates in sub iterables.
This approach can be faster than whole-container solutions
with flattening if duplicates in large iterables are found
early.
"""
seen = set()
for sub_list in iterable:
... | Finding repeated values in multiple lists | [
"",
"python",
""
] |
While I consider this to be a fairly simply query, apparently there is "Incorrect syntax near 'output'". Other online resources have not been helpful in debugging this problem.
What am I doing wrong here?
```
DECLARE @changes TABLE (client_id_copy INT, client_id INT);
UPDATE gmdev.contacts
SET client_id_copy=a.clie... | In come cases, **lazy system administrators** may not upgrade to an **up-to-date version of SQL**.
First, make sure the `OUTPUT` keyword is supported by running `Select @@version;` This will return a cell like so:
```
Microsoft SQL Server 2000 - 8.00.2282 (Intel X86)
Dec 30 2008 02:22:41
Copyright (c) 1988-2003 Mi... | **We** don't have your tables and data, so it's a bit tricky for us to *debug* any issues, but the following does compile and run:
```
create table contacts (client_id_copy int,custid int,client_id int)
create table profile(custid int,client_id int,custtype varchar(10))
DECLARE @changes TABLE (client_id_copy INT, clie... | SQL Output Syntax | [
"",
"sql",
"sql-server",
""
] |
I have an object called listings, and a listing can have a number of amenities (compare this to post, tags model). It's a sort of has/doesn't have relationship.
So I have an `amenities` table which stores what amenities there can be in the system, there is the `listings` table that stores listings, `listing_amenities` ... | Traditional database design recommends the model you describe, with the "many to many" relationship extracted into a separate table.
There are many reasons to do this - not just the "deletion" anomaly, but also performance - parsing a varchar column to extract the pattern "(\*)" is significantly slower than a join bet... | Unable to grasp the table model from your post... But in general I think you should use many to many relationship like this. A seperate table, just to hold the relationships.
```
ListingsAmenities
----------
ListingID
AmenitiesID
```
The Amenities table should hold each amenities only once. Then you need not have to ... | Storing many to many relationship objects in a column on database | [
"",
"sql",
"database",
"database-design",
""
] |
Let's consider the following table.
```
Id(PK, int) | DocDate(long) | Sender(varchar) | Recipient(varchar) | PeriodStart(long) | PeriodEnd(long)
```
For every `Sender`, `Recipient`, `PerdiodStart`, `PeriodEnd` I'm writting multiple entries at different points in time. So the `DocDate` differs.
Now I've to select the... | Lamak has the right idea but a few errors. This version should work.
```
with prevFilter as (
select Id,
RN = ROW_NUMBER() OVER(
PARTITION BY Sender, Recipient, PeriodStart, PeriodEnd
ORDER BY DocDate DESC)
from Table
)
select Id
from prevFilter t
where RN = 1
``` | You can use a CTE and `ROW_NUMBER`:
```
with prevFilter as (
select Id,
RN = ROW_NUMBER() OVER(PARTITION BY Sender, Recipient, PerdiodStart, PeriodEnd
ORDER BY DocDate DESC)
from Table
)
select Id
from prevFilter t
where RN = 1
``` | How to get id, based on ambiguous entries in table | [
"",
"sql",
"t-sql",
""
] |
I am currently developing an Android app that has some of its back-end features implemented in Python. I am looking for a way to integrate both these parts.
Ideally, the Python script should reside on some sort of server so that the Android app can make requests to it. The Python script uses an SQLite database that ne... | I've ran upon [Flask](http://flask.pocoo.org/) which is exactly what I needed. It is much easier to implement than what @pypal suggested above. | My company is doing the same thing here.
We have 1 backend where 3 clients: ios, android and web points to
The way we do is to use Flask and expose api end points, something like
```
@app.route("/api/dosomething/")
def randomfunction:
```
Then clients will make http requests to
```
https://dev.yourapp.com/api/dosome... | Python request from Android | [
"",
"android",
"python",
""
] |
Some of my data looks like:
```
date, name, value1, value2, value3, value4
1/1/2001,ABC,1,1,,
1/1/2001,ABC,,,2,
1/1/2001,ABC,,,,35
```
I am trying to get to the point where I can run
```
data.set_index(['date', 'name'])
```
But, with the data as-is, there are of course duplicates (as shown in the above), so I canno... | Let's imagine you have some function `combine_it` that, given a set of rows that would have duplicate values, returns a single row. First, group by `date` and `name`:
```
grouped = data.groupby(['date', 'name'])
```
Then just apply the aggregation function and *boom* you're done:
```
result = grouped.agg(combine_it)... | If you do not have numeric field values, aggregating with count, min, sum etc. will not be neither possible nor sensible. Nevertheless, you still may want to collapse duplicate records to individual records (e.g.) based on one or more primary keys.
```
# Firstly, avoid Nan values in the columns you are grouping on!
df... | How to merge mostly duplicated rows | [
"",
"python",
"duplicates",
"pandas",
"dataframe",
""
] |
How do i truncate the below URL next to the domain "com" using python. i.e you tube.com only
```
youtube.com/video/AiL6nL
yahoo.com/video/Hhj9B2
youtube.com/video/MpVHQ
google.com/video/PGuTN
youtube.com/video/VU34MI
```
Is it possible to truncate like this? | Check out Pythons [`urlparse`](http://docs.python.org/2/library/urlparse.html#module-urlparse) library. It is a standard library so nothing else needs to be installed.
So you could do the following:
```
import urlparse
import re
def check_and_add_http(url):
# checks if 'http://' is present at the start of the UR... | You can use split():
```
myUrl.split(r"/")[0]
```
to get "youtube.com"
and:
```
myUrl.split(r"/", 1)[1]
```
to get everything else | How do i truncate url using python | [
"",
"python",
""
] |
## The goal
Use the clause "where" only if parameter is not null.
## The problem
I do not know the syntax.
## What I have
The follow syntax that doesn't work.
```
CREATE DEFINER=`root`@`localhost` PROCEDURE `getProductsListForHome`
(IN `inOffer` INT, IN `categoryId` INT)
BEGIN
SELECT (MIN(`map`.`Product_Price... | So you want to get record which match that predicate if a field is not NULL. That's like saying get them if the field is NULL, otherwise filter. Simply combine the two predicates with `OR`:
```
AND (`categoryId` IS NULL OR `ca`.`Category_Id` = `categoryId`)
``` | How about a coalesce?
```
WHERE `map`.`Product_State` = inOffer
AND `ca`.`Category_Id` = coalesce(categoryId,`ca`.`Category_Id`)
``` | If isn't null, use "where" | [
"",
"mysql",
"sql",
"stored-procedures",
""
] |
I need to find unique rows in a `numpy.array`.
For example:
```
>>> a # I have
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 1, ... | As of NumPy 1.13, one can simply choose the axis for selection of unique values in any N-dim array. To get unique rows, use [`np.unique`](https://numpy.org/doc/stable/reference/generated/numpy.unique.html) as follows:
```
unique_rows = np.unique(original_array, axis=0)
``` | Yet another possible solution
```
np.vstack({tuple(row) for row in a})
```
Edit: As others have mentioned this approach is deprecated as of NumPy 1.16. In modern versions you can do
```
np.vstack(tuple(set(map(tuple,a))))
```
Where `map(tuple,a)` makes every row of the matrix `a` hashable by making it them tuples. ... | Find unique rows in numpy.array | [
"",
"python",
"arrays",
"numpy",
"unique",
""
] |
I am new to SQL Oracle.I have the following script:
```
create table students(
sid char(10),
honors char(10) not null,
primary key (sid),
Constraint studentConst foreign key (honors) references Courses(cid),
);
create table Courses(
cid char(10),
grader char(20) not null,
primary key (cid),
Constraint CoursesConst fo... | I don't think you can create a foreign key constraint on a table that doesn't yet exist.
Since you have a two-way constraint, you'll need to create the first table *without* the constraint, then add it with `alter table` *after* the second table has been created.
Deferred constraints are for checking *data.* Deferral... | It looks like line 5 is trying to reference `Courses(cid)`. However, at this point, the `Courses` table does not exist, as it's created in the following SQL block.
Try creating dependent tables first. | Adding constraints on table | [
"",
"sql",
"oracle11g",
""
] |
I am writing a piece of code and in the middle of it I want it to go into the main terminal and strip my data set of [] and '' however when i include the '' part python thinks i'm just finishing the string (i think) is there another way I can do this. Here is my code:
```
com=['cat new.txt | tr -d "s/,[]''*//g" >meant... | `'cat new.txt | tr -d "s/,[]''*//g" >meantenbri.txt2'` is not doing what you think it is, for example:
```
>>> print 'cat new.txt | tr -d "s/,[]''*//g" >meantenbri.txt2'
cat new.txt | tr -d "s/,[]*//g" >meantenbri.txt2
```
Note that those two single quotes in the middle are gone, this is happening because you actuall... | Use a triple quoted string instead:
```
com = ["""cat new.txt | tr -d "s/,[]''*//g" >meantenbri.txt"""]
```
python actually has 4 types of quotes at your disposal:
```
'...'
"...:
"""..."""
'''...'''
```
(the triple quoted variety also work over multiple lines):
```
"""foo
bar"""
```
Of course, if you're really i... | writing python code to execute command in main terminal however i need to include ' ' and its not workig | [
"",
"python",
"terminal",
""
] |
I have a table X
```
ID A B C D
1 T T F T
2 F T F T
3 T F T F
```
So if my input is 1 for ID, then I want all column names that have value T for row 1. In above case A,B,D or If ID is 3 then A and C.
How could I list t... | You can use `UNPIVOT` for this
```
SELECT Y
FROM Table1
UNPIVOT (X FOR Y IN ([A], [B], [C], [D])) U
WHERE [ID] = 1 AND X = 'T'
```
Returns
```
+---+
| Y |
+---+
| A |
| B |
| D |
+---+
```
[SQL Fiddle](http://sqlfiddle.com/#!3/a23f9/1) | Also you can use XQuery with powerful FLWOR Expression. And no matter how many columns contains a table;)
```
SELECT(
SELECT *
FROM Table1 t
WHERE ID = 1
FOR XML PATH(''), TYPE
).query(
'for $spec in ./*
where $spec [contains(., "T")]
... | Pull Columns based on row value | [
"",
"sql",
"sql-server-2005",
""
] |
Wrote this function in python that transposes a matrix:
```
def transpose(m):
height = len(m)
width = len(m[0])
return [ [ m[i][j] for i in range(0, height) ] for j in range(0, width) ]
```
In the process I realized I don't fully understand how single line nested for loops execute. Please help me understa... | The best source of information is the [official Python tutorial on list comprehensions](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions). List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a ... | You might be interested in [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product), which returns an iterable yielding tuples of values from all the iterables you pass it. That is, `itertools.product(A, B)` yields all values of the form `(a, b)`, where the `a` values come from `A` and t... | Single Line Nested For Loops | [
"",
"python",
"list-comprehension",
"nested-loops",
""
] |
Using the table EMP, where MANAGER represents the employee's manager:
```
EMPLOYEE MANAGER
1 NULL
2 1
3 1
4 2
5 2
```
How can I make a query that determines if an employee is a manager?
```
EMPLOYEE STATUS
1 IS MANAGER
2 IS MANAGER
3 IS NOT ... | You can `JOIN` the table on itself and use a `CASE` statement:
```
SELECT DISTINCT E.Employee,
CASE
WHEN M.Employee IS NOT NULL THEN 'IS MANAGER'
ELSE 'IS NOT MANAGER' END Status
FROM YourTable E
LEFT JOIN YourTable M ON E.Employee = M.Manager
```
Use an `OUTER JOIN` to get all the employees a... | To get the list of manager primary keys, just
```
SELECT DISTINCT
MANAGER
FROM
EMP;
```
To get more information about each manager assuming that the table also has such things as the manager's name:
```
SELECT DISTINCT
m.employee, m.given_name, m.surname
FROM
EMP m
JOIN
EMP e
ON
e.manager = ... | How to determine if an employee is a manager? | [
"",
"sql",
"oracle",
"join",
""
] |
```
def reverse(text):
final_string = ""
count = len(text)
while count > 0:
final_string += text[len(text)-1]
text = text[0:len(text)-1]
count -= 1
return final_string
```
This is the code snippet. I know it reverses the string "text" but can't seem to understand how it does so. | ```
def reverse(text):
final_string = ""
count = len(text) # sets the counter variable to the length of the string variable
while count > 0: # starts a loop as long as our counter is higher than 0
final_string += text[len(text)-1] #copies the last letter from text to final string
text = tex... | `final_string += text[len(text)-1` gets the last character of `text` and adds it to the end of `final_string`.
`text = text[0:len(text)-1]` removes the last character of `text`; basically it shortens `text` by the character that was just added to `final_string`.
`count -= 1` counts down to zero. When zero is reached ... | What does the following python code snippet do? | [
"",
"python",
""
] |
Is there any way to use infix operators (like +,-,\*,/) as higher order functions in python without creating "wrapper" functions?
```
def apply(f,a,b):
return f(a,b)
def plus(a,b):
return a + b
# This will work fine
apply(plus,1,1)
# Is there any way to get this working?
apply(+,1,1)
``` | You can use the [operator](http://docs.python.org/3/library/operator.html?highlight=operator#operator) module, which has the "wrapper" functions written for you already.
```
import operator
def apply(f,a,b):
return f(a,b)
print apply(operator.add,1,1)
```
Result:
```
2
```
You can also define the wrapper using ... | Use operator module and a dictionary:
```
>>> from operator import add, mul, sub, div, mod
>>> dic = {'+':add, '*':mul, '/':div, '%': mod, '-':sub}
>>> def apply(op, x, y):
return dic[op](x,y)
...
>>> apply('+',1,5)
6
>>> apply('-',1,5)
-4
>>> apply('%',1,5)
1
>>> apply('*',1,5)
5
```
Note that you can't use... | How to use infix operators as higher order functions? | [
"",
"python",
"higher-order-functions",
""
] |
I have one table `ABC` with `EMPLID`, `GRADE`, `SALARY` and `DATE` as its fields.
I am executing the following 3 statements:
```
select count(*) from ABC;
```
Result :- 458
```
select count(*) from ABC where GRADE LIKE '%def%';
```
Result :- 0
```
select count(*) from ABC where GRADE NOT LIKE '%def%';
```
Result... | Looks like you have 30 records where the GRADE is `null`.
`null` values are unknown, so do not match either condition. | Sql uses a three-valued logic: true, false &unknown. If you compare a NULL to any other value the result is unknown. NOT(unknown) is still unknown.
A WHERE clause only returns rows that evaluate to true. So the missing 30 rows in your example have a NULL in the Grade column. | Why don't counts using 'LIKE' in SQL match? | [
"",
"mysql",
"sql",
"oracle",
"oracle11g",
""
] |
I have the following table:
```
create table #tbl
(
[type] varchar(20),
[qty] int
)
insert into #tbl values ('Type A', 10)
insert into #tbl values ('Type A', 15)
insert into #tbl values ('Type B', 5)
insert into #tbl values ('Type B', 8)
```
Now I want to display the total qty of each individual 'type':
```
se... | The problem is that you don't have `Type C` in the table so there is nothing to return. One way you could this is to create a derived table with all of the values that you want include and then LEFT JOIN your table:
```
select d.type,
sum(coalesce(t.qty, 0)) Total
from
(
select 'Type A' type union all
select 'Ty... | You will need a table containing the list of types you want to report and do a left join on that. Something like the following:
```
create table #tbl
(
[type] varchar(20),
[qty] int
);
insert into #tbl values ('Type A', 10)
insert into #tbl values ('Type A', 15)
insert into #tbl values ('Type B', 5)
insert into #... | Sum when field does not exist | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"sql-server-2005",
""
] |
I've currently installed Django-CKEditor and have my own custom toolbar.
I'm struggling to find how to enable image uploading. When clicking the Image button, I can only upload via URL. I know that, in the plugin, there are views to handle file browsing and uploading but I'm not sure how to activate or use these.
The... | As I had mentioned in my question - Django CKEditor comes with a number of URLs to handle the viewing and browsing of images. The subsequent steps to activate this with your editor require you to add a filebrowserBrowseUrl when activating the editor and setting it to the appropriate /upload/ and /browse/ URLs.
See mor... | In the current version (5) you can use `RichTextUploadingField` instead of `RichTextField`, which enables uploading and browse files button.
Previously you have to install `django-uploader` package. | Django-CKEditor Image Upload | [
"",
"python",
"django",
"ckeditor",
"django-ckeditor",
""
] |
I have a list of lists:
```
[['a','b','c'], ['a'], ['a','b']]
```
I want to sort it and return a single list so the output looks like this:
```
['a', 'b', 'c']
```
i.e. ordered by the number of times each element appears. a appears 3 times, b appears twice, and c appears once.
How do I go about doing this? | Use [`collections.Counter`](http://docs.python.org/3.3/library/collections.html#collections.Counter), [`itertools.chain.from_iterable`](http://docs.python.org/3.3/library/itertools.html#itertools.chain.from_iterable), and a [list comprehension](http://docs.python.org/3.3/tutorial/datastructures.html#list-comprehensions... | Use `itertools.chain.from_iterable()` to first flatten the list, then [`collections.Counter()`](http://docs.python.org/2/library/collections.html#collections.Counter) to count the elements.
```
>>> from collections import Counter
>>> from itertools import chain
>>> [x[0] for x in Counter(chain.from_iterable(mylist)).m... | Python: given a list of lists, create a list ordered by the number of occurrences in inner list | [
"",
"python",
"list",
""
] |
let's say I have a table with columns `ID`, `Date1` and `Date2` where `Date2`can be `NULL`. I now want to have an SQL statement that ignores `Date2` if it is `NULL`.
So I need something like that:
```
SELECT *
FROM
[myTable]
WHERE
ID = @someId
AND Date1 <= GETDATE()
AND Date2 >= GETDATE() IF Date2 IS NOT NULL... | ```
AND Date1 <= GETDATE()
AND (Date2 IS NULL OR Date2 >= GETDATE() )
```
or
```
AND Date1 <= GETDATE()
AND COALESCE(Date2, GETDATE()) >= GETDATE()-- which means : if Date2 IS NULL say Date2 = GETDATE()
``` | `AND (Date2 >= GETDATE() OR Date2 IS NULL)` | WHERE clause condition checking for NULL | [
"",
"sql",
""
] |
This is a follow-up question from [How to know what classes are represented in return array from predict\_proba in Scikit-learn](https://stackoverflow.com/questions/16937243/how-to-know-what-classes-are-represented-in-return-array-from-predict-proba-in-s)
In that question, I quoted the following code:
```
>>> import ... | if you use `svm.LinearSVC()` as estimator, and `.decision_function()` (which is like svm.SVC's .predict\_proba()) for sorting the results from most probable class to the least probable one. this agrees with `.predict()` function. Plus, this estimator is faster and gives almost the same results with `svm.SVC()`
the onl... | `predict_probas` is using the Platt scaling feature of libsvm to callibrate probabilities, see:
* [How does sklearn.svm.svc's function predict\_proba() work internally?](https://stackoverflow.com/questions/15111408/how-does-sklearn-svm-svcs-function-predict-proba-work-internally)
So indeed the hyperplane predictions ... | Scikit-learn predict_proba gives wrong answers | [
"",
"python",
"scikit-learn",
""
] |
I've got a lot of data in a MySQL database, to make sense of it I want to pull it out in 10 minute intervals.
I can get the data from `lap_times`, but I'm unsure how to pull it out every 10 minutes, essentially I want to do the below (after the // is pseudo code).
```
SHOW * FROM lap_times // WHERE time is between 13... | ```
SET @start_time = CONVERT('2013-06-10 12:15', datetime);
SELECT *
FROM lap_times
WHERE time BETWEEN @start_time and @start_time + INTERVAL 10 MIN;
``` | If you can accept the 10 minute blocks starting at the top of the hour rather than at arbitrary offsets then you can use logic similar to this:
```
SELECT SUM(col) FROM lap_times GROUP BY time - (time % 600);
```
Arbitrary offsets *could* be handled by subtracting them from `time` to move them back into the "rounded"... | SHOW * FROM column in 10 minute period - mysql query | [
"",
"mysql",
"sql",
""
] |
I have 2 question regarding global variables:
1. Why can't I declare a list as a global variable as so: `global list_ex = []`?
2. I have already defined a global variable that I am trying to use in a function, but can't:
```
global column
def fx_foo(cols):
common = set(cols).intersection(set(column))... | You are not using `global` correctly. You don't need to use it **at all**.
You need to actually *set* a global `column` variable, there is none right now. `global` does not make the variable available. Just create a global `column` first:
```
column = []
```
then refer to it in your function. That is what the `NameE... | The keyword global means you are explicitly using a variable declared outside the scope of a function.
Your variable must be declared normally:
```
column = []
```
and declared global in the function that uses it
```
def fx_foo(cols):
global column
common = set(cols).intersection(set(column))
```
It is use... | Declaring global variables | [
"",
"python",
"global-variables",
""
] |
When I try to build my own version of Python using:
```
./configure --enable-shared --prefix=/app/vendor/python-dev && make && make install
```
I see some errors during installation:
> /usr/bin/ld: /usr/local/lib/libpython2.7.a(abstract.o): relocation
> R\_X86\_64\_32 against `.rodata.str1.8' can not be used when ma... | This looks to be a misfeature of the `setup.py` script always including `/usr/local` in the search path when `make` builds the target `sharedmods`.
You'll have to manually frob the `setup.py`, so do the...
```
./configure --enable-shared --prefix=/app/vendor/python-dev
```
...first, then edit `setup.py`, find lines ... | I solved with [this script](http://toomuchdata.com/2014/02/16/how-to-install-python-on-centos):
```
# Python 2.7.6:
wget http://python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz
tar xf Python-2.7.6.tar.xz
cd Python-2.7.6
./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /us... | How to ignore local python when building python from source | [
"",
"python",
"configure",
""
] |
I have a code that concatenates a string 'lst' on each item of the list.
```
i = 0
lim = len(lst)
while i < lim:
lst[i] = 'lst%s' % (lst[i])
i += 1
```
Is there a faster way of doing this? | This will modify the original `lst` object:
```
lst[:] = ['lst%s' % item for item in lst]
```
or using the new style string formatting:
```
lst[:] = ['lst{}'.format(item) for item in lst]
``` | Using a list comprehension slice assignment:
```
lst[:] = ['lst' + x for x in lst]
``` | Python, Appending string on each item on the list | [
"",
"python",
"arrays",
"string",
"list",
"append",
""
] |
I have 2 files named input.csv (composed of one column *count* ) and output.csv (composed of one column *id*).
I want to paste my *count* column in output.csv, just after the *id* column.
Here is my snippet :
```
with open ("/home/julien/input.csv", "r") as csvinput:
with open ("/home/julien/excel/output.csv", ... | You need to work with three files, two for reading and one for writing.
This should work.
```
import csv
in_1_name = "/home/julien/input.csv"
in_2_name = "/home/julien/excel/output.csv"
out_name = "/home/julien/excel/merged.csv"
with open(in_1_name) as in_1, open(in_2_name) as in_2, open(out_name, 'w') as out:
r... | 1. Open both files for input.
2. Open a new file for output.
3. In a loop, read a line from each, formatting an output line, which is then written to the output file
4. close all the files
5. Programmatically copy your output file on top of the input file
"output.csv".
Done | Add a column from a csv to another csv | [
"",
"python",
""
] |
How to sort the following Japanese Character in Sql Server,
```
賃貸人側連絡先 (Lessor side contact)
解約連絡先 (Termination contacts)
賃借人側連絡先 (Lessee side contact)
更新連絡先 (Update contact)
```
above `order(1,3,2,4)`
But, Actual order is ,(ie. output that i want)
```
賃貸人側連絡先 (Lessor side contact)
賃借人側連絡先 (Lessee side contact)
解約... | Looking at Windows [Japanese collations](http://msdn.microsoft.com/en-us/library/ms188046.aspx) rather then your SQL collations (SQL Server supports both), by trial and error, this works
```
DECLARE @t TABLE (id int, SomeString nvarchar(100));
INSERT @t VALUES
(1, N'賃貸人側連絡先'),
(3, N'解約連絡先'),
(2, N'賃借人側連絡先'),
(4, N'更新連... | In addition to @gbn's answer
* 賃 has Radical-Stroke Count 154.6
* 解 has 148.6
* 更 has 73.3
So the question should rather be, why do YOU want descending order? | How to sort the Japanese Character in Sql | [
"",
"sql",
"sql-server",
""
] |
I would like to generate a sequence such that the previously generated element was included in the next element, I am unsure how to do this.
i.e generate the list such that its items were:
where x is just a Sympy symbol
`[x,(x)*(x+1),(x)*(x+1)*(x+2)]`
rather than `[x,x+1,x+2]`
I'm thinking something like
`k.appen... | Maybe using a recursive `lambda` function and a `map` ?
```
>>> fact = lambda x: x == 0 and 1 or x * fact(x - 1)
>>> map(fact, range(4))
[1, 1, 2, 6]
```
and many other ways besides. If you want to return a `string` define your recursive function to return a `string`;
```
def fact(i):
if i == 0:
return '... | You can use `sympy.RaisingFactorial`:
```
import sympy.RaisingFactorial as RF
from sympy.abc import x
length=3
ans = [RF(x,i) for i in xrange(1,length+1)]
```
Which gives:
```
[x, x*(x + 1), x*(x + 1)*(x + 2)]
``` | Generate sequence using previous terms sympy | [
"",
"python",
"factorial",
"sympy",
"symbolic-math",
"symbolic-computation",
""
] |
Is the meaning of this regex: `(\d+).*?` - group a set of numbers, then take whatever that comes after (only one occurance of it at maximum, except a newline)?
Is there a difference in: `(\d+) and [\d]+`? | Take as many digits as possible (at least `1`), then take the smallest amount of characters as possible (except newline). The non greedy qualifier (`?`) doesn't really help unless you have the rest of your pattern following it, otherwise it will just match as little as possible, in this case, always `0`.
```
>>> impor... | ```
(\d)+ One or more occurance of digits,
.* followed by any characters,
? lazy operator i.e. return the minimum match.
``` | Meaning of regex Python | [
"",
"python",
"regex",
""
] |
I have a list:
```
data_list = ['a.1','b.2','c.3']
```
And I want to retrieve only strings that start with strings from another list:
```
test_list = ['a.','c.']
```
`a.1` and `c.3` should be returned.
I suppose I could use a double for-loop:
```
for data in data_list:
for test in test_list:
if data.st... | `str.startswith` can also take a *tuple* (but not a list) of prefixes:
```
test_tuple=tuple(test_list)
for data in data_list:
if data.startswith(test_tuple):
...
```
which means a simple list comprehension will give you the filtered list:
```
matching_strings = [ x for x in data_list if x.startswith(test... | Simply use [`filter`](http://docs.python.org/3.3/library/functions.html#filter) with a [lambda function](http://docs.python.org/3.3/reference/expressions.html#lambda) and [`startswith`](http://docs.python.org/3.3/library/stdtypes.html#str.startswith):
```
data_list = ['a.1','b.2','c.3']
test_list = ('a.','c.')
result... | Use list to filter another list in python | [
"",
"python",
""
] |
I installed python3.3 and I am learning django 1.5x.
I chose sqlite3 to learn with django and I am running python, django - and trying to run - sqlite3 in command line at windows.
All the problem is: where is the file of sqlite3 to run a command like `> sqlite3 my_db`
??
I tried to found at `C:\Python33\Lib\sqlite3;C:\... | Assuming that you want to inspect the database created by django, and assuming that the sqlite executable is installed, you can do the following to run sqlite in the command line:
```
./manage.py dbshell
```
More information on this command can be found in the [django documentation](https://docs.djangoproject.com/en/... | Python itself dosen't contain a sqlite3 command.
But the SQLite library includes a simple command-line utility named sqlite3 (or sqlite3.exe on windows) that allows the user to manually enter and execute SQL commands against an SQLite database. You can download it from [here](https://www.sqlite.org/download.html). | Run sqlite3 with python in command line | [
"",
"python",
"command-line",
"sqlite",
""
] |
is there a way to go back to this line of code to check for input again?:
```
say=raw_input("say: ")
```
after i do a if statement to check what the user inputed:
```
if say == "hello":
do something
```
It does the if statement but then It ends the program and i have to run it again.I really don't want to have ... | You can use a while loop:
```
while True:
say = raw_input('say: ')
if say == 'hello':
print "hi!"
break
elif say == 'bye':
print "bye!"
break
```
`while True` is an infinite loop. Every time the loop loops, it will ask the user what they want to say. If the reply is "hello"... | Use a loop, such as `while`:
```
while True:
say = raw_input("say: ")
if say == 'bye': break
# do something
```
I suggest reading a [Tutorial](http://docs.python.org/2/tutorial/index.html). | how to go back and check for another input | [
"",
"python",
"if-statement",
"raw-input",
""
] |
Good morning,
Is it possible to get the number of rows modified by an update in MySQL using a MySQL command?
I found this post but I didn't understand
[MYSQL number of records inserted and updated](https://stackoverflow.com/questions/11942024/mysql-number-of-records-inserted-and-updated?rq=1)
Thanks. | Use the [`ROW_COUNT()`](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count) function in MySQL:
```
UPDATE `table` SET `column` = 'data' WHERE `id` <= 10;
SELECT ROW_COUNT();
```
This will output the number of changed/deleted/added rows for `UPDATE`, `DELETE` and `INSERT`.
If you wis... | <http://dev.mysql.com/doc/refman/5.0/fr/update.html>
mysql update command return the number of modified rows... | Number of lines updated | [
"",
"mysql",
"sql",
""
] |
I have an sql statement like so
`select users.id, users.username, count(orders.number) as units from users inner join orders on orders.user_id = users.id where users.id = 1;`
Now this would the number or units user id one has made.
How do i get all users and the number or units they have purchased. The where keyword... | if you need all users, remove where clause and group by user id
```
select users.id, users.username, count(orders.number) as units
from users inner join orders
on orders.user_id = users.id
group by users.id,users.username;
``` | You should use `GROUP BY`:
```
SELECT users.id, users.username, count(orders.number) as units
FROM users
INNER JOIN orders on orders.user_id = users.id
GROUP BY users.id, users.username
```
You can check more here: [GROUP BY (Aggregate) Functions](http://dev.mysql.com/doc/refman/5.0/en/group-by... | How to write a sql statement to get a value from all users? | [
"",
"mysql",
"sql",
""
] |
I'm having trouble getting Kivy to work with PyCharm on Windows 7. I've managed to add most of the external libraries through File > Settings > Python interpreters > Paths Tab.
I'm using the Kivy version of Python.
When I run a Kivy app that works fine with using the [right click > send to > kivy.bat] method in PyChar... | This Kivy's Wiki page [Setting Up Kivy with various popular IDE's](https://github.com/kivy/kivy/wiki/Setting-Up-Kivy-with-various-popular-IDE's) has a better answer and detail commands. It is copied below with added information for Pycharm 3.4.
Go to your unzipped Kivy folder, create a symbol link for "kivy.bat" point... | Install and open `PyCharm`
1. If you already had it installed and have a project open, click `File -> Settings (Ctrl + Alt + S)`. (If not, create a new project, and click the '`...`' (or  ) next to interpreter, and skip step 2)
2. Under Project Settings, click `Pro... | How to configure Python Kivy for PyCharm on Windows? | [
"",
"python",
"windows",
"python-2.7",
"pycharm",
"kivy",
""
] |
Here is some Ruby code:
```
class Duck
def help
puts "Quaaaaaack!"
end
end
class Person
def help
puts "Heeeelp!"
end
end
def InTheForest x
x.help
end
donald = Duck.new
john = Person.new
print "Donald in the forest: "
InTheForest donald
print "John in the forest: "
InTheForest john
```
And, I tran... | The code does not show the whole story. Duck typing is about trying something and handling exceptions if they occur. As long it quacks, treat it like a duck, otherwise, treat it differently.
```
try:
dog.quack()
except AttributeError:
dog.woof()
```
This behavior is explained at the top of the [wikipedia Duck... | Yes, this is duck typing, which Python code can (and often does) use.
<http://en.wikipedia.org/wiki/Duck_typing#In_Python>
Further up on the page there is a more complete example in Python:
```
class Duck:
def quack(self):
print("Quaaaaaack!")
def feathers(self):
print("The duck has white and... | Is this duck-typing in Python? | [
"",
"python",
"python-3.x",
"duck-typing",
""
] |
Are there any libraries for computing semantic similarity scores for a pair of sentences ?
I'm aware of WordNet's semantic database, and how I can generate the score for 2 words, but I'm looking for libraries that do all pre-processing tasks like port-stemming, stop word removal, etc, on whole sentences and outputs a ... | The best package I've seen for this is Gensim, found at the [Gensim Homepage](http://radimrehurek.com/gensim/index.html). I've used it many times, and overall been very happy with it's ease of use; it is written in Python, and has an easy to follow [tutorial](http://radimrehurek.com/gensim/tut1.html) to get you started... | Unfortunately, I cannot help you with PY but you may take a look at my old project that uses dictionaries to accomplish the Semantic comparisons between the sentences (which can later be coded in PY implementing the vector-space analysis). It should be just a few hrs of coding to translate from JAVA to PY.
<https://sou... | Python: Semantic similarity score for Strings | [
"",
"python",
"semantics",
"wordnet",
"similarity",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.