Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
If the day of the current date = 14 then the values of the parameter need to change. The month and possibly year will need to advance by 1 - May need to consider that on the 14th day of the month there may be a technical problem that prevents this process from running. Example Friday is the 14th when the sql script is ...
this is what worked ``` DECLARE @curentday VARCHAR(2) select @curentday =datepart(day,getdate()) declare @yearmonth varchar (6) select @yearmonth =convert(varchar,getdate(),112) If @curentday in (14,15,16) begin if (select prmString11 from FC_App where prmName1='prmCurFCPrd') <> @yearmonth beg...
``` SET @start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()-13), 0) SET @stop = DATEADD(MONTH, 1, @start) ``` The `-13` moves everything back 13 days. - The 1st to 13th of each month, are moved to a date in the previous month - The 14th onwards of each month, stay in the same month The `DATEADD(DATEDIFF())` rou...
Write SQL Code to automate the changing of the parameter year and period
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm trying to sum up Customer balances using the following query: ``` select sum(balance) from mytable where customer = 'john' ``` However, if the customer has no balance (i.e. no matching rows in the `mytable` table), my query returns null and not 0. What's the problem?
Try this: ``` select COALESCE(sum(balance),0) from mytable where customer = 'john' ``` This should do the work. The coalesce method should return the 0.
That's not a problem. If there are no rows, `sum()` will return `null`. It will also return `null` if all rows have a `null` balance. To return zero instead, try: ``` select isnull(sum(balance),0) from mytable where customer = 'john' ```
My Select SUM query returns null. It should return 0
[ "", "sql", "sql-server", "" ]
I have a python alarm clock script, which needs to wake me up at some time.When I go to bed and leave it running, the laptop I use which has Linux Mint suspends itself after some time of inactivity.How can I prevent my script from being stopped and keep it running? My laptop is in my room and I need to close its lid be...
will if terminated because the script itself you could use the `atexit` <http://docs.python.org/2/library/atexit.html> if it's suspend because of the operating system "after period of time that the user haven't been active " i had faced that problem before then i've used the module xlib to control my mouse to move it ...
Even in [sleep mode S1](http://en.wikipedia.org/wiki/Advanced_Configuration_and_Power_Interface#Power_states) (your "suspend" I think), the CPU(s) stop executing instructions. So your program is no longer running -- hence cannot wake-up your computer... You will certainly have to explore other ways of doing, such as c...
How to prevent a script being stopped by suspend?
[ "", "python", "linux", "process", "" ]
Is there a Python-way to split a string after the nth occurrence of a given delimiter? Given a string: ``` '20_231_myString_234' ``` It should be split into (with the delimiter being '\_', after its second occurrence): ``` ['20_231', 'myString_234'] ``` Or is the only way to accomplish this to count, split and joi...
``` >>> n = 2 >>> groups = text.split('_') >>> '_'.join(groups[:n]), '_'.join(groups[n:]) ('20_231', 'myString_234') ``` Seems like this is the most readable way, the alternative is regex)
Using `re` to get a regex of the form `^((?:[^_]*_){n-1}[^_]*)_(.*)` where `n` is a variable: ``` n=2 s='20_231_myString_234' m=re.match(r'^((?:[^_]*_){%d}[^_]*)_(.*)' % (n-1), s) if m: print m.groups() ``` or have a nice function: ``` import re def nthofchar(s, c, n): regex=r'^((?:[^%c]*%c){%d}[^%c]*)%c(.*)' % ...
Split string at nth occurrence of a given character
[ "", "python", "string", "split", "" ]
Presently, I am executing the following query and receiving the above error message: ``` SELECT dbo.qryOtherFieldDataVerifySource.ItemID, dbo.qryOtherFieldDataVerifySource.EDGRDataID, dbo.qryOtherFieldDataVerifySource.LineItemID, dbo.qryOtherFieldDataVerifySource.ZEGCodeID, dbo.qryOtherFiel...
I suggest looking for the bad value that is preventing you from converting to type float (aka real) with the trick of concatenating `e0` to the value before testing it: ``` SELECT * FROM dbo.YourTable WHERE DataTypeID = '{5951994B-BF47-4117-805D-B8F85FAB76A8}' -- the type for float AND IsNumeric( DataValue...
Created the following cursor to cause the query to execute one row at a time, which allowed me to identify the problem data row: ``` SET ARITHABORT OFF SET ARITHIGNORE ON SET ANSI_WARNINGS OFF DECLARE @msg VARCHAR(4096) BEGIN TRY DECLARE @itemid AS NVARCHAR(255); DECLARE C CURSOR FAST_FORWARD FOR SELECT It...
Msg 8114, Level 16, State 5, Line 1 Error converting data type nvarchar to real
[ "", "sql", "sql-server", "t-sql", "" ]
If this is a stupid question, please don't mind me. But I spent some time trying to find the answer but I couldn't get anything solid. Maybe this is a hardware question, but I figured I'd try here first. Does Serial Communication only work one to one? The reason this came up is because I had an arduino board listening...
Multiple clients (e.g. Arduinos) communicating with one server (e.g. a desktop computer) is commonly done with the serial variant: [RS-485](http://en.wikipedia.org/wiki/RS-485) This is a simple method widely used in industrial settings where you want to have many devices connected to one computer via one serial port....
Well, your question can be quite wide, so I'm going to layer my answer: * On the hardware side, the same pair of wires can work be shared with many devices. It is mostly a question of electronics (maintaining the signal in the good voltage range), and not having all devices writing to the serial port at the same time ...
Serial Communication one to one
[ "", "python", "serial-port", "arduino", "pyserial", "" ]
I'm trying to figure out how to get `python setup.py test` to run the equivalent of `python -m unittest discover`. I don't want to use a run\_tests.py script and I don't want to use any external test tools (like `nose` or `py.test`). It's OK if the solution only works on python 2.7. In `setup.py`, I think I need to ad...
If you use py27+ or py32+, the solution is pretty simple: ``` test_suite="tests", ```
From [Building and Distributing Packages with Setuptools](http://setuptools.readthedocs.io/en/latest/setuptools.html) (emphasis mine): > test\_suite > > A string naming a unittest.TestCase subclass (or a package or module > containing one or more of them, or a method of such a subclass), or naming > **a function that ...
How to run unittest discover from "python setup.py test"?
[ "", "python", "unit-testing", "nose", "pytest", "unittest2", "" ]
I am attempting to get two counts and then divide those two counts to get the ratio of the items I am counting. I saw this post [here](https://stackoverflow.com/questions/9222664/getting-a-count-of-two-different-sets-of-rows-in-a-table-and-then-dividing-them) and tried that. I am getting an error in my results, no erro...
Use `SELECT A.NUM, A.DENOM, cast(A.NUM as float)/cast(A.DENOM as float)` SQL Server consider that A.NUM / A.DENOM are int, because A.NUM and A.DENUM are int
The structure of your query bothers me. You can do it much more efficiently as: ``` SELECT A.NUMer, A.DENOM, cast(A.NUMer as float)/A.DENOM FROM (SELECT COUNT(case when drg_no IN (061,062,063,064,065,066) then DRG_NO end ) as Numer, count(case when drg_no IN 061,062,063,064,065,066,067...
Getting two counts and then dividing them
[ "", "sql", "sql-server-2008", "" ]
A bit lame question but I got confused... Difference between isolation levels as far as I understood is how they managed their locks (<http://en.wikipedia.org/wiki/Isolation_(database_systems)>). So as mentioned in the article there are Read, Write and Range locks but there is no definition what they are itself. What a...
This is what I was looking for ... <http://en.wikipedia.org/wiki/Two-phase_locking>
> What happens when I have concurrent inserts (different users of web > app) into one table when my transactions isolation level is > READ\_COMMITED. "Read committed" means that other sessions cannot see the newly inserted row until its transaction is committed. A SQL statement that runs without an explicit transactio...
Sql isolation levels, Read and Write locks
[ "", "sql", "transactions", "isolation-level", "" ]
I have the following columns: ``` ID, Col1, Col2, Col3, Col4 1 Bruce Wayne Gotham City 2 Daffy Duck Sat on the pond 3 Bruce Wayne Gotham City ``` What i need to do is select all records (ID,Col1-Col4) and display a count of how many records there are for each entry. ``` SELECT Count(*) As Counter FROM TA...
If you want to select all four columns (id, col1, col2, col3) with number of records, you have to pick one of the ids from the grouped records. For example, you can select `Min(Id)`/`Max(Id)` as below; ``` select count(*) counter, min(id) id, col1, col2, col3 from t group by col1,col2,col3 ``` [**SQL FIDDLE EXAMPLE*...
If you need to select all records, then use a `window` function to get the count: ``` SELECT count(*) over (partition by Col1, Col2, Col3, Col4) as Counter, ID,Col1,Col2,Col3,Col4 FROM TABLE; ``` If you want only two records, then you want a group by: ``` SELECT count(*) as Counter, Col1, Col2, Col3, Col4 FR...
TSQL Query not working correctly
[ "", "sql", "t-sql", "" ]
I love [@rbates](https://twitter.com/rbates) [CanCan](https://github.com/ryanb/cancan) ruby library for authorization. Was wondering if anything similar existed for python / flask ? I guess there are three main requirements: 1. simple declarative way of defining abilities ([here is how CanCan does it](https://github....
One year later, I ended up writing one: <https://github.com/jtushman/bouncer> <https://github.com/jtushman/flask-bouncer>
I recommend you keep an eye on [Cork](http://cork.firelet.net/). Currently it's an authentication and authorization framework just for [Bottle](http://bottlepy.org/), but on the roadmap is Flask support. Pretty awesome.
Does something like CanCan (authorization library) exist for flask and python
[ "", "python", "authentication", "authorization", "flask", "" ]
I have a list of items as: ``` i = SearchQuerySet().models(Item) ``` now, each item in `i` has a attribute, `price` I want to narrow the result in which price information is **not available** along with the ones falling in a given range something like ``` i.narrow('price:( None OR [300 TO 400 ] )') ``` how can th...
Try this: ``` -(-price:[300 TO 400] AND price:[* TO *]) ``` is logically the same and it works in Solr.
As per the [SolrQuerySyntax](http://wiki.apache.org/solr/SolrQuerySyntax#Differences_From_Lucene_Query_Parser) Pure Negative Queries: `-field:[* TO *]` finds all documents without a value for field You can try: `q=(*:* -price:[* TO *]) OR price:[300 TO 400]`
how to filter search by values that are not available
[ "", "python", "django", "solr", "django-haystack", "" ]
I'm using SQL to get data from `SQL Server` and processing it in `R`. I could use either to solve my problem. Here's my data: ``` structure(list(id = c(1, 2, 3, 1, 2), FY = c(2010, 2008, 2009, 2011, 2009), sales = c(100, 200, 300, 400, 500)), .Names = c("id", "FY", "sales"), row.names = c(NA, -5L), class = "data.fram...
``` tbl <- xtabs( ~ id+FY, data=test) #...... tbl ``` So that's the positive sales and you want the ones where successive years are 1: ``` 0+( tbl[ , -1]==1 & tbl[,-ncol(tbl)]==1) #------- FY id 2009 2010 2011 1 0 0 1 2 1 0 0 3 0 0 0 ``` The logical operations will produce a ma...
The following is one way to do a pivot (using aggregation): ``` select id, p2008 * p2009 as [2008], p2009 * p2010 as [2009], p2010 * p2011 as [2010], p2011 * p2012 as [2011] from (select t.*, (case when FY = 2008 then 1 end) as p2008, (case when FY = 2009 then 1 en...
Calculating retention (or finding whether one record from a set exists in another)
[ "", "sql", "r", "" ]
Currently I load values like so (using configparser) ``` my_value = config.get("my", "value") ``` But I find myself loading alot of values sometimes as my program grows over time. Is there any "prettier"/better way to load all values in a config file? Was perhaps thinking of json but not really sure? One problem wit...
If you want to use ConfigParser, you can store your config values in a dictionary indexed by `[section name][item name]`, and load them without having to explicitly specify each variable name: ``` import ConfigParser from pprint import pprint cfg = ConfigParser.ConfigParser() cfg.read('config.cfg') CONFIG_DATA = {} fo...
I would suggest to save the configuration as a Python dict in a YAML file. YAML is human-readable and supports comments with a # sign at the beginning of a line. However, it does not support block comments. ``` import yaml conf = {"name":"john", "password":"asdf"} with open("conf.yaml", "w") as f: yaml.dump(conf, ...
Smarter way to load config values in python?
[ "", "python", "" ]
I have a mapping table referring to ids from two different tables. I would like to select the mapping table with each id being replaced by another field in the respective table. To be a little more explicit: there are three tables with two columns each: * Table1 has a id (the primary key) and field1 * Table2 has a id...
If i understood correctly you are trying to get `field1` from Table1 and `field2` from table 2. If so you just need to join the three tables ``` SELECT a.field1, c.field2 FROM Table1 a INNER JOIN Table3 b ON a.id=b.Table1_id INNER JOIN Table2 c ON b.Table2_id = c.id ```
Do another join. ``` SELECT Table1.field1, Table2.field FROM Table1 INNER JOIN Table3 ON Table1.id = Table3.Table1_id INNER JOIN Table 2 ON Table2.id = table3.table2_id; ```
Selecting a mapping table with fields from two other tables
[ "", "sql", "inner-join", "" ]
How to sum the values in a python dict when I add the same key? ``` d = {'key1':10,'key2':14,'key3':47} d['key1'] = 20 ``` After the above the value of `d['key1']` should be 30. Is this possible?
You can use `collections.Counter`: ``` >>> from collections import Counter >>> d =Counter() >>> d.update({'key1':10,'key2':14,'key3':47}) >>> d['key1'] += 20 >>> d['key4'] += 50 # Also works for keys that are not present >>> d Counter({'key4': 50, 'key3': 47, 'key1': 30, 'key2': 14}) ``` Counter has some advantages:...
``` from collections import defaultdict d = defaultdict(int) d['key1'] += 20 ```
Sum values in a Python dict?
[ "", "python", "dictionary", "" ]
I am trying to test for prime numbers between 2 and 100, but I am getting an error with my code and I don't know why. (I am a newbie to python) ``` def function(): mylist = [1,2] count = 0 for i in range(2,100): for j in range(2,i): if i % j == 0: count += 1 if count > 0: count +=...
It looks like an indentation problem, try this: ``` if count > 0: count += 0 else: mylist.append(i) ``` In Python, it's very, very important that the code is correctly indented. You see, the `else` keyword *has* to appear at the same level that the `if` keyword. Use a good IDE or text editor to help you catch thi...
Python indicates code blocks with whitespace in the same way that some languages use braces. Your innermost code block would look like this in a language with braces, which might make it easier to see where syntax error is: ``` if (count > 0) { count += 0; else { mylist.append(0); } } ```
Can anyone please tell me why I'm getting an invalid syntax error with my else statement?
[ "", "python", "python-2.7", "" ]
I have a text line and i want to assign a variable to a certain string which appears directly after the symbol '@' in this line of text ``` 09807754 18 n 03 aristocrat 0 blue_blood 0 patrician 0 013 @ 09623038 n 0000 ``` The only thing is that this word may not appear in the same location so I can't just go like this...
Just split on `@` and then split whatever comes after it. ``` before_at, after_at = line.split('@') K = int(after_at.split()[0]) ``` For extra efficiency, if you only want the first thing after the `@`, do `after_at.split(None, 1)` -- that only splits once (on whitespace). This will raise an exception when there's m...
[Partition](http://docs.python.org/2/library/stdtypes.html#str.rpartition) is your friend: ``` >>> s='09807754 18 n 03 aristocrat 0 blue_blood 0 patrician 0 013 @ 09623038 n 0000' >>> s.rpartition('@') ('09807754 18 n 03 aristocrat 0 blue_blood 0 patrician 0 013 ', '@', ' 09623038 n 0000') >>> k=int(s.rpartition('@')[...
Getting the first string after a symbol in a line of text python
[ "", "python", "" ]
How do I select the row of a column such that the row size is <= 5 ? Is there a query for this which will work on most/all databases ? eg. id, first\_name Select only those people whose firstname is more than 10 characters. Their name is too long ?
If you are bound to use a specific RDBMS then the solution is easy. ``` Use the LENGTH function. ``` Depending upon your database the length function can be LEN, Length, CarLength. Just search google for it. According to your question > How do I select the row of a column such that the row size is **<= 5** ? > Is t...
Assuming you want the length in characters, the function names vary with RDBMS; MySQL: [CHAR\_LENGTH()](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_char-length). Oracle: [LENGTH()](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions076.htm). SQL Server: [LEN()](http://msdn.mic...
How to select data items of a certain length?
[ "", "sql", "" ]
Consider: ``` >>> lst = iter([1,2,3]) >>> next(lst) 1 >>> next(lst) 2 ``` So, advancing the iterator is, as expected, handled by mutating that same object. This being the case, I would expect: ``` a = iter(list(range(10))) for i in a: print(i) next(a) ``` to skip every second element: the call to `next` shou...
What you see is the *interpreter* echoing back the return value of `next()` in addition to `i` being printed each iteration: ``` >>> a = iter(list(range(10))) >>> for i in a: ... print(i) ... next(a) ... 0 1 2 3 4 5 6 7 8 9 ``` So `0` is the output of `print(i)`, `1` the return value from `next()`, echoed by t...
What is happening is that `next(a)` returns the next value of a, which is printed to the console because it is not affected. What you can do is affect a variable with this value: ``` >>> a = iter(list(range(10))) >>> for i in a: ... print(i) ... b=next(a) ... 0 2 4 6 8 ```
Python list iterator behavior and next(iterator)
[ "", "python", "list", "iterator", "iteration", "" ]
This is probably a very straight forward question but would love a simple explanation as to the why? The below code requires a list in order to obtain a random card. ``` import random card = random.choice (["hearts", "clubs", "frogs"]) ``` I am puzzled as to why it requires a list and why I cannot do this. ``` im...
because, the first snippet ``` ["hearts","clubs","frogs"] ``` sends only one argument to the function (a list) while the second one sends three strings to the function. The function `choice` is equipped to take only a single argument. So, you have to send it as a list or anything that can be indexed, so that it choo...
Because of Murphy's law: anything that *can* be done the wrong way *will* be done the wrong way by someone, some day. Your suggested API would require ``` random.choice(*lst) ``` when the values to choose from are in the list (or other sequence) `lst`. When someone writes ``` random.choice(lst) ``` instead, they wo...
Why is a list needed for random.choice
[ "", "python", "list", "" ]
I'm trying to capture the dollar amount in a line: example: `blah blah blah (blah $23.32 blah) blah blac (blah)` I want to capture "$23.32" This is what I'm using:`r'?([\$][.*]+)'` I'm telling it to find one occurance of (...) with ? Then I tell it to find something which starts of with a "$" and any character which...
The question mark at the start is the cause of the `nothing to repeat` error. ``` >>> import re >>> re.compile(r'?') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/re.py", line 190, in compile return _compile(pattern, fla...
You should improve your basics about regular expressions. The error is due to the ? at the befinning. It's a quantifier and there is nothing before this quantifier. Your use of \* and + makes also not much sense. Without knowing your exact requirements it's hard to propose a better solution, because there are too many ...
Capture $ in regex Python
[ "", "python", "regex", "" ]
I had the impression that the code only below **name**='**main**' is executed if you run a module directly. However, I saw a line mr = MapReduct.MapReduce() appearing above that statement? How is that executed and what is the reason one would put it above the if clause? ``` import MapReduce import sys """ Word Count ...
Everything in the file is executed, but most of what you put above `__name__ == '__main__'` is just function or class definitions - executing those just define a function or class and don't produce any noticeable side effects. If you put a `print` statement in the file outside of those definitions for example, you'll ...
Of course, all the code before `if __name__ == '__main__':` gets executed. A script is processed from top to bottom, and each expression or statement that's found is executed in order. But the `if __name__ == '__main__':` line is special: it'll get run if the script is called from the command line. By convention, the ...
Are things above __name__=='__main__' executed?
[ "", "python", "" ]
So I completely understand how to use [resample](http://pandas-docs.github.io/pandas-docs-travis/generated/pandas.DataFrame.resample.html?highlight=dataframe%20resample#pandas.DataFrame.resample), but the documentation does not do a good job explaining the options. So most options in the `resample` function are pretty...
``` B business day frequency C custom business day frequency (experimental) D calendar day frequency W weekly frequency M month end frequency SM semi-month end frequency (15th and end of month) BM business month end frequency CBM custom business month end freq...
There's more to it than this, but you're probably looking for this list: ``` B business day frequency C custom business day frequency (experimental) D calendar day frequency W weekly frequency M month end frequency BM business month end frequency MS month start frequency BMS business month start frequency ...
pandas resample documentation
[ "", "python", "documentation", "pandas", "" ]
I think I've been working on this too long because I'm having a hard time answering a pretty simple question: In a retail environment, which customers have not spent money in categories for which I'm offering a coupon? Consider the following data: ``` -- The offer ID and the category for which it is valid. select * f...
``` SELECT a.HH FROM t_catspend a WHERE NOT EXISTS ( SELECT null FROM t_offers b INNER JOIN t_catspend c ON c.CAT_NBR = b.CAT_NBR WHERE b.offer = 'foo34' AND a.HH = c.HH ) GROUP BY a.HH ``` ...
Are you looking for this? ``` SELECT b.cat_nbr, b.hh FROM ( SELECT cat_nbr, hh FROM t_offers CROSS JOIN ( SELECT DISTINCT hh FROM t_catspend ) a ) b LEFT JOIN t_catspend s ON b.cat_nbr = s.cat_nbr AND b.hh = s.hh WHERE s.spend IS NULL GROUP BY b.cat_nbr, b.hh ``` Output based on provided sample da...
SQL: Finding customers with no spend in a category
[ "", "sql", "business-intelligence", "netezza", "" ]
I have a person table: ``` Phone | Id1 | Id2 | Fname | Lname| Street 111111111 | A1 | 1000 | David | Luck | 123 Main Street 111111111 | A2 | 1001 | David | Luck | blank 111111111 | A3 | 1002 | David | Luck | blank 222222222 | B1 | 2000 | Smith | Nema | blank 333333333 | C1 | 3000 | Lanyn | Buck | 456 Street ``` I...
You want to choose a particular row. This is where the window function `row_number()` is most useful. The challenge is finding the right `order by` clause: ``` select p.Phone, p.Id1, p.Id2, p.Fname, p.Lname, p.Street from (select p.*, row_number() over (partition by phone o...
If your street is blank (as in empty set '' or NULL) when not populated with an actual address, you can use this to get your results: ``` SELECT a.* FROM Person a JOIN (SELECT Phone, MAX(Street)'Street' FROM Person GROUP BY Phone )b ON a.Phone = b.Phone AND a.Street = b.Street ``` Demo: [SQL Fiddle...
Select duplicate records info
[ "", "sql", "sql-server-2008", "duplicates", "" ]
My code: ``` import math import cmath print "E^ln(-1)", cmath.exp(cmath.log(-1)) ``` What it prints: ``` E^ln(-1) (-1+1.2246467991473532E-16j) ``` What it should print: ``` -1 ``` (For Reference, [Google checking my calculation](https://www.google.com/search?q=ln+-1&oq=ln+-1&aqs=chrome.0.57j0j62l3.1058j0&sourceid...
**The problem is inherent to representing irrational numbers (like π) in finite space as floating points.** The best you can do is filter your result and set it to zero if its value is within a given range. ``` >>> tolerance = 1e-15 >>> def clean_complex(c): ... real,imag = c.real, c.imag ... if -tolerance < real...
As you've already demonstrated, `cmath.log(-1)` doesn't return **exactly** `i*pi`. Of course, returning `pi` exactly is impossible as `pi` is an irrational number... Now you raise `e` to the power of something that isn't exactly `i*pi` and you expect to get exactly `-1`. However, if `cmath` returned that, you would be...
Python thinks Euler has identity issues (cmath returning funky results)
[ "", "python", "floating-point", "cmath", "" ]
I'm developing an application for OS X. The application involves communicating with a server through python-requests, using a secure connection. I am able to run the python file I intend to package, and it succeeds with the SSL connection. However, when I package the file with py2app and try to run it, I get the follo...
The easiests workaround is to add an option for py2app to your setup.py file: ``` setup( ... options={ 'py2app':{ 'packages': [ 'requests' ] } } ) ``` This includes the entire package into the application bundle, including the certificate bundle. I've filed an [issue for this in my py...
Requests uses a bundle of ceritificates to verify a servers identity. This bundle is kept (it has to be) in an independent file. Normally requests ships with its own bundle, but if packaged into a single file the bundle is lost. You can ship a new bundle alongside your app or let requests use the systemwide certificate...
SSLError in Requests when packaging as OS X .app
[ "", "python", "macos", "python-requests", "buildout", "py2app", "" ]
I want to get only the time data out of this date format? In the following case it is 23:55:00. I have tried many methods including `datetime.strptime` , `from dateutil import parser` etc. but failed. :( How to do it with Python? ``` [15/Apr/2013:23:55:00 +0530] ```
Assuming you could access the "date" as a string: ``` >>> from datetime import datetime >>> time_string = "[15/Apr/2013:23:55:00 +0530]" >>> format = "[%d/%b/%Y:%H:%M:%S %z]" >>> dt = datetime.strptime(time_string, format) >>> dt datetime.datetime(2013, 4, 15, 23, 55, tzinfo=datetime.timezone(datetime.timedelta(0, 1...
could use a regex to grab just the time part ``` import re date = '15/Apr/2013:23:55:00 +0530' regex = ':(?P<time>[0-9]{2}:[0-9]{2}:[0-9]{2})' just_time = re.search(regex, date).groupdict()['time'] ```
Get only time data out of date and time string.
[ "", "python", "time", "" ]
I have a text file (data.txt) like below: ``` name height weight A 15.5 55.7 B 18.9 51.6 C 17.4 67.3 D 11.4 34.5 E 23.4 92.1 ``` I want to make list in python for each column using pandas. ``` import pandas with open (pandas.read_csv('data.txt')) as df: name= df.icol...
Its not clear why you want to use pandas because you haven't said why you want them specifically in a list, so here is a solution using `csv`: ``` import csv with open('data.txt') as f: reader = csv.DictReader(f, delimiter='\t') rows = list(reader) ``` Now `rows` is a list of dictionaries, each with a header...
Try something like this: ``` import pandas df = pandas.read_csv('data.txt') # Assuming there's a columns with the headers 'name', 'height', 'weight' name = list(df['name']) height = list(df['height']) weight = list(df['weight']) print name print height print weight ``` Figured this might work after playing with [this...
creating lists from text file using pandas in python
[ "", "python", "python-2.7", "python-3.x", "pandas", "" ]
I thought the point of ON DELETE CASCADE was that this wouldn't happen. :\ I have the following tables: ``` CREATE TABLE Tweets ( tweetID INTEGER NOT NULL AUTO_INCREMENT, userID INTEGER NOT NULL, content VARCHAR(140) NOT NULL, dateTime TIMESTAMP ...
That is indeed the point of `on delete cascade`. You get the error, because your code *doesn't declare `on delete cascade`* from "poll" to "tweet". ``` CREATE TABLE Polls ( pollID INTEGER NOT NULL AUTO_INCREMENT, tweetID INTEGER NOT NULL, pollOptionText VARCHAR(300), PRIMARY KEY (pollID), FOREIGN K...
You have to put `ON DELETE CASCADE` after `FOREIGN KEY (tweetID) REFERENCES Tweets(tweetID)` According to the [MySQL Foreign Key Constraints reference](http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html): > CASCADE: Delete or update the row from the parent table, and > automatically delete or ...
Getting a "foreign key constraint fails" even though I have "on delete cascade"
[ "", "mysql", "sql", "foreign-keys", "cascade", "" ]
How do I match numbers that are present between `]` and `[` (not `[` and `]`)? **EDIT-1** In other words, I want to extract those rows where I have a number between `]` and `[`. My table looks like this... ``` ID1 id mycolmn 1 100 [ab-ee]43[ddhj] 2 233 [aa-33]49[kl-00] 3 344 [ss-23][wdsd] ``` ...
You can use VBA or SQL. **VBA**: ``` Function GetCode(MyColumn As String) As String Dim RE As New RegExp Dim colMatches As MatchCollection With RE .Pattern = "\]\d\d\[" .IgnoreCase = True .Global = False .Multiline = False Set colMatches = .Execute(MyColumn) End...
Yo dawg I heard you like brackets so I put brackets in your brackets so you can escape your brackets ``` Select * FROM yourTable WHERE MAtch LIKE "*]##[ [ ]*" ```
How to match numbers that are present between ] and [?
[ "", "sql", "regex", "ms-access", "" ]
I have an oracle table which does not have any pk set up for some other reasons. It has 5 columns and I would like to be able to remove the duplicate records (if 5 column values are the same, they are duplicate). I have come up with this SQL, but it looks like this is not picking up the duplicate values: ``` SELECT DA...
You can reference the rowid as a pseudo-primary key, and run a query that deletes rows such as: ``` delete from my_table where rowid not in ( select min(rowid) from my_table group by column_1, column_2, column_3, etc) ``` The column\_1 etc are the set of co...
As you are on Oracle, you can try the following to remove the duplicates: ``` DELETE my_table WHERE ROWID IN ( SELECT ROWID FROM ( SELECT DATE_TIME, SITE, RESPONSE_TIME, AVAIL_PERCENT, AGENT, ROWID, ROW_NUMBER() OVER (PARTITION BY DATE_TIME, SITE, RESPONSE_TIME, AVAIL_PERCENT, AGENT ORDER BY D...
select duplicate values from the oracle table
[ "", "sql", "oracle", "" ]
Hey I'm fairly new to the world of Big Data. I came across this tutorial on <http://musicmachinery.com/2011/09/04/how-to-process-a-million-songs-in-20-minutes/> It describes in detail of how to run MapReduce job using mrjob both locally and on Elastic Map Reduce. Well I'm trying to run this on my own Hadoop cluser. I...
Error code 1 is a generic error for Hadoop Streaming. You can get this error code for two main reasons: * Your Mapper and Reducer scripts are not executable (include the #!/usr/bin/python at the beginning of the script). * Your Python program is simply written wrong - you could have a syntax error or logical bug. Unf...
I got the same error, `sub-process failed with code 1` ``` [cloudera@quickstart ~]$ hadoop jar /usr/lib/hadoop-mapreduce/hadoop-streaming.jar -input /user/cloudera/input -output /user/cloudera/output_join -mapper /home/cloudera/join1_mapper.py -reducer /home/cloudera/join1_reducer.py ``` 1. This is primarily because ...
Running a job using hadoop streaming and mrjob: PipeMapRed.waitOutputThreads(): subprocess failed with code 1
[ "", "python", "hadoop", "mapreduce", "hadoop-streaming", "mrjob", "" ]
i have a table "mydata" with some data data : ``` id name position =========================== 4 foo -3 6 bar -2 1 baz -1 3 knork -1 5 lift 0 2 pitcher 0 ``` i fetch the table ordered using `order by position ASC;` the position column value may be...
Something like: ``` with renumber as ( select id, -1 * row_number() over (order by position desc, id) as rn from foo ) update foo set position = r.rn from renumber r where foo.id = r.id and position <> r.rn; ``` [SQLFiddle Demo](http://sqlfiddle.com/#!12/9edc4/1)
Try this one - **Query:** ``` CREATE TABLE temp ( id INT , name VARCHAR(10) , position INT ) INSERT INTO temp (id, name, position) VALUES (4, 'foo', -3), (6, 'bar', -2), (1, 'baz', -1), (3, 'knork', -1), (5, 'lift', 0), (2, 'pitcher', 0) SELECT id , name , posit...
how to normalize / update a "order" column
[ "", "sql", "postgresql", "" ]
I would like to generate a sequence in a list, I know how to do this using a for loop, but if I wanted to generate the list such that the previously generated element was included in the next element, how would I do this? I am very unsure i.e generate the list such that its items were: where x is just a symbol `[x,(...
I like to use a generator for this sort of thing. ``` def sequence(x, N): i = 0 result = 1 while i < N: result *= (x + i) i += 1 yield result >>> list(sequence(5, 10)) [5, 30, 210, 1680, 15120, 151200, 1663200, 19958400, 259459200, 3632428800L] ``` If you have numpy installed, thi...
Basically, you need to maintain state between the elements, and the list comprehension won't do that for you. A couple of ways to maintain state that come to mind are, a) use a generator, b) use a class EDIT or c) a closure. Use a generator ``` def product(x, n): accumulator = 1 for i in xrange(n + 1): ...
Generate a sequence keeping previous element in next element python
[ "", "python", "" ]
I'm trying to email multiple recipients using the pyton script below. I've searched the forum for answers, but have not been able to implement any of them correctly. If anyone has a moment to review my script and spot/resolve the problem it would be greatly appreciated. Here's my script, I gather my issue is in the 's...
It should be more like ``` mail(["recipient1@email.com", "recipient2@email.com"], "Subject", "Message", "attchachment") ``` You already have a array of recipients declared,that too globally,You can use that without passing it as an argument to `mail`.
I wrote this bit of code to do exactly what you want. If you find a bug let me know (I've tested it and it works): ``` import email as em import smtplib as smtp import os ENDPOINTS = {KEY: 'value@domain.com'} class BoxWriter(object): def __init__(self): pass def dispatch(self, files, box_target, a...
Email multiple recipients Python
[ "", "python", "email", "" ]
Please help with my regex problem Here is my string ``` source="http://www.amazon.com/ref=s9_hps_bw_g200_t2?pf_rd_m=ATVPDKIKX0DER&pf_rd_i=3421" source_resource="pf_rd_m=ATVPDKIKX0DER" ``` The `source_resource` is in the `source` may end with `&` or with `.`[for example]. So far, ``` regex = re.compile("pf_rd_m=ATV...
You also have to escape the `.` ``` pattern=re.compile(source_resource + '[&\.]') ```
*If* the goal is to extract the `pf_rd_m` value (which it apparently is as you are using `regex.findall`), than I'm not sure regex are the easiest solution here: ``` >>> import urlparse >>> qs = urlparse.urlparse(source).query >>> urlparse.parse_qs(qs) {'pf_rd_m': ['ATVPDKIKX0DER'], 'pf_rd_i': ['3421']} >>> urlparse.p...
python regex on variable
[ "", "python", "regex", "" ]
I am doing research with mobile apps and need to analyze their code after unzipping the .apk file. However, the process of unzipping naturally involves lots of IO, which doesn't make it scalable, I am thinking if it's possible to hold the unzipped data in memory, with several variables representing it, thus saving the ...
Hope you are using Linux: ``` $ cd /dev/shm $ unzip /path/to/my.apk ``` that's it. Unzipped APK in memory.
Yes, the python [zipfile](http://docs.python.org/2/library/zipfile) module lets you read files into memory. It reads file-like objects so the zipfile itself could be in memory also, if you find that useful.
is it possible to unzip a .apk file(or generally any zipped file) into memory instead of writing it to fs
[ "", "android", "python", "unzip", "" ]
I have sensor data from a client which is in ongoing acquisition. Every week we get a table of new data (about one million rows each) and each table has the same prefix. I'd like to run a query and select some columns across all of these tables. what would be the best way to go about this ? I have seen some solutions...
I see you are using Postgresql. This is an *ideal* case for [**partitioning**](http://www.postgresql.org/docs/9.2/static/ddl-partitioning.html) with constraint exclusion based on dates. You create one master table *without data*, and the other tables added daily inherit from it. In your case, you don't even have to wor...
You are correct, sometimes you have to write dynamic SQL to handle cases such as this. If all of your tables are loaded you can query for table names within your stored procedure. Something like this: ``` SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' ``` Play with that to get the ...
Whats the best way to select fields from multiple tables with a common prefix?
[ "", "sql", "postgresql", "" ]
I have 2 dates in database like this: ``` from_dateTime = 2013-06-12 to_dateTime = 2013-07-10 ``` I want to search all records between `from_dateTime` and `to_dateTime`. I tried to use following code in mysql: ``` SELECT * FROM users i WHERE i.from_dateTime >= '2013-06-12' AND i.to_dateTime <= '2013-07-10' ``` Bu...
The problem is that you are comparing dates and datetimes. Dates start at midnight. Any time component is larger than the corresponding date. Try this: ``` SELECT * FROM users u WHERE date(NOW()) between u.from_dateTime AND u.to_dateTime ```
``` SELECT * FROM users i WHERE cast(NOW() as date) between i.from_dateTime AND i.to_dateTime ``` **[SQL FIDDLE](http://www.sqlfiddle.com/#!2/2fe74/3)**
MYSQL search between two date
[ "", "mysql", "sql", "" ]
I'm trying to retrieve the contents of a BLOB column from an Oracle Database using mybatis. There is a table 'Demo' that contains a column 'binfile' of type BLOB. I would like to select the BLOB column and display it as a byte array/raw binary data. I'm using a Oracle thin JDBC driver. The query in the mybatis mapper ...
You can use the BLOB directly, do `import oracle.sql.BLOB;` Examples: ``` BLOB blob = (BLOB)map.get("binfile"); //one way: as array byte[] bytes = blob.getBytes(1L, (int)blob.length()); System.out.println(new String(bytes)); //use for text data System.out.println(Arrays.toString(bytes)); //another way: as stream Bu...
Have you tried mapping the field to jdbcType=LONGVARBINARY?
Select a BLOB column from Oracle DB using mybatis
[ "", "sql", "oracle", "blob", "mybatis", "" ]
[The fine manual](http://docs.python.org/2/library/functions.html#str) does not address what the `str()` method does when provided three arguments, as I've found in this code from `requests/models.py`: ``` content = str(self.content, encoding, errors='replace') ``` Where is this documented? What does it do?
You're reading docs for version 2, but looking at code using (or matching) Python 3. [The docs for version 3](http://docs.python.org/3/library/functions.html#func-str) say: > ``` > str(object='') > str(object=b'', encoding='utf-8', errors='strict') > ``` > > Return a str version of object. See str() for details. Fol...
That's not the built-in `str` function. Look at the [imports at the top](https://github.com/kennethreitz/requests/blob/master/requests/models.py#L27): ``` from .compat import ( cookielib, urlparse, urlunparse, urlsplit, urlencode, str, bytes, StringIO, is_py2, chardet, json, builtin_str, basestring) ``` Kenne...
What does the `str()` method return when provided three arguments?
[ "", "python", "string", "" ]
i've found "CASE WHEN" statement very useful for my query. But this is my query (only select): ``` SELECT dbo.ARCHIVE.SYSTEM_KEY AS PROTOCOLLO, CASE dbo.ARCHIVEDEST.ERR_ID WHEN 0 THEN 'OK' ELSE 'KO' END AS ESITO, CASE WHEN dbo.ARCHIVEDEST.XMODE IN ('R', 'K', 'H') THEN 'RX' ELSE 'TX' END AS 'T/R', ...
Use a subquery to define the `T/R` alias; ``` SELECT * , CASE 'T/R' WHEN 'TX' THEN CONTACTORIGIN.address ELSE CONTACTDESTINATION.address END AS Utente FROM ( SELECT CASE dbo.ARCHIVEDEST.ERR_ID WHEN 0 THEN 'OK' ELSE 'KO' END AS ESITO , CASE WHEN dbo.ARCHIVEDEST.XMODE IN ('R...
You'll have to repeat the test: ``` SELECT dbo.ARCHIVE.SYSTEM_KEY AS PROTOCOLLO, CASE dbo.ARCHIVEDEST.ERR_ID WHEN 0 THEN 'OK' ELSE 'KO' END AS ESITO, CASE WHEN dbo.ARCHIVEDEST.XMODE IN ('R', 'K', 'H') THEN 'RX' ELSE 'TX' END AS 'T/R', CASE CASE WHEN dbo.ARCHIVEDEST.XMODE NOT IN ('R', 'K', '...
Sql Case When query
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "select", "" ]
I have a difficult access question I seem to be stuck on. My data is like the table below, each person has a start and end date and the time in days between the two. What I am trying to do is add together all of the Assignment Lengths that are consecutive, meaning the end date of one is the day before the start date of...
I added an additional record to the given data: ``` periodID fname startdate enddate 6 bob 8/1/2013 9/1/2013 ``` to have one period that did not span records. I named the table workperiods. With the modified data, we can find the work period starts with: ``` SELECT * FROM workperiods WHERE p...
I would use VBA and [DateDiff()](http://office.microsoft.com/en-us/access-help/datediff-function-HA001228811.aspx). Then you could loop through each and compare to see if the total is less than 1.
MS Access complex grouping and sum
[ "", "sql", "ms-access", "" ]
I have 2 tables , **table 1** has the following fields , ``` u_id id no 12 51 1 21 51 2 31 51 3 41 51 4 51 51 5 61 51 6 72 51 7 81 51 8 91 51 9 92 51 10 ``` **table 2** has the following fields, ``` id o...
id must be unique ``` select id, sum(u_id*(if no = 1 then 1 else 0 endif)) as one, sum(u_id*(if no = 2 then 1 else 0 endif)) as two, sum(u_id*(if no = 3 then 1 else 0 endif)) as three, sum(u_id*(if no = 4 then 1 else 0 endif)) as four, sum(u_id*(if no = 5 then 1 else 0 endif)) as five, sum(u_id*(if no = 6 then 1 else ...
If you want to create a new table or just need to return this set from database, you will require pivot table to do this... ``` select * from table 1 pivot (max (u_id) for id in ([1],[2],[3],[4],[5],[6],[7],[8],[9])[10]) as table 2 ```
Insert into a table values from another table using Oracle
[ "", "sql", "oracle", "pivot-table", "" ]
I have an SQL Server table structured as follows : ``` Table name : calendar. ``` Columns : ``` Calendar Date (smalldatetime) Working Day (bit) ``` Calendar date has all dates, structured in the format yyyy-mm-dd. Working day means that I have work if it is a 1, and if it is a weekend or a holiday it is marked as a...
Presumably you are interested in finding the working days in each month in each year and report which month the number of days is for. This will give you that: ``` SELECT YEAR([Calendar Date]) As [YEAR], Month([Calendar Date]) As [Month], SUM([Working Day] As [Working Days] FROM [Calendar] GROUP BY YEAR(...
Your query should look something like this: ``` SELECT Sum(Working Day) WHERE Working Day = 1 GROUP BY MONTH(calenderDate) ``` This will group by month as you asked. For more datetime functions your could check out [this link](http://msdn.microsoft.com/en-us/library/ms186724.aspx)
is it possible to Sum values grouped by month?
[ "", "sql", "sql-server", "database", "group-by", "sum", "" ]
I'm writing some code for a command line program and I'm using the `getopt()` function. Can someone explain the options / long\_options syntax? ``` getopt.getopt(args, options[, long_options]) ``` My question is this: Why does is the list fragmented between arguments? why is it options[ not options?
The function has 2 required arguments (`args` and `options`) and one option that is not required (`long_options`). The exact meaning of `args`, `options` and `long_options` can all be found in the [documentation](http://docs.python.org/2/library/getopt.html#getopt.getopt) Basically, if you want the commandline to be p...
you should be using `argparse` instead of `getopt` which is now deprecated. About explanations, the documentation is really accessible: * <http://docs.python.org/dev/library/argparse.html> * <http://docs.python.org/2/howto/argparse.html> and about your specific question, I think you'd have your answer there: * <http...
Why does the getopt method have getopt(args, options[, long_options]) not getopt(args, options,[ long_options]) as its signature?
[ "", "python", "getopt", "" ]
I want generate a contour plot/heat map with a color bar and then add an annotation box. This figure is ugly, but gets at what I want: ![example image](https://i.stack.imgur.com/o9P1g.png) `add_subplot()` is not enough. If I try to put everything in the same subplot, the box gets covered up. I can get around this by ...
## Annotation box to contour map: ![much better graph](https://i.stack.imgur.com/W9Sqk.png) Done like this: ``` import matplotlib.pyplot as plt import numpy as np from matplotlib import cm from numpy.random import randn from mpl_toolkits.axes_grid1.axes_divider import HBoxDivider import mpl_toolkits.axes_grid1.axes...
Here's a rather simple solution, using the `make_axes_locatable` function from `mpl_toolkits.axes_grid1`, as this makes the colorbar the same height as the image. Further it is very easy to set the placement, width and padding of the colorbar relative to the `Axes`. ``` import matplotlib.pyplot as plt import numpy as ...
Adding an annotation box to a matplotlib contour/heat map plot
[ "", "python", "matplotlib", "plot-annotations", "" ]
I want to replace negative values in a pandas DataFrame column with zero. Is there a more concise way to construct this expression? ``` df['value'][df['value'] < 0] = 0 ```
Here is the canonical way of doing it, while not necessarily more concise, is more flexible (in that you can apply this to arbitrary columns) ``` In [39]: df = DataFrame(randn(5,1),columns=['value']) In [40]: df Out[40]: value 0 0.092232 1 -0.472784 2 -1.857964 3 -0.014385 4 0.301531 In [41]: df.loc[df['val...
You could use the [clip method](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.clip.html#pandas-series-clip): ``` import pandas as pd import numpy as np df = pd.DataFrame({'value': np.arange(-5,5)}) df['value'] = df['value'].clip(0, None) print(df) ``` yields ``` value 0 0 1 0 2 0...
Return max of zero or value for a pandas DataFrame column
[ "", "python", "pandas", "" ]
Looking at [this](https://stackoverflow.com/questions/17075618/new-to-programming-and-i-am-having-a-conceptual-block-with-the-range-function-e) question, I tried OP's the code on my machine. Here are a [text version](http://pastebin.com/X2ukpXA9) and a screenshot: ![bad square](https://i.stack.imgur.com/utSId.png) Wh...
Easy! ``` def square(x): runningtotal = 0 for counter in range(x): runningtotal = runningtotal + x <tab>return runningtotal ``` > First, tabs are replaced (from left to right) by one to eight spaces > such that the total number of characters up to and including the > replacement is a multiple of **eig...
For Python indenting - a `tab` is counted as equivalent to 8 spaces Since people almost never have their tab width set to 8 spaces, it's never a good idea to mix the two. Like many people, I used to prefer tabs for indenting, but found that it is a constant source of confusion when emailing code or posting in forums,...
Possible mixed indentation in Python?
[ "", "python", "indentation", "cpython", "" ]
I made this script which removes every trailing whitespace characters and replace all bad french characters by the right ones. Removing the trailing whitespace characters works but not the part about replacing the french characters. The file to read/write are encoded in UTF-8 so I added the utf-8 declaration above my...
Not so quick, and mostly dirty, but... ``` with open("enc.txt","r") as f: content = f.read() import re def unicodize(seg): if re.match(r'\\u[0-9a-f]{4}', seg): return seg.decode('unicode-escape') return seg.decode('utf-8') replaced = (unicodize(seg) for seg in re.split(r'(\\u[0-9a-f]{4})',conte...
You are looking for `s.decode('unicode_escape')`: ``` >>> s = r""" ... * Cette m\u00e9thode permet d'appeller le service du module de tourn\u00e9e ... * <code>rechercherTechnicien</code> et retourne la liste repr\u00e9sentant le num\u00e9ro ... * de la tourn\u00e9e ainsi que le nom et le pr\u00e9nom du technicien e...
Python 2.7 reading and writing "éèàçê" from utf-8 file
[ "", "python", "python-2.7", "encoding", "utf-8", "character-encoding", "" ]
I am writing a SQL query, where my goal is to find the duplicate values based on the column names: ``` SELECT a.PROJECTNAME , a.OBJECTTYPE , a.OBJECTID1 , a.OBJECTVALUE1 , a.OBJECTID2 , a.OBJECTVALUE2 , a.OBJECTID3 , a.OBJECTVALUE3 , a.OBJECTID4 , a.OBJECTVALUE4 FROM PSPROJECTITEM a WHERE a.proj...
The main problem with your query is that it is "inside-out". That is, you are only selecting the project of interest in the outer query. The inner is selecting all the similar ones, but they are not being output because they are in a `where` clause. Try this variation: ``` SELECT a.PROJECTNAME , a.OBJECTTYPE , a....
Correct me if I am wrong, your objective is to use project name to find the duplicated value in PSPROJECTITEM. ``` SELECT t2.objecttype ,t2.objectid1 ,t2.objectvalue1 ,t2.objectid2 ,t2.objectvalue2 ,t2.objectid3 ,t2.objectvalue3 ,t2.objectid4 ,t2.objectvalue4 FROM PSPROJECTITEM t2, PROJECTNAME t1 WHERE t2.objecttype =...
How to find duplicate data
[ "", "sql", "oracle", "" ]
``` class A: def __init__(self): print 'A' class B(A): def __init__(self): print 'B' b = B() B ``` In C++, I would have expected to see `A B` output, but in Python I am getting only `B`. I know that I can do `super(B, self).__init__()` to achieve the same in Python, but as this is apparentl...
> So what are objects in Python Well, objects in python are like dictionaries of members and methods. It's no more sophisticated than that. You don't have visibility handling (if you want to hide a member, just do not talk about it in the public documentation, only with a comment). > what is their relation with class...
Python rarely does anything automatically. As you say, if you want to invoke the superclass `__init__`, then you need to do it yourself, usually by calling `super`: ``` class B(A): def __init__(self): print 'B' super(B, self).__init__() ``` The point to note is that instance attributes, like every...
Why are parent constructors not called when instantiating a class?
[ "", "python", "class", "oop", "python-2.7", "" ]
I am running a query that contains **same** sub-query used multiple times in a `WHERE` clause. I have a table having tow fields `client_id`, `buyer_id`. The sub-query returns the list of dates to be excluded from the result. This is how I am using it. ``` SELECT id, client_id, buyer_id FROM relation WHERE clien...
You can write this using `NOT EXISTS`: ``` SELECT id, client_id, buyer_id FROM relation AS r WHERE NOT EXISTS ( SELECT 1 FROM <some_table> WHERE (r.client_id = <some_id> OR r.buyer_id = <some_id>) AND ... ) ; ```
Queries of the form: ``` select ... from <main query> where <select field> not in (select <subquery field> from <subquery>) ``` can normally be reformulated as: ``` select <main query fields> from <main query> left join <subquery> on <select field> = <subquery field> where <subquery field> is null ``` If the sub-qu...
Same sub-query used multiple times in a single query
[ "", "mysql", "sql", "subquery", "" ]
I have regular expression for parsing many values like `a=b c=d e=f` which should result in dictionary like this: `{'a': 'b', 'c':'d', 'e':'f'}`. I wanted user to allow escaping values using `\` so instead of really simple regexp I've used `((?:[^\\\s=]+|\\.)+)` plus I've added `(?:^|\s)` and `(?=\s|$)` so expression w...
Your problem is that you nest repetitions and the re-engine seems to try all possible distributions among them: ``` r'(?:^|\s)([\w\d]+)=((?:[^\\\s=]+|\\.)+)(?=\s|$)' ^ ^ ``` Better: ``` r'(?:^|\s)([\w\d]+)=((?:[^\\\s=]|\\.)+)(?=\s|$)' ``` In fact the findall would finish (or run ...
Regular expressions aren't the right tool for your task beyond very simple cases. You need to tokenize the input string. In simple cases you can use `str.split()`: ``` for tok in s.split(" "): tok = tok.split("=", 1) key = tok[0] value = tok[1] ``` I haven't written python in quite some time, so I'm not ...
"Broken" regular expression?
[ "", "python", "regex", "python-3.2", "" ]
I have a text file (data.txt) delimited by tab as follows: ``` name height weight A 15.5 55.7 B 18.9 51.6 C 17.4 67.3 D 11.4 34.5 E 23.4 92.1 ``` The program below gives the result as the list of strings. ``` with open('data.txt', 'r') as f: col1 = [line.split()[0] for line in f] ...
There is no need of reading the file 3 times here, you can do this by defining a simple function that returns float value of the the item if it is a valid number otherwise returns it as it is. Now read all the lines one by one using a list comprehension and apply this function to the items of each line. So now you've ...
Use the `float()` function. It takes 1 arg, which would be the string/var you want to turn into a float.
from list of strings into list of floats
[ "", "python", "python-3.x", "" ]
I obtained a NumPy record `ndarray` from a CSV file using ``` data = matplotlib.mlab.csv2rec('./data.csv', delimiter=b',') ``` The data set is structured as: ``` date,a0,a1,a2,a3, b0, b1, b2, b3,[...], b9 2012-01-01, 1, 2, 3, 4,0.1,0.2,0.3,0.4,[...],0.9 ``` I want to select (in the SQL sense) just columns `b0...
Given that you have an record array, I think the following will work: ``` data[['b' + str(j) for j in range(10)]] ``` [doc/introduction](http://docs.scipy.org/doc/numpy/user/basics.rec.html) and [cookbook](http://www.scipy.org/Cookbook/Recarray)
`data[...,0:3]` will give you columns 0 through 2. `data[...,[0,2,3]]` will give you columns 0, 2 and 3. The thing is that you have an array of arrays, while the question you referenced is about 2D-arrays, which is slightly different. See also: [Numpy Array Column Slicing Produces IndexError: invalid index Exception]...
Select range of rows from record ndarray
[ "", "python", "select", "python-2.7", "numpy", "matplotlib", "" ]
Is there an efficient way to remove duplicates 'person\_id' fields from this data with python? In this case just keep the first occurrence. ``` { {obj_id: 123, location: { x: 123, y: 323, }, {obj_id: 13, location: { x: 23, y: 333, }, {obj_id: 123, location: { x: 122, ...
Presuming your JSON is valid syntax and you are indeed requesting help for `Python` you will need to do something like this ``` import json ds = json.loads(json_data_string) #this contains the json unique_stuff = { each['obj_id'] : each for each in ds }.values() ``` if you want to always retain the first occurrence, ...
Here's an implementation that preserves order of input json objects and keeps the first occurrence of objects with the same id: ``` import json import sys from collections import OrderedDict L = json.load(sys.stdin, object_pairs_hook=OrderedDict) seen = OrderedDict() for d in L: oid = d["obj_id"] if oid not i...
Remove duplicates from json data
[ "", "python", "" ]
I have the following table: ``` create table o_newstdata1 ( field1 raw(8) ); ``` the following input.data file: ``` 0x12345678 0x1234 0x12 ``` how can I insert such a data into my o\_newstdata1 table? I've tried to load it as a varchar data: ``` load data INFILE '/export/home/mine/input.data' replace into table o...
There are possibly two sources of errors: 1. Loading raw data with SQL\*Loader 2. Querying the raw data To check if the querying part works, use something like: ``` CREATE TABLE o_newstdata1 (field1 RAW(8)); INSERT INTO o_newstdata1(field1) VALUES ('12AB'); INSERT INTO o_newstdata1(field1) VALUES ('34EF'); ``` You...
If your data is not really binary/raw (as indicated by the size of the column), but just a number, you could store it as a number. Hex is just one way to *represent* a number (a notation). So I would just store it as a numeric, and put a *view* on top of it, so you can see/query hex values directly. This way you coul...
How to insert Hex data into the oracle table?
[ "", "sql", "oracle", "sql-loader", "" ]
Hi I want to create a list which contains strings differ only by suffix ie. like this ``` ['./name[@val="1"]/Output1', './name[@val="1"]/Output2','./name[@val="1"]/Output3'] ``` I tried to iterate through a for loop and appending the suffix int value like this ``` dummy = [] for I in range(1,5): dummy.append('./...
In your code change `i` to `str(i)` which typecasts the integer to a string. You should also try to use single line list comprehension, which is cleaner and more pythonic. ``` dummy = [ ('./name[@val="1"]/Output' + str(i) ) for i in xrange(0,5)] ``` And also use formatting instead of concatenations. ``` [ './name[@...
Use `str()` ``` dummy = [] for i in range(1,5): dummy.append('./Timestamp[@absCycle='"'+i'"']/Output'+str(i)) ```
list of strings differ by suffix
[ "", "python", "" ]
I have a csv file which contains 20 columns. Right now I can plot using this code taking first column as x axis and rest of them as y axis. ``` import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt('cs.csv',delimiter=',', dtype = float) a = [row[0] for row in data] b = [row[1] for row in data] c = [...
How about this: ``` [plt.plot(data[0],data[x]) for x in range(1,len(data[:,0]))] ```
You could try using [pandas](http://pandas.pydata.org/), which uses matplotlib for plotting. For example, if you have a CSV like this: ``` a,b,c 20,2,5 40,6,8 60,4,9 ``` You can plot columns `b` & `c` like this: ``` import pandas as pd df = pd.DataFrame.from_csv('test.csv', parse_dates=False) df.b.plot(color='g',lw...
matplotlib plot csv file of all columns
[ "", "python", "numpy", "matplotlib", "" ]
I have duplicate records in a table. I need to be able to identify only one unique identifier so I can delete it from the table. The only way I know there are a duplicate is from columns `subject` and `description` so if there are at least 2 of the same subject and the same description, I need to delete one and leave ...
One nice feature that I like about SQL Server is the use of CTEs with `update` and `delete` statements. You are looking for duplicate records and presumably want to keep either the lowest or highest `record_id`. You can get the count and the id to keep using a CTE and window functions: ``` with todelete as ( SELE...
Perhaps something like this? ``` SELECT max(p.record_id), p.accountid, p.subject, p.description, count(*) AS total FROM activities AS p WHERE (p.StateCode = 1) AND p.createdon >= getdate()-6 GROUP BY p.accountid, p.subject, p.description HAVING count(*) > 1 ORDER BY p.accountid ```
How to identify a unique identifier of a duplicate records?
[ "", "sql", "sql-server", "" ]
I'm currently having some issues with the math.floor() function in python. I am attempting to compute the following value: ``` math.floor((3710402416420168191+3710402416420167681)/2) ``` This is producing the answer ``` 3710402416420167680 ``` Which I know is not right. I think this has something to do with Python'...
Avoid using floating point numbers. Python only uses 53 bits of precision for floating point numbers, but integers can grow arbitrarily large: ``` >>> int((3710402416420168191 + 3710402416420167681) / 2) 3710402416420167680 >>> (3710402416420168191 + 3710402416420167681) // 2 3710402416420167936 ``` `//` is floor div...
I can't reproduce your results, in my machine this: ``` math.floor((3710402416420168191+3710402416420167681)/2) ``` Is returning this, which is correct for the given precision: ``` 3.7104024164201677e+18 ``` Maybe the error happens when you try to print the above result? which clearly has lost some precision, becau...
Python Math.floor not producing correct values with large ints
[ "", "python", "integer", "long-integer", "largenumber", "floor", "" ]
I am trying to read from a list and return a corresponding value in a dict. Please help me where I am going wrong. Thank you ``` DICT = {"b": "21", "g": "54", "f": "121", "t": "1", "j": "33"} n = ['b', 'w', 'f'] for keys in n: if keys in n: if n == DICT.keys(): print(DICT.values()) els...
very simple if you use `get` ``` for k in n: print(DICT.get(k, 'Not Available')) ```
``` for key in n: if key in dict.keys(): print(dict[key]) ``` Seems this is what you are trying to do
Looping a list returning a value in dict
[ "", "python", "list", "loops", "dictionary", "" ]
I have a long list of words and [regular expression patterns](http://docs.python.org/2/library/re.html) in a .txt file, which I read in like this: ``` with open(fileName, "r") as f1: pattern_list = f1.read().split('\n') ``` for illustration, the first seven look like this: ``` print pattern_list[:7] # ['abandon...
For matching shell-style wildcards you could (ab)use the module [`fnmatch`](http://docs.python.org/2/library/fnmatch.html#module-fnmatch) As `fnmatch` is primary designed for filename comparaison, the test will be case sensitive or not depending your operating system. So you'll have to normalize both the text and the ...
`abandon*` will match `abandonnnnnnnnnnnnnnnnnnnnnnn`, and not `abandonasfdsafdasf`. You want ``` abandon.* ``` instead.
Python: check if any word in a list of words matches any pattern in a list of regular expression patterns
[ "", "python", "regex", "" ]
I run the following code with Python 2.7.5. under Windows: ``` import os, shutil, stat, time with open('test.txt', 'w') as f: pass # create an arbitrary file shutil.copy('test.txt', 'test2.txt') # copy it shutil.copystat('test.txt', 'test2.txt') # copy its stats, too t1 = os.lstat('test.txt').st_mtime # get the time...
The problem is with conversion between different formats during the `copystat` call. This is because Windows stores file times in a fixed-point decimal format, while Python stores them in a floating-point binary format. So each time there is a conversion between the two formats, some accuracy is lost. During the `copys...
``` from decimal import * print Decimal(t1) print Decimal(t2) ``` Use round() for t1 and t2
File modification times not equal after calling shutil.copystat(file1, file2) under Windows
[ "", "python", "windows", "python-2.7", "filesystems", "" ]
I'm having a bit of a trouble with my Trigger. It's supposed to: * Update a history table on inserts in my primary table and add a timestamp. * If a row in the history table already has the same values, nothing should be added, but a counter should increase and the time should be updated. * If it was over 24hours ago ...
OMG I solved it ^^ Been trying to fix it for like 2 hours and just when I post it to stackoverflow I manage to fix it ^^ **What I did:** Changed the second "EXIST" test from: ``` OR EXISTS ( --or if it has been added over 24h ago SELECT History.value1 FROM History, INSERTED WHERE History.value1 LIKE ...
I think your trigger is still broken if `inserted` contains a mixture of rows - since your `IF`/`ELSE` structure makes a single decision on what action to take. It would be better to have a [`MERGE`](http://msdn.microsoft.com/en-us/library/bb510625%28v=sql.110%29.aspx), something like: ``` ;MERGE INTO History h USING...
Trigger doesn't work as expected
[ "", "sql", "sql-server", "database", "triggers", "" ]
I'm trying to understand how to do this: Some producers creates N number of queues ( lets say `foo.1 foo.2 foo.3` ). Than I have one consumer on another part of the Rabbit that needs to get messages from all N (in my example 3 ) queues. I know I can do something like this: ``` (method_frame, header_frame, body) = sel...
The RabbitMQ admin interface/api will have access to all of the queues on the server. There is an easy to use Python client [PyRabbit](http://pyrabbit.readthedocs.org/en/latest/) that will let you [get\_queues](http://pyrabbit.readthedocs.org/en/latest/api.html#pyrabbit.api.Client.get_queues). From there you can do wha...
Here's what I see: You need to get all the messages from a provided number `n` of queues. From my personal experience, I would just write a for loop and create a string by adding `"foo.%s" % (iteration)`. Here is an example to what I mean: ``` for i in range(queues): str = 'foo.%s' % (i) (method_frame, header...
How to subscribe consumer to N number of unknown queues?
[ "", "python", "queue", "rabbitmq", "amqp", "pika", "" ]
This is probably laughably easy for an SQL expert, but SQL (although I can use it) is not really my thing. I've got a table in a DB. (Let's call it COMPUTERS) About 10.000 rows. 25 columns. 1 unique key: Column ASSETS. Occasionally an external program will delete 1 or more of the rows, but isn't supposed to do that...
just create a trigger for insert computers table ``` CREATE TRIGGER newComputer ON [Computers] AFTER INSERT Begin INSERT INTO COMPUTERS_BACKUP SELECT * FROM Inserted End ``` It'll work when you insert new computer to computers table and it'll also insert the record to bakcup table When you update computers you c...
Besides creating triggers, you may look into enabling [Change Data Capture](http://msdn.microsoft.com/en-us/library/bb933994%28v=sql.105%29.aspx), which is available in SQL Server Enterprise Edition. It may be an overshot, but it should be mentioned and you may find it useful for other tables and objects.
Keep a shadow copy of a table while retaining records removed from the original
[ "", "sql", "sql-server", "" ]
The way that class variables in Python are handled does not make any sense to me. It seems that the scope of a class variable is dependent upon its type! Primitive types are treated like instance variables, and complex types are treated like class variables: ``` >>> class A(object): ... my_class_primitive = True ......
It's not about primitive and complex. When you append to `a.my_class_object`, you modify the existing object. When you assign to a variable, you don't modify it. The same "problem" exists for lists if you treat them like you did the boolean: ``` >>> class Foo(object): ... x = [] ... >>> i1 = Foo() >>> i2 = Foo() >...
The feature exists as a form of caching for Python's class definitions. Attributes defined in the class definition itself are considered `static` attributes of the class. e.g. they should not be modified. I'm sure the decision was made assuming you were following best practices with respect to modifying static attrib...
correct way to use class-level primitives
[ "", "python", "" ]
I'm aware that floating points aren't 100% accurate in most programming languages but I've come across an odd problem just now. I'm still learning Python so have made a simple program that calculates change given in the least possible amount of coins. However, when it gets to 0.02 it seems to fail at giving a 2p coin a...
Well since you are aware that floating points aren't 100% accurate, it shouldn't surprise you to find out that 0.02 can't be represented exactly as a Python float. It is in fact stored as something slightly higher that 0.02, which you can see if you print the value with very high precision: ``` >>> print '{0:.32f}'.fo...
First of all, `amountLeft / 0.02 >= 1` is mostly the same as `amountLeft >= 0.02` (assuming `amountLeft` is not negative), and a bit simpler. Using integer arithmetic (working with pennies directly, would give you exact results, although you would have to add the `.` manually when displaying results: ``` from Decimal...
Floating point problems
[ "", "python", "floating-point", "floating-accuracy", "" ]
My problem is about managing insert/append methods within loops. I have two lists of length `N`: the first one (let's call it `s`) indicates a subset to which, while the second one represents a quantity `x` that I want to evaluate. For sake of simplicity, let's say that every subset presents T elements. ``` cont = 0;...
I think to have found a simple solution. I cycle from the last subset backwards, putting the copies at the end of each subset. This way, I avoid encountering the "new" elements and get rid of counters and *similia*. ``` for i in range(NSUBSETS-1, -1, -1): for j in range(T-1, -1, -1): if (x[(i*T)+j] < 100):...
I'm guessing that your desire not to copy the lists is based on your C background - an assumption that it would be more expensive that way. In Python lists are not actually lists, inserts have O(n) time as they are more like vectors and so those insert operations are each copying the list. Building a new copy with the...
Most efficient way to cycle over Python sublists while making them grow (insert method)?
[ "", "python", "algorithm", "" ]
I am having a table with a years data with the following columns: ``` Table "myData" (( "Status" character varying, "Project" character varying, "Product" character varying, "Identifier" character varying, "Submittedon" date ) ``` etc., Now to fetch a count of records submitted on a par...
``` select date_trunc('month', submittedOn) "month", count("Status") total from "myData" group by 1 order by 1 ```
This looks like a "Pivot"-Table so use the crosstab() function of the tablefunc extention (<http://www.postgresql.org/docs/current/static/tablefunc.html>): ``` CREATE TABLE mydata (status text, submitteton date); INSERT INTO mydata VALUES ('a', '2013-01-02'), ('b', '2013-01-05'), ('c', '2013-02-09'), ('d', '2013-04-11...
fetching monthwise data from a database with a year's record in postgres
[ "", "sql", "postgresql", "" ]
I am using this to get the name of a given date, so the following gives me MONDAY: ``` Select to_char(to_date('01/04/2013','dd/mm/yyyy'), 'DAY') from dual ``` However if I apply the same thing to a table and extract dates with their names I am getting a wrong day name, in the case of '01/April/2013' it gives me SATUR...
Since your date column is a date: ``` Select to_char(myDateColumn, 'DAY'), myDateColumn From myTable WHERE myDateColumn = to_date('01/04/2013','dd/mm/yyyy') ``` should suffice (this should be a comment, not an answer but it wouldn't be readable)
This is partially following up other answers, but explaining (hopefully) what's happening. When you do this, assuming `myDateColumn` is a `DATE`: ``` to_char(to_date(myDateColumn,'dd/mm/yyyy'), 'DAY') ``` you have an implicit conversion; it's really doing this: ``` to_char(to_date(to_char(myDateColumn),'dd/mm/yyyy'...
Oracle get day name returns wrong name
[ "", "sql", "oracle", "oracle10g", "" ]
I am trying to read an excel file this way : ``` newFile = pd.ExcelFile(PATH\FileName.xlsx) ParsedData = pd.io.parsers.ExcelFile.parse(newFile) ``` which throws an error that says two arguments expected, I don't know what the second argument is and also what I am trying to achieve here is to convert an Excel file to ...
Close: first you call `ExcelFile`, but then you call the `.parse` method and pass it the sheet name. ``` >>> xl = pd.ExcelFile("dummydata.xlsx") >>> xl.sheet_names [u'Sheet1', u'Sheet2', u'Sheet3'] >>> df = xl.parse("Sheet1") >>> df.head() Tid dummy1 dummy2 dummy3 dummy4 dummy5 \ 0 2006...
This is much simple and easy way. ``` import pandas df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1') # or using sheet index starting 0 df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2) ``` Check out [documentation full details](http://pandas.pydata.org/pandas-doc...
Reading an Excel file in python using pandas
[ "", "python", "python-2.7", "pandas", "" ]
The following code fills all my memory: ``` from sys import getsizeof import numpy # from http://stackoverflow.com/a/2117379/272471 def getSize(array): return getsizeof(array) + len(array) * getsizeof(array[0]) class test(): def __init__(self): pass def t(self): temp = numpy.zeros([200,1...
The implementation of `diagonal()` failed to decrement a reference counter. This issue had been previously fixed, but [the change](https://github.com/numpy/numpy/commit/80b3a3401382cb3f14c5b76dd90d9f932f50ad15) didn't make it into 1.7.0. Upgrading to 1.7.1 solves the problem! The [release notes](https://numpy.org/devd...
Python allocs memory from the OS if it needs some. If it doesn't need it any longer, it may or may not return it again. But if it doesn't return it, the memory will be reused on subsequent allocations. You should check that; but supposedly the memory consumption won't increase even more. About your estimations of me...
Is this a memory leak? (python + numpy)
[ "", "python", "memory-leaks", "numpy", "" ]
I have table Match, with this **columns:** `ID(with Identity spec.),Team1,Team2`. I need copy the row with `ID=1` with all columns to NEW row with new `automatic ID`. Now I have this **code:** ``` SET IDENTITY_INSERT Match ON INSERT INTO Match (ID,Team1,Team2) SELECT ???,Team1,Team2 FROM Match WHERE ID='1'; ``` ...
If your ID column is auto-increment then do ``` INSERT INTO Match (Team1,Team2) SELECT Team1,Team2 FROM Match WHERE ID='1'; ```
By not turning on `IDENTITY_INSERT` and letting the system create the `ID`: ``` INSERT INTO Match (Team1,Team2) SELECT Team1,Team2 FROM Match WHERE ID=1; ``` When `IDENTITY_INSERT` is turned on, you're telling the system "I'm going to assign a value where normally you would auto-generate one", and so you would ha...
Copy row to same table with different ID
[ "", "sql", "" ]
I have a large excel worksheet that I want to add to my database. Can I generate an SQL insert script from this excel worksheet?
I think importing using one of the methods mentioned is ideal if it truly is a large file, but you can use Excel to create insert statements: ``` ="INSERT INTO table_name VALUES('"&A1&"','"&B1&"','"&C1&"')" ``` In MS SQL you can use: ``` SET NOCOUNT ON ``` To forego showing all the '1 row affected' comments. And if...
There is a handy tool which saves a lot of time at <http://tools.perceptus.ca/text-wiz.php?ops=7> You just have to feed in the table name, field names and the data - tab separated and hit Go!
Generate sql insert script from excel worksheet
[ "", "sql", "excel", "" ]
I'd like to build something like: ``` A = ( 'parlament', 'queen/king' if not country in ('england', 'sweden', …), 'press', 'judges' ) ``` Is there any way to build a tuple like that? I tried ``` 'queen/king' if not country in ('england', 'sweden', …) else None, 'queen/king' if not country in ('england', 'sw...
I ran into a similar problem. You can use the spread operator `*`: ``` A = ( 'parlament', *(('queen/king',) if not country in ('england', 'sweden', …) else tuple()), 'press', 'judges' ) ``` Looks a little bit complicated but does exactly what is requested. First it "packs" the whatever answer is needed into a...
Yes, but you need an `else` statement: ``` >>> country = 'australia' >>> A = ( ... 'parlament', ... 'queen/king' if not country in ('england', 'sweden') else 'default', ... 'press', ... 'judges' ... ) >>> print A ('parlament', 'queen/king', 'press', 'judges') ``` --- Another example: ``` >>> country = ...
Is it possible to have an if inside a tuple?
[ "", "python", "if-statement", "conditional-expressions", "" ]
This should be an really easy task using the `re` library. However, I can't seem to split my string at the delimiters `]` and `[`. I already read [Splitting a string with multiple delimiters in Python](https://stackoverflow.com/questions/10393157/splitting-a-string-with-multiple-delimiters-in-python), [Python: Split s...
``` >>> re.split(r'\[|\]', data2) ['A new string. ', 'with brackets', ' another line ', 'and a bracket', ''] ```
As arshajii points out, you don't need groups at all for this particular regexp. If you did need groups to express a more complex regexp, you could use noncapturing groups to split without capturing the delimiter. It's potentially useful for other situations but syntactically messy overkill here. > (?:...) > > ``` > ...
Split at multiple delimiter without delimiter in the list
[ "", "python", "regex", "split", "" ]
Python 3.3, a dictionary with key-value pairs in this form. ``` d = {'T1': ['eggs', 'bacon', 'sausage']} ``` The values are lists of variable length, and I need to iterate over the list items. This works: ``` count = 0 for l in d.values(): for i in l: count += 1 ``` But it's ugly. There must be a more Pythonic w...
Use `sum()` and the lengths of each of the dictionary values: ``` count = sum(len(v) for v in d.itervalues()) ``` If you are using Python 3, then just use `d.values()`. Quick demo with your input sample and one of mine: ``` >>> d = {'T1': ['eggs', 'bacon', 'sausage']} >>> sum(len(v) for v in d.itervalues()) 3 >>> d...
``` >>> d = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['spam', 'ham', 'monty', 'python']} >>> sum(map(len, d.values())) 7 ```
Python count items in dict value that is a list
[ "", "python", "list", "dictionary", "count", "python-3.3", "" ]
I'm trying to create a report from an Oracle query. The data is like this: ``` GROUP_ID | COUNT_1 | COUNT_2 1 | 100 | 123 1 | 101 | 123 1 | 283 | 342 1 | 134 | 123 2 | 241 | 432 2 | 321 | 920 2 | 432 | 121 2 | 135 | ...
Not tested, but this should be the idea. If you need to sort by COUNT\_1 or COUNT\_2, you should include it in the analytic functions' `over` clause, `partition by GROUP_ID order by COUNT_1` Refer [here](http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm) to understand what an analytic function is....
``` CREATE TABLE tt(g NUMBER, c1 NUMBER, c2 NUMBER); INSERT INTO tt VALUES(1, 100, 123); INSERT INTO tt VALUES(1, 101, 123); INSERT INTO tt VALUES(1, 283, 342); INSERT INTO tt VALUES(1, 134, 123); INSERT INTO tt VALUES(2, 241, 432); INSERT INTO tt VALUES(2, 321, 920); INSERT INTO tt VALUES(2, 432, 121); INSERT INTO tt ...
Oracle 11g: only return a value if row is first or last in group
[ "", "sql", "oracle", "oracle11g", "" ]
Considering that [the `bytes` type is not necessarily a string](https://stackoverflow.com/questions/17063502/python-strings-and-str-method-encoding-and-decoding), how can one see the actual bytes (ones and zeros, or octal/hexadecimal representation of such) of a `bytes` object? Trying to `print()` or `pprint()` such an...
Use `bin`, `oct` or `hex` and access the byte using bracket notation: ``` >>> print(hex(se[0])) 0x68 >>> print(hex(se[1])) 0x69 ``` Obviously a cycle will be better: ``` for a_byte in se: print (bin(a_byte)) ```
Use [Python string formatting](http://docs.python.org/2/library/stdtypes.html#string-formatting-operations) to show the hexadecimal values of your bytes: ``` >>> se = b'hi' >>> ["{0:0>2X}".format(b) for b in se] ['68', '69'] ```
How to see the bytes of a Python3 <class 'bytes'> object?
[ "", "python", "python-3.x", "type-conversion", "" ]
here is the simple query, that I am using (in real world I am using active record and its big query to show you, so please consider this one for now) ``` SELECT *,(id/* another big query*/) as distance FROM members having distance<=8 ``` if I run the above query then its return perfect results total 5 but I run this ...
Do you want to do something like that: ``` select count (*) from ( SELECT *,(id/* another big query/) as distance FROM members having distance<=8 ) ```
You want to filter with a `WHERE` clause (which is applied *before* aggregation), instead of a `HAVING` clause (which is applied *after* aggregation): ``` SELECT COUNT(*) FROM members WHERE distance <= 8 ```
Having Problems with COUNT when using HAVING condtion
[ "", "mysql", "sql", "database", "" ]
Like the title, I'm still a rookie of SQLServer, when I creating a table 'Mytable', it's showed 'dbo.Mytable' in the database But can anyone give me a better understanding of schema? Also, in the book Server 2008 TSQL, Itzik says 'in your database, table belongs to schema, schema belongs to your own database' then h...
The "new flavor" is to use schema's like namespaces. The default of "dbo" goes back a long ways. But I treat the schema name as part of the name. Like, I never write ``` Select * from Employee ``` I always write ``` Select ColA, ColB from dbo.Employee ``` I'd get a copy of the AdventureWorks database, it has goo...
If you are new to SQL Server and to databases in general, then the concept of schema probably is confusing. A basic understanding is: ``` A schema is the unit of security (as described [here][1] if you must know). A database is the unit of backup and recovery. ``` If you are new to SQL Server, security may not be to...
a better understanding of Schema in SQLServer
[ "", "sql", "sql-server", "" ]
i'm trying to sum consecutive numbers in a list while keeping the first one the same. so in this case 5 would stay 5, 10 would be 10 + 5 (15), and 15 would be 15 + 10 + 5 (30) ``` x = [5,10,15] y = [] for value in x: y.append(...) print y [5,15,30] ```
You want [`itertools.accumulate()`](http://docs.python.org/dev/library/itertools.html#itertools.accumulate) (added in Python 3.2). Nothing extra needed, already implemented for you. In earlier versions of Python where this doesn't exist, you can use the pure python implementation given: ``` def accumulate(iterable, f...
``` y = [sum(x[:i+1]) for i in range(len(x))] ```
Sum consecutive numbers in a list. Python
[ "", "python", "function", "numbers", "sum", "" ]
Having a very simple table: ``` CREATE TABLE users ( name VARCHAR(50) NOT NULL, registered TIMESTAMP NOT NULL, CONSTRAINT users_pk PRIMARY KEY (name) ); ``` How to select the number of user registrations in each month e.g. ``` Jan 2010 - 19, Feb 2010 - 0, Mar 2010 - 7 ```
To get those zero entries you need to join across `generate_series`: ``` select to_char(gen_month, 'Mon YYYY'), count(name) FROM generate_series(DATE '2010-01-01', DATE '2010-04-01', INTERVAL '1' MONTH) m(gen_month) LEFT OUTER JOIN users ON (registered BETWEEN gen_month AND gen_month + INTERVAL '1' MONTH - INTER...
``` SELECT MONTH(registered),YEAR(registered),COUNT(name), FROM users GROUP BY YEAR(registered), MONTH(registered) ```
Select count of users registered in each month
[ "", "sql", "postgresql", "" ]
See [here](https://stackoverflow.com/q/3217673/340947) for related discussion on the merits of the various option and arg parsing choices we have in Python. I'm making a diff script that does neat things with the output of Python's `difflib`, and part of what that involves is handling the different ways that it can be...
You could define a [custom Action](http://docs.python.org/2/library/argparse.html#action) for this, though its really not that different than post-processing `args` yourself unless you have many such arguments that would require this action: ``` import argparse class TwoOrSeven(argparse.Action): def __call__(self...
Just add an argument that has no dashes in front of it. ``` import argparse parser = argparse.ArgumentParser() # You can change nargs to '+' for at least one argument parser.add_argument('positional', nargs=2) # Positionals have no dashes parser.add_argument('second_positional', nargs=1) parser.add_arguemnt('--option...
Python argparse: How to get simple parsing behavior?
[ "", "python", "command-line", "command-line-arguments", "argparse", "" ]
I'm trying to convert C++ code to python but I'm stuck original C++ code ``` int main(void) { int levels = 40; int xp_for_first_level = 1000; int xp_for_last_level = 1000000; double B = log((double)xp_for_last_level / xp_for_first_level) / (levels - 1); double A = (double)xp_for_first_level / (ex...
For the last line, you can simply use: ``` print(i, new_xp - old_xp) ``` As @pfnuesel commented, you will need to adjust the range of your for loop slightly. Finally, you don't need `import math`. You can replace the first 3 lines with: ``` from math import log, exp ```
Change the `print` line to: ``` print("%i %i" % (i, new_xp - old_xp)) ``` Refer to this [list of allowed type conversion specifiers](http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) for more informations. Or use the new [format](http://docs.python.org/3/library/functions.html#format) me...
python code to calculate xp for a project
[ "", "python", "python-3.x", "" ]
I have to control a modbus device with a serial interface. I have no experience with modbus, but my short research revealed several modbus libraries * [pymodbus](https://pypi.python.org/pypi/pymodbus) * [MinimalModbus](https://pypi.python.org/pypi/MinimalModbus/) * [Modbus-tk](https://github.com/ljean/modbus-tk) * [uM...
About the same time I faced the same problem - which library to choose for python modbus master implementation but in my case for serial communication (modbus RTU) so my observations are only valid for modbus RTU. In my examination I didn't pay too much attention to documentation but examples for serial RTU master wer...
I just discovered [uModbus](https://github.com/AdvancedClimateSystems/uModbus), and for deployment in something like a Raspberry PI (or other small SBC), it's a dream. It's a simple single capable package that doesn't bring in 10+ dependencies like pymodbus does.
Python modbus library
[ "", "python", "modbus", "" ]
I have a python list containing multiple list: ``` A = [['1/1/1999', '3.0'], ['1/2/1999', '4.5'], ['1/3/1999', '6.8'], ...... ...... ['12/31/1999', '8.7']] ``` What I need is to combine all the values corresponding to each month, preferably in the form of a dictionary containing month...
``` from collections import defaultdict from datetime import date month_aggregate = defaultdict (list) for [d,v] in A: month, day, year = map(int, d.split('/')) date = date (year, month, 1) month_aggregate [date].append (v) ``` I iterate over each date and value, I pull out the...
Pandas is perfect for this, if you don't mind another dependency: For example: ``` import pandas import numpy as np # Generate some data dates = pandas.date_range('1/1/1999', '12/31/1999') values = (np.random.random(dates.size) - 0.5).cumsum() df = pandas.DataFrame(values, index=dates) for month, values in df.grou...
Aggregate Monthly Values
[ "", "python", "datetime", "" ]
From two columns in my table I want to get a unified count for the values in these columns. As an example, two columns are: Table: reports ``` | type | place | ----------------------------------------- | one | home | | two | school | | three | work | | ...
you can use `case` in this case - ``` SELECT type, sum(case when place = 'home' then 1 else 0 end) as Home, sum(case when place = 'school' then 1 else 0 end) as school, sum(case when place = 'work' then 1 else 0 end) as work, sum(case when place = 'cafe' then 1 else 0 end) as cafe, ...
Answer by praktik garg is correct, it is not necessary to use `else 0`: ``` SELECT type, sum(case when place = 'home' then 1 end) as home, sum(case when place = 'school' then 1 end) as school, sum(case when place = 'work' then 1 end) as work, sum(case when place = 'cafe' then 1 end)...
Postgresql Multiple counts for one table
[ "", "sql", "postgresql", "count", "group-by", "" ]
In MS SQL Server 2012 I have a database with a table containing a varchar column that holds some text that might even include line breaks. Basic example: ``` CREATE TABLE Example ( [ID] INT , [Text] VARCHAR(100) ); INSERT INTO Example ([ID], [Text]) VALUES (1, 'This is a test'), (2, 'This is an...
Use `Replace` to eliminate the line breaks through replacing with nothing (`''`). Then you can substract the lengh of the modified text from the original.
Try this : ``` select id, text,LEN(Text)-LEN(replace(text,char(10),''))+1 LinesOfText from Example ```
Get number of lines for specific varchar in MS SQL
[ "", "sql", "sql-server", "xml", "t-sql", "" ]
I'm a self taught programmer, and I just started using python. I'm having a bit of a problem, when I execute this code: ``` x = 0 while x == 0: question = raw_input("Would you like a hint? ") if question == "y" or "yes": print "Ok" first.give_hint("Look over there") x = 1 elif question == "n" or "no"...
The problem is this line: ``` if question == "y" or "yes": ``` `"yes"` will always evaluate to `True`. What you really want is: ``` if question == "y" or question == "yes": ``` Similar changes must be made for the other conditions.
You made a mistake in your if statement, this should be : ``` if (question == "y") or (question == "yes"): print "Ok" ``` Explanation : ``` (question == "y" or "yes") ``` is equivalent to : ``` (question == "y" or "yes" != 0) # operator 'or' having the prevalence ``` "yes" string being non-null, `("yes" !=...
If Statement and while loop
[ "", "python", "loops", "if-statement", "while-loop", "" ]
I have a statement that tries to insert a record and if it already exists, it simply updates the record. ``` INSERT INTO temptable (col1,col2,col3) VALUES (1,2,3) ON DUPLICATE KEY UPDATE col1=VALUES(col1), col2=VALUES(col2), col3=VALUES(col3); ``` The full statement has multiple inserts and I'm looking to count numbe...
From [Mysql Docs](http://dev.mysql.com/doc/refman/5.1/en/mysql-affected-rows.html) > In the case of "INSERT ... ON DUPLICATE KEY UPDATE" queries, the return value will be 1 if an insert was performed, or 2 for an update of an existing row. Use `mysql_affected_rows()` after your query, if `INSERT` was performed it wil...
I've accomplished what you're describing using a while loop so that each iteration creates a MySQL statement that affects one row. Within the loop, I run the mysql\_affected\_rows() and then increment a counter depending upon whether the value returned was a 0 or a 1. At the end of the loop, I echo both variables for v...
Getting count of insert/update rows from ON DUPLICATE KEY UPDATE
[ "", "mysql", "sql", "on-duplicate-key", "" ]
I have a database table of all US zip codes and their corresponding state and congressional district like this below.. ``` id | zipcode | state_abbr | district 1 30080 GA 1 2 30080 TN 2 ``` I need a query that will return any zipcodes that show up in more than one state. How ca...
``` SELECT zipcode FROM ( SELECT zipcode FROM temp GROUP BY zipcode, state_abbr ) AS t GROUP BY zipcode HAVING COUNT(*) > 1 ```
Try this sql. [SQL Fiddle](http://sqlfiddle.com/#!2/2fcb4/1) **MySQL 5.5.30 Schema Setup**: ``` CREATE TABLE Table1 (`id` int, `zipcode` int, `state_abbr` varchar(2), `district` int) ; INSERT INTO Table1 (`id`, `zipcode`, `state_abbr`, `district`) VALUES (1, 30080, 'GA', 1), (2, 30080, 'TN', 2) ; ``...
Database Query for Multiple Instances
[ "", "sql", "database", "" ]
``` Imports System.Data Imports System.Data.SqlClient Public Class Reservation Dim sqlConn As SqlConnection Private Sub Reservation_Load(sender As Object, e As EventArgs) Handles MyBase.Load sqlConn = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|EasyReserv.mdf;Integrated Secur...
This situation is quite common. Your connection string is `AttachDbFilename=|DataDirectory|EasyReserv.mdf`. This means that the MDF file, used by your program, is located in the folder pointed by the substitution string |DataDirectory| which is BIN\DEBUG or BIN folder depending if your application is an ASP.NET app o...
``` Try If con.State = ConnectionState.Open Then con.Close() con.Open() global_command = New SqlCommand("UPDATE products_tbl set running_no = '" & txt_running.Text & "' where template_code = 'n'and prod_no = '" & txt_product.Text & "'", con) global_command.ExecuteNonQuery() g...
Cannot update SQL Server with VB.net
[ "", "sql", "sql-server", "vb.net", "" ]
I have an application written in Django and I have to extend it and include some other solution as an "app" in this application. For example, my app to be integrated is named "my\_new\_app" Now there is a backend authentication written for the main application and I cannot use it. I have a MySQL DB to query from and ...
You *can* have multiple authentication backends. Just set the `AUTHENTICATION_BACKENDS` in `settings.py` of your Django project to list the backend implementations you want to use. For example I often use a combination of OpenID authentication and the standard Django authentication, like this in my `settings.py`: ``` ...
I've been through this problem before. This is the code I used. This is the authentication backend at the `api/backend.py` ``` from django.contrib.auth.models import User class EmailOrUsernameModelBackend(object): def authenticate(self, username=None, password=None): if '@' in username: kwarg...
Django Multiple Authentication Backend for one project
[ "", "python", "django", "authentication", "backend", "" ]
I would like to split a list at points where an item is over a certain length. a simplified version of my data is: ``` li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300] ``` the outcome I am trying to achieve is as below ``` new_li = [[1,2,3],[4000,5,6,7,8],[9000,10,11,12,1300]] ``` I am new to programming and a little ...
Something like this: ``` li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300] r = [[]] # start with a list containing an empty sub-list for i in li: if i >= 2000: # start a new sub-list when we see a big value r.append([i]) else: # append to the last sub-list of r r[-1].append(i) ```
``` from itertools import groupby li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300] class GroupbyHelper(object): def __init__(self, val): self.val = val self.i = 0 def __call__(self, val): self.i += (val > self.val) return self.i >>> [list(g) for k, g in groupby(li, key=GroupbyH...
Split a list into nested list at points where item matches criteria
[ "", "python", "list", "split", "" ]