Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the query below which seems to work, but it really feels like I should be able to do it in a simpler manner. Basically I have an orders table and a production\_work table. I want to find all orders which are not complete, meaning either there's no entry for the order in the production\_work table, or there are e...
The two queries in your UNION are almost identical so you can merge them into a single query as follows. I just changed the JOIN to the pw subquery to be a OUTER LEFT JOIN - which has the same reslut as your union because I incldued an additional OR clause in the WHERE statement to return these orders that dont have a ...
Here's the query I ended up with: ``` WITH work_totals AS ( SELECT p.order_id, SUM(p.ud + p.dp + p.swrv + p.sh + p.jmsw + p.sw + p.prrv + p.mhsw + p.bmsw + p.mp + p.pr + p.st) AS total FROM production_work p GROUP BY p.order_id ), order_totals AS ( SELECT ident, SUM(ud + dp + swrv + sh + jmsw + sw + pr...
SQL query too big - Can I merge this?
[ "", "sql", "postgresql", "optimization", "union", "" ]
I have this program that calculates the time taken to answer a specific question, and quits out of the while loop when answer is incorrect, but i want to delete the last calculation, so i can call `min()` and it not be the wrong time, sorry if this is confusing. ``` from time import time q = input('What do you want t...
If I understood the question correctly, you can use the slicing notation to keep everything except the last item: ``` record = record[:-1] ``` But a better way is to delete the item directly: ``` del record[-1] ``` Note 1: Note that using record = record[:-1] does not really remove the last element, but assign the ...
you should use this ``` del record[-1] ``` The problem with ``` record = record[:-1] ``` Is that it makes a copy of the list every time you remove an item, so isn't very efficient
How to delete last item in list?
[ "", "python", "time", "python-3.x", "" ]
I'm wondering if anybody can help me solve this question I got at a job interview. Let's say I have two tables like: ``` table1 table2 ------------ ------------- id | name id | name ------------ ------------- 1 | alpha 1 | alpha 3 | charlie 3 |...
``` select id,name--,COUNT(*) from( select id,name from table1 union all select id,name from table2 ) x group by id,name having COUNT(*)=1 ```
Well, you could use `UNION` instead of `OUTER JOIN`. ``` SELECT * FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id UNION SELECT * FROM table1 t1 RIGHT JOIN table2 t2 ON t1.id = t2.id ``` Here's a little trick I know: *not equals* is the same as XOR, so you could have your `WHERE` clause something like this: ``` W...
SQL how to simulate an xor?
[ "", "sql", "" ]
I generated a list of data from a CSV file. It came out as format as a list within a list: ``` Wind = [['284'], ['305'], ['335'], ['331'], ['318'], ['303'], ['294'], ['321'], ['324'], ['343']] ``` I need to list as regular list. So here is my attempt at solving this problem: ``` i = 0 for ii in Wind: Wind[i] = W...
You want to flatten the list, which can be done in python using a list comprehension (essentially a shorter, faster, version of a for loop). ``` Wind = [x for y in Wind for x in y] ``` The equivalent code using nested `for` loops would be: ``` newWind = [] for y in Wind: for x in y: newWind.append(x) ```
Another option, using itertools: ``` import itertools newWind = list(itertools.chain.from_iterable(Wind)) ``` and another one using numpy: ``` import numpy newWind = numpy.array(Wind).transpose()[0].tolist() ``` and one using a list comprehension that assumes there will always be only one element in the inner lists...
List elements within a list
[ "", "python", "list", "python-3.x", "" ]
I am making a small database at the moment (less than 50 entries) and I am having trouble with a query. My query at the moment is ``` SELECT Name FROM Customers WHERE Name LIKE '%Adam%' ``` The names are in the format of "Adam West". The query works fine in retrieving all the people with "Adam" in their name but I...
SELECT Name FROM Customers WHERE Name LIKE 'Adam%'
if you are storing name with space as separator example "Adam abcd" where 'Adam' is firstname and 'abcd' as lastname then following will work ``` SELECT Expr1 FROM (SELECT LEFT(Name, CHARINDEX(' ', Name, 1)) AS Expr1 FROM Customers) AS derivedtbl_1 WHERE (Expr1 LIKE ...
SQL - retrieval query for specific string
[ "", "sql", "" ]
I have this mysql query for Drupal 6. However it doesn't return distinct nid as it is meant to be. Can someone help identify the bug in my code? ``` SELECT DISTINCT( n.nid), pg.group_nid, n.title, n.type, n.created, u.uid, u.name, tn.tid FROM node n INNER JOIN users u on u.uid = n.uid LEFT JOIN og_primary_gr...
DISTINCT is meant to return the DISTINCT row selected, so not a single column as part of the select clause, but the ENTIRE select clause. [SELECT Syntax](http://dev.mysql.com/doc/refman/5.5/en/select.html) > The ALL and DISTINCT options specify whether duplicate rows should be > returned. ALL (the default) specifies ...
Remove "Distinct" from first line of your query because already you have distinct id's in where clause. Then it should work.
mysql distinct query not working
[ "", "mysql", "sql", "drupal", "" ]
I have captured four points(coordinate) of a plot using a gps device. Point 1:- lat- 27.54798833 long- 80.16397166 Point 2:- lat 27.547766, long- 80.16450166 point 3:- lat 27.548131, long- 80.164701 point 4:- --- now I want to save these coordinate in oracle database which save it as an polygon. Thanks
If you're intending to use Oracle Spatial for storage or processing of polygons, then you'll need to store the data as an `SDO_GEOMETRY` object. Here's a quick example: ``` CREATE TABLE my_polygons ( id INTEGER , polygon sdo_geometry ) / INSERT INTO my_polygons ( id , polygon ) VALUES ( 1 , sdo_geometry ( 2...
Create a table for a Polygon storing the Polygon details (PolygonId). Now create another table Coordinates and for the above PolygonID store the point locatins such as. ``` Polygoind Id Longitude Latitude ``` With this if you polygon is having n number or coordinates than also you can store it.And the ...
saving a polygon in oracle database
[ "", "sql", "oracle10g", "spatial", "oracle-spatial", "" ]
I am writing a SQL query using PostgreSQL that needs to rank people that "arrive" at some location. Not everyone arrives however. I am using a `rank()` window function to generate arrival ranks, but in the places where the arrival time is null, rather than returning a null rank, the `rank()` aggregate function just tre...
Just use a `case` statement around the `rank()`: ``` select Person, (case when arrival_time is not null then rank() over (partition by Restaurant order by arrival_time asc) end) as arrival_rank from dinner_show_up; ```
A more general solution for all aggregate functions, not only rank(), is to partition by 'arrival\_time is not null' in the over() clause. That will cause all null arrival\_time rows to be placed into the same group and given the same rank, leaving the non-null rows to be ranked relative only to each other. For the sa...
Ignoring null values in in a postgresql rank() window function
[ "", "sql", "postgresql", "" ]
I'm trying to practice OOP by making a class selection program ``` # let's make a character selection program class player: def __init__(self, username, age, weight, height, gender): self.username = username self.age = age self.weight = weight self.height = height ...
Since you assign attributes to your `player` in `__init__()`, they don't get created until `player` is instantiated. However, in your `soldier` class, you're trying to set *class* attributes *at class creation time* based on variables that don't exist at that time, because they only exist on instances (of a different c...
Soldier is a class, yet you haven't instantiated it anywhere. You've tried instantiating a player, with character\_obj, but when you attempt to print soldier.xxx it's looking at the class, not any object.
passing variables with inheritance
[ "", "python", "python-2.7", "" ]
I asked a question earlier, but I wasn't really able to explain myself clearly. I made a graphic to hopefully help explain what I'm trying to do. ![enter image description here](https://i.stack.imgur.com/o8w4s.png) I have two separate tables inside the same database. One table called 'Consumers' with about **200 fie...
``` INSERT INTO new_table SELECT * FROM (SELECT a.*, b.* FROM Consumers a INNER JOIN CustomerInfo b ON a.METER_NUMBER = b.METER and a.Location = b.Location WHERE a.METER_NUMBER IS NOT NULL AND a.METER_NUMBER <> 0 UNION ALL SELECT a.*, NULL as Meter, NULL as CustomerInfo_Location, NULL as Field2, NULL as Fi...
select \* into New\_Table From (select METER\_NUMBER,Consumers.Location AS Location,Field4,Field5,Meter,Customer\_Info.Location As Customer\_Info\_Location,Field2,Field3 From Consumers full outer Join Customer\_Info on Consumers.METER\_NUMBER=Customer\_Info.Meter And Consumers.Location=Customer\_Info.Location) AS t
How can I create a new table based on merging 2 tables without joining certain values?
[ "", "sql", "sql-server", "syntax", "" ]
Below is my query, I use four joins to access data from three different tables, now when searching for 1000 records it takes around 5.5 seconds, but when I amp it up to 100,000 it takes what seems like an infinite amount of time, (last cancelled at 7 hours..) Does anyone have any idea of what I am doing wrong? Or what...
Your test based on 100,000 rows is not meaningful if you are then going to run it for many millions. The optimiser knows that it can satisfy the query faster when it has a stopkey by using nested loop joins. When you run it for a very large data set you're likely to need a different plan, with hash joins most likely. ...
First of all, can you make sure there is an index on S\_CONTACT table and it is enabled ? If it is so, try the select statement with /\*+ CHOOSE \*/ hint and have another look at the explain plan to see if optimizer mode is still RULE. I believe cost based optimizer would result better in this query. If still rule tr...
Issues with Oracle Query execution time
[ "", "sql", "performance", "oracle", "" ]
I've install matplotlib in my virtualenv using pip. It was a failure at the beginning, but after I do `easy_install -U distribute`, the installation goes smoothly. Here is what I do (inside my git repository root folder): ``` virtualenv env source env/bin/activate pip install gunicorn pip install numpy easy_install -...
Finally I'm able to manage this. First of all, I use this buildpack: <https://github.com/dbrgn/heroku-buildpack-python-sklearn> To use this buildpack I run this (maybe it is not a necessary step): ``` heroku config:set BUILDPACK_URL=https://github.com/dbrgn/heroku-buildpack-python-sklearn/ ``` Then I change the requ...
For those currently looking this answer up, I just deployed on the lastest heroku with the latest matplotlib/numpy as a requirement (1.4.3, 1.9.2 respectively) without any issues.
Deploy matplotlib on heroku failed. How to do this correctly?
[ "", "python", "python-2.7", "heroku", "matplotlib", "" ]
Please see the code below: ``` Imports System.Data.SqlClient Imports System.Configuration Public Class Form1 Private _ConString As String Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim objDR As SqlDataReader Dim objCommand As...
You can look up the column by index, rather than by name. Either of the following would work: ``` id = objDR(0) id = objDR.GetInt32(0) ``` Otherwise, your best bet is the "As" keyword or double-quotes (which are the ansi standard) to create an alias.
In your case, becuase of the inner join, you do not need to include both in the select clause, as equality is required, so only include either one. So either ``` SELECT Person.URN FROM Person INNER JOIN Car ON Person.URN = Car.URN AND PersonID=1 ``` or ``` SELECT Car.URN FROM Person INNER JOIN ...
Alternative to the T-SQL AS keyword
[ "", "sql", "vb.net", "" ]
I want to transfer one table from my SQL Server instance database to newly created database on Azure. The problem is that insert script is 60 GB large. I know that the one approach is to create backup file and then load it into storage and then run import on azure. But the problem is that when I try to do so than whil...
You can use tools out there that make this very easy (point and click). If it's a one time thing, you can use virtually any tool ([Red Gate](http://cloudservices.red-gate.com), [BlueSyntax](http://bluesyntax.net/backup20.aspx)...). You always have [BCP](http://technet.microsoft.com/en-us/library/ms162802.aspx) as well....
I don't know that I'd ever try to execute a 60gb script. Scripts generally do single inserts which aren't very optimized. Have you explored using various bulk import/export options? <http://msdn.microsoft.com/en-us/library/ms175937.aspx/css> <http://msdn.microsoft.com/en-us/library/ms188609.aspx/css> If this is a one...
Import large table to azure sql database
[ "", "sql", "sql-server", "t-sql", "azure", "sql-server-2008-r2", "" ]
Given a simple string like `"@dasweo where you at?"` i would like to write a regular expression to extract the `"dasweo"`. What I have so far is: ``` print re.findall(r"@\w{*}", "@dasweo where you at?") ``` This does not work though. Can anyone help me with this?
Since you don't want the `@` to be included in the match, you can use a [positive lookbehind](http://www.regular-expressions.info/lookaround.html): ``` >>> import re >>> re.findall(r"(?<=@)\w+", "@dasweo where you at?") ['dasweo'] ``` In general, a regex of the form `(?<=X)Y` matches `Y` that is preceded by `X`, but ...
Drop the `{..}` curly braces, they are not used with `*`: ``` >>> re.findall(r"@\w*", "@dasweo where you at?") ['@dasweo'] ``` Only use `{..}` quantifiers with fixed numbers: ``` \w{3} ``` matches exactly 3 letters, for example.
Simple regex to get a twitter username from a string
[ "", "python", "regex", "" ]
I have been stuck into a question. The question is I want to get all Table name with their Row Count from Teradata. I have this query which gives me all View Name from a specific Schema. I ] `SELECT TableName FROM dbc.tables WHERE tablekind='V' AND databasename='SCHEMA' order by TableName;` & I have this query which...
This is a SP to collect row counts from all tables within a database, it's very basic, no error checking etc. It shows a cursor and dynamic SQL using dbc.SysExecSQL or EXECUTE IMMEDIATE: ``` CREATE SET TABLE RowCounts ( DatabaseName VARCHAR(30) CHARACTER SET LATIN NOT CASESPECIFIC, TableName VARCHAR(...
Use dnoeth's answer but instead use create "create volatile table" this will use your spool to create the table and will delete all data when your session is closed. **You need no write access to use volatile tables.**
Select all Table/View Names with each table Row Count in Teredata
[ "", "sql", "teradata", "rowcount", "tablename", "dynamic-queries", "" ]
I'm currently having terrible Problems with SQL, I am trying to calculate certain values, similiar to the ex. below: ``` SELECT Sum(OrdersAchieved)/ Sum(SaleOpportunities) as CalculatedValue FROM ( SELECT Count(OT.SalesOpportunity) AS SaleOpportunities Count(VK.Orders) AS OrdersAchieved ...
``` select 2/7 as Value ``` ...using two integers means integer division, which is correct as 0. ``` select 2.0/7 as Value ``` ...using at least one floating point type gives 0.285714 which is what you seem to be looking for. In other words, cast either of the operands to float, and the division will give the resul...
Try to convert both values before dividing ``` select convert(float,2)/convert(float,7) as Value ``` or one of them ``` select convert(float,2)/7 as Value select 2/convert(float,7) as Value ```
SQL: Only Rounded numbers shown, everything else: Useless
[ "", "sql", "numbers", "rounding", "division", "" ]
The [documentation](http://docs.python.org/2/library/functions.html#open) states that the default value for buffering is: `If omitted, the system default is used`. I am currently on Red Hat Linux 6, but I am not able to figure out the default buffering that is set for the system. Can anyone please guide me as to how d...
Since you linked to the 2.7 docs, I'm assuming you're using 2.7. (In Python 3.x, this all gets a lot simpler, because a lot more of the buffering is exposed at the Python level.) All `open` actually does (on POSIX systems) is call `fopen`, and then, if you've passed anything for `buffering`, `setvbuf`. Since you're no...
I'm not sure it's the right answer but [python 3.0 library](https://docs.python.org/3.0/library/io.html) and [python 20 library](https://docs.python.org/2/library/io.html) both describe `io.DEFAULT_BUFFER_SIZE` in the same way that the default is described in the docs for `open()`. Coincidence? If not, then the answer...
Default buffer size for a file on Linux
[ "", "python", "linux", "file", "buffer", "rhel6", "" ]
I've been learning Python lately and tonight I was playing around with a couple of examples and I just came up with the following for fun: ``` #!/usr/bin/env python a = range(1,21) # Range of numbers to print max_length = 1 # String length of largest number num_row = 5 # Number of elements per row for l...
* You don't need to make `format_string` every time. Using [str.rjust](http://docs.python.org/2/library/stdtypes#str.rjust), you don't need to use format string. * Instead of using `x % num_row` (an element of list), use `i` (1-based index using `enumerate(a, 1)`). Think about a case `a = range(3, 34)`. + You can dro...
I think you could do more pythonic calculation of maxlength :) ``` max_length = len(str(max(a))) ``` if your numbers could be negative or float ``` max_length = max([len(str(x)) for x in a]) ```
Thinking Python
[ "", "python", "optimization", "formatting", "" ]
I want to covert varchar (50) column to date format. I used following code: ``` Update [dbo].[KYCStatus062013] Set [REGISTRATION_DATE_]= convert(datetime,[REGISTRATION_DATE_] ,103) ``` But there is an error that says: > Msg 241, Level 16, State 1, Line 1 Conversion failed when converting > date and/or time from cha...
Try this one. ``` Update [dbo].[KYCStatus062013] Set [REGISTRATION_DATE_]= REPLACE(CONVERT(VARCHAR(11),[REGISTRATION_DATE_],106),' ' ,'-') ``` this will give output as dd-mmm-yyyy if you want to update as date format then you have to modify your table. Edit 1 = ``` Update [dbo].[KYCStatus062013] Set [REGISTR...
The error suggests that one of the values in your table does not match the 103 format and cannot be converted. You can use the ISDATE function to isolate the offending row. Ultimately the error means your table has bad data, which leads to my main concern. Why don't you use a datetime or date data type and use a conver...
Convert varchar to date format
[ "", "sql", "sql-server", "t-sql", "type-conversion", "" ]
**Question** I am having trouble figuring out how to create new DataFrame column based on the values in two other columns. I need to use if/elif/else logic. But all of the documentation and examples I have found only show if/else logic. Here is a sample of what I am trying to do: **Code** ``` df['combo'] = 'mobile' ...
In cases where you have multiple branching statements it's best to create a function that accepts a row and then apply it along the `axis=1`. This is usually much faster then iteration through rows. ``` def func(row): if row['mobile'] == 'mobile': return 'mobile' elif row['tablet'] =='tablet': ...
I tried the following and the result was much faster. Hope it's helpful for others. ``` df['combo'] = 'other' df.loc[df['mobile'] == 'mobile', 'combo'] = 'mobile' df.loc[df['tablet'] == 'tablet', 'combo'] = 'tablet' ```
Create Column with ELIF in Pandas
[ "", "python", "pandas", "" ]
In C++, two things can happen in the same line: something is incremented, and an equality is set; i.e.: ``` int main() { int a = 3; int f = 2; a = f++; // a = 2, f = 3 return 0; } ``` Can this be done in Python?
Sure, by using multiple assignment targets: ``` a, f = f, f + 1 ``` or by just plain incrementing `f` on a separate line: ``` a = f f += 1 ``` because readable trumps overly clever. There is no `++` operator because integers in Python are immutable; you rebind the name to a new integer value instead.
No var`++` equivalent in python. ``` a = f f += 1 ```
What's the Python equivalent of C++'s "a = f++;", if any?
[ "", "python", "syntax", "" ]
I have an ndb.Model that has a ndb.DateTimeProperty and a ndb.ComputedProperty that uses the ndb.DateTimeProperty to create a timestamp. ``` import time from google.appengine.ext import ndb class Series(ndb.Model): updatedDate = ndb.DateTimeProperty(auto_now=True) time = ndb.ComputedProperty(lambda self: time...
After further investigation into this issue, to avoid the default value from being evaluated when the module is imported. I have just gone with setting the initial value of `updatedDate` when creating a new `Series`. ``` import datetime series = Series(updatedDate = datetime.datetime.now()) series.put() ``` I would h...
Figured out the problem, it was actually a simple solution. I simply edited the line ``` updatedDate = ndb.DateTimeProperty(auto_now=True) ``` To include the default parameter ``` updatedDate = ndb.DateTimeProperty(auto_now=True, default=datetime.datetime.now()) ``` Also had to import the datetime module ``` impor...
ndb.ComputedProperty from ndb.DateTimeProperty(auto_true=now) first call error
[ "", "python", "google-app-engine", "datetime", "" ]
I have the following tables (unrelated columns left out): ``` games: id 1 2 3 4 bets: id | user_id | game_id 1 | 2 | 2 2 | 1 | 3 3 | 1 | 4 4 | 2 | 4 users: id 1 2 ``` I have "games" on which "users" can place "bets". Every user can have a maximum of one bet on any single ga...
You have to use LEFT JOIN, but you also have to put the conndition for user into your JOIN and not WHERE, otherwise will not work. So like this: ``` SELECT g.id AS game_id, b.id AS bet_id FROM games g LEFT OUTER JOIN bets b ON g.id=b.game_id AND b.user_id = 1 ```
have you tried this one? ``` SELECT a.id GameID, b.id BetID FROM Games a LEFT JOIN bets b ON a.id = b.game_id AND b.user_id = 1 -- <<== ID of the User ORDER BY a.ID ASC ```
SQL joins - Games where Users can place Bets
[ "", "sql", "join", "left-join", "" ]
I have a list of dictionaries: ``` lis = [{'score': 7, 'numrep': 0}, {'score': 2, 'numrep': 0}, {'score': 9, 'numrep': 0}, {'score': 2, 'numrep': 0}] ``` How can I format the output of a `print` function: ``` print(lis) ``` so I would get something like: ``` [{7-0}, {2-0}, {9-0}, {2-0}] ```
A list comp will do: ``` ['{{{0[score]}-{0[numrep]}}}'.format(d) for d in lst] ``` This outputs a list of strings, so *with* quotes: ``` ['{7-0}', '{2-0}', '{9-0}', '{2-0}'] ``` We can format that a little more: ``` '[{}]'.format(', '.join(['{{{0[score]}-{0[numrep]}}}'.format(d) for d in lst])) ``` Demo: ``` >>>...
``` l = [ {'score': 7, 'numrep': 0}, {'score': 2, 'numrep': 0}, {'score': 9, 'numrep': 0}, {'score': 2, 'numrep': 0} ] keys = ['score', 'numrep'] print ",".join([ '{ %d-%d }' % tuple(ll[k] for k in keys) for ll in l ]) ``` *Output:* ``` { 7-0 },{ 2-0 },{ 9-0 },{ 2-0 } ```
List of dictionaries - how to format print output
[ "", "python", "" ]
I know ruby pretty well, but I've never used python before. There's this great [python script called colorific](https://github.com/99designs/colorific). I've checked this script out in the lib folder in my rails app and installed the rubypython gem. I was wondering how I now import this sciprt into the app, so far I'...
> colorific is a command-line utility. It doesn't appear to provide an > API to import. I'd not use a Ruby-to-Python bridge here, just run the > tool using the Ruby equivalent of the Python subprocess module; as a > separate process. (Martijin Pieters) The colorific test suite itself imports colorific, and there is a ...
Your original code needed a few extra lines: ``` RubyPython.start # start the Python interpreter sys = RubyPython.import("sys") # (add) method used to search for a directory sys.path.append('./lib/colorific') # (add) execute search in directory RubyPython.import("setup") # (add) call on setup.py in the directory RubyP...
Using the rubypython gem in ruby on rails, how do you call a python script from the lib folder?
[ "", "python", "ruby-on-rails", "ruby", "rubygems", "rubypython", "" ]
I have a mysql table with visitor\_id, country, time\_of\_visit. I want to get the average duration of visit by country. To get duration, I get the difference between the earliest and latest time\_of\_visit for each visitor\_id. So this gets me the average duration of all visits: ``` SELECT AVG(duration) FR...
You have to select the country column in your subquery and then have to reference the country field from the derived table `tracker.country` ``` SELECT tracker.country, AVG(tracker.duration) FROM ( SELECT TIMESTAMPDIFF(SECOND, MIN(time_of_visit), MAX(time_of_visit))/60 as duration ,country FROM tracker GROUP BY...
You need to specify the column in the subquery which you want to show it in the outer query Try this:: ``` SELECT country, AVG(duration) FROM ( SELECT TIMESTAMPDIFF(SECOND, MIN(time_of_visit), MAX(time_of_visit))/60 as duration, country FROM tracker GROUP BY visitor_id ) as tracker GROUP BY country ``` You can al...
MySql subquery: average difference, grouped by column
[ "", "mysql", "sql", "group-by", "subquery", "" ]
I recently asked [this question](https://stackoverflow.com/questions/18084769/search-for-sub-directory-python) and got a wonderful answer to it involving the `os.walk` command. My script is using this to search through an entire drive for a specific folder using `for root, dirs, files in os.walk(drive):`. Unfortunately...
If you're just looking for a small constant improvement, there are ways to do better than `os.walk` on most platforms. In particular, `walk` ends up having to `stat` many regular files just to make sure they're not directories, even though the information is (Windows) or could be (most \*nix systems) already available...
Use [subprocess.Popen](http://docs.python.org/2/library/subprocess.html#popen-constructor) to start a native 'find' process.
Quickly Search a Drive with Python
[ "", "python", "python-2.7", "" ]
I have a pretty ridiculous looking somewhat list like this. ``` [['Biking', '10'], ['Biking|Gym', '14'], ['Biking|Gym|Hiking', '9'], ['Biking|Gym|Hiking|Running', '27']] ``` I'd like to get it into a format of ['Type', total, %], like this: ``` [['Biking',60,'34.7%'],['Gym',50,'28.9%'],['Hiking',36,'20.8%'],['Runnin...
Given an initial list like ``` >>> test_list = [['Biking', '10'], ['Biking|Gym', '14'], ['Biking|Gym|Hiking', '9'], ['Biking|Gym|Hiking|Running', '27']] ``` You could first make up a `defaultdict` for summing up the values (getting the second element of your final result), something like ``` >>> from collections imp...
You can use a `collections.defaultdict` here. A dict is a better data-structure here as you can access values related to any `'Type'` in `O(1)` type. ``` >>> from collections import defaultdict >>> lis = [['Biking', '10'], ['Biking|Gym', '14'], ['Biking|Gym|Hiking', '9'], ['Biking|Gym|Hiking|Running', '27']] >>> ...
Grouping and totaling a pipe separated list
[ "", "python", "django", "" ]
I know d[key] will take the 'd' items and return them as keys, but if I only use d[key] I always get a keyerror. I've only seen it been used with .get(). For example I saw another question on here that I copied to study from: ``` myline = "Hello I'm Charles" character = {} for characters in myline: character[cha...
The KeyError is raised **only** if the key is not present in the dict. `dict.get` is interpreted as: ``` >>> print dict.get.__doc__ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. ``` In your particular example, you're trying to calculate count of each character. As the dict is initially empty, so you n...
`dict.get(a,b)` means if key a is not in dict, will return value `b`, else return the value of key `a`. While `d[key]` get the value of key, but if key is not in dict it will raise a keyerror
Does the d[key] operation always have to be used with .get()?
[ "", "python", "key", "" ]
I have a table which stores chat messages for users. Every message is logged in this table. I have to calculate chat duration for a particular user. Since there is a possibility that user is chatting at x time and after x+10 times he leaves chatting. After X+20 time, again user starts chatting. So the time period betw...
first need to calculate the gap between adjacent messages, if the gap of more than 600 seconds, so the time between these messages 0 ``` SELECT SUM(o.duration) / 60.00 AS duration FROM dbo.tbl_chatMessages t1 OUTER APPLY ( SELECT TOP 1 CASE WHEN DATEDIFF(second, t2.messageTime, t1.me...
Here is the reasoning behind my solution. First, identify each chat that *starts* a chatting period. You can do this with a flag that identifies a chat that is more than 10 minutes from the previous chat. Then, take this flag and do a cumulative sum. This sum actually serves as a grouping identifier for the chat perio...
SQL Server 2008 : how to select sum of all sessions where difference between two consecutive sessions is less than 10 minutes
[ "", "sql", "sql-server", "sql-server-2008", "" ]
So I have made a python spider which gets all links from given site and then prints out that one which contains `'impressum'` in itself. Now I wanted to make an `elif` function which prints out link that contains `'kontakt'` in istelf if that one with `'impressum'` was not found in links. My code for now looks like thi...
You see both links because they are occurring in separate iterations of the `for` loop. A single `if` block only looks at a single URL, and the `elif` makes sure that single URL isn't printed twice in case it contains both `"impressum"` and `"kontakt"`. It doesn't prevent more links from being printed in later iteratio...
I *think* I understand what you're trying to achieve, you only want to print one of those URLs per page; always print the `impressum` link even if `kontakt` is also on the page, and in the case `impressum` isn't on the page then print `kontakt`, correct? If so, you could either add a flag to say whether `impressum` is...
Python, if 'word' is in link print link else if '2ndword' in link print that one
[ "", "python", "loops", "if-statement", "hyperlink", "" ]
I have the following DataFrame: ``` a b c b 2 1 2 3 5 4 5 6 ``` As you can see, column `b` is used as an index. I want to get the ordinal number of the row fulfilling `('b' == 5)`, which in this case would be `1`. The column being tested can be either an index column (as with `b` in this case) or a regula...
You could use [np.where](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html#numpy-where) like this: ``` import pandas as pd import numpy as np df = pd.DataFrame(np.arange(1,7).reshape(2,3), columns = list('abc'), index=pd.Series([2,5], name='b')) print(df) # a ...
Use [Index.get\_loc](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html) instead. Reusing @unutbu's set up code, you'll achieve the same results. ``` >>> import pandas as pd >>> import numpy as np >>> df = pd.DataFrame(np.arange(1,7).reshape(2,3), columns = list('abc')...
Getting the integer index of a Pandas DataFrame row fulfilling a condition?
[ "", "python", "numpy", "pandas", "" ]
The reason I want to this is I want to use the tool `pyobfuscate` to obfuscate my python code. But`pyobfuscate` can only obfuscate one file.
I've answered your direct question separately, but let me offer a different solution to what I suspect you're actually trying to do: Instead of shipping obfuscated source, just ship bytecode files. These are the `.pyc` files that get created, cached, and used automatically, but you can also create them manually by jus...
There are a definitely ways to turn a tree of modules into a single module. But it's not going to be trivial. The simplest thing I can think of is this: First, you need a list of modules. This is easy to gather with the `find` command or a simple Python script that does an `os.walk`. Then you need to use `grep` or Py...
Is there a way to combine a python project codebase that spans across different files into one file?
[ "", "python", "obfuscation", "" ]
I need to check a condition for all the items in two 1-dimensional lists For example: ``` L = [12,23,56,123,13,15] B = [45,89,12,45,19,89] ``` For the above two lists, how do I need to check the condition `if(L[i] > (float(B[i]*1.1)))` where 'i' is the index's starting from index 0 to all the items in the lists (in ...
In order to print the ones who are matching, you could use ``` matching = (l > float(b * 1.1) for l, b in zip(L, B)) ``` This gives you a generator which you can use as you want. E.g.: ``` for m, l in zip(matching, L): if m: print l ``` But you could as well directly generate an iterator of matching one...
If I understood you right, you can do this with generator expression and [zip](http://docs.python.org/2/library/functions.html#zip) function ``` L = [12,23,56,123,13,15] B = [45,89,12,45,19,89] all(x[0] > (x[1]*1.1) for x in zip(L, B)) ``` or, as Ashwini Chaudhary suggested in comments, with values unpacking: ``` L ...
to check a condition for all the items in two list in python
[ "", "python", "list", "" ]
I have a very complex table which is like this :- ``` Snos Column1 Column2 Column3 Column4 Column5 Column6 1 AD AD1 C1 2011 P1 6435200 2 AD AD1 C1 2010 P1 234 3 AD AD1 C1 2009 P1 6435 4 BD AD2 C2 2010 P2 19844...
Here is an example of query you could use : ``` insert into tablename (Column1, Column2, Column3, Column4, Column5, Column6) select "BD","AD2","C2", column4,"P2","0" from tablename where column4 in (select distinct column4 from test) and column4 not in (select distinct column4 from test where column5 = "P2"); ```
First, I am ignoring the `Snos` column. This looks like an auto-numbered identity column. The ordering should not make a difference for such a column. The idea is to insert each group of rows (for a given year) independently. The following query, for instance, finds the rows needed for 2009. These are the rows that --...
Inserting Duplicate rows by updating its value in MYSQl
[ "", "mysql", "sql", "duplicates", "" ]
We have a table in Oracle with a BLOB column that needs to be filled with a small amount of arbitrary byte data--we will never put in more than 4000 bytes of data. I am working with an existing C++ OCI-based infrastructure that makes it extremely difficult to use bind variables in certain contexts, so I need to popula...
Apparently you can exceed these limits if you use PL/SQL. It doesn't work if you do the `HEXTORAW` within the `UPDATE` statement directly, either--it needs to be done in a separate statement, like this: ``` DECLARE buf RAW(4000); BEGIN buf := HEXTORAW('C2B97041074...lots of hex...0CC00CD00'); UPDATE MyTable ...
To update a `BLOB` longer than 16383 bytes something like this may by used (each line has even number of hex digits up to 32766): ``` DECLARE buf BLOB; BEGIN dbms_lob.createtemporary(buf, FALSE); dbms_lob.append(buf, HEXTORAW('0EC1D7FA6B411DA58149')); --...lots of hex data... dbms_lob.append(buf, HEXTORAW('...
Oracle 10: Using HEXTORAW to fill in blob data
[ "", "sql", "oracle", "blob", "varbinary", "" ]
I've been doing this for a while: ``` x = x if x else y ``` In all sorts of contexts where x might be `None`, `False`, `0`, `''`, `[]`, or `{}`. I know the purists would rather I: ``` if not x: x = y ``` but forget that, that's not my question. **My question** is: Is there anything 'wrong' with `x = x if x el...
There is nothing wrong with using ternary for `x = x if c else y`, however, in the case of `x = x if x else y` the logic really does just reduce to ``` x = x or y ``` This is because in Python `x or y` evaluates to ['if x is false, then y, else x'](http://docs.python.org/2/library/stdtypes.html#boolean-operations-and...
Nope, nothing wrong with it. It's very pythonic in fact. I recall reading that that's the preferred (by Guido himself) ternary-equivalent. I'll see if I can dig up the reference. Personally, I find the other way more readable, but you didn't ask for my personal opinon. ;) UPDATE: Here's the citation. Core Python P...
self-referencing ternary
[ "", "python", "idioms", "ternary", "" ]
I'm trying to play some .flac files using PySide's Phonon module (on Mac if it makes a difference) but it's not an available mimetype for playback. Is there a way to enable this or a plugin I need to install?
[Phonon](http://qt-project.org/doc/qt-4.8/phonon-overview.html#phonon-overview) does not directly support audio formats but uses the underlying OS capabilities. The answer therefore depends on if there is a service registered for the mime type `audio/flac`. For me there is and here is a short example script to find out...
You can play all the popular audio formats including flac using [Pydub](https://pypi.python.org/pypi/pydub) and [Pyaudio](https://pypi.python.org/pypi/PyAudio) Example code: ``` #-*- coding: utf-8 -*- from pydub import AudioSegment from pydub.utils import make_chunks from pyaudio import PyAudio from threading import ...
Is it possible to play FLAC files in Phonon?
[ "", "python", "qt", "pyside", "phonon", "flac", "" ]
Are there any helper methods to draw a rotated rectangle that is returned by [cv2.minAreaRect()](http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=minarearect#cv2.minAreaRect) presumably as `((x1,y1),(x2,y2),angle)`? [cv2.rectangle()](http://docs.opencv.org/modules/core...
``` rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) # cv2.cv.BoxPoints(rect) for OpenCV <3.x box = np.int0(box) cv2.drawContours(im,[box],0,(0,0,255),2) ``` should do the trick. sources: 1. <http://opencvpython.blogspot.in/2012/06/contours-2-brotherhood.html> 2. [Python OpenCV Box2D](https://stackoverflow.com/...
In extension to Tobias Hermann's answer: in case you don't have a contour, but a rotated rectangle defined by its center point, dimensions and angle: ``` import cv2 import numpy as np # given your rotated rectangle is defined by variables used below rect = ((center_x, center_y), (dim_x, dim_y), angle) box = cv2.cv.B...
OpenCV Python: Draw minAreaRect ( RotatedRect not implemented)
[ "", "python", "opencv", "" ]
I'm using the `sqlite3` python module to write the results from batch jobs to a common `.db` file. I chose SQLite because multiple processes may try to write at the same time, and as I understand it SQLite should handel this well. What I'm unsure of is what happens when multiple processes finish and try to write at the...
The `sqlite` library will lock the database *per process* when writing to the database and each process will wait for the lock to be released to get their turn. The database doesn't need to be written to until *commit* time however. You are using the connection as a context manager (good!) so the commit takes place af...
If each process holds it's own connection than it should be fine. What will happen is that when writing the process will lock the DB, so all other process will block. They will throw an exception if the timeout to wait for the DB to be free is exceeded. The timeout can be configured through the connect call: <http://d...
Concurrent writing with sqlite3
[ "", "python", "concurrency", "sqlite", "" ]
I have some code that I am trying to accelerate. My goal is to download and save about a million files. I am using the requests library to access the content. I am more confused then ever. Most of the Q/A suggest that the proper method is to use the threading module when a task is I/O bound and since I am connecting to...
Threading can get messy and require varible locking through mutexes. Your applications seems fit for multiprocessing which is simple to implement. Take your code and put it in a method say: ``` def download_and_save_the_file(some_url): thestring = requests.get(some_url).content #Make sure you create unique nam...
Either will work, but multiprocessing will be safer and perhaps easier to implement. Keep in mind that for Python in particular, the [Global Interpreter Lock](http://wiki.python.org/moin/GlobalInterpreterLock) means that multiple threads won't get much benefit from multiple cores, whereas with multiprocessing that's no...
Threading or Multiprocessing
[ "", "python", "multithreading", "" ]
I have a weird issue, which is probably easy to resolve. I have a class Database with an `__init__` and an `executeDictMore` method (among others). ``` class Database(): def __init__(self, database, server,login, password ): self.database = database my_conv = { FIELD_TYPE.LONG: int } self....
You have another `Database` module or package in your path somewhere, and it is getting imported instead. To diagnose where that other module is living, add: ``` import Database print Database.__file__ ``` before the `from Database import Database` line; it'll print the filename of the module. You'll have to rename ...
You should insert (not append) into your `sys.path` if you want it first in the search path: ``` sys.path.insert(0, '/path/to/your/Database/class') ```
instance has no attribute (python)
[ "", "python", "class", "attributeerror", "" ]
I have got stuck in writing the SQL stored prosedure in MS SQL Server Management Studio 2005 The table looks like following ``` [Quantity] | [Plant] 10 | Apple 20 | Carrot 30 | Lemon 40 | Orange ``` The procedure looks like that: ``` SELECT * FROM dbo.PLANTS where [Plant] in (@Name)...
You could do ``` SELECT * FROM dbo.PLANTS where (@Name='Fruits' and [Plant] in ('Apple', 'Lemon', 'Orange')) ``` If you'll want to select other things based on `@Name`, you could do that: ``` SELECT * FROM dbo.PLANTS where (@Name='Fruits' and [Plant] in ('Apple', 'Lemon', 'Orange')) or (@Name='Vegetables' an...
You could re-write it this way: ``` WHERE @Name = 'Fruits' AND Plant IN ('Apple','Lemon','Orange') ``` But much better would be to add a category to the other table and make a simpler join, this way you don't need to keep a list of fruits and a list of veggies hard-coded in your stored procedure.
Usage of multiple text names in CASE... WHEN Statement after THEN (SQL)
[ "", "sql", "sql-server-2005", "case", "case-when", "" ]
In Celery, you can `retry` any task in case of exception. You can do it like so: ``` @task(max_retries=5) def div(a, b): try: return a / b except ZeroDivisionError, exc: raise div.retry(exc=exc) ``` In this case, if you want to to divide by zero, task will be retied five times. But you have to...
I searched this issue for a while, but found only [this feature request](https://github.com/celery/celery/issues/1175). I decide to write my own decorator for doing auto-retries: ``` def task_autoretry(*args_task, **kwargs_task): def real_decorator(func): @task(*args_task, **kwargs_task) @functool...
Celery (since version 4.0) has exactly what you were looking for: ``` @app.task(autoretry_for=(SomeException,)) def my_task(): ... ``` See: <http://docs.celeryproject.org/en/latest/userguide/tasks.html#automatic-retry-for-known-exceptions>
How to implement autoretry for Celery tasks
[ "", "python", "celery", "" ]
Is there an efficient way to write a log-like function for a numpy array that gives `-inf` for negative numbers? The behaviour I would like is: ``` >>> log_inf(exp(1)) 1.0 >>> log_inf(0) -inf >>> log_inf(-1) -inf ``` with `-inf` returned for any negative numbers. *EDIT*: At the moment I am using `clip` to substit...
For numpy *arrays* you can calculate the log and then apply a simple mask. ``` >>> a=np.exp(np.arange(-3,3,dtype=np.float)) >>> b=np.log(a) >>> b array([-3., -2., -1., 0., 1., 2.]) >>> b[b<=0]=-np.inf >>> b array([-inf, -inf, -inf, -inf, 1., 2.]) ``` To save a bit of time and to have the option of calling in ...
You could use [`numpy.log`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html) with a conditional test for negative numbers: ``` import numpy as np def log_inf(x): return np.log(x) if x>0 else -float('Inf') log_inf(-1) -inf log_inf(0) -inf log_inf(np.exp(1)) 1.0 ``` With type checking: ``` def...
numpy: log with -inf not nans
[ "", "python", "numpy", "nan", "logarithm", "" ]
Is it possible to mock a return value of a function called within another function I am trying to test? I would like the mocked method (which will be called in many methods I'm testing) to returned my specified variables each time it is called. For example: ``` class Foo: def method_1(): results = uses_some...
There are two ways you can do this; with patch and with patch.object Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following ``` #foo.py def some_fn(): return 'some_fn' class Foo(object): def method_1(self): return some_...
This can be done with something like this: ``` # foo.py class Foo: def method_1(): results = uses_some_other_method() # testing.py from mock import patch @patch('Foo.uses_some_other_method', return_value="specific_value"): def test_some_other_method(mock_some_other_method): foo = Foo() the_value...
Using python's mock patch.object to change the return value of a method called within another method
[ "", "python", "unit-testing", "mocking", "patch", "" ]
I need to list all the states. For examples values in my state table is ``` 01 - Tamilnadu 2 - Andhra 03 - MP 4 - Kerala ``` etc.,, What i need is if the number before - is one digit then i have to append zero with it. For example andhra have only one digit i need it as 02 - Andhra during the selection else return t...
A possible solution if you need to fix digits while you do a `SELECT` ``` SELECT CASE WHEN state LIKE '[0-9] - %' THEN '0' + state ELSE state END state FROM states WHERE state IS NOT NULL ORDER BY Id DESC ``` Sample output: ``` state -------------- 01 - Tamilnadu 02 - Andhra 03 - M...
Please have a look at this. ``` SELECT state, CASE LENGTH(SUBSTRING_INDEX(state, '-', 1)) WHEN 1 THEN CONCAT('0', state) END AS changedstate FROM states WHERE state ID NOT NULL ORDER BY id desc; ``` Thank you
Find and replace it with new value in sql query in a column
[ "", "sql", "sql-server", "" ]
For example, after I set xlim, the ylim is wider than the range of data points shown on the screen. Of course, I can manually pick a range and set it, but I would prefer if it is done automatically. Or, at least, how can we determine y-range of data points shown on screen? plot right after I set xlim: ![plot right af...
This approach will work in case `y(x)` is non-linear. Given the arrays `x` and `y` that you want to plot: ``` lims = gca().get_xlim() i = np.where( (x > lims[0]) & (x < lims[1]) )[0] gca().set_ylim( y[i].min(), y[i].max() ) show() ```
To determine the y range you can use ``` ax = plt.subplot(111) ax.plot(x, y) y_lims = ax.get_ylim() ``` which will return a tuple of the current y limits. It seems however that you will probably need to automate setting the y limits by finding the value of y data at at your x limits. There are many ways to do this, ...
How to automatically set ylim from data shown on the screen after setting xlim
[ "", "python", "matplotlib", "plot", "" ]
I wonder what is the behaviour of Oracle regarding the subquery and the execution of the update and delete clause. I wonder if Oracle: 1. executes the subquery and for each row it executes the update and the delete clauses 2. executes the subquery for update and then executes the subquery for delete 3. 1) and 2), the...
Forgot to answer this issue. The issue is known and should be fixed with patch 11.2.0.4 (released Q4 2013). Oracle suggests the following temporary workaround : ``` alter session set "_complex_view_merging"=false;" ``` Or the hint `NO_MERGE`
The SQL standard guarantees three phases: 1. Computing the new values for all rows being updated (read-only phase) 2. Changes are applied all at once 3. Constraints are verified This means that all "subqueries" logically execute before the first write happens. This might be implemented using different physical plan s...
What is the execution order of Oracle MERGE INTO clauses with a subquery
[ "", "sql", "oracle", "" ]
I am trying my very first formal python program using Threading and Multiprocessing on a windows machine. I am unable to launch the processes though, with python giving the following message. The thing is, I am not launching my threads in the **main** module. The threads are handled in a separate module inside a class....
On Windows the subprocesses will import (i.e. execute) the main module at start. You need to insert an `if __name__ == '__main__':` guard in the main module to avoid creating subprocesses recursively. Modified `testMain.py`: ``` import parallelTestModule if __name__ == '__main__': extractor = parallelTestMod...
Try putting your code inside a main function in testMain.py ``` import parallelTestModule if __name__ == '__main__': extractor = parallelTestModule.ParallelExtractor() extractor.runInParallel(numProcesses=2, numThreads=4) ``` See the [docs](http://docs.python.org/2/library/multiprocessing.html): ``` "For an ex...
RuntimeError on windows trying python multiprocessing
[ "", "python", "windows", "multiprocessing", "" ]
Say we do: ``` class thing(object): pass ``` and then I do `>>> thing.__eq__`, then I get `<method-wrapper '__eq__' of type object at 0x0E8B68D0>`. But if we do `'__eq__' in dir(thing)`, I get an `NameError` exception saying that `__eq__` is not defined, but if its not defined, then how did I get a method wrapper...
`dir(thing)` returns a *list* of method names, all strings. Test with the actual string: ``` '__eq__' in dir(thing) ``` This will still return `False` as `dir()` only lists a summary of the most important methods. You'd have to additionally list everything on the metaclass of `thing` as well, which in this case is `t...
`dir` does not list all attributes: [The docs](http://docs.python.org/2/library/functions.html#dir) say: > The resulting list is not necessarily complete... > The default dir() mechanism behaves differently with different types > of objects, as it attempts to produce the most relevant, rather than > complete, informa...
Where is this protocol defined?
[ "", "python", "protocols", "" ]
I use MS Access (2003) database. Once I create a column I set NOT NULL using sql statement: ``` ALTER TABLE Table1 ALTER column myColumn INTEGER not null ``` Is there a way to change it back to allow null values? I already tried: ``` ALTER TABLE Table1 ALTER column myColumn INTEGER null ``` but nothing...
You cant specify `null` in `ALTER TABLE` (although `not null` is allowed) See the below [documentation](http://msdn.microsoft.com/en-us/library/office/bb177883%28v=office.12%29.aspx) and also this [discussion on this toppic](http://social.msdn.microsoft.com/Forums/office/en-US/5feef52c-85a8-4041-9c88-36aef2afe4cf/how-...
Try something like this using `MODIFY` :- ``` ALTER TABLE Table1 MODIFY myColumn INT NULL; ```
MS Access - sql expression for allow null?
[ "", "sql", "database", "ms-access", "alter-table", "alter-column", "" ]
I have the following json ``` { "response": { "message": null, "exception": null, "context": [ { "headers": null, "name": "aname", "children": [ { "type": "cluster-connectivity", ...
You have to follow the data structure. It's best to interactively manipulate the data and check what every item is. If it's a list you'll have to index it positionally or iterate through it and check the values. If it's a dict you'll have to index it by it's keys. For example here is a function that get's the context a...
`json['response']['context']` is a list, so *that* object requires you to use integer indices. Each item in that list is itself a dictionary again. In this case there is only *one* such item. To get all `"name": "health-state"` dictionaries out of that structure you'd need to do a little more processing: ``` [attr['...
Unable to pull data from json using python
[ "", "python", "json", "" ]
``` Here is some text here is line two of text ``` I visually select from `is` to `is` in Vim: (brackets represent the visual selection `[` `]`) ``` Here [is some text here is] line two of text ``` Using Python, I can obtain the range tuples of the selection: ``` function! GetRange() python << EOF import vim buf ...
Try this: ``` fun! GetRange() python << EOF import vim buf = vim.current.buffer (lnum1, col1) = buf.mark('<') (lnum2, col2) = buf.mark('>') lines = vim.eval('getline({}, {})'.format(lnum1, lnum2)) lines[0] = lines[0][col1:] lines[-1] = lines[-1][:col2] print "\n".join(lines) EOF endfun ``` You can use `vim.eval` t...
This would probably work if you used pure vimscript ``` function! GetRange() let @" = substitute(@", '\n', '\\n', 'g') endfunction vnoremap ,r y:call GetRange()<CR>gvp ``` This will convert all newlines into `\n` in the visual selection and replace the selection with that string. This mapping yanks the selectio...
Vim obtain string between visual selection range with Python
[ "", "python", "vim", "" ]
Assume I have 2 tables defined as follows: ``` Items ----- Id (Primary Key) ItemName ItemsTags ----- ItemId (Primary Key) TagName (Primary Key) ``` and filled with the following data: ``` Items ----- 1, Item1 2, Item2 3, Item3 ItemsTags -------- 1, Tag1 1, Tag2 1, Tag3 2, Tag3 3, Tag4 3, Tag5 ``` Assuming I want...
Another way to do the same: ``` SELECT DISTINCT Items.Id FROM Items WHERE Items.Id IN (SELECT ItemId FROM ItemsTags WHERE TagName = 'Tag1') AND Items.Id IN (SELECT ItemId FROM ItemsTags WHERE TagName = 'Tag3') ```
Try this: ``` SELECT DISTINCT i.Id FROM Items i INNER JOIN ItemsTags it1 ON i.Id = it1.ItemId and it1.TagName='Tag1' INNER JOIN ItemsTags it3 ON i.Id = it3.ItemId and it3.TagName='Tag3' ``` [Here](http://sqlfiddle.com/#!3/3be19/1)'s a SQL Fiddle.
SQL Where Clause with Joined Table - OR works, but AND Doesn't
[ "", "sql", "t-sql", "" ]
I have a Projects table with ID and Responsible manager. The Responsible manager columns has values as `John,Jim` for Project 1 and `Jim,Julie` for Project 2. But if I pass Jim to my stored procedure I should get 2 projects (1,2). This returns no rows because the column is `John,Jim` but SQL Server is looking for `='J...
``` WHERE ',' + Manager + ',' LIKE '%,Jim,%' ``` Or I suppose to match your actual code: ``` WHERE ',' + Manager + ',' LIKE '%,' + @Manager + ',%' ``` Note that your design is extremely flawed. There is no reason you should be storing names in this table at all, never mind a comma-separated list of any data points. ...
You may try the following: ``` SELECT DISTINCT ID, Manager FROM Projects WHERE ( (Manager LIKE @Manager + ',*') OR (Manager LIKE '*,' + @Manager) OR (Manager = @Manager) ) ``` That should cover both names and surnames, while still searching for literal values. Performance can...
Find manager in a comma-separated list
[ "", "sql", "sql-server-2008", "split", "" ]
For a built-in dialog like QInputDialog, I've read that I can do this: ``` text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:') ``` How can I emulate this behavior using a dialog that I design myself in Qt Designer? For instance, I would like to do: ``` my_date, my_time, ok = MyCustomDateT...
Here is simple class you can use to prompt for date: ``` class DateDialog(QDialog): def __init__(self, parent = None): super(DateDialog, self).__init__(parent) layout = QVBoxLayout(self) # nice widget for editing the date self.datetime = QDateTimeEdit(self) self.datetime.s...
I tried to edit the answer of [hluk](https://stackoverflow.com/users/454171/hluk) with the changes below but it got rejected, not sure why because it got some clear bugs as far is I can see. bugfix 1: removed *self.* from *self.layout.addWidget(self.buttons)* bugfix 2: connected OK and Cancel buttons to its correct a...
How can I show a PyQt modal dialog and get data out of its controls once its closed?
[ "", "python", "qt", "dialog", "pyqt", "modal-dialog", "" ]
If I have a `pandas.core.series.Series` named `ts` of either 1's or NaN's like this: ``` 3382 NaN 3381 NaN ... 3369 NaN 3368 NaN ... 15 1 10 NaN 11 1 12 1 13 1 9 NaN 8 NaN 7 NaN 6 NaN 3 NaN 4 1 5 1 2 NaN 1 NaN 0 NaN ``` I would like to calculate cumsum of th...
A simple Numpy translation of your Matlab code is this: ``` import numpy as np v = np.array([1., 1., 1., np.nan, 1., 1., 1., 1., np.nan, 1.]) n = np.isnan(v) a = ~n c = np.cumsum(a) d = np.diff(np.concatenate(([0.], c[n]))) v[n] = -d np.cumsum(v) ``` Executing this code returns the result `array([ 1., 2., 3., 0., 1....
Even more pandas-onic way to do it: ``` v = pd.Series([1., 3., 1., np.nan, 1., 1., 1., 1., np.nan, 1.]) cumsum = v.cumsum().fillna(method='pad') reset = -cumsum[v.isnull()].diff().fillna(cumsum) result = v.where(v.notnull(), reset).cumsum() ``` Contrary to the matlab code, this also works for values different from 1.
Cumsum reset at NaN
[ "", "python", "numpy", "pandas", "cumsum", "" ]
I'm a little confused with the results I'm getting with the logical operators in Python. I'm a beginner and studying with the use of a few books, but they don't explain in as much detail as I'd like. here is my own code: ``` five = 5 two = 2 print five and two >> 2 ``` It seems to be just outputting the two variab...
Python Boolean operators return the last value evaluated, not True/False. The [docs](http://docs.python.org/2/reference/expressions.html#boolean-operations) have a good explanation of this: > The expression `x and y` first evaluates `x`; if `x` is `false`, its value is returned; otherwise, `y` is evaluated and the res...
As a bit of a side note: (i don't have enough rep for a comment) The AND operator is not needed for printing multiple variables. You can simply separate variable names with commas such as `print five, two` instead of `print five AND two`. You can also use escapes to add variables to a print line such as `print "the var...
Python's Logical Operator AND
[ "", "python", "operator-keyword", "" ]
I have a table in MYSQL: ``` CREATE TABLE test.tem(a INT,b INT); ``` With below data: ``` INSERT INTO test.tem VALUES(1,2),(1,1),(1,NULL),(2,3); ``` Now the data should be: ``` +------+------+ | a | b | +------+------+ | 1 | 2 | | 1 | 1 | | 1 | NULL | | 2 | 3 | +------+------+ ``` I wan...
You don't have an unique column to identifies your rows. So your`JOIN` will probably update more rows as you think. --- You probably want something like that instead: ``` UPDATE tem AS t1 JOIN (SELECT a, MIN(b) AS m FROM tem GROUP BY a) AS t2 USING (a) SET t1.b = t2.m; ``` See <http://sqlfiddle.com/#!2/c6a04/1> --...
[Write it as a `JOIN` instead](http://sqlfiddle.com/#!2/762ec/1): ``` UPDATE tem JOIN ( SELECT a, MIN(b) AS min_b FROM tem GROUP BY a ) AS mins USING (a) SET tem.b = mins.min_b ; ```
how mysql update self table work
[ "", "mysql", "sql", "group-by", "sql-update", "" ]
i have the following mysql database table designed, ``` ticket(id, code, cust_name); passenger(id, ticket_id, name, age, gender, fare); service(id, passenger_id, item, cost); ``` A ticket can have many passenger and each passenger can have multiple services purchased. What I want is to get the grand total of each tic...
First of all in your current table schema you have no way to distinguish between services that have been sold to the same passenger in different tickets. Therefore you have no way to correctly calculate `total_cost` per ticket. You have to have `ticket_id` in your `service` table. Now, if you were to have a `ticket_id...
You can just join the three tables together, then you can do the SUMs directly without the subselect. You'll need to use `GROUP BY` to group by ticket.id if you want it per ticket. Something like: ``` SELECT t.id, SUM(p.fare) AS total_far, SUM(s.cost) AS total_cost FROM ticket t, passenger p, service s WHERE t.i...
SQL SUM operation of multiple subqueries
[ "", "mysql", "sql", "database", "" ]
I know that if I want to re-raise an exception, I simple use `raise` without arguments in the respective `except` block. But given a nested expression like ``` try: something() except SomeError as e: try: plan_B() except AlsoFailsError: raise e # I'd like to raise the SomeError as if plan_...
As of Python 3, the traceback is stored in the exception, so a simple `raise e` will do the (mostly) right thing: ``` try: something() except SomeError as e: try: plan_B() except AlsoFailsError: raise e # or raise e from None - see below ``` The traceback produced will include an addition...
Even if the [accepted solution](https://stackoverflow.com/a/18188660/1513933) is right, it's good to point to the [Six](https://pypi.org/project/six/) library which has a Python 2+3 solution, using [`six.reraise`](https://six.readthedocs.io/index.html#six.reraise). > six.**reraise**(*exc\_type*, *exc\_value*, *exc\_tr...
How to re-raise an exception in nested try/except blocks?
[ "", "python", "exception", "nested", "raise", "" ]
I am installing **virt-manager0.10.0** on Mac OS X First I installed python,libvirt, gtk+3, pygtk, and other dependencies with **homebrew** But when I run virt-manager I got this error ``` from gi.repository import GObject ImportError: No module named gi.repository ``` When I run this import in python command line ...
The `gi` module is in the `pygobject` package but if you install this package on OS/X, you won't get the `gi` module. To really install `gi` on OS/X you need to install `pygobject3` module which may look like it's for Python3 but it's not, the `3` comes from GTK version. So if you're on the OS/X, the simple `brew insta...
pyGTK is for GTK 2 only. If you want the python bindings for GTK 3, you need to install pyGObject. See <https://stackoverflow.com/a/9672426/518853>
ImportError: No module named gi.repository Mac OS X
[ "", "python", "gtk", "pygtk", "homebrew", "" ]
A numerical integration is taking exponentially longer than I expect it to. I would like to know if the way that I implement the iteration over the mesh could be a contributing factor. My code looks like this: ``` import numpy as np import itertools as it U = np.linspace(0, 2*np.pi) V = np.linspace(0, np.pi) for (u,...
If `U.shape == (nu,)` and `(V.shape == (nv,)`, then the following arrays vectorize most of your calculations. With numpy you get the best speed by using arrays for the largest dimensions, and looping on the small ones (e.g. 3x3). Corrected version ``` A = np.cos(U)[:,None]*np.sin(V) B = np.sin(U)[:,None]*np.sin(V) C ...
In ipython I did simple sum calculations on your 50 x 50 gridspace ``` In [31]: sum(u*v for (u,v) in it.product(U,V)) Out[31]: 12337.005501361698 In [33]: UU,VV = np.meshgrid(U,V); sum(sum(UU*VV)) Out[33]: 12337.005501361693 In [34]: timeit UU,VV = np.meshgrid(U,V); sum(sum(UU*VV)) 1000 loops, best of 3: 293 us per ...
Slow computation: could itertools.product be the culprit?
[ "", "python", "performance", "iteration", "mesh", "" ]
I am trying to extract java script from `google.com` using regular expression. **Program** ``` import urllib import re gdoc = urllib.urlopen('http://google.com').read() scriptlis = re.findall(r'<script>(.*?)</script>', gdoc) print scriptlis ``` **Output:** ``` [''] ``` Can any one tell me how to extract java scrip...
This works: ``` import urllib import re gdoc = urllib.urlopen('http://google.com').read() scriptlis = re.findall('(?si)<script>(.*?)</script>', gdoc) print scriptlis ``` The key here is `(?si)`. The "s" sets the "dotall" flag (same as `re.DOTALL`), which makes Regex match over newlines. That was actually the root of ...
If you don't have an issue with third party libraries, [`requests`](http://docs.python-requests.org/en/latest/) combined with [`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) makes for a great combination: ``` import requests from bs4 import BeautifulSoup as bs r = requests.get('http://www.goog...
Extract java script from html document using regular expression
[ "", "python", "regex", "" ]
I am having trouble figuring out how to make this work with substitution command, which is what I have been instructed to do. I am using this text as a variable: ``` text = 'file1, file2, file10, file20' ``` I want to search the text and substitute in a zero in front of any numbers less than 10. I thought I could do ...
You can use: ``` re.sub('[a-zA-Z]\d,', lambda x: x.group(0)[0] + '0' + x.group(0)[1:], s) ```
You can use `re.sub` with `str.zfill`: ``` >>> text = 'file1, file2, file10, file20' >>> re.sub(r'(\d+)', lambda m : m.group(1).zfill(2), text) 'file01, file02, file10, file20' #or >>> re.sub(r'([a-z]+)(\d+)', lambda m : m.group(1)+m.group(2).zfill(2), text) 'file01, file02, file10, file20' ```
using regular expression substitution command to insert leading zeros in front of numbers less than 10 in a string of filenames
[ "", "python", "regex", "expression", "regex-group", "" ]
I have this query ``` UPDATE f1 SET col = (SELECT ABS(300 + RANDOM() % 3600)) ``` that update the "col" column with a random number between 300 and 3600. But it returns the same random number for all the rows. Is there a way to update the rows with different random numbers?
It's using the same random number because the subquery only needs to run once for the UPDATE. In other words, the SQL engine knows that the inner SELECT only needs to be run once for the query; it does so, and uses the resultant value for each row. You actually don't need a subquery. This will do what you want: ``` U...
You can also try this which worked for me in oracle database. For Example, use query below if you want to have four digit random number using RPAD : `Update tableName set ColName=RPAD(round(dbms_random.value(0,9999)),4,'0');`
update table column with different random numbers
[ "", "sql", "sqlite", "" ]
I have started to learn python, and I would like to ask you about something which I considered a little magic in this language. I would like to note that before learning python I worked with PHP and there I haven't noticed that. What's going on - I have noticed that some call constructors or methods in Python are in ...
These are called [keyword arguments](http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments), and they're usually used to make the call more readable. They can also be used to pass the arguments in a different order from the declared parameters, or to skip over some default parameters but pass arguments ...
Specifying arguments by keyword often creates less risk of error than specifying arguments solely by position. Consider this function to compute loan payments: ``` def pmt(principal, interest, term): return **something**; ``` When one tries to compute the amortization of their house purchase, it might be invoked ...
Why a calling function in python contains variable equal to value?
[ "", "python", "" ]
In Python, if I `print` different data types separated by commas, they will all act according to their `__str__` (or possibly `__repr__`) methods, and print out a nice pretty string for me. I have a bunch of variables like `data1, data2...` below, and I would love to get their total approximate size. I know that: * n...
"A great solution would show me a way to return the string that print prints in Python 2.7." This is roughly what `print` prints (possibly extra spaces, missing final newline): ``` def print_r(*args): return " ".join((str(arg) for arg in args)) ``` If you run in to lots of objects that aren't `str`-able use ...
First of all, `sys.getsizeof()` is **not** the method to use to determine printed size. A python object *memory* footprint is a poor indicator for the number of characters required to represent a python object as a string. You are looking for `len()` instead. Use a simple generator expression plus `sum()` to get a tot...
Python print length OR getting the size of several variables at once
[ "", "python", "class", "python-2.7", "printing", "size", "" ]
I want to fill rainbow color under a curve. Actually the function matplotlib.pyplot.fill\_between can fill area under a curve with a single color. ``` import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 100, 50) y = -(x-50)**2 + 2500 plt.plot(x,y) plt.fill_between(x,y, color='green') plt.show() ``` ...
This is pretty easy to hack if you want "fill" with a series of rectangles: ``` import numpy as np import pylab as plt def rect(x,y,w,h,c): ax = plt.gca() polygon = plt.Rectangle((x,y),w,h,color=c) ax.add_patch(polygon) def rainbow_fill(X,Y, cmap=plt.get_cmap("jet")): plt.plot(X,Y,lw=0) # Plot so th...
If you mean giving some clever argument to "color=" I'm afraid this doesn't exist to the best of my knowledge. You could do this manually by setting a quadratic line for each color and varying the offset. Filling between them with the correct colors will give a rainbowish This makes a fun project to learn some python b...
How to fill rainbow color under a curve
[ "", "python", "matplotlib", "" ]
I have the following snippet code: ``` WHERE (Person.WorkGroupId = 2 or Person.RoleId = 2) ``` What I would like to happen is for this to return the first occurrence with a `WorkGroupId` of 2 on Person table. But, if there is not a person with a `WorkgroupId` of 2, then choose the first occurrence with `RoldId` of 2 ...
``` SELECT TOP (1) * FROM ( SELECT TOP (1) *, o = 1 FROM Person WHERE WorkGroupId = 2 UNION ALL SELECT TOP (1) *, o = 2 FROM Person AND RoleId = 2 ) AS x ORDER BY o; ```
You would get more than one record if you use just that. I would do something like: (The table in question will be scanned only once) ``` Select top 1 * From dbo.SomeTable where WorkGroupId=2 or RoleId=2 Order by case when WorkGroupId=2 then 1 when RoleId=2 then 2 end ```
Priority of an OR statement SQL
[ "", "sql", "sql-server-2008", "" ]
I would like a compact way to parse one-line strings that start with mandatory list-elements (unspecified number) and ends with dictionary-like definitions using `=`. * The **element-separator** should be `,` and *spaces* should become part of the element -- which rules out `shlex`, I think. * **Spaces** should/may be...
In this solution, `opts` is essentially the same as yuvi's (with the added `strip`). The splitter is a customization of `shlex`, using `posix` mode to handle quotes. ``` def mylex(x): lex = shlex.shlex(x, posix=True) lex.whitespace = ',' lex.whitespace_split = True return list(lex) def opts(x): ll...
What you probably want is to create your own split function, with a flag that toggles when " are introduced. Something like this: ``` def my_split(string, deli): res = [] flag = True start = 0 for i, c in enumerate(string): if c == '"': if flag: flag = False ...
How to parse optional and named arguments into list and dict?
[ "", "python", "parsing", "" ]
I'm trying to install xlrd on mac 10.8.4 to be able to read excel files through python. I have followed the instructions on <http://www.simplistix.co.uk/presentations/python-excel.pdf> I did this: 1. unzipped the folder to desktop 2. in terminal, cd to the unzipped folder 3. $ python setup.py install This is what I...
try `sudo python setup.py install` the /Library folder needs root permission to be accessed.
Try `python setup.py install --user` You shouldn't use `sudo` as suggested above for two reasons: 1. You're allowing arbitrary untrusted code off the internet to be run as root 2. Passing the `--user` flag to `python setup.py install` will install the package to a user-owned directory. Your normal non-root user won't...
error: could not create '/Library/Python/2.7/site-packages/xlrd': Permission denied
[ "", "python", "installation", "xlrd", "" ]
I'm having some issues with a simple bit of code not working correctly and I'm totally baffled as to why... ``` errors = open('ERROR(S).txt', 'w') try: execfile("AEAPER.py") except Exception as e: errors.write(e) errors.close() ``` I get the following error: ``` Traceback (most recent call last): File "...
Unlike the `print` statement, the [`file.write`](http://docs.python.org/2/library/stdtypes.html#file.write) function only takes strings. So, you just need to convert to string explicitly: ``` errors.write(str(e)) ``` Of course in real-life code, you often want to do some formatting, so you often forget about this thi...
`e` isn't a string. `write` needs a string. Make a string out of it with ``` repr(e) ``` or ``` str(e) ``` depending on what kind of output you want.
Saving an error exceptions to file erroring out
[ "", "python", "python-2.7", "exception", "error-handling", "" ]
I have a huge logging file with time stamp in the format like below: ``` 08/07/2013 11:40:08 PM INFO ``` I want to convert that to mysql timestamp using python, like: ``` 2013-04-11 13:18:02 ``` I have written a python script to do that but I am wondering is there some build-in python package/function written alrea...
Use `time.strptime` to parse the time, then `time.strftime` to reformat to new format? ``` import time input_format = "%m/%d/%Y %I:%M:%S %p INFO" # or %d/%m... output_format = "%Y-%m-%d %H:%M:%S" def convert_time(logging_time): return time.strftime(output_format, time.strptime(logging_time, input_format)) print...
I would recommend using the [`datetime`](http://docs.python.org/2/library/datetime.html) module. You can convert your date string into a python `datetime` object, which you can then use to output a reformatted version. ``` from datetime import datetime mysqltime = "2013-04-11 13:18:02" timeobj = datetime.strptime(mys...
Python logging time stamp convert to mysql timestamp
[ "", "python", "mysql", "timestamp", "" ]
To make it simple, I have a table with stock in/out like this : ``` date,in_out 2013-08-05,+5 2013-08-07,-2 2013-08-12,-1 ``` What I would like to do is to have the number of items in stock for each date : ``` date,in_out,quantity 2013-08-05,+5,5 2013-08-07,-2,3 2013-08-12,-1,2 ``` But even if I normally know Postg...
you are looking for a running sum: ``` select date, in_out, quantity, sum(quantity) over (order by date) as quantity from table_stock order by date; ``` Btw: `date` is a horrible name for a column. First it's also a reserved word and secondly it doesn't document what the column contains. A "star...
Great I found a solution for Postgres 8.3 and earlier version : ``` CREATE OR REPLACE FUNCTION hds_csum_init() RETURNS void LANGUAGE plperl AS $hds_csum_init$ $_SHARED{csum} = 0; $hds_csum_init$; ``` and ``` CREATE OR REPLACE FUNCTION hds_csum_sum(integer) RETURNS integer LANGUAGE plperl AS $h...
How to have a field in Postgresql depending on the previous rows found?
[ "", "sql", "database", "postgresql", "select", "" ]
I've got a stored procedure that contains a try-catch block. In the catch block I call raiserror() to rethrow the error with some context. I was expecting that if an error occurred the raiserror() would be called and execution would immediately return from the stored procedure to the calling code. However, this doesn'...
That's not how it works in T-SQL. Nothing in the documentation for [`TRY...CATCH`](http://technet.microsoft.com/en-us/library/ms175976.aspx) or [`RAISERROR`](http://technet.microsoft.com/en-us/library/ms178592.aspx) specifies any special cases that would override: > When the code in the CATCH block finishes, *control ...
As I understand it, if you want the execution to stop, you need to raise the error within the `TRY` block, and then raise the error again in your `CATCH` block this will make sure that the error is "raised" to the caller. Or you could add a `RETURN` statement after your `RAISERROR` statement in the `CATCH` block. This...
When does RAISERROR fire in a stored procedure?
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I am using pandas/python and I have two date time series s1 and s2, that have been generated using the 'to\_datetime' function on a field of the df containing dates/times. When I subtract s1 from s2 > s3 = s2 - s1 I get a series, s3, of type > timedelta64[ns] ``` 0 385 days, 04:10:36 1 57 days, 22:54:00 2 ...
You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day. ``` >>> x = np.timedelta64(2069211000000000, 'ns') >>> days = x.astype('timedelta64[D]') >>> days / np.timedelta64(1, 'D') 23 ``` Or, as @PhillipCloud suggested, just `days.astype(in...
Use [`dt.days`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.days.html) to obtain the days attribute as integers. For eg: ``` In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T')) In [15]: s Out[15]: 0 1 days 00:00:00 1 3 days 02:00:00 2 5 days 04...
extracting days from a numpy.timedelta64 value
[ "", "python", "numpy", "pandas", "" ]
I understand that I can use variables in the order by section of sql queries like this: ``` order by case when @var1 = 'priority' then priority end desc, case when @var2 = 'report_date' then report_date end asc ``` But how do I use variables for the asc and desc sections too?
without `Dynamic SQL` each option it's clause for example: ``` ORDER BY case when @var1 = 'priority asc' THEN priority END ASC , case when @var1 = 'priority desc' then priority end DESC, case when @var2 = 'report_date asc' then report_date end ASC, case when @var2 = 'report_date desc' then report_date end DESC...
Assuming your variable `@var3` stores `'ASC'` or `'DESC'` keywords, you can write something like this: ``` order by case when @var1 = 'priority' and @var3 = 'DESC' then priority end DESC, case when @var1 = 'priority' and @var3 = 'ASC' then priority end ASC, case when @var2 = 'report_date' and @var3 = 'ASC' then repo...
Using variables for asc and desc in order by
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
I have a dictionary where the values are a tuple ``` dict={'A':('1','2','3'),'B':('2','3','xxxx')....} ``` I need to find out if all values have a '' or None in their third element. It just needs to be a boolean evaluation. What is most concise way to make this happen? This is what I did: ``` all(not v[2] for v...
You could use (Use itervalues() for Py2x) ``` all(elem[2] in ('', None) for elem in test.values()) ``` See the demo - ``` >>> test = {'a': (1, 2, None), 'b':(2, 3, '')} >>> all(elem[2] in ('', None) for elem in test.values()) True >>> test['c'] = (1, 2, 3) >>> all(elem[2] in ('', None) for elem in test.values()) Fal...
Python 2: ``` boolean = all(value[2] in ('', None) for value in your_dict.itervalues()) ``` Python 3: ``` boolean = all(value[2] in ('', None) for value in your_dict.values()) ```
evaluating values of a dictionary
[ "", "python", "" ]
How do I import a Python file and use the user input later? For example: ``` #mainprogram from folder import startup name #startup name = input('Choose your name') ``` What I want is to use the startup program to input the name, then be able to use the name later in the main program.
You can access that variable via `startup.name` later in your code.
I think is better do your code in classes and functions. I suggest you to do: ``` class Startup(object): @staticmethod def getName(): name = "" try: name = input("Put your name: ") print('Name took.') return True except: "Can't get name." return False >> import star...
Importing and storing the data from a Python file
[ "", "python", "" ]
When I'm opening a network connection in Python like ``` s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('www.heise.de', 80)) ``` I can read the connection state from the console: ``` netstat --all --program|grep <PID> tcp 0 0 10.10.10.6:39328 www.heise.de:http VERBUNDEN 23829/python ``` But...
This is only for **Linux**: You need getsockopt call. level is **"IPPROTO\_TCP"** and option is **"TCP\_INFO"**, as suggested by [tcp manual](http://man7.org/linux/man-pages/man7/tcp.7.html). It is going to return the **tcp\_info** data as defined [here](http://www.cse.scu.edu/~dclark/am_256_graph_theory/linux_2_6_sta...
I've just duct-taped together half of a solution for this problem in case Google brings anyone else here. ``` import urllib2 import psutil page = urllib2.urlopen(URL) # dummy URL sock = page.fp # The socket object that's being held open fileno = sock.fileno() proc = psutil.Process() connections = proc.c...
Query TCP socket connection state in Python
[ "", "python", "sockets", "networking", "tcp", "" ]
A person for which I am working under constantly has reserves about me updating programs that were written in python 2.5 and 2.7 to python 3.3. I work in bioninformatics and a lot of the python code I am trying to work with is pre 3.0 and while I have a linux that runs 2.7 it on a virtual machine, on my main machine I ...
It is quite easy to write **new** code that works both python 2.6+ and 3.3+. Use the following at the beginning of each file ``` from __future__ import division, absolute_import \ unicode_literals, print_function ``` And then know the differences; you can use the [`six`](http://pythonhosted.org/six/) to ease ...
I don't know if SO is the best place to ask this question, but this link here lists every difference between Python 2.x and 3.x: <http://docs.python.org/3.0/whatsnew/3.0.html> After reading it, you can easily tell what needs to be done to your 2.x programs to bring them into 3.x.
Dangers of updating from python 2.7 to 3.0 and above
[ "", "python", "python-2.7", "python-3.x", "" ]
I have a large file which I need to read in and make a dictionary from. I would like this to be as fast as possible. However my code in python is too slow. Here is a minimal example that shows the problem. First make some fake data ``` paste <(seq 20000000) <(seq 2 20000001) > largefile.txt ``` Now here is a minima...
There was a blog post series "Wide Finder Project" several years ago about this at Tim Bray's site [1]. You can find there a solution [2] by Fredrik Lundh of ElementTree [3] and PIL [4] fame. I know posting links is generally discouraged at this site but I think these links give you better answer than copy-pasting his ...
It may be possible to parallelize this to speed it up, but doing multiple reads in parallel is unlikely to help. Your OS is unlikely to usefully do multiple reads in parallel (the exception is with something like a striped raid array, in which case you still need to know the stride to make optimal use of it). What yo...
Read large file in parallel?
[ "", "python", "performance", "multiprocessing", "" ]
I have a python program with two lists that look like the example below: ``` list1=["a","b","c","d"] list2=[0,1,1,0] ``` Is there a elegant way to create a third list, that contains the elements of list1 at the position where list2 is 1? I am looking for something similar to the numpy.where function for arrays or bet...
You could use a list comprehension here. ``` >>> array1 = ["a", "b", "c", "d"] >>> array2 = [0, 1, 1, 0] >>> [array1[index] for index, val in enumerate(array2) if val == 1] # Or if val ['b', 'c'] ``` Or use, ``` >>> [a for a, b in zip(array1, array2) if b] ['b', 'c'] ```
This is exactly what [itertools.compress](http://docs.python.org/3.1/library/itertools.html#itertools.compress) does. ``` >>> list1=["a","b","c","d"] >>> list2=[0,1,1,0] >>> import itertools >>> list(itertools.compress(list1, list2)) ['b', 'c'] ```
python numpy.where function for lists
[ "", "python", "list", "numpy", "where-clause", "" ]
So I was trying to retrieve the date only from the database but then it always comes with time, I don't know why but the data type of that field in my database is date. Now, how to retrieve the data with having date only. Here my code: ``` Dim strA As String = ddlSChedName.SelectedValue.ToString() ...
One way is to convert the dates (WHich I'm assuming are "To" and "From") and output them as strings that include the date only ``` Dim strA As String = ddlSChedName.SelectedValue.ToString() sqlcon = New SqlConnection(conString) sqlcon.Open() Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM dbo.CS_refSched WHERE S...
Use `DateTime.ToShortDateString()` which will honor your culture/locale.
How to remove the time?
[ "", "asp.net", ".net", "sql", "vb.net", "" ]
I'm using pandas.Series and np.ndarray. The code is like this ``` >>> t array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]]) >>> pandas.Series(t) Exception: Data must be 1-dimensional >>> ``` And I trie to convert it into 1-dimensional array: ``` >>> tt = t.reshape((1,-1)) >>> tt array([[ 0., 0...
An alternative is to use [np.ravel](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html): ``` >>> np.zeros((3,3)).ravel() array([ 0., 0., 0., 0., 0., 0., 0., 0., 0.]) ``` The importance of `ravel` over `flatten` is `ravel` only copies data if necessary and usually returns a view, while `flatt...
Use [`.flatten`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html): ``` >>> np.zeros((3,3)) array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]]) >>> _.flatten() array([ 0., 0., 0., 0., 0., 0., 0., 0., 0.]) ``` EDIT: As pointed out, this returns a copy of the i...
How to convert ndarray to array?
[ "", "python", "numpy", "multidimensional-array", "" ]
Say I have this table for high-scores: ``` id : primary key username : string score : int ``` User names and scores themselves can be repeating, only id is unique for each person. I also have an index to get high-scores fast: ``` UNIQUE scores ( score, username, id ) ``` How can I get rows below the given person? B...
Here's one way to get the result: ``` SELECT t.score , t.username , t.id FROM scores t WHERE ( t.score < 77 ) OR ( t.score = 77 AND t.username < 'name7' ) OR ( t.score = 77 AND t.username = 'name7' AND t.id < 70 ) ORDER BY t.score DESC , t.username DESC , t.id DESC ``` (NOTE: the ...
The concept of "below" for repeating scores is quite fuzzy: Think of 11 users having the same score, but you want the "10 below" a special row. That said, you can do something like (assuming you start with id=70) ``` SELECT score, username, id FROM scores WHERE score<=(SELECT score FROM scores WHERE id=77) ORDER BY i...
Mysql, get rows before specific row in a multi-column index
[ "", "mysql", "sql", "indexing", "sql-order-by", "multiple-columns", "" ]
``` Tables _________________________ _________________________ |__________items__________| |_______readStatus________| |___itemId___|____data____| |___itemId___|___status___| | 1 | cats | | 1 | 1 | | 2 | dogs | | 2 ...
Use the LEFT JOIN instead of INNER JOIN: ``` SELECT * FROM items LEFT JOIN //left join readStatus ON items.itemId = readStatus.itemId WHERE (readStatus.status != 1 OR readStatus.status IS NULL); ``` Read the [**LEFT JOIN**](http://dev.mysql.com/doc/refman/5.0/en/left-join-optimization.html) tutorial.
Actually, this sounds like something that would be better solved with EXIST rather than a (left) join: ``` SELECT * FROM items WHERE NOT EXISTS ( SELECT * FROM readStatus WHERE items.itemId = readStatus.itemId AND readStatus.status = 1 ) ```
Select Items that don't have matching Items in another table
[ "", "mysql", "sql", "" ]
I have this sql, ``` IF(@ID = '') BEGIN SET @ID = NULL; END IF(@Name = '') BEGIN SET @Name = NULL; END IF(@PhoneNumber = '') BEGIN SET @PhoneNumber = NULL; END IF(@Price = '') BEGIN SET @Price = NULL; END IF(@NewPrice = '') BEGIN SET @NewPrice = NULL; END IF(@ModelNumber = '') BEGIN S...
Try [NULLIF](http://technet.microsoft.com/en-gb/library/ms177562%28v=sql.105%29.aspx) as below ``` NULLIF(@SKU,'') ```
Please try: ``` SET @YourValue=ISNULL(NULLIF(@YourValue,' '), NULL) ``` which returns NULL if value is NULL, empty or space. Note: `NULLIF` returns the first expression if the two expressions are not equivalent. If the expressions are equivalent, `NULLIF` returns a null value of the type of the first expression.
IsEmpty function like ISNULL in SQL Server?
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I just want to know the internal execution of this query especially how the values in from subquery are being used ``` SELECT bu, location FROM ( SELECT DISTINCT bu, hqname, location FROM DOCTOR UNION SELECT DISTINCT bu, hqname, location FROM CHEMIST UNION SELECT DISTINCT bu, hqname, location...
Commented SQL ``` SELECT -- bu and location from doctors, chemists and stockists -- (see inner query) bu, location FROM ( -- All doctors, chemists and stockists -- with duplicates removed: -- e.g. if a person is a chemist and a doctor, only one record is pre...
The subquery returns unique cobinations of `bu, hqname, location` Then they are grouped and only locations where there are more than one hqname remain.
Difficulty understanding this query oracle sql
[ "", "sql", "oracle", "subquery", "" ]
I cannot get the `colorbar` on `imshow` graphs like this one to be the same height as the graph, short of using Photoshop after the fact. How do I get the heights to match? ![Example of the colorbar size mismatch](https://i.stack.imgur.com/EXLiY.png)
You can do this easily with a matplotlib [AxisDivider](http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axesdivider). The example from the linked page also works without using subplots: ``` import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np ...
This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display. ``` plt.colorbar(im,fraction=0.046, pad=0.04) ``` It also does not require sharing the axis which can get the plot out of square.
Set Matplotlib colorbar size to match graph
[ "", "python", "image", "matplotlib", "colorbar", "imshow", "" ]
So I have a couple tables structured similar to this: * `Run ([RunID], [PlayerID], [Score])` * `Jump ([ID], [RunID], [Time], [Type])` There are 4 "types" of time 2 "up" and 2 "down". I need to get the time between an "up" and an "down" on a given run. Basically, during a "run" when a "jump" is made, I record an up ...
**EDIT** Based on your updated question this will work. I've joined on your *jump type* table rather than assuming the id's (personally I think its a bad idea to assume id's eg assume 1 and 3 are the *up* type) Also I've used an *inner* join to get the corresponding down jump - **I am assuming that if the jumper goes...
``` select r.RunID, r.PlayerID, ju.Time as TimeUp, jd.Time as TimeDown from Run as R left outer join Jump as ju on ju.RunID = r.RunID and ju.[Type] in (1, 3) left outer join Jump as jd on jd.RunID = r.RunID and jd.[Type] in (2, 4) ``` [**sql fiddle demo**](http://sqlfiddle.com/#!3/5d565/17)
SQL Server : Sum of DateDiff From Multiple Rows
[ "", "sql", "sql-server", "t-sql", "" ]
I'm having a problem with the following SQL INNER JOIN statement. I'm probably missing something syntactically: ``` SELECT * from (SELECT DISTINCT Name from Table.Names WHERE Haircolor='Red') uniquename INNER JOIN (SELECT * FROM Table.Names) allnames ON uniquenames.Name = allnames.Name; ``` I want all the names which...
Possibly: ``` select * from (SELECT DISTINCT Name from Names WHERE Haircolor='Red') uniquenames INNER JOIN (SELECT * FROM Names) allnames ON uniquenames.Name = allnames.Name ``` - it depends on what you actually want to see. UPDATE: SQLFiddle for original answer [here](http://sqlfiddle.com/#!2/cc2e4/2). However, a ...
Here's an example of a `ROW_NUMBER` query. I can't test it right now, so there may be some bugs to work out. But to give you a general idea, it starts with a query like this: ``` select t.*, row_number() over (partition by name order by address) as rn from table t where haircolor = 'red' ``` That gives you a ...
SQL Query Distinct Inner Join Issue
[ "", "sql", "sql-server", "" ]
I have a directed graph in NetworkX. The edges are weighted from 0 to 1, representing probabilities that they occurred. The network connectivity is quite high, so I want to prune the edges such for every node, only the highest probability node remains. I'm not sure how to iterate over every node and keep only the high...
The solution I had was inspired by Aric. I used the following code: ``` for node in G.nodes(): edges = G.in_edges(node, data=True) if len(edges) > 0: #some nodes have zero edges going into it min_weight = min([edge[2]['weight'] for edge in edges]) for edge in edges: if edge[2]['weig...
Here are some ideas: ``` import networkx as nx G = nx.DiGraph() G.add_edge('A','B', weight=1.0) G.add_edge('A','C', weight=1.0) G.add_edge('A','D', weight=0.5) G.add_edge('B','C', weight=0.9) G.add_edge('B','D', weight=0.8) G.add_edge('C','D', weight=0.9) print "all edges" print G.edges(data=True) print "edges >= 0...
Find highest weight edge(s) for a given node
[ "", "python", "python-2.7", "networkx", "" ]
I am using `SFTPClient` to download files from the remote server. However, I don't know if the remote path is a file or a directory. If the remote path is a directory, I need to handle this directory recursively. This is my code: ``` def downLoadFile(sftp, remotePath, localPath): for file in sftp.listdir(remotePa...
`os.path.isfile()` and `os.path.isdir()` only work on **local** filenames. I'd use the `sftp.listdir_attr()` function instead and load full `SFTPAttributes` objects, and inspect their `st_mode` attribute with the `stat` module utility functions: ``` import stat def downLoadFile(sftp, remotePath, localPath): for ...
Below steps to be followed to verify if remote path is FILE or DIRECTORY: 1) Create connection with remote ``` transport = paramiko.Transport((hostname,port)) transport.connect(username = user, password = pass) sftp = paramiko.SFTPClient.from_transport(transport) ``` 2) Suppose you have directory "/root/testing/" an...
How to check a remote path is a file or a directory?
[ "", "python", "file", "directory", "paramiko", "" ]
When developing a Python package, it's very convenient to use the `-m` option to run modules inside the package as scripts for quick testing. For example, for `somepackage` with module `somemodule.py` inside it, invoking ``` python -m somepackage.somemodule ``` from the directory where `somepackage` resides will run ...
After experimenting with this for quite some time, it turns out that this approach actually works: ``` python -c "import runpy; import pdb; pdb.runcall(runpy.run_module, 'somepackage.somemodule', run_name='__main__')" ``` For some reason, the use of `pdb.runcall` over `pdb.run` is important.
There are [efforts](https://bugs.python.org/issue9325) [underway](https://bugs.python.org/issue32206) to solve this in Python itself. Looks like with Python 3.7, you can do: ``` python -m pdb -m somepackage.somemodule ``` And I've provided [a backport](https://pypi.org/project/backports.pdb) for older Python versions...
Launch Python debugger while simultaneously executing module as script
[ "", "python", "pdb", "" ]
I would like to be able to test whether two callable objects are the same or not. I would prefer identity semantics (using the "is" operator), but I've discovered that when methods are involved, something different happens. ``` #(1) identity and equality with a method class Foo(object): def bar(self): pass...
Python doesn't keep a canonical `foo.bar` object for every instance `foo` of class `Foo`. Instead, a method object is created when Python evaluates `foo.bar`. Thus, ``` foo.bar is not foo.bar ``` As for `==`, things get messy. Python 3.8 [fixed method comparison](https://bugs.python.org/issue1617161) so two methods a...
**tldr:** Methods are descriptors, which is why this can happen. Use `==` if you really need to compare for equality. `is` (in effect) tests for equality of `id`. So let's check that out: ``` >>> id(foo.bar) 4294145364L >>> id(foo.bar) 4294145364L >>> id(foo.bar) 4294145364L >>> b = foo.bar >>> id(foo.bar) 4293744796...
How should functions be tested for equality or identity?
[ "", "python", "" ]
I'm having trouble with **summing** the fields values **based on another** fields value. I need to `SUM(activities.points)` based on `activities.activity_type` if it's `used_points` or `added_points` and put it in `AS used_points/added_points`. Table *activities*: ``` id | subscription_id | activity_type | points -...
You want to use `SUM(IF( ))`. You want to add up the values returned from the `IF`. You want that `IF` expression to be evaluated for each individual row. Then, use the `SUM` aggregate to add up the value returned for each row. Remove the `SUM` aggregate from inside the `IF` expression and instead, wrap the `IF` insid...
Your code is only slightly out: ``` SELECT subscriptions.name, subscriptions.current_points, SUM(IF(activities.activity_type="used_points", 0, activities.points)) AS used_points, SUM(IF(activities.activity_type="added_points", 0, activities.points)) AS added_points FROM activities JOIN...
Sum columns depending on another column value
[ "", "mysql", "sql", "" ]