Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm currently having a strange problem with a complex sql code. Here is the schema: ``` CREATE TABLE category ( category_id SERIAL PRIMARY KEY, cat_name CHARACTER VARYING(255) ); CREATE TABLE items ( item_id SERIAL PRIMARY KEY, category_id INTEGER NOT NULL, item_name CHARACTER VARYING(255), CON...
If you want to get the latest price for every `item`, you cn use `Window Function` since PostgreSQL supports it. * [List of Supported Window Function](http://www.postgresql.org/docs/9.1/static/functions-window.html) The query below uses `ROW_NUMBER()` which basically generates sequence of number based on how the reco...
The inner query only returns one record, which happens not to be item id #1. The inner query is run in full, then the results of that is used "as f". I think what you are trying to get is this: ``` SELECT category.*, items.*, f.max_price FROM items JOIN category ON category.category_id = items.category_id JOIN...
PostgreSQL returns null in a complex sql query
[ "", "sql", "postgresql-9.1", "" ]
I am creating a sitemap parser with LXML and want to extract the tags with its' values. The resulted tags, however, always contain the xmlns information e.g. `{http://www.sitemaps.org/schemas/sitemap/0.9}loc`. ``` body = cStringIO.StringIO(item['body']) parser = etree.XMLParser(recover=True, load_dtd=True, ns_clean=Tr...
In a perfect world you would use an XML parsing or html scraping library to parse your html to make sure you have the exact tags that you need, in context. It is almost certainly simpler, quicker and good enough in this case to simply use a regular expression to match what you need. ``` >>> import re >>> samp = """<si...
Not sure this is the best approach, but it uses `lxml` as you've asked and it works: ``` import cStringIO from lxml import etree text = """<sitemap xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <loc>http://www.some_page.com/sitemap-page-2010-11.xml</lo...
LXML: remove the x
[ "", "python", "xml", "lxml", "" ]
Very inexperienced with python and programming in general. I'm trying to create a function that generates a list of palindromic numbers up to a specified limit. When I run the following code it returns an empty list []. Unsure why this is so. ``` def palin_generator(): """Generates palindromic numbers.""" p...
Your `if` statement does *not* do what you think it does. You are applying operator chaining and you are testing 2 things: ``` (n == n[::-1]) and (n[::-1] is True) ``` This will *always* be `False` because `'0' is True` is not `True`. Demo: ``` >>> n = str(0) >>> n[::-1] == n is True False >>> n[::-1] == n True ``...
Going through all numbers is quite inefficient. You can generate palindromes like this: ``` #!/usr/bin/env python from itertools import count def getPalindrome(): """ Generator for palindromes. Generates palindromes, starting with 0. A palindrome is a number which reads the same in both di...
Palindrome generator
[ "", "python", "python-2.7", "palindrome", "" ]
How would I modify the following query to return Quote.Quote for only the most recent Quote\_Date for each unique Part\_Number? Since Quote is unique I am unable to return only the first record. I know this has been asked many times in almost the same fashion, however, I cant quite get it right using row\_number, rank,...
This query will number the maximum dates as '1', because of `partition...order by quote_date desc` clause. ``` select Quote, Part_number, Quote_date, rank() over (partition by part_number order by quote_date desc) as date_order from sample ``` The rank() function is usually a better choice...
Give this a shot. I'm not sure if you need the Part\_Number where clause, but you included it in your original SQL (as a HAVING clause) so I kept it. I obviously don't know exactly how your data looks, but the important thing is the rest of the sub-select. ``` SELECT a.Quote, a.Part_Number, a.Quote_Date FROM (SELE...
SQL: Return ID for the most recent date for unique part
[ "", "sql", "sql-server", "t-sql", "aggregate-functions", "" ]
I have two strings , the length of which can vary based on input. I want to format them aligning them to middle and filling up the rest of the space with `' '`. Each string starting adn ending with `^^` . **Case1:** ``` String1 = Longer String String2 = Short ``` **Output required:** ``` ^^ Longer String ^^ ^^ ...
Simply use [**`str.center`**](http://docs.python.org/dev/library/stdtypes.html#str.center): ``` assert '^^' + 'Longer String'.center(19) + '^^' == '^^ Longer String ^^' assert '^^' + 'Short'.center(19) + '^^' == '^^ Short ^^' ```
If you want to reference just setting the centering with respect to two strings: ``` cases=[ ('Longer String','Short'), ('Equal 1','Equal 2'), ('Short','Longer String'), ] for s1,s2 in cases: w=len(max([s1,s2],key=len))+6 print '^^{:^{w}}^^'.format(s1,w=w) print '^^{:^{w}}^^'.format(s2,w=w...
String Formatting - Python
[ "", "python", "string", "python-2.7", "printing", "" ]
I have two tables. An orders table with customer, and date. A date dimension table from a data warehouse. The orders table does not contain activity for every date in a given month, but I need to return a result set that fills in the gaps with date and customer. **For Example, I need this:** ``` Customer Date ===...
The problem is that you need all customers for all dates. When you do the `left outer join`, you are getting NULL for the customer field. The following sets up a driver table by `cross join`ing the customer names and dates: ``` SELECT driver.customer, driver.fulldate, o.amount FROM (select d.fulldate, customer ...
You can use recursive CTE to get all dates between two dates without need for `datetable`: ``` ;WITH CTE_MinMax AS ( SELECT Customer, MIN(DATE) AS MinDate, MAX(DATE) AS MaxDate FROM dbo.orders GROUP BY Customer ) ,CTE_Dates AS ( SELECT Customer, MinDate AS Date FROM CTE_MinMax UNION ALL SEL...
Fill In The Date Gaps With Date Table
[ "", "sql", "t-sql", "join", "sql-server-2008-r2", "left-join", "" ]
I'm running Numpy 1.6 in Python 2.7, and have some 1D arrays I'm getting from another module. I would like to take these arrays and pack them into a structured array so I can index the original 1D arrays by name. I am having trouble figuring out how to get the 1D arrays into a 2D array and make the dtype access the rig...
One way to go is ``` wtype=np.dtype([('x',x.dtype),('y',y.dtype),('z',z.dtype)]) w=np.empty(len(x),dtype=wtype) w['x']=x w['y']=y w['z']=z ``` Notice that the size of each number returned by randint depends on your platform, so instead of an int32, i.e. 'i4', on my machine I have an int64 which is 'i8'. This other wa...
You want to use [`np.column_stack`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html): ``` import numpy as np x = np.random.randint(10,size=3) y = np.random.randint(10,size=3) z = np.random.randint(10,size=3) w = np.column_stack((x, y, z)) w = w.ravel().view([('x', x.dtype), ('y', y.dtype)...
numpy Stacking 1D arrays into structured array
[ "", "python", "numpy", "" ]
So I have a fully functional py script running on Ubuntu 12.04, everything works great. Except I don't like my input methods, it's getting annoying as you'll see below. Before I type out the code, I should say that the code takes two images in a .img format and then does computations on them. Here's what I have: ``` i...
Seeing that the parsing code already exists, all you need to do is accept command-line arguments with Python's [sys module](http://docs.python.org/2/library/sys.html): ``` import sys first = sys.argv[1] second = sys.argv[2] ``` Or, more generally: ``` import os import sys if __name__ == '__main__': if len(sy...
You want to parse the command line arguments instead of reading input after the program starts. Use the [`argparse` module](http://docs.python.org/2/library/argparse.html) for that, or parse [`sys.argv`](http://docs.python.org/2/library/sys.html#sys.argv) yourself.
I'd like my code to flow with my terminal a little better
[ "", "python", "linux", "python-2.7", "" ]
I'm plotting a line using matplotlib and would like to update my line data as soon as new values are generated. However, once in the loop, no window appears. Even though the printed line indicates the loop is running. Here's my code: ``` def inteprolate(u,X): ... return XX # generate initial data XX = intepr...
You need to call `plt.pause` in your loop to give the gui a chance to process all of the events you have given it to process. If you do not it can get backed up and never show you your graph. ``` # get new values and re-plot plt.ion() # make show non-blocking plt.show() # show the figure while True: print "!" ...
You'll need plt.ion(). Take a look a this: [pylab.ion() in python 2, matplotlib 1.1.1 and updating of the plot while the program runs](https://stackoverflow.com/questions/12822762/pylab-ion-in-python-2-matplotlib-1-1-1-and-updating-of-the-plot-while-the-pro). Also you can explore the Matplotlib animation classes : <htt...
Dynamically updating a graphed line in python
[ "", "python", "numpy", "matplotlib", "" ]
If I have the following list to start: ``` list1 = [(12, "AB"), (12, "AB"), (12, "CD"), (13, Null), (13, "DE"), (13, "DE")] ``` I want to turn it into the following list: ``` list2 = [(12, "AB", "CD"), (13, "DE", Null)] ``` Basically, if there is one or more text values with their associated keys, the second list h...
A simple way would loop through `list1` multiple times, grabbing the relevant values each time. First time to grab all the keys. Then for each key, grab all the values ([repl.it](http://repl.it/J9K/1)): ``` Null = None list1 = [(12, "AB"), (12, "AB"), (12, "CD"), (13, Null), (13, "DE"), (13, "DE")] keys = [] for k,v ...
the simplest way i can see is the following: ``` >>> from collections import OrderedDict >>> d = OrderedDict() >>> for (k, v) in [(12, "AB"), (12, "AB"), (12, "CD"), (13, None), (13, "DE"), (13, "DE")]: ... if k not in d: d[k] = set() ... d[k].add(v) >>> d OrderedDict([(12, {'AB', 'CD'}), (13, {'DE', None})]...
How to create a new list out of an existing list by removing duplicates and shifting values?
[ "", "python", "list", "" ]
I'm currently trying to read data from .csv files in Python 2.7 with up to 1 million rows, and 200 columns (files range from 100mb to 1.6gb). I can do this (very slowly) for the files with under 300,000 rows, but once I go above that I get memory errors. My code looks like this: ``` def getdata(filename, criteria): ...
You are reading all rows into a list, then processing that list. **Don't do that**. Process your rows as you produce them. If you need to filter the data first, use a generator function: ``` import csv def getstuff(filename, criterion): with open(filename, "rb") as csvfile: datareader = csv.reader(csvfil...
Although Martijin's answer is prob best. Here is a more intuitive way to process large csv files for beginners. This allows you to process groups of rows, or chunks, at a time. ``` import pandas as pd chunksize = 10 ** 8 for chunk in pd.read_csv(filename, chunksize=chunksize): process(chunk) ```
Reading a huge .csv file
[ "", "python", "python-2.7", "file", "csv", "" ]
I am working on a traffic study and I have the following problem: I have a CSV file that contains time-stamps and license plate numbers of cars for a location and another CSV file that contains the same thing. I am trying to find matching license plates between the two files and then find the time difference between t...
You should check out [difflib](http://docs.python.org/2/library/difflib.html). You can perform matches like this: ``` >>> import difflib >>> a='ASD456' >>> b='ASF456' >>> seq=difflib.SequenceMatcher(a=a.lower(), b=b.lower()) >>> seq.ratio() 0.83333333333333337 ```
What you're asking is about a fuzzy search, from what it sounds like. Instead of checking string equality, you can check if the two string being compared have a levenshtein distance of 1 or less. Levenshtein distance is basically a fancy way of saying how many insertions, deletions or changes will it take to get from w...
Python Matching License Plates
[ "", "python", "comparison", "" ]
Hello I am trying the alter this function to return the date of the first day of the week which I want to be Monday.The problem is when the input date is Sunday it returns the following Monday instead of the previous one.For example it should yield Input->Output given ``` 2013-06-11 -> 2013-06-10 2013-06-16 -> 2013-06...
You need to have the `RETURN` before the `CASE` statement, not in it. ``` ALTER FUNCTION [dbo].[ufn_GetFirstDayOfWeek] ( @pInputDate DATETIME ) RETURNS DATETIME BEGIN SET @pInputDate = CONVERT(VARCHAR(10), @pInputDate, 111) RETURN CASE WHEN DATENAME(dw, @pInputDate) = 'Sunday' THEN DATEADD(DD, -5- DATEPART(DW, @...
Day 0 of the SQL calendar is a Monday: ``` select datename(dw, 0); ``` Armed with this knowledge, we can easily do the math, just divide by 7, take the floor and multiply back by 7: ``` declare @d datetime = '20130611'; select dateadd(day, floor(cast(@d as int) / 7.00) * 7.00, 0); set @d = '20130616'; select dateadd...
First day of the week
[ "", "sql", "sql-server", "sql-server-2008", "" ]
``` declare @BranchId int declare @PaymentDate date set @DebtIsPayed =null set @BranchId =3 set @PaymentDate='2013-01-01' select og.StudentId, og.Name,sb.BranchName,bt.DeptValue,DebtIsPayed,PaymentDate ,bt.DebtDescriptionName from StudentPayment od left outer join DebtDescription bt on od.DebtDescriptionId= bt.Debt...
Maybe something like ``` where ( (@BranchID is null and od.DebtIsPayed=@DebtIsPayed) or (@DebtIsPayed is null and og.BranchId=@BranchId) ) and (@PaymentDate is null or PaymentDate > @PaymentDate ) ```
There is a way to do it without case operator. Here is the sample query: ``` declare @BranchId int declare @PaymentDate date set @DebtIsPayed =null set @BranchId =3 set @PaymentDate='2013-01-01' select og.StudentId, og.Name,sb.BranchName,bt.DeptValue,DebtIsPayed,PaymentDate ,bt.DebtDescriptionName from StudentPaymen...
Depents on the declared values,List the records
[ "", "sql", "t-sql", "" ]
I've got an MS SQL 2008 database table that looks like the following: `Registration | Date | DriverID | TrailerID` An example of what some of the data would look like is as follows: ``` AB53EDH,2013/07/03 10:00,54,23 AB53EDH,2013/07/03 10:01,54,23 ... AB53EDH,2013/07/03 10:45,54,23 AB53EDH,2013/07/03 10:46,54,NULL <...
This query uses CTEs to: 1. Create an ordered collection of records grouped by Registration 2. For each record, capture the data of the previous record 3. Compare current and previous data to determine if the current record is a new instance of a driver / trailer assignment 4. Get only the new records 5. For each n...
try-: ``` DECLARE @TempTable AS TABLE ( [Registration] [nvarchar](50) NOT NULL, [Date] [datetime] NOT NULL, [DriverID] [int] NULL, [TrailerID] [int] NULL ) INSERT INTO @TempTable VALUES ('AB53EDH','2013-07-03 10:00', 54,23), ('AB53EDH','2013-07-03 10:01', 54,23), ('AB53EDH','2013-07-03 10:45', 54,23)...
How to group together sequential, timestamped rows in SQL and return the date range for each group
[ "", "sql", "sql-server-2008", "" ]
I have a table `TAB` having two fields `A` and `B`, `A` is a `Varchar2(50)` and `B` is a `Date`. Supposing we have these values: ``` A | B ------------------ a1 | 01-01-2013 a2 | 05-05-2013 a3 | 06-06-2013 a4 | 04-04-2013 ``` we need to have the value of field `A` corresponding to the maximum of field `B`...
I made an [sqlfiddle](http://sqlfiddle.com/#!3/5d8e6/6/3) where I listed 4 different ways to achieve what you want. Note, that I added another row to your example. So you have two rows with the maximum date. See the difference between the queries? Manoj's way will give you just one row, although 2 rows match the criter...
You can try this way also ``` SELECT TOP 1 A FROM TAB ORDER BY B DESC ``` Thanks Manoj
getting the row corresponding to the max of other row
[ "", "sql", "" ]
I need to check some sublist for a particular property, and then return the bin which satisfies that property, but as an index of the original list. Currently I'm having to do this manually: ``` sublist = mylist[start:end] positive = search(sublist) positive = start + positive posiveList.append(positive) ``` Is the...
I think what you're asking is this: > If I search and find an index in a sublist, is there a straightforward way to convert it to its index in the original list? No, the only way is what you're already doing: you need to add the `start` offset back to the index to get the index in the original list. This makes sense...
If I understood you correctly, you want to save indexes of all matching element. If so, then think you are looking for this: ``` positiveList = [i for i, item in enumerate(mylist[start:end]) if validate_item(item)] ``` Where `validate_item` should essentially check whether this item is required or no...
Making sublist indices refer to the original list
[ "", "python", "" ]
I'm trying to **add custom time to datetime in SQL Server 2008 R2**. Following is what I've tried. ``` SELECT DATEADD(hh, 03, DATEADD(mi, 30, DATEADD(ss, 00, DATEDIFF(dd, 0,GETDATE())))) as Customtime ``` Using the above query, I'm able to achieve it. But is there any shorthand method already available to add custo...
Try this ``` SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), '03:30:00') ```
For me, this code looks more explicit: ``` CAST(@SomeDate AS datetime) + CAST(@SomeTime AS datetime) ```
How to add time to DateTime in SQL
[ "", "sql", "sql-server-2008", "datetime", "" ]
I have a list, `root`, of lists, `root[child0]`, `root[child1]`, etc. I want to sort the children of the root list by the first value in the child list, `root[child0][0]`, which is an `int`. Example: ``` import random children = 10 root = [[random.randint(0, children), "some value"] for child in range(children)] ```...
You may specify a [`key` function](http://wiki.python.org/moin/HowTo/Sorting/#Key_Functions) which will determine the sorting order. ``` sorted(root, key=lambda x: x[0], reverse=True) ``` You said you aren't familiar with lambdas. Well, first off, [you can read this](http://www.secnetix.de/olli/Python/lambda_function...
You can the `key` parameter to specify the function or item you want to use for comparing the items. ``` key = lambda x : x[0] ``` or better : `key = operator.itemgetter(0)` or you can also define your own function if necessary and pass it to `key`. ``` >>> root = [[random.randint(0, children), "some value"] for ch...
Sorting a meta-list by first element of children lists in Python
[ "", "python", "list", "sorting", "python-2.x", "" ]
I have a following table: **trade\_id | stock\_code | date | amount** This table contains all trades I made. And I want to know the number of amount I made in last week and the total amount I have on every stock. **stock\_code | amount\_in\_lst\_week | amount\_remaining** For example: ``` 1 | A | 2013-01-01 | 200 ...
How about this: ``` select Stock_code ,[1st week] = sum(case when [date] >= getDate()-7 then amount else 0 end) ,remainder = sum(amount) from data group by Stock_code ```
Most databases support window functions. You can get what you want as: ``` select stock_code, sum(case when date >= CURRENT_TIMESTAMP - 7 then amount_remaining else 0 end) as amount_in_lst_week, sum(sum(amount_remaining)) over () from trade group by stock_code, amount_in_lst_week ; ``` The e...
Is there any way to retrieve both aggregated and non-aggregated values without subquery?
[ "", "mysql", "sql", "" ]
I am trying to recreate maximum likelihood distribution fitting, I can already do this in Matlab and R, but now I want to use scipy. In particular, I would like to estimate the Weibull distribution parameters for my data set. I have tried this: ``` import scipy.stats as s import numpy as np import matplotlib.pyplot a...
My guess is that you want to estimate the shape parameter and the scale of the Weibull distribution while keeping the location fixed. Fixing `loc` assumes that the values of your data and of the distribution are positive with lower bound at zero. `floc=0` keeps the location fixed at zero, `f0=1` keeps the first shape ...
It is easy to verify which result is the true MLE, just need a simple function to calculate log likelihood: ``` >>> def wb2LL(p, x): #log-likelihood return sum(log(stats.weibull_min.pdf(x, p[1], 0., p[0]))) >>> adata=loadtxt('/home/user/stack_data.csv') >>> wb2LL(array([6.8820748596850905, 1.8553346917584836]), ad...
Fitting a Weibull distribution using Scipy
[ "", "python", "numpy", "scipy", "distribution", "weibull", "" ]
My objective is to take string(containg UTC date and time) as the input and convert it to local timezone based on Timezone difference. I have come up with the following code **Code** ``` import time print "Timezone Diff", time.timezone/3600 def convertTime(string): print "Before Conversion" print "ye...
Here's a solution with the [`datetime`](http://docs.python.org/2/library/datetime.html) and [`pytz`](http://pytz.sourceforge.net/) modules, using my timezone as an example: ``` import pytz import datetime s = '2013:07:04:14:00' mydate = datetime.datetime.strptime(s, '%Y:%m:%d:%H:%M') mydate = mydate.replace(tzinfo=tim...
To convert UTC time to a local timezone using only stdlib, you could use an intermediate timestamp value: ``` from datetime import datetime def convertTime(timestring): utc_dt = datetime.strptime(timestring, '%Y:%m:%d:%H:%M') timestamp = (utc_dt - datetime.utcfromtimestamp(0)).total_seconds() return datet...
Python date string manipulation based on timezone - DST
[ "", "python", "python-2.7", "timezone", "" ]
I am trying to use kmeans clustering in scipy, exactly the one present here: <http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html#scipy.cluster.vq.kmeans> What I am trying to do is to convert a list of list such as the following: ``` data without_x[ [0, 0, 0, 0, 0, 0, 0, 20.0, 1.0, 48.0,...
That is exactly how to convert a list of lists to an ndarray in python. Are you sure your `data_without_x` is filled correctly? On my machine: ``` data = [[1,2,3,4],[5,6,7,8]] data_arr = np.array(data) data_arr array([[1,2,3,4], [5,6,7,8]]) ``` Which is the behavior I think you're expecting Looking at your i...
`vq.whiten` and `vq.kmeans` expect an array of shape `(M, N)`, where *each row* is an observation. So transpose your `data_array`: ``` import numpy as np import scipy.cluster.vq as vq np.random.seed(2013) data_without_x = [ [0, 0, 0, 0, 0, 0, 0, 20.0, 1.0, 48.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1224.0, 125....
List of List to ndarray
[ "", "python", "numpy", "scipy", "k-means", "multidimensional-array", "" ]
As far as I know this question is not a repeat, as I have been searching for a solution for days now and simply cannot pin the problem down. I am attempting to print a nested attribute from an XML document tag using Python. I believe the error I am running into has to do with the fact that the tag I from which I'm tryi...
You fail at .find('second-tag'), not on the .get. For what you want, and your idiom, BeautifulSoup shines. ``` from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup(xml_string) whatyouwant = soup.find('second-tag')['status'] ```
I dont know with elementtree but i would do so with ehp or easyhtmlparser here is the link. <http://easyhtmlparser.sourceforge.net/> a friend told me about this tool im still learning thats pretty good and simple. ``` from ehp import * data = '''<?xml version="1.0" encoding="UTF-8"?> <first-tag xmlns="http://somewebs...
XML Python Choosing one of numerous attributes using ElementTree
[ "", "python", "xml", "elementtree", "" ]
``` USE tempdb CREATE TABLE A ( id INT, a_desc VARCHAR(100) ) INSERT INTO A VALUES (1, 'vish'),(2,'hp'),(3,'IBM'),(4,'google') SELECT * FROM A CREATE TABLE B ( id INT, b_desc VARCHAR(100) ) INSERT INTO B VALUES (1, 'IBM[SR4040][SR3939]'),(2,'hp[GR3939]') SELECT * FROM B SELECT * FROM A WH...
Try this one - **Query:** ``` SELECT * FROM A WHERE EXISTS( SELECT 1 FROM B WHERE b_desc LIKE '%' + a_desc + '%' ) ``` **Output:** ``` id a_desc ----------- ---------- 2 hp 3 IBM ``` **Execution plan:** ![proff](https://i.stack.imgur.com/MjGob.png) **Extended statistics:...
you can simple join: ``` SELECT distinct a.* from A inner join b on b.b_desc like '%' + a.a_desc + '%' ```
Using [like] like in clause in SQL?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to write a python function to return the number of primes less than a given value and the values of all the primes. I need to use the Sieve of Eratosthenes algorithm. I believe I'm missing something in the function - For example, when I want to find the primes under 100. All I got is 2, 3, 5, 7. I am aware ...
"I am told I need to use square root". Why do you think that is? Usually the sieve of E. is used to remove all "non prime" numbers from a list; you can do this by finding a prime number, then checking off all multiples of that prime in your list. The next number "not checked off" is your next prime - you report it (wit...
Your logic is correct, except for the `for` loop. It terminates after reaching `sqrt(n)-1`. For `p(100)`, it will run only from 2 to 9. Hence you get prime numbers only till 9.
Sieve of Eratosthenes in Python
[ "", "python", "sieve-of-eratosthenes", "" ]
I have two objects which represent the same one. I even insured they had the same hash. I still got an error though from a dictionary: ``` >>> hash(one) 1098414562 >>> hash(one+zero) 1098414562 >>> a={one:1} >>> a[one+zero] Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> a[one+zero] ...
To be properly [hashable](http://docs.python.org/2/glossary.html#term-hashable) dict keys, the objects must also define `__eq__()` or `__cmp__()`. They must compare equal to be recognized as the same key. If the objects have the same hash, but do not compare equal, a hash collision is assumed, and they go separately i...
> If a class does not define a `__cmp__()` or `__eq__()` method it should not define a `__hash__()` operation either; if it defines `__cmp__()` or `__eq__()` but not `__hash__()`, its instances will not be usable in hashed collections. If a class defines mutable objects and implements a `__cmp__()` or `__eq__()` method...
Objects have same hash, dictionary not recognizing as same
[ "", "python", "dictionary", "hashtable", "" ]
When I execute the following code : ``` file1 = open("sources.conf", "r"); datalist = list(file1.readlines()); datalist[3][32]= "11"; ``` I get this error: `'str' object does not support item assignment`. After reading a bit, I discovered that it is not possible to change the string in python. Is there any other work...
Slice the string and reassign it to the same position in your list: ``` datalist[3] = datalist[3][:31] + '11' + datalist[3][33:] ```
How about this (using slices): ``` datalist[3] = datalist[3][:31] + "11" + datalist[3][33:] ``` Also, Python doesn't use `;` after each statement. You can also change your string to a list, and back again: ``` temp = list(datalist[3]) temp[32:34] = "11" datalist[3] = "".join(temp) ```
How to modify a part of string in python
[ "", "python", "" ]
I've created a simple text-based escape the room game in Python, with the intention of embedding a Pure Data patch (via libPd) in order to playback a different soundfile (this will later be replaced with an algorithm for generative music) for each of my different rooms. The python code I'm currently working with was t...
I ended up using a workaround and imported pygame (as opposed to pyaudio) to handle the audio and initialise the patch. It works without a hitch. Thanks for your help. \*For anyone that encounters a similar problem, check out "pygame\_test.py" in the libPd github for python.
I had similar problems. Using a callback fixed it for me. Here is the python to play a sine wave. ``` import pyaudio from pylibpd import * import time def callback(in_data,frame_count,time_info,status): outp = m.process(data) return (outp,pyaudio.paContinue) p = pyaudio.PyAudio(...
Implementing libPD (Pure Data wrapper) in Python
[ "", "python", "puredata", "" ]
I'd like to accept a single argument in my script, much like "mkdir". If the argument is just a name, ie `helloworld`, it would use `[pwd]/helloworld`. If it contains something that could be taken as a filepath, ie `../helloworld`, `/home/x/helloworld`, `~/helloworld`, etc, then it would use those to resolve the final ...
I think this is what you're looking for: ``` import os os.path.realpath(__file__) ```
The way to do it is the following: ``` os.path.realpath(os.path.expanduser(__file__)) ``` By default, realpath() doesn't handle tildas, so you need the expanduser() to do the dirty work.
Get filepath from shell working directory in Python?
[ "", "python", "filesystems", "" ]
I have a `order` table like this ``` id | bookId | bookAuthorId -------------------------- 1 3 2 2 2 1 3 1 2 ``` and another table ``` bookId | book --------------- 1 bookA 2 bookB 3 bookC ``` and ``` bookAuthorId | author ----------...
You can do it using the `where` clause ``` select id, book, author from `order`, book, author where `order`.bookId = book.bookId and `order`.authorId = author.authorId ``` --- Or ``` select o.id, b.book, a.author from `order` o natural join book b natural join author a ...
``` select o.id, b.book, a.author from 'order' o join book b on o.bookid=b.bookid join author a on o.bookauthorid=a.bookauthorid where o.id=1 ```
SQL Query to Join tables
[ "", "mysql", "sql", "database", "join", "" ]
I'd like to create an [Argand Diagram](http://mathworld.wolfram.com/ArgandDiagram.html) from a set of complex numbers using matplotlib. * Are there any pre-built functions to help me do this? * Can anyone recommend an approach? [![enter image description here](https://i.stack.imgur.com/3to4S.png)](https://i.stack.img...
I'm not sure exactly what you're after here...you have a set of complex numbers, and want to map them to the plane by using their real part as the x coordinate and the imaginary part as y? If so you can get the real part of any python imaginary number with `number.real` and the imaginary part with `number.imag`. If yo...
To follow up @inclement's answer; the following function produces an argand plot that is centred around 0,0 and scaled to the maximum absolute value in the set of complex numbers. I used the plot function and specified solid lines from (0,0). These can be removed by replacing `ro-` with `ro`. ``` def argand(a): i...
How to plot complex numbers (Argand Diagram) using matplotlib
[ "", "python", "numpy", "matplotlib", "plot", "complex-numbers", "" ]
What is a good way to do `some_string.split('')` in python? This syntax gives an error: ``` a = '1111' a.split('') ValueError: empty separator ``` I would like to obtain: ``` ['1', '1', '1', '1'] ```
Use [`list()`](http://docs.python.org/2/library/functions.html#list): ``` >>> list('1111') ['1', '1', '1', '1'] ``` Alternatively, you can use [`map()`](http://docs.python.org/2/library/functions.html#map) (Python 2.7 only): ``` >>> map(None, '1111') ['1', '1', '1', '1'] ``` Time differences: ``` $ python -m timei...
One can cast strings to list directly ``` >>> list('1111') ['1', '1', '1', '1'] ``` or using list comprehensions ``` >>> [i for i in '1111'] ['1', '1', '1', '1'] ``` second way can be useful if one wants to split strings for substrings more than 1 symbol length ``` >>> some_string = '12345' >>> [some_string[i:i+2]...
How to split a string using an empty separator in Python
[ "", "python", "string", "split", "" ]
I am using Django DeleteView in a template and I've created a url & view. Is it possible to skip the process of loading the \_confirm\_delete template and just post the delete immediately.
`DeleteView` responds to `POST` and `GET` requests, `GET` request display confirmation template, while `POST` deletes instance. You can send `POST` request, without confirmation with form like this: ``` <form method="POST" action="{% url "your_delete_url_name" %}"> {% csrf_token %}<input type="submit" value="DELET...
Or you can redefine `get()` method in your `DeleteView`: ``` class YourDeleteView(DeleteView): model = YourModel success_url = '<success_url>' def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) ``` But be careful with that, ensure that this doesn't affect other f...
Django DeleteView without confirmation template
[ "", "python", "django", "" ]
when I enter this ``` INSERT INTO works_on (essn, pno, hours) values ('123456789', 1, 32.5), ('123456789', 2, 7.5), ('666884444', 3, 40.0), ('453453453', 1, 20.0), ('453453453', 2, 20.0), ('333445555', 2, 10.0), ('333445555', 3, 10.0), ('333445555', 10, 10.0), ('333445555', 20, 10.0), ('999887777', 30, 30.0), ('999887...
In Oracle, you can't specify multiple sets of values like this (I'm guessing that you're coming from a MySQL background where that syntax is allowed). The simplest approach is to generate multiple `INSERT` statements ``` INSERT INTO works_on (essn, pno, hours) values ('123456789', 1, 32.5); INSERT INTO works_on (essn...
You cannot combine all your values in a single insert like that in Oracle unfortunately. You can either separate your SQL statements, or use another approach like this to run in a single statement: ``` INSERT INTO works_on (essn, pno, hours) SELECT '123456789', 1, 32.5 FROM DUAL UNION SELECT '123456789', 2, 7.5 FROM ...
I'm getting an error in SQL command not properly ended
[ "", "sql", "oracle11g", "sqlcommand", "" ]
Let's say I have this table ``` Table name: Traffic Seq. Type Amount 1 in 10 2 out 30 3 in 50 4 out 70 ``` What I need is to get the previous smaller and next larger amount of a value. So, if I have 40 as a value, I will get... ``` Table name: Traffic Seq. ...
How about a CTE? From memory (no machine to test with): ``` with less as (select * from traffic where amount < 40), more as (select * from traffic where amount > 40) select * from traffic where id = (select id from less where amount = (select max(amount from less))) or id = (select id from more where amou...
I looked at this question from possibly another point of view. I have seen other questions about date-time ranges between rows, and I thought perhaps what you might be trying to do is establish what range some value might fall in. If working with these ranges will be a recurring theme, then you might want to create a ...
Using "order by" and fetch inside a union in SQL on as400 database
[ "", "sql", "ibm-midrange", "" ]
I am new to hive, and want to know if there is anyway to insert data into Hive table like we do in SQL. I want to insert my data into hive like ``` INSERT INTO tablename VALUES (value1,value2..) ``` I have read that you can load the data from a file to hive table or you can import data from one table to hive table bu...
Some of the answers here are out of date as of Hive 0.14 <https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-InsertingvaluesintotablesfromSQL> It is now possible to insert using syntax such as: ``` CREATE TABLE students (name VARCHAR(64), age INT, gpa DECIMAL(3, 2)); INSERT INTO T...
You can use the table generating function `stack` to insert literal values into a table. First you need a dummy table which contains only one line. You can generate it with the help of limit. ``` CREATE TABLE one AS SELECT 1 AS one FROM any_table_in_your_database LIMIT 1; ``` Now you can create a new table with lite...
Hive insert query like SQL
[ "", "sql", "hadoop", "hive", "hiveql", "" ]
I am working of a project that has 2 tables as follows: **users\_fb** and **posts** *I spent 3 hours playing with the code and then I gave up.* table: posts ``` +-----+---------+---------+---------+---------+-----------+ | id | by_user | by_page | votes | status | time | +-----+---------+---------+---------...
You don't appear to have anything to join your tables together to match up with posts / votes go with which user. Something like this should do it ``` SELECT users_fb.username, Sub1.postcount, Sub2.votecount FROM users_fb LEFT OUTER JOIN( SELECT a.username, COUNT(*) AS postcount FROM users_fb a ...
``` SELECT a.username, COUNT(b.by_user) totalCount, SUM(IFNULL(b.votes,0)) total_votes FROM users_fb a LEFT JOIN posts b ON a.id = b.by_user WHERE b.by_page = '0' GROUP BY a.id,a.username ```
MySQL syntax issue, multiple SELECT statements
[ "", "mysql", "sql", "database", "database-schema", "" ]
I am trying to get a better understanding of the following python code and why the author has used the "AND" statement in the return. ``` def valid_password(self, password): PASS_RE = re.compile(r'^.{6,128}$') return password and PASS_RE.match(password) ``` further down the code... ``` if not self.va...
In Python, both `and` and `or` will return one of their operands. With `or`, Python checks the first operand and, if it is a "truthy" value (more on truthiness later), it returns the first value without checking the second (this is called Boolean shortcut evaluation, and it can be important). If the first is "falsey", ...
The line in question verifies that the password is ['truthy'](http://docs.python.org/release/2.5.2/lib/truth.html) and that it matches a predefined password regular expression. Here's how it breaks down: * The function returns `password` if `password` is ['falsey'](http://docs.python.org/release/2.5.2/lib/truth.html)...
What is this "and" statement actually doing in the return?
[ "", "python", "object", "boolean", "return", "" ]
Basically I want to check and update a new column (**in\_downtown**) in above table by using a **function** if the above data lies in following location of Downtown Seattle with these coordinates: Point A: ‐122.341518 47.578047 (longitude latitude) Point B: ‐122.284355 47.578047 (longitude latitude) Point C: ‐122.27800...
``` BEGIN FOR a IN (SELECT * FROM clean.households) LOOP UPDATE clean.households set geom=ST_GeomFromText('POINT(' || a.x_coord || ' ' || a.y_coord || ')',2285) where hhid ='a.hhid'; UPDATE clean.households set wkt = ST_AsText(ST_Transform(ST_GeomFromText('POINT(' || a.x_coord || ' ' || a.y_coord || ')',2285),4269))whe...
``` BEGIN -- (IN wkt TEXT) DECLARE pos TEXT; DECLARE X FLOAT; DECLARE Y FLOAT; DECLARE spa INT; DECLARE TOP_EDGE FLOAT; DECLARE BOTTOM_EDGE FLOAT; DECLARE LEFT_EDGE FLOAT; DECLARE RIGHT_EDGE FLOAT; -- You'll need to set the above variables here TOP_EDGE = 47.630362; BOTTOM_EDGE = 47.578047; LEFT_EDGE = -122.341518; R...
SQL: How to check if an area is within a latitude / longitude position?
[ "", "sql", "postgresql", "gis", "" ]
![enter image description here](https://i.stack.imgur.com/wupwN.png) I have a table like `figure (1)`. 10000 is the moneyStock of 12 months of all products. 5000 is the moneyStock of 12 months of product 384. Now I like to get money, moneyStock and total of product 384 like `figure (3)`. How to do it? Figure (2) is wh...
``` select a.month_str,a.money,ifnull(b.moneyStock,0) moneyStock, a.money+ifnull(b.moneyStock,0) total from (select siire_code code,month_str, sum(money) money from yourtable where siire_code = 384 group by siire_code,month_str)a left outer join (select zaiko_code code, month_s...
``` SELECT s.month_str, s.money, IFNULL(z.money, 0) 'moneyStock', (IFNULL(z.money, 0) + s.money) 'total' FROM Source s LEFT JOIN Source z ON s.siire_code = z.zaiko_code AND s.month_str = z.month_str AND z.siire_code = 560 WHERE s.siire_code = 384 ``` Working **[DEMO!](http:/...
Move value from line to another line?
[ "", "mysql", "sql", "" ]
using MS SQL server 2008. I have a query as follows: ``` SELECT * FROM #PreModuleAllData WITH(NOLOCK) WHERE (@Country != 'DEFAULT' AND @Country != '' AND([Language] = @Country )) OR (@UserType != 'DEFAULT' AND @UserType != '' AND([UserType] = @UserType )) OR (@Group != 'DEFAULT' AND @Group != '' A...
Try this: ``` SELECT * FROM #PreModuleAllData WITH(NOLOCK) WHERE (@Country = 'DEFAULT' OR @Country = '' OR ([Language] = @Country )) AND (@UserType = 'DEFAULT' OR @UserType = '' OR ([UserType] = @UserType )) AND (@Group = 'DEFAULT' OR @Group = '' OR ([Company] = @Group )) AND (@CodeUsage = 'DEFAUL...
You need a boolean condition in your where clause: ``` WHERE ((@Country = 'DEFAULT') OR @Country!= 'DEFAULT' AND @Country != '' AND([Language] = @Country )) AND ``` if the parameter country is not `default`, it will apply that condition. otherwise if the paremeter is default then the second condition will be skipped.
SQL query not returning data from where clause
[ "", "sql", "sql-server-2008", "" ]
**How can I print the numerical value of a theano TensorVariable?** I'm new to theano, so please be patient :) I have a function where I get `y` as a parameter. Now I want to debug-print the shape of this `y` to the console. Using ``` print y.shape ``` results in the console output (i was expecting numbers, i.e. `(2...
If y is a theano variable, y.shape will be a theano variable. so it is normal that ``` print y.shape ``` return: ``` Shape.0 ``` If you want to evaluate the expression y.shape, you can do: ``` y.shape.eval() ``` if `y.shape` do not input to compute itself(it depend only on shared variable and constant). Otherwise...
For future readers: the previous answer is quite good. But, I found the 'tag.test\_value' mechanism more beneficial for debugging purposes (see [theano-debug-faq](http://deeplearning.net/software/theano/tutorial/debug_faq.html#using-test-values)): ``` from theano import config from theano import tensor as T config.com...
theano - print value of TensorVariable
[ "", "python", "debugging", "theano", "" ]
``` log_date log_time emp_id emp_name log_action 2013-06-16 08:48:48.0000000 30170 Sarah John 1 2013-06-16 16:48:48.0000000 30170 Sarah John 4 2013-06-15 07:18:48.0000000 30160 Paula Fred 1 2013-06-15 16:38:48.0000000 30160 Paula Fred ...
``` SELECT StartLog.emp_id, StartLog.log_date, SUM(datediff(Minute,stm, etm))/60.0 FROM ( SELECT emp_id, log_date, MIN(log_time) AS stm FROM tblLogs WHERE log_action = '1' GROUP BY emp_id, log_date ) AS StartLog INNER JOIN ( SELECT emp_id, log_date, MIN(log_time) AS etm FROM ...
Since you only want the first entry per employee-day-action: ``` SELECT [log_date], [emp_id], [emp_name], [1] AS [first_log_in], [4] AS [first_log_out], DATEDIFF(minute,[1],[4])/60.0 AS [hours] FROM @tblLogs PIVOT(MIN(log_time) FOR log_action IN ([1],[4])) p ``` This assumes your log data is in good shape...
Total work hours
[ "", "sql", "sql-server", "sql-server-2008", "" ]
The following is the overall structure of my typical Python Tkinter program. ``` def funA(): def funA1(): def funA12(): # stuff def funA2(): # stuff def funB(): def funB1(): # stuff def funB2(): # stuff def funC(): def funC1(): # stuff de...
I advocate an object oriented approach. This is the template that I start out with: ``` # Use Tkinter for python 2, tkinter for python 3 import tkinter as tk class MainApplication(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent =...
Putting each of your top-level windows into it's own separate class gives you code re-use and better code organization. Any buttons and relevant methods that are present in the window should be defined inside this class. Here's an example (taken from [here](https://stackoverflow.com/questions/16115378/tkinter-example-c...
What is the best way to structure a Tkinter application?
[ "", "python", "tkinter", "" ]
In Python 3, when I opened a text file with mode string 'rb', and then did f.read(), I was taken aback to find the file contents enclosed in single quotes after the character 'b'. In Python 2 I just get the file contents. I'm sure this is well known, but I can't find anything about it in the doco. Could someone point...
You get "just the file contents" in Python 3 as well. Most likely you can just keep on doing whatever you were doing anyway. Read on for a longer explanation: The b'' signifies that the result value is a `bytes` string. A `bytes`-string is quite similar to a normal string, but not quite, and is used to handle binary, ...
First of all, the Python 2 `str` type has been renamed to `bytes` in Python 3, and byte literals use the `b''` prefix. The Python 2 `unicode` type is the new Python 3 `str` type. To get the Python 3 file behaviour in Python 2, you'd use `io.open()` or `codecs.open()`; Python 3 decodes text files to Unicode *by default...
Python 3 file input change in binary mode
[ "", "python", "file", "python-3.x", "" ]
I tried to use GradientBoostingClassifier in scikit-learn and it works fine with its default parameters. However, when I tried to replace the BaseEstimator with a different classifier, it did not work and gave me the following error, ``` return y - np.nan_to_num(np.exp(pred[:, k] - IndexError: too many indices ``` Do...
As suggested by scikit-learn developers, the problem can be solved by using an adaptor like this: ``` def __init__(self, est): self.est = est def predict(self, X): return self.est.predict_proba(X)[:, 1] def fit(self, X, y): self.est.fit(X, y) ```
An improved version of [iampat](https://stackoverflow.com/users/456984/iampat)'s answer and slight modification of [scikit-developers](http://comments.gmane.org/gmane.comp.python.scikit-learn/9011)'s answer should do the trick. ``` class init: def __init__(self, est): self.est = est def predict(self, X...
GradientBoostingClassifier with a BaseEstimator in scikit-learn?
[ "", "python", "numpy", "machine-learning", "scikit-learn", "ensemble-learning", "" ]
Class `Foo` has a `bar`, and it is not loaded until it is accessed. Further accesses to `bar` should incur no overhead. ``` class Foo(object): def get_bar(self): print "initializing" self.bar = "12345" self.get_bar = self._get_bar return self.bar def _get_bar(self): pr...
There are some problems with the current answers. The solution with a property requires that you specify an additional class attribute and has the overhead of checking this attribute on each look up. The solution with `__getattr__` has the issue that it hides this attribute until first access. This is bad for introspec...
Sure, just have your property set an instance attribute that is returned on subsequent access: ``` class Foo(object): _cached_bar = None @property def bar(self): if not self._cached_bar: self._cached_bar = self._get_expensive_bar_expression() return self._cached_bar ``` The `...
Lazy loading of class attributes
[ "", "python", "" ]
I want to use [os.mkfifo](http://docs.python.org/2/library/os.html#os.mkfifo) for simple communication between programs. I have a problem with reading from the fifo in a loop. Consider this toy example, where I have a reader and a writer working with the fifo. I want to be able to run the reader in a loop to read ever...
A FIFO works (on the reader side) exactly this way: it can be read from, until all writers are gone. Then it signals EOF to the reader. If you want the reader to continue reading, you'll have to open again and read from there. So your snippet is exactly the way to go. If you have mutliple writers, you'll have to ensu...
You do not need to reopen the file repeatedly. You can use select to block until data is available. ``` with open(FIFO_PATH) as fifo: while True: select.select([fifo],[],[fifo]) data = fifo.read() do_work(data) ``` In this example you won't read EOF.
fifo - reading in a loop
[ "", "python", "mkfifo", "" ]
I am stuck on a seemingly simple Python problem since 2 days. It involves updating a 'database' of mixed string/tuple sequences (with always the same structure) but with case-sensitive mistake correction. For instance the database is: ``` [['Abc', ('Def', 'Ghi'), 'Jkl'], ['Abc', ('Def', 'Mno'), 'Pqr'], ['123'...
I'd suggest using a dictionary to convert your words from some generic form (perhaps all lowercase) to the "correct" form that you want to have all items use in the database. Since the path to a word matters, I suggest using a tuple including all the previous normalized paths as the key into the dictionary: ``` _corre...
Try NLTK using Brown and PorterStemmer. Brown have a very wide word list and a pre-learned stemmer. Example: ``` from nltk import PorterStemmer from nltk.corpus import brown import sys from collections import defaultdict import operator def sortby(nlist ,n, reverse=0): nlist.sort(key=operator.itemgetter(n), rev...
Auto-correct case spelling of a word database
[ "", "python", "" ]
I am trying to read text from a file and display it, yet it doesn't work. I get either a blank result, or I get ``` <_io.TextIOWrapper name='/Users/student/Desktop/Harry.txt' mode='r' encoding='US-ASCII'> ``` Code ``` text1 = open('/Users/student/Desktop/Harry.txt', 'r') text1.read() ``` And I have tried ``` text1...
Assign the return value of `text.read()` to a variable and print it ``` text1 = open('/Users/student/Desktop/Harry.txt', 'r') x = text1.read() print(x) ```
did you try this? ``` text1 = open('/Users/student/Desktop/Harry.txt', 'r') data = text1.read() print data text1.close() ```
Reading contents of file
[ "", "python", "" ]
I've just started learning some pygame (quite new to programming overall), and I have some very basic questions about how it works. I haven't found a place yet that explains when I need to blit or not to include a certain surface on the screen. For example, when drawing a circle: ``` circle = pygame.draw.circle(scree...
# The short answer > I haven't found a place yet that explains when I need to blit or not to include a certain surface on the screen. Each operation will behave differently, and you'll need to read the documentation for the function you're working with. # The long answer ## What Is Blitting? First, you need to rea...
Blit means 'BL'ock 'I'mage 'T'ranfser When you are displaying things on the screen you will, in some way, use `screen` because that's where you are putting it. When you do: ``` pygame.draw.circle(screen, (0, 0, 0), (100, 100), 15, 1) ``` you are still using screen but you are just not blitting because pygame is dra...
A bit confused with blitting (Pygame)
[ "", "python", "pygame", "blit", "" ]
How would I make a manager that will return all the entries in a model with todays date, the model field is a datetime field, not a datefield? ``` timestamp = models.DateTimeField(auto_now=True) class ValidEntryManager(models.Manager): def get_query_set(self): return super(ValidEntryManager, self).get_que...
You could try setting both dates to midnight: ``` class ValidEntryManager(models.Manager): def get_query_set(self): today = datetime.today() start_date = datetime(today.year, today.month, today.day) end_date = datetime(today.year, today.month, today.day+1) return super(ValidEntryMan...
Try this ``` from datetime import datetime, timedelta class ValidEntryManager(models.Manager): def get_query_set(self): return super(ValidEntryManager, self).get_query_set().filter(timestamp__range=(datetime.now(), datetime.now()- timedelta(days=1)) ```
Django manager return all entries for today - DateTimeField
[ "", "python", "django", "datetime", "django-managers", "" ]
I have a Users table. Every user can create one or more lists of movies. So I searched a little bit and found an answer in Stack Overflow that the best way to create lists is to create A List Table With `List_Id` And `User_ID` Columns and a `ListEntry` Table With `List_ID` and `Movie_ID` Column.Then I retrieve list en...
Assuming that you are NOT going to store IDs of movies as anything but int(11) or probably less than in(11) - I am pretty sure there is no need for THAT many movies :} - the table will be "big" in amount of rows, but not big in amount of data. MySQL is very efficient at locating and sorting values that have a small ke...
100,000 entries? MySQL isn't even going to feel it - and neither will you. Come back when you have in excess of 10 million.
MySQL Array/List Of Items And Performance
[ "", "mysql", "sql", "database", "" ]
To my knowledge, Celery acts as both the producer and consumer of messages. This is not what I want to achieve. I want Celery to act as the consumer only, to fire certain tasks based on messages that I send to my AMQP broker of choice. Is this possible? Or do I need to make soup by adding carrot to my stack?
Celery brokers acts as a message stores and publish them to one or more workers that subscribe for those, so: celery pulishes messages to a broker (rabbitmq, redist, celery itself through django db, etc..) those messages are retrieved by a worker following the protocol of the broker, that memorizes them (usually they ...
Celery uses the [message broker architectural pattern](http://en.wikipedia.org/wiki/Message_broker). A number of implementations / broker transports can be used with Celery including [RabbitMQ](http://docs.celeryproject.org/en/latest/getting-started/brokers/rabbitmq.html) and a [Django database](http://docs.celeryproje...
Celery and custom consumers
[ "", "python", "rabbitmq", "celery", "amqp", "" ]
QuickExplain :My elementList is [1, 2, 3, 4] and if 3, 4 is not present in table I want 3, 4. PS. If you use "NOT IN" this returns you values from table But I want only elements from elementList I queried.
A bit verbose but solves the purpose cleanly select \* from (select 'item1' as items UNION select 'item2' as items UNION . . . select 'itemN' as items ) as notFoundItemList where items NOT IN ( Select ITEM from table WHERE AND itemName in )
You can use a temporary table: ``` create table #elements (name varchar(50)) insert into #elements (name) values ('1') insert into #elements (name) values ('2') insert into #elements (name) values ('3') insert into #elements (name) values ('4') select name from #elements where name not in (select col1 from tab); dr...
select items where column NOT IN itemList
[ "", "sql", "database", "algorithm", "sybase", "" ]
I need to sum the elements of a list, containing all zeros or ones, so that the result is 1 if there is a 1 in the list, but 0 otherwise. ``` def binary_search(l, low=0,high=-1): if not l: return -1 if(high == -1): high = len(l)-1 if low == high: if l[low] == 1: return low else: return -1 ...
> I need to sum the elements of a list, containing all zeros or ones, so that the result is 1 if there is a 1 in the list, but 0 otherwise. No need to sum the whole list; you can stop at the first 1. Simply use `any()`. It will return `True` if there is at least one truthy value in the container and `False` otherwise,...
You don't actually want a sum; you want to know whether `upper` or `lower` contains a `1` value. Just take advantage of Python's basic container-type syntax: ``` if 1 in upper: # etc if 1 in lower: # etc ``` --- The reason you're getting the error, by the way, is because you're wrapping `upper` and `lower` w...
(Binary) Summing the elements of a list
[ "", "python", "" ]
I am trying to disable a lot of products that do not have images in my Magento installation. The following SQL query is supposed to get all products with no images but I need a way to set all products with no images to status disabled? ``` SELECT * FROM catalog_product_entity_media_gallery RIGHT OUTER JOIN ca...
Here is what you are looking for Kode: ``` -- here you set every one as DISABLED (id 2) UPDATE catalog_product_entity_int SET value = 2 -- here you are change just the attribute STATUS WHERE attribute_id = 4 -- here you are looking for the products that match your criteria AND entity_id IN ( -- your o...
I use this for magento 2.2.3 ``` update catalog_product_entity_int m left join eav_attribute a on a.entity_type_id = 4 and a.attribute_id = m.attribute_id set value = 2 where a.attribute_code = 'status' and m.entity_id in ( select m.entity_id from catalog_product_entity m left join catalog_pr...
Magento disable products with no images
[ "", "mysql", "sql", "magento", "" ]
It would be convenient when distributing applications to combine *all* of the eggs into a single zip file so that all you need to distribute is a single zip file and an executable (some custom binary that simply starts, loads the zip file's main function and kicks python off or similar). I've seen some talk of doing t...
You can automate most of the work with regular python tools. Let's start with clean virtualenv. ``` [zart@feena ~]$ mkdir ziplib-demo [zart@feena ~]$ cd ziplib-demo [zart@feena ziplib-demo]$ virtualenv . New python executable in ./bin/python Installing setuptools.............done. Installing pip...............done. ``...
You could use the [zipapp](https://docs.python.org/3.9/library/zipapp.html) module from the standard library to create executable Python zip archives. It is available from Python 3.5 onwards. One way to create a bundle is to add a top-level file named `__main__.py`, which will be the script that Python runs when the z...
How can you bundle all your python code into a single zip file?
[ "", "python", "setup.py", "pypi", "" ]
There is some method, which output two variables, for example: ``` def some_method(): #some calculations return first_value, second_value ``` Now I want to put in one line results into variable and list (put `first_value` to some variable and `second_value` add to list as a new element). I know that I can do...
Can you return the second value in a list? Like this: ``` >>> L = [1, 2, 3] >>> def bar(): ... return 'shenanigan', [4] ... >>> myVar, L[len(L):] = bar() >>> L [1, 2, 3, 4] ``` really, though, you might as well assign the second return value to an intermediate variable and just use list.append(), using two line...
If you really want it, you can subclass list and make something like this: ``` >>> def f(): ... return 1, 2 >>> class MyList(list): ... def __setattr__(self, name, value): ... if name == '_assign_append': ... self.append(value) ... >>> l = MyList() >>> a, l._assign_append = f() >>> a 1 ...
Append part of result into list in python
[ "", "python", "" ]
I am trying to select sum of items based on their monthly entry date: The Inventory table is as below: ``` EntryDate Items 1/1/2013 2 1/20/2013 5 1/23/2013 3 1/30/2013 2 2/4/2013 4 2/17/2013 34 ``` The desired output with Total row added: ``` EntryDate ...
If you actually want results like your example, you can use the following: ``` SELECT EntryDate, Items FROM (SELECT YEAR(EntryDate)'Year_',MONTH(EntryDate)'Month_',CAST(EntryDate AS VARCHAR(12))'EntryDate',Items,1 'sort' FROM Inventory UNION ALL SELECT YEAR(EntryDate)'Year_',MONTH(EntryDate)'Month_',...
Try this, it will give you the month total in a new column, it will also work when your dates stretch over more than 1 year ``` SELECT EntryDate, Items, SUM(Items) OVER (partition by dateadd(month, datediff(month, 0, entrydate), 0)) Total FROM [Inventory] ``` Result: ``` EntryDate Items Total 2013-01-01 2 ...
Select sum of items based on their monthly entry date
[ "", "sql", "sql-server", "t-sql", "" ]
When I try a django view that loads an external URL using requests, I get a 'module' object has no attribute 'create\_connection'. However, when I use urllib2 or the same requests code from the interactive shell, it works. My environment: * Python 2.5.2 * Requests 0.10.0 (I am using a 3rd party api which requires thi...
It looks like you've run into a bug in requests 0.10.0 (or, really, in urllib3) with HTTPS in Python 2.5 with the `ssl` module installed. If you trace through the [0.10.0 source](https://github.com/kennethreitz/requests/tree/v0.10.0/requests), you can see that if `ssl` is installed and you make an HTTPS requests, you ...
As abarnert [pointed out](https://stackoverflow.com/a/17432500/263328), this is caused by a bug in requests 0.10.0 and it won't be fixed since python 2.5 support was dropped in version 0.10.1. So I edited this file requests/packages/urllib3/connectionpool.py (on line 67). The original line: ``` sock = socket.cre...
python requests does not work for https from apache with wsgi
[ "", "python", "django", "python-requests", "" ]
I'm used to mysql when you can do that with no problems. I would like to run the following statement in SQL Server however it doesn't see the column `C_COUNT`. ``` SELECT A.customers AS CUSTOMERS, (SELECT COUNT(ID) FROM Partners_customers B WHERE A.ID = B.PIID) AS C_COUNT FROM Partners A WHERE CUSTOMERS <> [C_...
SQL Server does not allow you to use aliases in the `WHERE` clause. You'll have to have something like this: ``` SELECT *, Customers - C_COUNT "Difference" FROM ( SELECT A.customers AS CUSTOMERS, (SELECT COUNT(ID) FROM Partners_customers B WHERE A.ID = B.PIID) AS C_COUNT FROM Partners A ) t WH...
``` WITH A AS ( SELECT A.customers AS CUSTOMERS, (SELECT COUNT(ID) FROM Partners_customers B WHERE A.ID = B.PIID) AS C_COUNT FROM Partners A WHERE CUSTOMERS <> [C_COUNT] ) SELECT *, (CUSTOMERS - C_COUNT) AS DIFFERENCE FROM A ```
How to compare two rows in SQL Server
[ "", "sql", "sql-server", "" ]
I have the following query. But currently i'm struggling to get it to return rows that don't have and data in them with the aggregation. I thought it would work with the aggregation and group by clause, so if anyone could expalin why that would be great! ``` SELECT a.id, a.name, a.slug, COUNT(i.area_id) as numItems F...
It's because you're referencing the item table in your `WHERE` criteria which is off setting the `OUTER JOIN`. Move that to the `JOIN` instead: ``` SELECT a.id, a.name, a.slug, COUNT(i.area_id) as numItems FROM `area` `a` LEFT JOIN `item` `i` ON a.id=i.area_id AND i.date_expired > CURDATE() AND i.live = 1 GROUP BY...
you should be filtering on the `ON` clause because you are doing `LEFT JOIN`. eg. ``` SELECT a.id, a.name, a.slug, COUNT(i.area_id) as numItems FROM area a LEFT JOIN item i ON a.id = i.area_id AND i.date_expired > CURDATE() AND i.live = 1 GROUP BY a.name ORDER BY a.name `...
MySQL not returning 0 aggregation rows with Left Join and Group By
[ "", "mysql", "sql", "" ]
I have the following docstring: ``` def progress_bar(progress, length=20): ''' Returns a textual progress bar. >>> progress_bar(0.6) '[##########--------]' :param progress: Number between 0 and 1 describes the progress. :type progress: float :param length: The length of the progress bar i...
`defaults to` is the keyword now. See <https://github.com/sglvladi/Sphinx-RTD-Tutorial/blob/a69fd09/docs/source/docstrings.rst#the-sphinx-docstring-format> ``` """[Summary] :param [ParamName]: [ParamDescription], defaults to [DefaultParamVal] :type [ParamName]: [ParamType](, optional) ... :raises [ErrorType]: [ErrorD...
I have adopted Voy's answer and made a [package](https://github.com/zwang123/sphinx-autodoc-defaultargs) which automatically does this for you. You are very welcome to try it and to report issues. The following code ``` def func(x=None, y=None): """ Example docstring. :param x: The default value ``None``...
Make sphinx's autodoc show default values in parameters' description
[ "", "python", "python-sphinx", "autodoc", "" ]
Just like the famous BeautifulSoup package, I am wondering whether there is a standard way to convert the package into a standalone py file or files?
This should do the trick. It will download the package as an archive into a directory: ``` mkdir BeautifulSoup pip install BeautifulSoup -d BeautifulSoup/ ``` Or simply: ``` sudo pip install -t . BeautifulSoup ``` Will download and install Beautiful soup in the current directory.
I do not know if there is a standard way / some module to do it , but you can pretty much do it by first installing the package using pip and then you can find the .py file/files at lib/python2.7/site-packages location.
How to convert a pip package into a standalone py file(or files)?
[ "", "python", "pip", "" ]
I have simple table (test) where I need to perform some averages (I want to get a row average and a 'total' column average). ``` id var1 var2 var3 1 7 NULL 3 2 10 NULL 6 ``` I notice that MySQL AVG() function excludes NULL values from the count (they're not counted as 0), which is what I want. In ...
How about this? nice and simple... ``` SELECT AVG(var1) AS var1, AVG(var2) AS var2, AVG(var3) AS var3, ( SUM(ifnull(var1,0))+ SUM(ifnull(var2,0))+ SUM(ifnull(var3,0)) ) / (COUNT(var1)+COUNT(var2)+COUNT(var3)) AS metric_total FROM test ```
``` SELECT avg1, avg2, avg3, ( (COALESCE(avg1, 0) + COALESCE(avg2, 0) + COALESCE(avg3, 0)) -- only add non-null values / -- division ( IF(avg1 IS NULL, 0, 1) + IF(avg2 IS NULL, 0, 1) + IF(avg3 IS NULL, 0, 1) ) -- number of non-null averages ) AS metric_total FROM ( SELECT (SEL...
Row average in MySQL - how to exclude NULL rows from the count
[ "", "mysql", "sql", "" ]
How do I make a simple Menu/Directory using Python? I would like to have letters that the user would press to do tasks, and when they enter the letter after the prompt, the task is done... for example: A. Create Username B. Edit Username C. Exit Choice: And then all the user has to do is enter one of the lette...
A (very) basic approach would be something like this: ``` print "A. Create Username" print "B. Edit Username" input = raw_input("Enter your choice") if input == "A": print "A was given" if input == "B": print "B was given" ```
A very basic version: ``` def foo(): print "Creating username..." def bar(): print "Editing username..." while True: print "A. Create Username" print "B. Edit Username" print "C. Exit" choice = raw_input() if choice.lower() == 'a': foo() elif choice.lower() == 'b': bar()...
How to create a menu or directory?
[ "", "python", "menu", "directory", "" ]
so i have two tables that i need to be able to get counts for. One of them holds the content and the other on the relationship between it and the categories table. Here are the DDl : ``` CREATE TABLE content_en ( id int(11) NOT NULL AUTO_INCREMENT, title varchar(100) DEFAULT NULL, uid int(11) DEFAULT NULL,...
There are too many records to count. If you want a faster solution, you'll have to store aggregate data. MySQL does not support materialized views (or indexed views in SQL Server's terms) so you would need to create and maintain them yourself. Create a table: ``` CREATE TABLE page_active_category ( ...
I downloaded your data and tried a few experiments. I'm running MySQL 5.6.12 on a CentOS virtual machine on a Macbook Pro. The times I observed can be used for comparison, but your system may have different performance. ## Base case First I tried without the USE INDEX clauses, because I avoid optimizer overrides wher...
mysql slow count in join query
[ "", "mysql", "sql", "" ]
I am a python novice. I have a bunch of sets which are included in the list 'allsets'. In each set, I have multiple string elements. I need to print all of my sets in a text file, however, I would like to find a way to separate each element with a '|' and print the name of the set at the beginning. E.g.: ``` s1= [stri...
``` for s in allsets: for item in s: file_out.write("%s|" % item) file_out.write("\n") ``` \n changes the line.
Those are not "sets", in Python, they're just lists. The names of the variables (`s1` and so on) are not easily available programmatically, since Python variables are ... weird. Note that you can have the same object given multiple names, so it's not obvious that there is a single name. You can go around this by usin...
Python format output
[ "", "python", "text", "formatting", "" ]
I have the following code snippet from page source: ``` var myPDF = new PDFObject({ url: "http://www.site.com/doc55.pdf", id: "pdfObjectContainer", width: "100%", height: "700px", pdfOpenParams: { navpanes: 0, statusbar: 1, toolbar: 1, view: "FitH" } }).embed("pdf_placeholder"); ``` the ```...
In order to be able to find "something that happens in the line after something else", you need to match things "including the newline". For this you use the (dotall) modifier - a flag added during the compilation. Thus the following code works: ``` import re r = re.compile(r'(?<=PDFObject).*?url:.*?(http.*?)"', re.D...
Here is an alternative for solving your problem without using regex: ``` url,in_object = None, False with open('input') as f: for line in f: in_object = in_object or 'PDFObject(' in line if in_object and 'url:' in line: url = line.split('"')[1] break print url ```
Retrieving a string using REGEX in Python 2.7.2
[ "", "python", "regex", "" ]
I have a quick question I am trying to solve. I have a script that processes about 2000 files, generates images and saves images to either PDF or image format. But I am not able to prevent images from appearing on the screen. I read and researched but couldn't solve my problem. I assume there is something wrong with my...
OK, looks like I found some kind of a solution. I forced the matplotlib to switch the backend: ``` matplotlib.pyplot.switch_backend('Agg') ``` After that I am not getting thousands of GUI windows on my screen. Have not tested with PDFs yet though. Source: [from here](http://matplotlib.org/api/pyplot_api.html?highlig...
You **may** have a place in your script where you say `plt.show()`. Replace that with `plt.savefig('fig-name.pdf')`, where `fig-name.pdf` is the name you want to save as. If you want to save as a .png, you just change the extension to `.png`, etc. Here is some [documentation](http://matplotlib.org/faq/howto_faq.html#s...
How to prevent images from appearing on the screen in Matplolib? Python
[ "", "python", "linux", "image", "matplotlib", "plot", "" ]
Here is my query: ``` SELECT TOP 8 id, rssi1, date FROM history WHERE (siteName = 'CCL03412') ORDER BY id DESC ``` This the result: ![enter image description here](https://i.stack.imgur.com/u8wj0.png) How can I reverse this table based on date (Column2) by using SQL?
You can use the first query to get the matching ids, and use them as part of an `IN` clause: ``` SELECT id, rssi1, date FROM history WHERE id IN ( SELECT TOP 8 id FROM history WHERE (siteName = 'CCL03412') ORDER BY id DESC ) ORDER BY date ASC ```
You could simply use a sub-query. If you apply a `TOP` clause the nested `ORDER BY` is allowed: ``` SELECT X.* FROM( SELECT TOP 8 id, Column1, Column2 FROM dbo.History WHERE (siteName = 'CCL03412') ORDER BY id DESC) X ORDER BY Column2 ``` [Demo](http://msdn.microsoft.com/en-us/library/aa213252%28v=sql.80%29....
How to reverse the table that comes from SQL query which already includes ORDER BY
[ "", "sql", "sql-server", "sql-order-by", "" ]
I have simple table (test) where I need to perform some additions (I want to get a row total and a column total). ``` id var1 var2 1 NULL NULL 2 10 NULL ``` For column totals, summing works as expected (NULL is ignored in the addition): ``` SELECT SUM(var1) FROM test 10 ``` For row totals, addition do...
use the `IFNULL` function ``` SELECT IFNULL(var1, 0) + IFNULL(var2, 0) FROM test ```
You want to use `coalesce()`: ``` select coalesce(var1, 0) + coalesce(var2, 0) ``` `coalesce()` is ANSI standard and available in most databases (including MySQL).
Adding columns in MySQL - how to treat NULL as 0
[ "", "mysql", "sql", "" ]
I've read several posts about csrf protection in Django, including [Django's documentation](https://docs.djangoproject.com/en/dev/ref/contrib/csrf/) , but I'm still quite confused in how to use it correctly. The clearest part is the HTML one, but the Python's one is kinda confusing. ## HTML `{% csrf_token %}` inside...
The point of using the `render` shortcut is that it then runs all the context processors automatically. Context processors are useful little functions that add various things to the template context every time a template is rendered. And there is a built-in context processor that already adds the CSRF token for you. So...
As far as I remember Django has its own middleware for the csrf protection that handles everthing transparently for you. Just include the `{% csrf_token %}` inside you forms. CSRF token is mandatory for POST requests (except you use the @csrf\_exempt decorator). So a form would be: ``` <form action="." method="post"> ...
Python - render with csrf protection
[ "", "python", "django", "csrf", "" ]
I'm running a script that uses a module that prints a lot of things on screen and I'm running out of RAM. I can't make the module not to write anything for now. The Python Shell stores absolutely everything and I want to clear it. On similar questions the only answer I could find was to write `os.system('cls')` (...
By python shell, do you mean IDLE? Some quick googling suggests that IDLE doesn't have a clear screen even though lots of people seem to want one. If it's in a shell, then I'm surprised 'cls' isn't working. If you like working in Idle, you might look at this for getting the functionality you want: <http://idlex.source...
How are you running the script? Are you calling it from a shell? If so, you can redirect all output to a file like this: ``` python my_script.py > /out/to/some/path.log ```
How to clear Python Shell in IDLE
[ "", "python-idle", "python", "" ]
I want to find the matching item from the below given list.My List may be super large. The very first item in the tuple "N1\_10" is duplicated and matched with another item in another array tuple in 1st array in the ListA `('N1_10', 'N2_28')` tuple in 2nd array in the ListA `('N1_10', 'N3_98')` ``` ListA = [[('N1...
**Update**: After rereading your question, it appears that you're trying to create equivalence classes, rather than collecting values for keys. If ``` [[(1, 2), (3, 4), (2, 3)]] ``` should become ``` [(1, 2, 3, 4)] ``` , then you're going to need to interpret your input as a graph and apply a connected components a...
``` tupleList = [(1, 2), (3, 4), (1, 4), (3, 2), (1, 2), (7, 9), (9, 8), (5, 6)] newSetSet = set ([frozenset (aTuple) for aTuple in tupleList]) setSet = set () while newSetSet != setSet: print '*' setSet = newSetSet newSetSet = set () for set0 in setSet: merged = False for set1 in setS...
Find duplicate items within a list of list of tuples Python
[ "", "python", "list", "duplicates", "tuples", "match", "" ]
Having the follow tables examples: ``` JOBS jobid jobname COMMENTS jobid userid comment date USERS userid name ``` I need to retrieve the last comment from each jobid I've been trying distinct and such but no luck so far. the jobid can be multiple times in the comments table(mu...
As long as date from a comment and a jobID is unique this will work fine. If not then this answer will get you the most recent comment, including ties. ``` select comment, jobid from (select max(date) as MaxDate, jobid from comments group by jobid) x inner join comments c on c.jobid = x.jobid and c.date = x.MaxDate ``...
You can use ROW\_NUMBER() to select the last comment per jobid: ``` SELECT jobid, userid, comment, date FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY jobid ORDER BY date DESC)'RowRank' FROM COMMENTS )sub WHERE RowRank = 1 ``` The ROW\_NUMBER() function assigns a number to each row based on some criteria,...
Retrieving Last comment from joining 3 tables
[ "", "sql", "sql-server-2008", "" ]
I want to append everything in Field1 to Field2 and then make Field1 values NULL for all records in the table. I do not want to merge these fields into a single field, I still want both fields to remain. Take the following example: ``` Field 1 Field 2 Test Value NULL NULL Another Value My Value ...
How about: ``` UPDATE table SET Field2 = isnull(Field2,'') + isnull(Field1,''), Field1 = NULL ``` What I would suggest if you are not sure about it is to wrap the update in a BEGIN TRAN, ROLLBACK like so: ``` BEGIN TRAN SELECT * FROM thistable UPDATE thistable SET Field2 = isnull(Field2,'') + isnull(Field1,'') , F...
How about: ``` UPDATE MyTable SET Field2 = ISNULL(Field2, '') + ISNULL(Field1, '') ``` To join the values into Field2. And ``` UPDATE MyTable SET Field1 = NULL ``` To clear out Field1 once you are sure the first script worked.
Append column's data to another column in SQL Server
[ "", "sql", "sql-server", "" ]
I have a set of 50 urls...and from each url, i am retrieving some data using urllib2. The procedure I am following (including setting cookies for each url) goes as follows: ``` urls = ['https://someurl', 'https://someurl', ...] vals = [] for url in urls: req2 = urllib2.Request(url) req2.add_header('cookie', coo...
The speed of `urllib2` won't be the limiting factor here, most of the time it will be waiting for TCP connections or for the remote server to respond. Use of Python's [multiprocessing](http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing) module is fairly straightforward, but you could also use...
So if 15-20 secs are costly there are couple of things you can try : 1. using threading with urllib2 itself . example is [here](https://stackoverflow.com/questions/3472515/python-urllib2-urlopen-is-slow-need-a-better-way-to-read-several-urls) 2. you can try pycurl .( not sure about performance improvement) 3. Once I u...
Replacement for urllib2
[ "", "python", "urllib2", "" ]
I have a text that contains string of a following structure: ``` text I do not care about, persons name followed by two IDs. ``` I know that: * a person's name is always preceded by `XYZ` code and that is always followed by two, space separated numbers. * `Name` is not always just a last name and first name. It ca...
`(?<=XYZ\s)(\w[^\d]+\d+\s\d+)` where your names and numbers `(\w[^\d]+\d+\s\d+)` are preceded by `XYZ`
You can use this regex ``` (?<=XYZ\s+)[a-zA-Z\s,]+\d+\s+\d+ ---------- ---------- --------- | | |->matches two numbers separated by space | |->matches names separated by , |->lookbehind assertion which checks for a XYZ followed by space before matching the string ```
Extract string that is delimited with constant and ends with two numbers (numbers have to be included)
[ "", "python", "regex", "" ]
Be forewarned: I'm new to MySQL so expect stupid follow-up questions. I am writing an application that keeps track of exam scores for students. Each student will have multiple exams taken at different times. I want to be able to calculate the change in the exam scores between two consecutive exams for the same student...
If the score ids are sequential for each student, then a simple join will do: ``` select s.score_id, s.score - sprev.score from scores s left outer join scores sprev on s.student_id = sprev.student_id and s.score_id = sprev.score_id + 1; ``` I would be surprised, though, if the input data were actua...
This is very inefficient, not sure if it can be optimised, but i dont see how you can do what you want without doing an extra query per row thats found, but i haven't spent a lot of time thinking of optimisation routes, so this is just A solution, not THE BEST solution ``` SELECT score_id, (score-(SELECT score FROM ta...
Find growth over previous
[ "", "mysql", "sql", "" ]
How can I securely remove a file using python? The function `os.remove(path)` only removes the directory entry, but I want to securely remove the file, similar to the apple feature called "Secure Empty Trash" that randomly overwrites the file. What function securely removes a file using this method?
You can use [srm](http://en.wikipedia.org/wiki/Srm_%28Unix%29) to securely remove files. You can use Python's [os.system()](http://docs.python.org/2/library/os.html#os.system) function to call srm.
You can very easily write a function in Python to overwrite a file with random data, even repeatedly, then delete it. Something like this: ``` import os def secure_delete(path, passes=1): with open(path, "ba+") as delfile: length = delfile.tell() with open(path, "br+") as delfile: for i in ran...
Python securely remove file
[ "", "python", "file", "erase", "" ]
This is odd. I can successfully run the example `grid_search_digits.py`. However, I am unable to do a grid search on my own data. I have the following setup: ``` import sklearn from sklearn.svm import SVC from sklearn.grid_search import GridSearchCV from sklearn.cross_validation import LeaveOneOut from sklearn.metric...
As noted already, for **`SVM`**-based Classifiers ( as `y == np.int*` ) **preprocessing is a must**, otherwise the ML-Estimator's prediction capability is lost right by skewed features' influence onto a decission function. As objected the processing times: * try to get better view what is your AI/ML-Model Overfit/Gen...
Support Vector Machines are [sensitive to scaling](http://scikit-learn.org/stable/modules/svm.html#tips-on-practical-use). It is most likely that your SVC is taking a longer time to build an individual model. GridSearch is basically a brute force method which runs the base models with different parameters. So, if your ...
GridSearchCV extremely slow on small dataset in scikit-learn
[ "", "python", "numpy", "scikit-learn", "" ]
If I instantiate/update a few lists very, very few times, in most cases only once, but I check for the existence of an object in that list a bunch of times, is it worth it to convert the lists into dictionaries and then check by key existence? Or in other words is it worth it for me to convert lists into dictionaries ...
Dictionary lookups are faster the list searches. Also a `set` would be an option. That said: If "a bunch of times" means "it would be a 50% performance increase" then go for it. If it doesn't but makes the code better to read then go for it. If you would have fun doing it and it does no harm then go for it. Otherwise ...
You should be using a `set`, since from your description I am guessing you wouldn't have a value to associate. See [Python: List vs Dict for look up table](https://stackoverflow.com/questions/513882/python-list-vs-dict-for-look-up-table) for more info.
Converting lists to dictionaries to check existence?
[ "", "python", "" ]
The following example: ``` import numpy as np class SimpleArray(np.ndarray): __array_priority__ = 10000 def __new__(cls, input_array, info=None): return np.asarray(input_array).view(cls) def __eq__(self, other): return False a = SimpleArray(10) print (np.int64(10) == a) print (a == np....
This is somewhere between a bug and a wart. When you call `a op b` and `b` is a subclass of `a` python checks to see if `b` has a reflected version of `op` and calls that (`__eq__` is the reflected version of itself), So for example this `np.array(10) == a` gives the expected result because SimpleArray is a subclass of...
By default, an equality expression `a == b` calls `A.__eq__()` where `A` is the class of variable `a`. This means the type of the left operand dictates which equality function is called. The only way to ensure the equality function you wrote is called, is to ensure your variable is always the left operand. However, in ...
Equality not working as expected with ndarray sub-class
[ "", "python", "numpy", "" ]
How do I drop `nan`, `inf`, and `-inf` values from a `DataFrame` without resetting `mode.use_inf_as_null`? Can I tell `dropna` to include `inf` in its definition of missing values so that the following works? ``` df.dropna(subset=["col1", "col2"], how="all") ```
First [`replace()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html) infs with NaN: ``` df.replace([np.inf, -np.inf], np.nan, inplace=True) ``` and then drop NaNs via [`dropna()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html): ``` df.dropna(su...
With option context, this is possible without permanently setting `use_inf_as_na`. For example: ``` with pd.option_context('mode.use_inf_as_na', True): df = df.dropna(subset=['col1', 'col2'], how='all') ``` Of course it can be set to treat `inf` as `NaN` permanently with ``` pd.set_option('use_inf_as_na', True) ...
Dropping infinite values from dataframes in pandas?
[ "", "python", "pandas", "numpy", "" ]
using python I am wanting to subtract 256 from a value in the list if a value is greater than 256, but i want the output to be in a tuple format, this is where i need help. ``` x = [85, 229, 162, 45, 280, 186, 275, 265, 252, 188, 135, 150, 351, 326, 217, 43, 301, 281, 333, 39, 246, 150, 139, 186, 195, 132, 196, 171, 3...
Instead of printing the values, append them to a list: ``` z = [] for y in x: if y>256: z.append(y-256) else: z.append(y) ``` You can shorten the `if/else` statement like this: ``` z = [] for y in x: z.append(y-256 if y>256 else y) ``` And then, you can put all these lines into a [list c...
To get list use [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) / [generator expression](http://docs.python.org/2/reference/expressions.html#generator-expressions). ``` >>> x = [85, 229, 162, 45, 280, 186, 275, 265, 252, 188, 135, 150, 351, 326, 217, 43, 301, 281, 333, 3...
Tuple Subtract statement in Python
[ "", "python", "list", "if-statement", "tuples", "" ]
I'm making a Temperature Calculator **Celsius and Farenheit** I'm a completely begginer in Python I have Python 3.3 So, I made this function to calculate a Farenheit value to a Celsius value ``` def C(): print('Enter a temperature:') Fvalue = input() print(int(Fvalue) - int(32) * int((5/9))) ``` I run ...
Your real problem lies here: ``` int(5/9) ``` `5/9` gives you `0.555` which when cast to `int()` gives you `0` Try this: ``` print((int(Fvalue) - 32) * 5/9) ```
The problem is, you are casting the value of `5 / 9` to an `int`, which will give you 0 as a value. Just remove the cast, and it will be fine. And also you need to add parenthesis around the subtraction. Change your print statement to: ``` print((int(Fvalue) - 32) * 5/9) ```
My function doesn't calculate a simple math operation
[ "", "python", "python-3.x", "" ]
I'm having a go at writing an image generator for a graphical format that I created that uses 0 as a delimiter: Here is an example. An extract from a sample file: ``` 202000200030FFFF000F0122202071960104203023302024..... ``` Breaking this down ``` 2 0 Version is 2 200 0 Image Width is 200 pixels 200 0 Image H...
Personally I would change your delimiter since you can not know if a 0 is a delimiter or a part of a value, also you should use a fixed number of digits for colour values, possibly specified as part of the header, after that it is just a matter of reading the header then reading the data into an array and calling PIL.I...
Your method is called run-length encoding, or RLE. It was used as a compression scheme in the BMP format. You can find a Python implementation of some simple BMP file storage (including RLE) at <http://www.ptmcg.com/geo/python/bmp.py.txt>. But the choice of '0' for delimiter is baffling. In your posted example, how do...
How to generate an image in python pixel by pixel?
[ "", "python", "python-imaging-library", "" ]
I am trying to read every second line in a CSV file and print it in a new file. Unfortunately i am getting a blank line which i am unable to remove. ``` lines = open( 'old.csv', "r" ).readlines()[::2] file = open('new.csv', "w") n = 0 for line in lines: n += 1 if ((n % 2) == 1): print >> file, line...
In answer to your question, your blank line is coming from: ``` print >> file, line ``` Using `print` like that automatically outputs a new line, either use `sys.stdout.write` or, use a trailing comma to suppress the newline character, eg: ``` print >> file, line, ``` Anyway, the better way to approach this overall...
Try taking a look at the python library for [csv](http://docs.python.org/2/library/csv.html) files. It is pretty comprehensive and should help you do what you are looking to do more cleanly.
Read every second line and print to new file
[ "", "python", "" ]
I have a database table that contains the following data: ``` ID | Date | Bla 1 | 2013-05-01 | 1 2 | 2013-05-02 | 2 3 | 2013-05-03 | 3 4 | 2013-05-05 | 4 ``` Note that there is a date missing: `2014-05-04`. How should I alter the following query: ``` SELECT * FROM table where DATE >= '2013-05-01' AND DAT...
You can join with a `generate_series` output: ``` select '2013-05-01'::date + g.o AS "date with offset" from generate_series(0, 30) AS g(o) ``` Output: ``` "2013-05-01" "2013-05-02" "2013-05-03" ... "2013-05-29" "2013-05-30" "2013-05-31" ``` Or... an easier method after defining a new stored procedure :) `...
``` select * from ( select generate_series( '2013-05-01'::date, '2013-05-05', '1 day' )::date ) s("date") left join t using ("date") ``` Replace both `"date"` with the actual column name.
PostgreSQL incremental dates?
[ "", "sql", "postgresql", "generate-series", "" ]
Consider the following string building statement: ``` s="svn cp %s/%s/ %s/%s/" % (root_dir, trunk, root_dir, tag) ``` Using four `%s` can be confusing, so I prefer using variable names: ``` s="svn cp {root_dir}/{trunk}/ {root_dir}/{tag}/".format(**SOME_DICTIONARY) ``` When `root_dir`, `tag` and `trunk` are defined ...
You can use [`locals()`](http://docs.python.org/2/library/functions.html#locals) function ``` s="svn cp {root_dir}/{trunk}/{root_dir}/{tag}/".format(**locals()) ``` **EDIT:** Since python 3.6 you can use [string interpolation](https://www.python.org/dev/peps/pep-0498/ "PEP link"): ``` s = f"svn cp {root_dir}/{trunk...
Have you tried `s="svn cp {root_dir}/{trunk}/ {root_dir}/{tag}/".format(**locals())` ?
Python: Formatting a string using variable names placeholders
[ "", "python", "string-formatting", "iterable-unpacking", "" ]
I'm trying to do some scraping using Python 2.7.2. I've just started with Python and unfortunately it is not as intuitive as I thought it will be. I try to collect all specific -s from all pages. I don't know how to accumulate results from all pages in string array. So far I'm getting results from 1 page only. I know t...
1. put all invariant code outside the `for` loop 2. outside the `for` loop init `s` to the empty list ``` s = [] ``` 3. inside the `for` loop ``` s.extend(re.findall(pattern, htmltext)) ``` If you prefer `s += re.findall(pattern, htmltext)` will do the same
Change ``` spans=re.findall(pattern,htmltext) ``` to ``` spans.extend(re.findall(pattern,htmltext)) ``` I'd also change your loop syntax a bit ``` import urllib import re spans = [] for j in range(1,11): url="http://www.site.com/search?page=" + str(j) + "&query=keyword" print url htmlfile=urllib.urlope...
Using string array in Python 2.7
[ "", "python", "python-2.7", "" ]
I have a list of PubMed entries along with the PubMed ID's. I would like to create a python script or use python which accepts a PubMed id number as an input and then fetches the abstract from the PubMed website. So far I have come across NCBI Eutilities and the importurl library in Python but I don't know how I shoul...
Wow, I was working on a similar project myself just a week or so ago! **Edit:** I recently updated the code to take advantage of [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/ "BeautifulSoup"). I have my own virtualenv for it, but you can install it with pip. Basically, my program takes a pubmed ID, a...
Using [Biopython](http://biopython.org)'s module called [Entrez](http://biopython.org/DIST/docs/api/Bio.Entrez-module.html), you can get the abstract along with all other metadata quite easily. This will print the abstract: ``` from Bio.Entrez import efetch def print_abstract(pmid): handle = efetch(db='pubmed', i...
Obtaining data from PubMed using python
[ "", "python", "text-mining", "" ]
I want to calculate current age of person from DOB(date of birth) field in Oracle table. Data type of DOB field is varchar and the is date stored in format 'DD-MON-YY'. when I calculate current age of a person from date like `10-JAN-49` the query will return age in negative. Also, I observed that if date has year 13 ...
To get round the 21st century problem, just modifying @the\_silk's answer slightly: ``` SELECT CASE WHEN SUBSTR(dob, -2, 2) > 13 THEN FLOOR ( MONTHS_BETWEEN ( SYSDATE , TO_DATE(SUBSTR(dob, 1, 7) || '19' || SUBSTR(dob, -2, 2), 'DD-MON-YYYY') ...
``` /* A value between 0-49 will return a 20xx year. A value between 50-99 will return a 19xx year. */ ``` Source: <http://www.techonthenet.com/oracle/functions/to_date.php> ``` SELECT FLOOR ( MONTHS_BETWEEN ( SYSDATE , TO_DATE(SUBSTR(d_date, 1, 7) || '19...
Oracle query to calculate current age
[ "", "sql", "oracle", "" ]
This may be super simple to a lot of you, but I can't seem to find much on it. I have an idea for it, but I feel like I'm doing way more than I should. I'm trying to read data from file in the format *(x1, x2) (y1, y2)*. My goal is to code a distance calculation using the values x1, x2, y1 and y2. Question: How do I e...
with regex ``` >>> import re >>> s = "(5, 42) (20, -32)" >>> x1, y1, x2, y2 = map(int, re.match(r"\((.*), (.*)\) \((.*), (.*)\)", s).groups()) >>> x1, y1 (5, 42) >>> x2, y2 (20, -32) ``` or without regex ``` >>> x1, y1, x2, y2 = (int(x.strip("(),")) for x in s.split()) ```
It's called [sequence unpacking](http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences) and can be done like this ``` >>> a =(1,2) >>> x1,x2=a >>> x1 1 >>> x2 2 >>> b = [[1,2],[2,3]] >>> (x1,x2),(y1,y2)=b >>> x1 1 >>> x2 2 >>> y1 2 >>> y2 3 >>> ```
Extracting integers from a string of ordered pairs in Python?
[ "", "python", "tuples", "sequence", "split", "iterable-unpacking", "" ]
I would like to replace sections of punctuation in a string such as `,'".<>?;:` with the corresponding HTML entities, `&#44;&#39;&#34;&#60;&#62;&#59;&#58;`. So far I've looked into using the `string` library with `.maketrans` and `string.punctuation`. It seems that you can convert `ascii` to `string` (but not the other...
You can do it yourself converting each character separately. For example: ``` def htmlentities(string): def char_htmlentities(c): return '&#%d;' % ord(c) if c in html_symbols else c html_symbols = set(',\'".<>?;:') return ''.join(map(char_htmlentities, string)) ``` UPD: I rewrote the solution to be linea...
The regex solution will probably be the simplest, since you can just use a single call to `re.sub()`. ``` import re def htmlentities(s): return re.sub('[,\'".<>?;:]', lambda m: return '#%d;' % m.group(0), s) ```
How to replace punctuation with HTML entities
[ "", "python", "string", "ascii", "" ]
I have a list [1,2,3,4,5,6,7,8] I want to convert this as [[1,2,3,4][5,6,7,8]] in python. Can somebody help me with this
To take an input: ``` def chunks(l, n): return [l[i:i+n] for i in range(0, len(l), n)] mylist = [1,2,3,4,5,6,7,8] while 1: try: size = int(raw_input('What size? ')) # Or input() if python 3.x break except ValueError: print "Numbers only please" print chunks(yourlist, size) ``` Pr...
You can use `itertools.islice`: ``` >>> from itertools import islice def solve(lis, n): it = iter(lis) return [list(islice(it,n)) for _ in xrange(len(lis)/n)] ... >>> solve(range(1,9),4) [[1, 2, 3, 4], [5, 6, 7, 8]] >>> solve(range(1,9),2) [[1, 2], [3, 4], [5, 6], [7, 8]] ```
Python transforming one dimensional array into two dimensional array
[ "", "python", "arrays", "multidimensional-array", "" ]
I am trying to populate a dictionary with the contents of my text file ("out3.txt"). My text file is of the form: ``` vs,14100 mln,11491 the,7973 cts,7757 ``` ...and so on... I want my dictionary `answer` to be of the form: ``` answer[vs]=14100 answer[mln]=11491 ``` ...and so on... My code is: ``` import os...
You have empty `line`s in your input file and I suspect one of the `line`s that you have not shared with us has too many commas in it (hence "too many values to unpack"). You can protect against this, like so: ``` import collections answer = collections.defaultdict(list) with open('out3.txt', 'r+') as istream: f...
Your solution doesn't give your desired output. You'll have (assuming it worked), `answer['vs'] = [14100]`, the below does what you intended: ``` import csv with open('out3.txt') as f: reader = csv.reader(f, delimiter=',') answer = {line[0].strip():line[1].strip() for line in reader if line} ```
How can I fix ValueError: Too many values to unpack" in Python?
[ "", "python", "python-3.x", "" ]