Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I execute the code below: ``` use AdventureWorks2008R2 begin transaction BEGIN alter table HumanResources.Department add newcolumn int update HumanResources.Department set newcolumn=1 where departmentid=1 END commit ``` The error I get is: > Invalid column name 'newcolumn'. Can `ALTER` statements be included in Tra...
Yes, you can include an `ALTER` in a transaction. The problem is that the parser validates the syntax for your `UPDATE` statement, and can't "see" that you are also performing an `ALTER`. One workaround is to use dynamic SQL, so that the parser doesn't inspect your syntax (and validate column names) until runtime, wher...
Aaron has explained everything already. Another alternative that works for ad-hoc scripts in SSMS is to insert the batch separator `GO` so that the script is sent as two parts to the server. This only works if it is valid to split the script in the first place (you can't split an `IF` body for example).
Alter statement in a Transaction
[ "", "sql", "sql-server", "t-sql", "transactions", "" ]
I have an xml I am parsing, making some changes and saving out to a new file. It has the declaration `<?xml version="1.0" encoding="utf-8" standalone="yes"?>` which I would like to keep. When I am saving out my new file I am loosing the `standalone="yes"` bit. How can I keep it in? Here is my code: ``` templateXml = "...
You can pass `standalone` keyword argument to `tostring()`: ``` etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone=True) ```
Specify `standalone` using [tree.docinfo.standalone](http://lxml.de/api/lxml.etree.DocInfo-class.html). Try following: ``` from lxml import etree tree = etree.fromstring(templateXml).getroottree() # NOTE: .getroottree() xmlFileOut = '/Users/User1/Desktop/Python/Done.xml' with open(xmlFileOut, "w") as f: f.wr...
XML Declaration standalone="yes" lxml
[ "", "python", "xml", "parsing", "xml-parsing", "lxml", "" ]
Python bit me today. I'm trying to access an object's attribute inside its `__setattr__` implementation - I can't figure out how. This is what I've tried so far: ``` class Test1(object): def __init__(self): self.blub = 'hi1' def __setattr__(self, name, value): print self.blub class Test2(obje...
OP, you haven't told us the whole story. You did not just run code like this: ``` TestX().bip = 'bap' ``` You ran code like this: ``` try: TestX().bip = 'bap' except Exception as ex: print ex ``` There's a big difference. Why, you ask? Well, your output seems on first glance to indicate that `Test6` works, ...
Because inside the `__init__` it is trying to set `blub` which calls `__setattr__`; and it does not set anything but tries to access (and print) `blub`, finds nothing and raises the error. Check this: ``` >>> class Test2(object): def __init__(self): print "__init__ called" self.blub = 'hi2' print "blub w...
Accessing an object's attribute inside __setattr__
[ "", "python", "" ]
I need to create SQL statements from Enterprise architect v.9 table description, since I need "CREATE TABLE" to be placed in a text file. Please advice me where to look in EA interface!
In the diagram where your tables are designed, select all of them and right click in one of the tables. Look for *SQL Code Generation* and choose one of the options: single DDL script or not. The difference is that in the single script all create table statements will be generated in only one file (which is usually be...
After open your database diagram, 1. Look at **Tools** tab and expand **Database Engineering** menu, 2. Select **Generate Package DLL**, 3. Enter output file name and generate it.
Need to export SQL for creating table(s) from Enterprise Architect
[ "", "sql", "enterprise-architect", "" ]
Within my program, I audit incoming data, which can be of 4 types. If the data meets all required criteria, it gets stored with success in a table column, along with the message type and timestamp of when the row was entered into the table. Data can also be written to the table with error, due to something like a conn...
I want to note that a simple modification to your query allows you to do what you want (although I prefer the `row_number()` method in Valex's answer). That is to turn the subquery in the `where` clause to a correlated subquery: ``` SELECT * FROM auditingTable at1 WHERE timestamp = (SELECT MAX(timestamp) ...
You haven't mentioned your Sybase version. You can use [ROW\_NUMBER() function](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc00800.1530/doc/html/san1276751057140.html) For example your table has `MessageId`,`MessageTime` fields you can use following query: ``` SELECT * FROM ( SELECT...
SQL - Returning distinct row for data with Max created timestamp value
[ "", "sql", "database", "sybase", "" ]
I went through these threads: * [Find unique rows in numpy.array](https://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array) * [Removing duplicates in each row of a numpy array](https://stackoverflow.com/questions/7438438/removing-duplicates-in-each-row-of-a-numpy-array) * [Pandas: unique dataframe]...
Essentially, you want np.unique to return the indexes of the unique columns, and the indices of where they're used? This is easy enough to do by transposing the matrix and then using the code from the other question, with the addition of `return_inverse=True`. ``` at = a.T b = np.ascontiguousarray(at).view(np.dtype((n...
First lets get the unique indices, to do so we need to start by transposing your array: ``` >>> a=a.T ``` Using a modified version of the above to get unique indices. ``` >>> ua, uind = np.unique(np.ascontiguousarray(a).view(np.dtype((np.void,a.dtype.itemsize * a.shape[1]))),return_inverse=True) >>> uind array([0, ...
Find unique columns and column membership
[ "", "python", "numpy", "unique", "" ]
I have a python dictionary of user-item ratings that looks something like this: ``` sample={'user1': {'item1': 2.5, 'item2': 3.5, 'item3': 3.0, 'item4': 3.5, 'item5': 2.5, 'item6': 3.0}, 'user2': {'item1': 2.5, 'item2': 3.0, 'item3': 3.5, 'item4': 4.0}, 'user3': {'item2':4.5,'item5':1.0,'item6':4.0}} ``` I was look...
Try following code: ``` import pandas sample={'user1': {'item1': 2.5, 'item2': 3.5, 'item3': 3.0, 'item4': 3.5, 'item5': 2.5, 'item6': 3.0}, 'user2': {'item1': 2.5, 'item2': 3.0, 'item3': 3.5, 'item4': 4.0}, 'user3': {'item2':4.5,'item5':1.0,'item6':4.0}} df = pandas.DataFrame([ [col1,col2,col3] ...
I think the operation you're after -- to unpivot a table -- is called "melting". In this case, the hard part can be done by `pd.melt`, and everything else is basically renaming and reordering: ``` df = pd.DataFrame(sample).reset_index().rename(columns={"index": "item"}) df = pd.melt(df, "item", var_name="user").dropna...
Pandas data frame from dictionary
[ "", "python", "pandas", "" ]
What I'd like to do is basically I have this file with data in separate lines, except the last piece which is a biography and may stretch across many lines. The biography may be any number of lines long, and all I know is that it starts on the 5th line. Now what I need is a way to retrieve the biography from the fifth ...
Another way to phrase your question would be "how do I discard the first four lines of a file I read?" Taking the answer to that a step at a time: ``` filename = "/a/text/file" input_file = open(filename) ``` where the default mode for `open()` is `'r'` so you don't have to specify it. ``` contents = input_file.read...
If you just want to put the entire biography in a string, you can do this: ``` with open('biography.txt') as f: for i in range(4): # Read the first four lines f.readline() s = '' for line in f: s += line ``` "`for line in f`" iterates over `f`. `iter(f)` returns a generator function that y...
Python: How do you read a chunk of text from a file without knowing how long the file actually is?
[ "", "python", "file", "operating-system", "lines", "" ]
So I would like to join 2 tables with 1 where condition: Here is what I've tried so far: ``` SELECT * FROM (ci_usertags) JOIN ci_tags ON ci_usertags.utag_tid WHERE utag_uid = 1 ``` My tables look like this: ``` ci_usertags utag_id utag_uid utag_tid ci_tags tag_id tag_name ``` I want to select all `t...
Your query is: ``` SELECT * FROM (`ci_usertags`) JOIN `ci_tags` ON `ci_usertags`.`utag_tid` WHERE `utag_uid` ``` This is sort of non-sensical SQL. The conditions are that `utag_tid` is not 0 or NULL and `utag_uid` is not 0 or NULL. This is because there are no conditions, so it is only looking at the value ...
Solution with nested query as replacement for join (speed improvement) ``` Select tag_id, tag_name FROM ci_tags WHERE tag_id IN (Select utag_tid FROM ci_usertags WHERE utag_id = 1 GROUP BY 1) GROUP BY 1,2 ```
SQL join tables with condition
[ "", "sql", "database-design", "join", "" ]
A part of my table is as follows, ``` Key|Value --------- A | V1 B | V2 C | V3 ``` I know the following query would definitely return no result, but then what is the correct query of achieving a positive result, i.e. '1'. I mean what query should I apply that checks that A has a value as V1 and B has a value as V...
if you only want to check if there are rows that fulfill certain conditions you can use following construct ``` select count(*) from dual where exists ( select 1 from myTable where (key = 'A' and value = 'V1') ) AND exists ( ...
I think this is what you want. ``` select 1 from dual where exists( select 1 from mytable where key = 'A' and value = 'V1') and exists( select 1 from mytable where key = 'B' and value = 'V2') ```
Select statement having multiple conditions over multiple columns
[ "", "sql", "oracle", "" ]
I am using MySQL. I have produced the following result-set using a select with joins etc but I wish to remove the nulls if possible and produce a result similar to the second table. ``` ----------------------------------- |#|IMG_KEY|IMAGE|XX_STYLE|YY_STYLE| ----------------------------------- |1| 1 |PIX01| <NULL>...
Try using `GROUP_CONCAT()`: ``` SELECT MIN(ID) ID, IMG_KEY, IMAGE ,GROUP_CONCAT(XX_STYLE) XX_STYLE ,GROUP_CONCAT(YY_STYLE) YY_STYLE FROM MyTable GROUP BY IMG_KEY, IMAGE ``` Result: ``` | ID | IMG_KEY | IMAGE | XX_STYLE | YY_STYLE | ---------------------------------------------- | 1 | 1 | PIX01 | STYLEA ...
remove those 'null' values using query itself. For that add following line in your query ``` where XX_STYLE is not null and YY_STYLE is not null ``` If you provide your query, then i'll give you complete query
Removing NULLs from ResultSet
[ "", "mysql", "sql", "null", "" ]
I need to write a programm that collects different datasets and unites them. For this I have to read in a comma seperated matrix: In this case each row represents an instance (in this case proteins), each column represents an attribute of the instances. If an instance has an attribute, it is represented by a 1, otherwi...
You can use `numpy.loadtxt`, for example: ``` import numpy as np a = np.loadtxt(filename, delimiter=',',usecols=(1,2,3,4), skiprows=1, dtype=float) ``` Which will result in something like: ``` #array([[ 1., 1., 1., 0.], # [ 0., 1., 0., 1.], # [ 1., 0., 0., 0.], # [ 1., 1., ...
Take a look at [pandas](http://pandas.pydata.org/). > pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.
Recomended way to create a matrix containing strings in python
[ "", "python", "arrays", "string", "numpy", "" ]
I've been struggling with this problem. Head against the wall. I know this has to be easy. I want to select items that match multiple criteria on a reference table. Here is a example schema that can help illustrate the problem ``` tblCars ------------ CarID CarName tblCarColors ------------ ColorID Color tblCarColo...
You can try this. ``` select carid from tblCarColorXRef where colorid in (1,2) group by carid having count(colorid = 2); ``` You can use `count(disinct colorid) = 2`, if the car, color combination is not unique.
I would suggest a couple of other things. 1. Remove "tbl" from the table names. 2. Try to get rid of the ID columns -- in this example they wouldn't be necessary as Types of cars is the actual key you're looking for (Honda, Toyota, etc..) - Same with Colors. This may help your Xref as well - which would have a composi...
Find rows with multiple reference values in MySQL
[ "", "mysql", "sql", "" ]
I have a small problem with my Python 2 program. Here is my function: ``` def union(q,p): q = q + p q = set(q) return q, p ``` Then I have created new two lists and called my function: ``` a = [1,2,3] b = [2,4,6] union(a,b) ``` Finally I'm printing out `a` and `b`: ``` >>>print a [1,2,3] >>>prin...
Assign return values back to `a` and `b`: ``` >>> def union(q,p): ... q = q + p ... q = set(q) ... return q, p ... >>> a = [1,2,3] >>> b = [2,4,6] >>> a, b = union(a, b) >>> a set([1, 2, 3, 4, 6]) >>> b [2, 4, 6] ``` To get a list from set, use `list` as Haidro commented: ``` >>> list(a) [1, 2, 3,...
Your function doesn't change it in place, it returns the new items. Thus, you have to return the result to a variable: ``` a, b = union(a, b) ```
Python 2: Function didn't change the list data
[ "", "python", "list", "function", "python-2.7", "" ]
Is there a way that I can find where stored procedures are saved so that I can just copy the files to my desktop?
Stored procedures aren't stored as files, they're stored as metadata and exposed to us peons (thanks Michael for the reminder about [`sysschobjs`](http://technet.microsoft.com/en-us/library/ms179503.aspx)) in the catalog views [`sys.objects`](http://technet.microsoft.com/en-us/library/ms190324.aspx), [`sys.procedures`]...
Stored procedures are not "stored" as a separate file that you're free to browse and read without the database. It's stored in the database it belongs to in a set of system tables. The table that contains the definition is called [sysschobjs] which isn't even accessible (directly) to any of us end users. To retrieve t...
How to script out stored procedures to files?
[ "", "sql", "sql-server", "" ]
I have a table in SQL server, I have a column in it with datatype DateTime, I want to get data on specific month or year, ie ``` Select * from Table where datejoined='07'//Getting July Data ``` or ``` Select * from Table where datejoined='2013'//Getting 2013 Data ``` I have tried this,but its comparing the minutes ...
What you're looking for is something like this: ``` SELECT * FROM TABLE WHERE Year(DATEJOINED) = 2013 ``` or: ``` SELECT * FROM TABLE WHERE Month(DATEJOINED) = 7 ```
Maybe following solutions are complicated but the will give you better performance (this means Index Seek) if you have indexes. These examples are based on [AdventureWorks2008R2](http://msftdbprodsamples.codeplex.com/releases/view/59211) database: ``` SET NOCOUNT ON; GO DECLARE @StartDate DATETIME,@EndDate DATETIME; P...
SQL server apply Month or year condition
[ "", "sql", "sql-server-2008", "" ]
I want to know about relation dependent destroy and dependent nullify on rails and relation with SQL. Thanks
Example: Table users and table cars user has many cars car belongs to users in table car you have user\_id on each row if you set dependent destroy when defining the relationship in users, then when you delete a user, all cars having that user\_id will be deleted also if you set nullify, cars will remain, but the u...
You use these options when you want to get rid of orphaned records. Most common used is `destroy` because it removes all associated objects one by one.
Rails When using dependent destroy and dependent nullify
[ "", "sql", "database", "ruby-on-rails-3", "" ]
Is there a good way to share a multiprocessing Lock between gunicorn workers? I am trying to write a json API with Flask. Some of the API calls will interact a python class that manages a running process (like ffmpeg for video conversion). When I scale up my number of web workers to more than 1, how can I ensure that o...
Follow peterw's answer, the workers can share the lock resource. But, It is better to use `try-finally` block to ensure the lock will always be released. ``` # dummy.py from multiprocessing import Lock import time lock = Lock() def start(): lock.acquire() try: # TODO do work for i in range(...
I tried something, and it seems to work. I put `preload_app = True` in my `gunicorn.conf` and now the lock seems to be shared. I am still looking into exactly what's happening here but for now this is good enough, YMMV.
Sharing a lock between gunicorn workers
[ "", "python", "concurrency", "flask", "multiprocessing", "gunicorn", "" ]
When I tried to embed album art in an MP3, mutagen updated the ID3 tag to version 2.4 - which I don't want, because in ID3v2.4 my cell phone (which runs Windows Phone 8) and my computer can't recognize the tags. Apparently, simply changing the `mutagen.id3.version` attribute doesn't work: the real version doesn't chan...
**Update:** this is now fixed, as pointed out by [JayRizzo](https://stackoverflow.com/questions/18248200/how-can-i-stop-mutagen-automatically-updating-the-id3-version/18255921?noredirect=1#comment130424055_18255921) in a comment to this answer. --- Sadly, you can't. From [the docs](https://mutagen.readthedocs.org/en/...
There is a "v2\_version" option in tags saving function, shown below. ``` import mutagen audio=mutagen.File('1.mp3') #audio.tags.update_to_v23() audio.tags.save(v2_version=3) ``` It is also documented in help() ``` help(audio.tags.save) ``` as below: > save(self, filename=None, v1=1, v2\_version=4, v23\_sep='/')
How can I stop mutagen automatically updating the ID3 version?
[ "", "python", "mp3", "id3", "id3v2", "mutagen", "" ]
Trying to obtain the Userid value in a row where the max(DateOccurred) was found. I'm getting lost in all these sub-queries. I'm using SQL Server 2008. NOTE: Need to return single value since part of another larger query in a SELECT statement. Example of how I obtain max date (which works); but now I need the userid...
I cannot see your whole query, but you probably want to use a window function instead: ``` max(case when lc.lc = 'ABCDEF' then lc.[DATE] end) over () as maxdate ``` This may not be exactly right. It is hard to say without seeing the rest of the query. Getting the user id would use similar logic. EDIT: You can also...
Use this sub query - ``` (SELECT Userid, Date FROM (SELECT Userid, Date FROM table_LC) b WHERE date = (SELECT MAX(LC.[Date]) FROM table_LC LC LEFT JOIN table_LM LM ON LC.[c] = LM.[c] AND LC.[L] = LM.[L] WHERE LM.[c] = LC.[c] AND LM.[L] = LC.[L] AND LC.[LC] = 'ABCDEF')) ```
sql - select different value of a max value nested query
[ "", "sql", "sql-server", "sql-server-2008", "" ]
currently I am getting errors in python but I cannot seem to find them ``` def dictionaryObjectParsed(): a = [] b = [] a, b = zip(*(map(lambda x: x.rstrip('\n\r').split('\t'), open('/Users/settingj/Desktop/NOxMultiplier.csv').readlines()))) for x in range(0,len(a)): print a[x] print b[x...
Pass the function without calling it (drop the '()').. ``` timer(dictionaryObjectParsed) ``` and ``` def timer(f): threading.Timer(1,f).start() print time.strftime('%I:%M:%S %p %Z') ``` instead of ``` threading.Timer(1,timer) ``` You are trying to create a recursive timer function, I think, by mistake. Th...
You have multiple errors. Try this: ``` def timer(f): f() # NOTE THIS NEW LINE threading.Timer(1,timer, f).start() # NOTE CHANGE ON THIS LINE print time.strftime('%I:%M:%S %p %Z') timer(dictionaryObjectParsed) # NOTE CHANGE ON THIS LINE ``` Note that on the final line, you...
Passing Functions to Functions
[ "", "python", "function", "timer", "" ]
``` class Product(models.Model): products = models.CharField(max_length=256) def __unicode__(self): return self.products class PurchaseOrder(models.Model): product = models.ManyToManyField('Product') vendor = models.ForeignKey('VendorProfile') dollar_amount = models.FloatField(verbose_...
You may not be able to do it directly. [From the documentation of `list_display`](https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display) > ManyToManyField fields aren’t supported, because that would entail > executing a separate SQL statement for each row in the table. I...
This way you can do it, kindly checkout the following snippet: ``` class Categories(models.Model): """ Base category model class """ title = models.CharField(max_length=100) description = models.TextField() parent = models.ManyToManyField('self', default=None, blank=True) when = ...
How to show a many-to-many field with "list_display" in Django Admin?
[ "", "python", "django", "django-models", "django-admin", "django-queryset", "" ]
is it possible to make a select and update at the same time? ``` select id,name from mytable where booled = 0 UPDATE mytable SET booled=1 WHERE (select id,name from mytable where booled = 0) ``` So to say those 2 commands in one.
There is no need to reinvent the wheel - you simply need to properly use transactions. MySQL supports transactions as long as you use InnoDB engine for your tables (old MyISAM would not work). Following series of statements would do what you want: ``` BEGIN; SELECT id,name FROM mytable WHERE booled=0; UPDATE mytable ...
Why not this ? ``` UPDATE mytable SET booled=1 WHERE booled=0 ```
Database update and select at the same time
[ "", "mysql", "sql", "" ]
I have a list and I want to filter my Queryset when any of these items is found in a foreign table's non-primary key 'test'. So I write something like this: ``` test_list = ['test1', 'test2', 'test3', 'test4', 'test5'] return cls.objects.filter(reduce(lambda x, y: x | y, [models.Q(next_task__test = item) for item in t...
This issue is quite interesting, it seems to happen with SQLite only. It's known here: <https://code.djangoproject.com/ticket/14091> and in the [docs](https://docs.djangoproject.com/en/dev/ref/databases/#sqlite-connection-queries). So basically the query might not be wrong, but when you get the query back with Django ...
I really like the answer from @Andrey-St, but a colleague pointed out that this makes a round trip to the database to do the work. So instead, we changed it to just grab the formatted query from the cursor. ``` def stringify_queryset(qs): sql, params = qs.query.sql_with_params() with connection.cursor() as ...
Django Queryset Filter Missing Quotes
[ "", "python", "django", "" ]
Sorry for the clunky title. An example will explain. Say I have a likes table, with an entry for each like ``` user_id | liked_id -------------------- 1 | a 2 | a 1 | b 2 | c ``` Meaning user `1` has liked items `a` and `b`, and user `2` has liked items `a` and `c`. To ...
Sure: Join the table to itself: ``` SELECT t1.liked_id, COUNT(*) FROM likes t1 JOIN likes t2 on t2.liked_id = t1.liked_id WHERE t1.user_id = 1 GROUP BY t1.liked_id ``` Not only is this an elegant way to code it, it is also the best performing, as long as there is an index on `liked_id` for join perfomance, and an ind...
You can try something like: ``` SELECT liked_id, COUNT(*) FROM likes GROUP BY liked_id HAVING count(case when user_id = 1 then 1 end) > 0; ``` `count(case when user_id = 1 then 1 end)` will count how many times `user_id = 1` liked particular `liked_id`. This query will get the results in one full scan. It will be...
Efficient way to aggregate a table only considering items that have a particular entry
[ "", "sql", "postgresql", "" ]
When I try to do the following construction in Python, I get, `"No module named foo"` **on the second line** ``` import my_package.my_very_long_module_name as foo from foo import f1, f2, f3 from foo import a, b, c from foo import x, y, z ``` `my_very_long_module_name` is a module (`my_very_long_module_name.py`) withi...
``` import my_package.my_very_long_module_name as foo from foo import f1, f2, f3 ``` The second line fails because python will try to find a module name `foo.py`, it won't use the variable `foo` you just imported. You can try something like this: ``` import my_package.my_very_long_module_name as foo f1, f2, f3 = foo...
While it is correct that you cannot use variables in import statements, you can simply access the variables of the module. Thus, you can do: ``` a = foo.a ``` And you can even write to `globals` if you insist. Honestly, though, I encourage you to just use the qualified `foo.a` in your code. It'll make it more readab...
Importing names from an aliased module. Is it possible?
[ "", "python", "python-import", "" ]
If I want to return more that one variable from a function in Python I have been doing the following: ``` def foo(): firstName = 'Bob' lastName = 'Jones' return [firstName, lastName] ``` Then if I wanted to find only the first name I would do this ``` [firstName, dummy] = foo() ``` However, say I initia...
No, there isn't. You are better of either changing all the code calling `fooInitial()`, or by adding a *different* method that returns the two parameters and have `fooInitial()` use that method: ``` def barInitial(): first_name, last_name = 'Bob', 'Jones' return first_name, last_name def fooInitial(): ret...
You could do this: ``` def foo(last=None): # current behaviour, change no code If not last: return 'bob' # new behaviour return first and last list return ['bob', 'jones'] ``` The addition of the named keyword with a default argument gives you your current behaviour for code you don't want to...
Python Function Return
[ "", "python", "function", "" ]
Let's take a look of the following example: ``` >>> class Foo(object): ... pass ... ``` ***My current understanding is when Python interpreter reads the line `class Foo(object)` [Foo class definition], it will create a Foo class object in memory.*** Then I did the following two tests: ``` >>> dir() ['Foo', '__b...
To be more specific, Python creates the class type object when it finishes processing the *entire* class definition (so being pedantic, it wouldn't create it until it had parsed and processed the `pass` line as well, in your example). This is typically only relevant in esoteric edge cases, like the following: ``` >>>...
The class object is created by the line `class Foo(object):`, yes. It is not created when it reads that line, though, it's created when it reaches the end of the class definition. The `id` of the class does not need to have any relation to the memory address. That's an implementation detail, and one you don't have any...
When does Python create class object in memory?
[ "", "python", "class", "object", "memory", "" ]
So this is the brief: i need to input something like: ``` BaSe fOO ThE AttAcK ``` and return: ``` attack the base. ``` As you can see to decode this i need to start by reading the words in reverse order and if the first letter of the word isupper() then make it lowercase and append it to a list which i will later p...
You're close, but you're switching between treating `i` as an index (`for i in range...`) and as the word itself (`uncrypted.append(i)`). And you probably meant `listdefault[i].istitle()` rather than `listdefault[:-i].istitle()`. The best solution is to change it to: ``` for w in listdefault[::-1]: if w.istitle()...
This can be done much simpler... ``` text = input("Code: ") result = [w.lower() for w in reversed(text.split()) if w[0].isupper()] print(' '.join(result)) ``` ``` Code: BaSe fOO ThE AttAcK attack the base ``` I hope this makes you want to learn Python deeper. By the way, you can't use `.istitle()` for this task, be...
Uncrypting a very simple code in python
[ "", "python", "python-3.x", "decode", "lowercase", "" ]
I am very new to Python, thus am possibly asking a simple question. I am wrting a multiprocess code with Python: ``` from multiprocessing import Process from multiprocessing import Queue class myClass(object): def __init__(self): self.__i = 0 self.__name = 'rob' return def target_fu...
`target_func` is called in separated process. `mc` is copied to each subprocess; not shared between processes. Using Thread, you will get expected(?) result. For safety you should use lock; I omitted it in following code. ``` from threading import Thread from Queue import Queue .... if __name__ == '__main__': ...
Processes don't share memory, unlike threads. The name \_\_i in the second process refers to a different variable, whose initial value was copied from the original process when you launched the subprocess. You can use the Value or Array data types to transfer information from one process to another, or you can use the...
change object value in threads using python
[ "", "python", "multiprocessing", "" ]
I have written a code that returns a phrase depending on the length of a name. Problem is, I can't submit it unless i fix this tiny error. Here's what I've written: ``` name = input('Enter your name: ') if len(name) <= 3: print ('Hi',name,', you have a short name.') elif len(name) > 8: print ('Hi',name,', you...
You're are right, print(x, y, z) will sequentially print x, y and z with a space inbetween. As you suggest, concatenate your name to your greeting, and then print the greeting: ``` name = input('Enter your name: ') if len(name) <= 3: greeting = "Hi {}, you have a short name.".format(name) elif len(name) > 8: gree...
The `print` function prints a space between its arguments. You can explicitly concatenate the strings to control the separation: ``` print('Hi ' + name + ', you have a short name.') ``` or use string formatting: ``` print('Hi {}, you have a short name.'.format(name)) ```
Concatenation - Python
[ "", "python", "concatenation", "" ]
I want to get the last cost with latest costing date and minimum cost for products. When I use the query below, it is giving me the Max Date and Min Cost for each column. Please see the screenshots below. ``` SELECT MAX(CostingDate) AS LatestDate, MIN(Cost) AS MinPrice, OutletCode, ProductID FROM AccountsCosting WH...
First you need to get the Latest Date then you can find the minimum cost for them. e.g. ``` select a.OutletCode, a.ProductID, LatestDate, MIN(Cost) AS MinPrice from ( SELECT MAX(CostingDate) AS LatestDate, OutletCode, ProductID FROM AccountsCosting WHERE OutletCode = 'C&...
If i understand you correctly, you want the minimum cost for the latest date?! Try this: ``` SELECT CostingDate AS LatestDate, Cost AS MinPrice, OutletCode, ProductID FROM AccountsCosting WHERE OutletCode = 'C&T01' and CostingDate in (SELECT MAX(CostingDate) as CostingDate FROM AccountsCosting WHERE OutletCode = 'C...
How to return MAX and MIN of a value from a table?
[ "", "sql", "max", "min", "" ]
I have a table with a column named `Skills` which contains comma separated values for different employees like ``` EmpID Skills 1 C,C++,Oracle 2 Java,JavaScript,PHP 3 C,C++,Oracle 4 JavaScript,C++,ASP 5 C,C++,JavaScript ``` So I want to write a query which will order all the employees first ...
Try this ``` SELECT * FROM ( SELECT * ,CASE WHEN Skills LIKE '%JavaScript%' THEN 0 ELSE 1 END AS Rnk FROM MyTable ) T ORDER BY rnk,EmpID ``` [**DEMO**](https://data.stackexchange.com/stackoverflow/query/edit/129130) OR ``` SELECT * FROM #MyTable ORDER BY CASE WHEN Skills LIKE '%JavaScript%' THEN 0...
You should **not** use one attribute to store multiple values. That goes against relation DB principles. Instead of that you should create additional table to store skills and refer to employee in it. Then, your query will looks like: ``` SELECT * FROM employees LEFT JOIN employees_skills ON employee.i...
How to use Order By clause on a column containing string values separated by comma?
[ "", "sql", "sql-server-2012", "sql-order-by", "" ]
I have a string that looks like this: ``` "{\\x22username\\x22:\\x229\\x22,\\x22password\\x22:\\x226\\x22,\\x22id\\x22:\\x222c8bfa56-f5d9\\x22, \\x22FName\\x22:\\x22AnkQcAJyrqpg\\x22}" ``` as far as I understand `\x22` is `"`. So how could I convert this into a readable JSON with quotes around keys and values?
Decode from `string_escape`: ``` >>> import json >>> value = "{\\x22username\\x22:\\x229\\x22,\\x22password\\x22:\\x226\\x22,\\x22id\\x22:\\x222c8bfa56-f5d9\\x22, \\x22FName\\x22:\\x22AnkQcAJyrqpg\\x22}" >>> value.decode('string_escape') '{"username":"9","password":"6","id":"2c8bfa56-f5d9", "FName":"AnkQcAJyrqpg"}' >>...
For a Unicode string under Python3, I found this: ``` value.encode('utf8').decode('unicode_escape') ``` <https://stackoverflow.com/a/14820462/450917>
How to convert characters like \x22 into a string?
[ "", "python", "encoding", "ascii", "" ]
I have the following code, and the idea is to be able to iterate over `root` for each string in `some_list[j]`. The goal is to stay away from nested for loops and learn a more pythonic way of doing this. I would like to return each `value` for the first item in `some_list` then repeat for the next item in `some_list`. ...
I *think* what you're trying to do is this: ``` values = ('{0}'.format(root.iter(item)) for item in some_list) for i, value in enumerate(values): # ... ``` But really, `'{0}'.format(foo)` is silly; it's just going to do the same thing as `str(foo)` but more slowly and harder to understand. Most likely you already...
So, given List A, which contains multiple lists, you want to return the first element of each list? I may not be understanding you correctly, but if so you can use a list comprehension...very "Pythonic" ;) ``` In [1]: some_list = [[1,2,3],[4,5,6],[7,8,9]] In [2]: new = [x[0] for x in some_list] In [3]: n...
Pythonic way of handling string formatted loop
[ "", "python", "python-3.3", "" ]
How can I ask if a string pattern, in this case `C`, exists within any element of this set without removing them each and looking at them? This test fails, and I am not sure why. My guess is that Python is checking if any element in the set **is** `C`, instead of if any element **contains** `C`: ``` n [1]: seto = set...
``` 'C' in seto ``` This checks to see if any of the members of seto is the exact string `'S'`. Not a substring, but exactly that string. To check for a substring, you'll want to iterate over the set and perform a check on each item. ``` any('C' in item for item in seto) ``` The exact nature of the test can be easil...
Taking [John's answer](https://stackoverflow.com/a/18196208/102441) one stage further, if you want to use the subset of items containing `C`: ``` items_with_c = {item for item in seto if 'C' in item} if items_with_c: do_something_with(items_with_c) else: print "No items contain C" ```
How can I tell if a string pattern exists within any element of a set in Python?
[ "", "python", "python-3.x", "iteration", "" ]
With this DataFrame, how can I conditionally set `rating` to 0 when `line_race` is equal to zero? ``` line_track line_race rating foreign 25 MTH 10 84 False 26 MTH 6 88 False 27 TAM 5 87 False 28 GP 2 86 False 29 ...
``` df.loc[df['line_race'] == 0, 'rating'] = 0 ```
Use [numpy.where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) to say *if ColumnA = x then ColumnB = y else ColumnB = ColumnB*: ``` df['rating'] = np.where(df['line_race']==0, 0, df['rating']) ```
How to conditionally update DataFrame column in Pandas
[ "", "python", "pandas", "" ]
I'm working on a code-checker for my students (I tutor). The project is that they write a function that prints a specific string using the `print` keyword. I want to be able to test what they have printed by storing it and matching to a list (or something similar). The basic setup is: ``` def checker(): #run user ...
You can assign a different file-like object to [`sys.stdout`](http://docs.python.org/2/library/sys.html#sys.stdout); anything that is printed is written to that object. You can use a [`io.BytesIO()` object](http://docs.python.org/2/library/io.html#io.BytesIO) to replace `stdout`: ``` import sys from io import BytesIO...
Here's one way - you can replace the standard output file object with a custom one: ``` import sys # A very basic logging class (it should really implement all the file object methods, but for your purposes, this will probably suffice. class basicLogger: def __init__(self): self.log = [] def write(sel...
Python 2.7 Keeping track of what's been printed
[ "", "python", "logging", "python-2.7", "" ]
I want to show the content of an object using the following code: ``` def get(self): url="https://www.googleapis.com/language/translate/v2?key=MY-BILLING-KEY&q=hello&source=en&target=ja" data = urllib2.urlopen(url) parse_data = json.load(data) parsed_data = parse_data['data']['translations'] // Th...
All I need, is convert from String to JSON object, as the following code : ``` # Convert to String parsed_data = json.dumps(parsed_data) # Convert to JSON Object json_object = json.loads(parsed_data) # Parse JSON Object translatedObject = json_object[0]['translatedText'] # Output to page, by using HTML self.respons...
``` parse_data = json.load(data) parsed_data = parse_data['data']['translations'] ``` Those lines already did the json.load, and extracted 'data' and 'translations'. Then instead of: ``` self.response.out.write(str( json.loads(parsed_data)[u'data'][u'translations'][u'translatedText'])) ``` you should: ``` self....
TypeError: expected string or buffer in Google App Engine's Python
[ "", "python", "json", "google-app-engine", "typeerror", "" ]
Sorry for my English, it's not my native language. I want to develop application with this basic functionality: 1. User can create tasks with subtasks. Level of hierarcy should be unlimited, so subtasks can have subtasks themselfs and so on. 2. User can create tags and every tasks can have unlimited level of tags, so...
Here are a few ideas - couchDB is considered a good type of key-value store for replication across multiple servers/clients. This is probably an appropriate type of database for the problem you are describing. Otherwise, using any kind of SQL/noSQL style database with a REST access point will work in your scenario. I...
Couchbase Lite is an embedded native NoSQL database for iOS and Android. It stores JSON documents and transparently syncs them via your cloud servers to other devices, with a security model designed for fine grained access control in multi-user interactive applications. Github repos here: * <https://github.com/couchb...
bare JSON, nosql db or sqlite for android and web app (maybe iOS) for task managment
[ "", "android", "sql", "json", "web", "nosql", "" ]
I have a "date" table similar to: ``` id date ---------------- 1 2012-02-02 2 2013-02-02 3 2014-04-06 ``` and a "date\_range" table similar to: ``` start end -------------------------- 2011-01-01 2013-01-01 2014-01-01 2016-01-01 ``` How can I get results from the "date" tabl...
Use `NOT EXISTS` ``` SELECT * FROM [Date] D WHERE NOT EXISTS ( SELECT 1 FROM Date_Range DR WHERE D.[Date] >= DR.[Start] AND D.[Date] <= DR.[End] ) ``` [**Demo**](http://sqlfiddle.com/#!6/14c0b/3/0)
``` SELECT * FROM date LEFT JOIN date_range ON date.date >= date_range.start AND date.date <= date_range.end WHERE date_range.start IS NULL ```
SQL results from a second table's ranges
[ "", "sql", "nested", "between", "" ]
I've been using ZeroMQ's request/response sockets for the purpose of exchanging messages between a web application and slave applications that were used for offloading processing. I've noticed that in a few cases, not all ZMQ messages sent were actually received by the other side. What's even weirded that this happens ...
I'm not familiar with the IPC protocol, but I've worked with ZMQ/TCP extensively. Even the simplest ZMQ REQ/REP pattern over TCP **will never drop messages** if you're using it properly. It may hang indefinitely if your network connection or remote endpoint goes down, but it will never silently fail. There are certain...
> What could be responsible for the sent message not being delivered, > while not producing any errors? If you're using `ROUTER` sockets to intermediate messages from server to zmq worker processes, `ROUTER`s, by default, will drop any outbound messages they can't deliver. What does "can't deliver" mean? ROUTERs maint...
ZeroMQ reliability?
[ "", "python", "zeromq", "" ]
I want to run the Linux word count utility wc to determine the number of lines currently in the /var/log/syslog, so that I can detect that it's growing. I've tried various test, and while I get the results back from wc, it includes both the line count as well as the command (e.g., var/log/syslog). So it's returning: 1...
I suggest that you use `subprocess.getoutput()` as it does exactly what you want—run a command in a shell and get its [string output](http://docs.python.org/3.1/library/subprocess.html#subprocess.getoutput) (as opposed to [byte string](http://docs.python.org/3.1/library/subprocess.html#subprocess.check_output) output)....
Since Python 3.6 you can make `check_output()` return a `str` instead of `bytes` by giving it an *encoding* parameter: ``` check_output('wc --lines /var/log/syslog', encoding='UTF-8') ``` But since you just want the count, and both `split()` and `int()` are usable with `bytes`, you don't need to bother with the encod...
Python3 subprocess output
[ "", "python", "python-3.x", "subprocess", "" ]
I have a table in my PostgreSQL database which has 3 columns - `c_uid`, `c_defaults` and `c_settings`. `c_uid` simply stores the name of a user and `c_defaults` is a long piece of text which contains a lot of data w.r.t that user. I have to execute a statement from a bash script which selects the value of the `c_defau...
Try this one: ``` #!/bin/bash psql -U postgres -d database_name -c "SELECT c_defaults FROM user_info WHERE c_uid = 'testuser'" ``` Or using `su`: ``` #!/bin/bash su -c "psql -d database_name -c \"SELECT c_defaults FROM user_info WHERE c_uid = 'testuser'\"" postgres ``` And also `sudo`: ``` #!/bin/bash sudo -u po...
You can connect to psql as below and write your sql queries like you do in a regular postgres function within the block. There, bash variables can be used. However, the script should be strictly sql, even for comments you need to use -- instead of #: ``` #!/bin/bash psql postgresql://<user>:<password>@<host>/<db> << E...
PostgreSQL - query from bash script as database user 'postgres'
[ "", "sql", "bash", "postgresql", "" ]
I have a function `accuracy(n)` which sets accuracy for float number n. Is it possible to overload somekind of operator of type float so that: ``` f = 1.5 x = f ``` would be automatically implemented (in the background) as: ``` x = accuracy(f) ``` Thanks a lot **Edit** Is it possible to overload `__eq__` of `float...
There isn't any overloading you can do so that those exact lines will behave the way you described, but you can get something similar: ``` class Foo(object): @property def x(self): return self._x @x.setter def x(self, value): self._x = accuracy(value) foo = Foo() f = 1.5 foo.x = f ...
No. But you can create a class that defines `__float__()` so that the new value is used when the object is used in a float context.
redefine behaviour of float
[ "", "python", "operator-overloading", "" ]
I want to check if a string the user inputted contains one of the strings in a list. I know how to check if the string contains **one string** but I want to know how to check if a string contains either this string, or that string, or another string. For example, if I am checking the user's input to see if it contain...
``` >>> vowels = set(['a', 'e', 'i', 'o', 'u']) >>> inp = "foobar" >>> bool(vowels.intersection(inp)) True >>> bool(vowels.intersection('qwty')) False ```
Using [any](http://docs.python.org/2/library/functions.html#any): ``` >>> vowels = 'a', 'e', 'i', 'o', 'u' >>> s = 'cat' >>> any(ch in vowels for ch in s) True >>> s = 'pyth-n' >>> any(ch in vowels for ch in s) False ```
How to check if a string contains a string from a list?
[ "", "python", "python-3.x", "" ]
Using Cython, I am developing an extension module which gets build as an .so file. I then test it using IPython. During development, I frequently need to make changes and rebuild. I also need to exit the IPython shell and reenter all commands. Reimporting the module with ``` import imp imp.reload(Extension) ``` does ...
C extensions cannot be reloaded without restarting the process (see [this official Python bug](http://bugs.python.org/issue1144263) for more info). Since you are already using IPython, I might recommend using one of the two-process interfaces such as the Notebook or QtConsole, if it's acceptable to you. These allow yo...
You can try setting an `autoreload` in the `ipython shell`, [documentation here](http://ipython.org/ipython-doc/dev/config/extensions/autoreload.html). Set `autoreload` ``` In [1]: %load_ext autoreload In [2]: %autoreload 2 ``` Set `autoreload` on specific module ``` %aimport foo ``` Also, take a look at [`dreloa...
Reloading a Python extension module from IPython
[ "", "python", "python-3.x", "ipython", "cython", "" ]
There are two tables named *masters* and *versions*. The *versions* table holds entries of the *master* table at different points in time. ``` ------------------------- masters ------------------------- id | name | added_at ----+-------+------------ 1 | a-old | 2013-08-13 2 | b-new | 2012-04-19 3 | c-old | 2...
There is no need to fire subquery twice. * [Here is SQLFiddle Demo](http://sqlfiddle.com/#!2/e56eb9/1) Below is the update statement ``` update masters m, ( select id, name, added_at, master_id from versions order by added_at desc ) V set m.name = v.name, m.added_at = v.added_at where v.master_id =...
This might do what you need: ``` REPLACE INTO masters SELECT v.master_id,v.name,v.added_at FROM versions v WHERE v.added_at = (SELECT MAX(vi.added_at) FROM versions vi WHERE vi.master_id = v.master_id); ``` Note that this relies on masters having a primar...
How to update multiple columns based on values from an associated table?
[ "", "mysql", "sql", "sql-update", "sqldatetime", "sql-limit", "" ]
I just tried to learn both list comprehensions and Lambda functions. I think I understand the concept but I have been given a task to create a program that when fed in a positive integer creates the identity matrix. Basically if I fed in 2 it would give me: [[1, 0],[0, 1]] and if I gave it 3: [[1, 0, 0],[0, 1, 0], [0, ...
How about: ``` >>> imatrix = lambda n: [[1 if j == i else 0 for j in range(n)] for i in range(n)] >>> imatrix(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] ``` `1 if j == i else 0` is an example of Python's [conditional expression](http://www.python.org/dev/peps/pep-0308/).
This would be my favorite way to do it: ``` identity = lambda x: [[int(i==j) for i in range(x)] for j in range(x)] ``` It takes advantage of the fact that `True` maps to 1 and `False` maps to 0.
Python Lambda Identity Matrix
[ "", "python", "python-3.x", "matrix", "lambda", "algebra", "" ]
Can the list ``` mylist = ['a',1,2,'b',3,4,'c',5,6] ``` be used to create the dict ``` mydict = {'a':(1,2),'b':(3,4),'c':(5,6)} ```
You can try something like this: ``` >>> mylist = ['a',1,2,'b',3,4,'c',5,6] >>> >>> v = iter(mylist) >>> mydict = {s: (next(v),next(v)) for s in v} >>> mydict {'a': (1, 2), 'c': (5, 6), 'b': (3, 4)} ```
Only if you have some kind of criteria which ones are the keys. If the strings are the keys then: ``` d = {} key = None for item in my_list: if isinstance(item, str): key = item else: d.setdefault(key, []).append(item) ```
Python list to dict with multiple values for each key
[ "", "python", "" ]
I'm trying to setup a Flask application on a machine running Apache and mod\_wsgi. My application runs 'randomly' well, meaning that sometimes it works and sometimes I refresh it and it throws an Internal Server Error. It seems quite random.. I have cleared the cache of my browser, tried a different browser, tried inco...
Miguel's answer makes sense and indeed restarting the server fixes this and other problems (changes not taking effect). My uneducated guess is that the different processes running under Apache load at some point the modules of the application and when a refresh is issued they won't 'bother' to update this information....
I had the same problem on Apache+wsgi+Django. I have tried [setting up wsgi in Daemon mode](https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/#using-mod-wsgi-daemon-mode), as recommended by Django manual, and that seems to solve the problem. I have now done 1000 pageloads with no 500 responses. The s...
Intermitent 500 HTTP errors with Flask and WSGI
[ "", "python", "apache", "flask", "mod-wsgi", "wsgi", "" ]
I have some arbitrary curve in 3 dimensions made up of a list of XYZ cartesian points. The points are not evenly distributed (theres a time factor). How can I 'rebuild' the curve with a given number of points that should make up the curve. I see this done in 3D modeling programs so im pretty sure its possible, I just d...
I'd use [interparc](http://www.mathworks.com/matlabcentral/fileexchange/34874-interparc), a tool of mine designed to do exactly that. It fits a spline through a general space curve in 2 or more dimensions, then chooses points that are equally spaced in terms of distance along that curve. In the case of a cubic spline, ...
First of all, thank you to Mr. John D'Errico for interparc. What a great job! I too was facing this problem but am not familiar with the MATLAB engine API. Given that, I tried to convert part of the interparc Matlab code to Python (just including the linear interpolant because it would be enough to address my problem)...
How to redistribute points evenly over a curve
[ "", "python", "math", "3d", "" ]
I have following two code samples Example 1: ``` class MyClass(object): def __init__(self, key, value): self._dict = self._dict.update({key:value}) m = MyClass('ten',10) print m._dict ``` Output: ``` AttributeError: 'MyClass' object has no attribute '_dict' ``` Example2: ``` class MyClass(object): ...
The `None` output is because `dict.update` returns None. It modifies the dictionary itself, but does not return anything. So you probably wanted `self._dict.update({key:value})`. However, `self._dict` doesn't exist at initialization. So it would make more sense to do `self._dict = {key: value}`. If you're trying to mod...
Your 'example 2' defines a single dictionary at the class level. All instances of the class will share that same dictionary, at least unless you reassign \_dict on the instance. See this question for a detailed explanation: [Why do attribute references act like this with Python inheritance?](https://stackoverflow.com/...
Python : Behavior of class and instance variables
[ "", "python", "instance-variables", "class-variables", "" ]
I'm new to Django but I've been really enjoying it. But occasionally I seem to run into places where I just don't seem to get things correct. So, I'm asking for some help and guidance. I'm trying to extend the object-tools for one of my models so I can have a Print button next to History. My templates is as follows: ...
The problem is that `admin/change_form.html` in your `{% extend %}` block is getting resolved as `project/app/templates/admin/change_form.html`. One solution is to create a subdirectory of `templates` named for your app - possibly `project/templates/admin/app/change_form.html`. > In order to override one or more of t...
That's because you're extending the template with itself. What I do is put my custom admin templates in `templates/admin`. Then in that same folder I symlink to the django admin folder (`templates/admin/admin`). So my extends looks like: ``` {% extends 'admin/admin/change_form.html' %} ``` Make sure you also overri...
Django 1.5 extend admin/change_form.html object tools
[ "", "python", "django", "recursion", "django-templates", "django-admin", "" ]
I need to replace/update values in my table according att\_id for each customer\_id. The table looks like: ``` ID att_id customer_id value 1 5 1 name 2 30 1 12345 3 40 1 4 5 2 name2 5 30 2 12345 6 40 2 ``` I'd like to replace it...
**UPDATE**: Based on your comments *...I need to find values for attribute 30, check if they are mobile phone numbers, and if it's true, write it itno value for attribute 40...* your query might look like this ``` UPDATE table1 t1 JOIN table1 t2 ON t1.customer_id = t2.customer_id AND t1.att_id = 40 AND t2.a...
Here is a general approach for swapping the values on rows with `att_id` equal to 30 and 40: ``` update t join t t30 on t.customer_Id = t30.customer_Id and t30.att_id = 30 join t t40 on t.customer_Id = t40.customer_Id and t40.att_id = 40 join set t.value = (case when att_id = 30 then t4...
How to update value in same table using mysql?
[ "", "mysql", "sql", "" ]
I have a simple MySQL query like this: ``` SELECT * , ( MATCH (table.get) AGAINST('playstation ' IN BOOLEAN MODE) ) + ( table.get LIKE '%playstation%') AS _score FROM table JOIN users on table.id_user = users.id WHERE table.expire_datetime > 1375997618 HAVING _score > 0 ORDER BY RAND(table.id) ,_score DESC ; `...
``` select * from <my_table> ORDER BY RAND() LIMIT 4 ```
You would quit seeding the random number generator. My guess is that it is returning the first table id encountered, so the numbers are generated in the same sequence: ``` SELECT * , ( MATCH (table.get) AGAINST('playstation ' IN BOOLEAN MODE) ) + ( table.get LIKE '%playstation%') AS _score FROM table JOIN users o...
Get random record in a set of results
[ "", "mysql", "sql", "random", "" ]
In a table we have schools' data: ``` ID | Name | City ------------------ 1 A X 2 B X 3 C Z 4 D Z ``` I want to have a list of each two schools that are in the same city: ``` Name1 | Name2 -------------- A B C D ``` I chose schools in th...
**UPDATE** Another way to do it One way to do that if you insist on grouping ``` SELECT City, MIN(Name) Name1, MAX(Name) Name2 FROM Schools GROUP BY City -- HAVING COUNT(*) > 1 ``` Another way ``` SELECT City, MIN(CASE WHEN rnum = 1 THEN Name END) Name1, MIN(CASE WHEN rnum = 2 THEN Na...
``` SELECT a.Name, b.Name FROM Schools a JOIN Schools b ON a.City = b.City AND a.ID != b.ID AND a.Name < b.Name; ``` This returns all the pairs of schools in the same city, not only a pair for each city.
Select 2 records which were grouped, Then put them in 2 columns along side
[ "", "sql", "sql-server", "database", "pivot", "" ]
I'm trying to write a python tool that will read a logfile and process it One thing it should do is use the paths listed in the logfile (it's a logfile for a backup tool) ``` /Volumes/Live_Jobs/Live_Jobs/*SCANS\ and\ LE\ Docs/_LE_PROOFS_DOCS/JEM_lj/JEM/0002_OXO_CorkScrew/3\ Delivery/GG_Double\ Lever\ Waiters\ Corkscr...
If you're reading paths out of a file, and passing them to functions like `os.path.getsize`, you don't need to escape them. For example: ``` >>> with open('name with spaces', 'w') as f: ... f.write('abc\n') >>> os.path.getsize('name with spaces') 4 ``` In fact, there are only a handful of functions in Python that...
Try this: ``` myfile = open(r'c:\tmp\junkpythonfile','w') ``` The 'r' stands for a raw string. You could also use \ like ``` myfile = open('c:\\tmp\\junkpythonfile','w') ```
Escape space in filepath
[ "", "python", "regex", "" ]
If have a text (actually lots of texts), where somewhere is one ISBN inside, and I have to find it. I know: my ISBN-13 will start with "978" followed by 10 digits. I don't kow: how many '-' (minus) there are and if they are at the correct place. My code will only find me the ISBN without any Minus: ``` regex=r'978[...
This matches 10 digits and allows one optional hyphen before each: ``` regex = r'978(?:-?\d){10}' ```
Since you can't have 2 consecutive hyphens, and it must end with a digit: `r'978(-?\d){10}'` ... allowing for a hyphen right after then `978`, mandating a digit after every hyphen (does not end in a hyphen), and allowing for consecutive digits by making each hyphen optional. I would add `\b` before the `978` and aft...
Find ISBN with regex in Python
[ "", "python", "regex", "" ]
So what I am trying to do if a result in my select has the same post\_data\_id as another post\_id remove that result but show one of them. I've been trying for days to try to get this to work but have failed miserably. Please check my SQL Fiddle asweel as the screenshot for what I mean View the [SQLFiddle](http://sql...
There's likely a simpler method for this, but you could use: ``` SELECT p.* FROM posts p LEFT JOIN following f ON f.user_id=1 AND p.post_user_id = f.follower_id WHERE (post_user_id=1 OR f.follower_id IS NOT NULL) AND (POST_DATA_ID NOT IN (SELECT POST_ID FROM posts p ...
You can't really DELETE *and* SELECT in one statement. You will always need to execute two statements consecutively. I am not sure which rows you wanted to delete (the duplicate post\_id or the duplicate post\_data\_id), but you're going to need two of the following four statements: ``` SELECT * FROM posts WHERE post...
Need some help hiding duplicates from results MYSQL
[ "", "mysql", "sql", "" ]
Im writing a simple function to take out any odd numbers from a list and return a list of only the even ones. ``` def purify(numbers): for i in numbers: if i%2!=0: numbers.remove(i) return numbers print(purify([4,5,5,4])) ``` However, the above returns: ``` [4, 5, 4] ``` Why doesn't...
When you remove an item, the items that follow get moved one position to the left. This results in the loop skipping some items. BTW, a more idiomatic way to write that code is ``` numbers = [num for num in numbers if num % 2 == 0] ```
One option I didn't see mentioned was, ironically `filter`: ``` >>> filter(lambda x: not x % 2, [4,5,5,4]) [4, 4] ```
How to filter a list
[ "", "python", "" ]
This is kind of hard to explain in words but here is an example of what I am trying to do in SQL. I have a query which returns the following records: ``` ID Z --- --- 1 A 1 <null> 2 B 2 E 3 D 4 <null> 4 F 5 <null> ``` I need to filter this query so that each unique record...
If you need to return both 2-B and 2-E rows: ``` SELECT * FROM YourTable t1 WHERE Z IS NOT NULL OR NOT EXISTS (SELECT * FROM YourTable t2 WHERE T2.ID = T1.id AND T2.z IS NOT NULL) ```
You can use `GROUP BY` for that: ``` SELECT ID, MAX(Z) -- Could be MIN(Z) FROM MyTable GROUP BY ID ``` Aggregate functions ignore `NULL`s, returning them only when all values on the group are `NULL`.
Filter unique records from a database while removing double not-null values
[ "", "sql", "sql-server-2008-r2", "" ]
Is there a way that I can execute a shell program from Python, which prints its output to the screen, and read its output to a variable without displaying anything on the screen? This sounds a little bit confusing, so maybe I can explain it better by an example. Let's say I have a program that prints something to the...
To add to Ryan Haining's answer, you can also handle stderr to make sure nothing is printed to the screen: ``` p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, close_fds=True) out,err = p.communicate() ```
If `subprocess.check_ouput` is not working for you, use a [Popen](http://docs.python.org/2/library/subprocess.html#subprocess.Popen) object and a `PIPE` to capture the program's output in Python. ``` prog = subprocess.Popen('./myprog', shell=True, stdout=subprocess.PIPE) output = prog.communicate()[0] ``` the `.commu...
Executing shell program in Python without printing to screen
[ "", "python", "python-2.7", "subprocess", "" ]
I am trying to delete from a table(`MyTable`) that has a `foreign key` reference linking it to 4 other tables. I needed to delete all the data `MyTable` that is referenced by `Table1` and `Table2`, but NOT `Table3` and `Table4`. I have already deleted the data in `Table1` and `Table2` I tried something like this: ``...
(Rewritten answer to SQL Server syntax after some basic research and finding [The DELETE statement in SQL Server](https://www.simple-talk.com/sql/learn-sql-server/the-delete-statement-in-sql-server/).) Use the multiple table syntax of the `DELETE` statement. ``` DELETE MyTable FROM MyTable LEFT JOIN Table1 ON M...
Probably not too efficient, but the below should work. It should "delete all the data [in] MyTable that is referenced by Table1 and Table2, but NOT Table3 and Table4". Your query seems to not exactly match up with desiring to do this. ``` DELETE FROM MyTable WHERE ID IN (SELECT MyTableID FROM Table1) AND ID IN (S...
delete from table with foreign keys to other tables
[ "", "sql", "sql-server", "" ]
I'm trying to do something that may appear to be simple, but I can't figure it out. As always, django surprises me with its complexity... My view generates an instance of a model and "passes it on" in a context to a template. On that template, the user fills a form and submits it. And this is what should happen next: ...
This is not related to django. It's how the web works. HTTP is stateless. When you generate the page, you've finished with that task. The model instance is destroyed. When the user submits the form or sends the modifications in any other way, a new connection starts with a new request and a new context. At this point ...
You cannot pass a model (or any Python object) directly to another page. There are workarounds (sessions, serializers) but in most cases these are not necessary. In your case it's not necessary or even recommended to pass the actual Python object. Django supplies many features and options for [form handling](https://d...
Reusing an object from a context after submitting a form
[ "", "python", "django", "" ]
I have a one liner `if` statement that looks like this: ``` var = var if var < 1. else 1. ``` The first part `var = var` looks a bit ugly and I'd bet there's a more pythonic way to say this.
The following is *39%* shorter and in my opinion is simpler and more pythonic than other answers. *But* we should note that sometimes people get it wrong thinking that 1 is a lower bound being confused by `min` function when actually 1 is an upper bound for `var`. ``` var = min(var, 1.0) ```
``` if var >= 1.: var = 1 ``` or if you like one liners ``` if var >= 1.: var = 1 ```
Simplify one line if statement
[ "", "python", "if-statement", "" ]
I'm taking a beginning Python course, and am having problems trying to do a regex substitution. The question states: Write a substitution command that will change names like file1, file2, etc. to file01, file02, etc. but will not add a zero to names like file10 or file20. Here's my solution: ``` re.sub(r'(\D+)(\d)$'...
``` import re print re.sub(r'(\D+)(\d)$',r'\g<1>0\2','file1') ``` Don't ask.. just do the \g<#> thing and it'll work fine in python. Other languages have the same issue: <http://resbook.wordpress.com/2011/01/04/regex-with-back-references-followed-by-number/>
dont know python, but in your regex you just want one digit and not two for the match you can do it like this ``` .+[^\d]\d$ ``` test1 will match test1 will not match Good luck
Python regex reference conflicting with substitution number
[ "", "python", "regex", "substitution", "" ]
I need to write 1 state that would do multiple things. **Here is first select which selects count and it works fine.** ``` select PLANNED from (SELECT count(FACT.EVENT) AS PLANNED FROM FACT FACT WHERE FACT.PLANNEDOTGFLAG = 1 AND FACT.STARTDATETIME >= SYSDATE - 365 ) ``` I n...
Your second query will give you an error as the table that is resulted in FROM clause will return only one column (2 rows), first row will have `PLANNED_OUTAGES` and 2nd will have `effect` count respectively. For your requirement you could change your query to: Included 3rd query: ``` SELECT A.PLANNED_OUTAGES,B.effe...
Since you're getting two different counts from the same table, I suggest using case statements: ``` SELECT Planned_Outages = COUNT(CASE WHEN Fact.PlannedOTGFlag = 1 AND Fact.StartDateTime >= Sysdate - 365 THEN Fact.Event END), Effec = COUNT(CASE WHEN FactStartTime between '01/01/2013' and '01/02/2013' THEN F...
multiple select from query Error
[ "", "jquery", "sql", "oracle", "oracle11g", "" ]
I have field of `REAL` type in db. I use PostgreSQL. And the query ``` SELECT * FROM my_table WHERE my_field = 0.15 ``` does not return rows in which the value of `my_field` is `0.15`. But for instance the query ``` SELECT * FROM my_table WHERE my_field > 0.15 ``` works properly. How can I solve this problem and ...
To *solve* your problem use the data type [**`numeric`**](https://www.postgresql.org/docs/current/datatype-numeric.html) instead, which is not a floating point type, but an arbitrary precision type. If you enter the [numeric literal](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS-...
Your problem originates from [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). `0.15` is not `0.15`, but `0.15000000596046448` (assuming double precision), as it can not be exactly represented as a binary floating point number. ([check this calculator](http://users.minet.uni-jena.de/~sack/SS04/download/IE...
Value of real type incorrectly compares
[ "", "sql", "postgresql", "types", "floating-point", "numeric", "" ]
Using CQL3, how does one enumerate all the partition keys of a table in Cassandra? In particular there are complications with returning distinct keys, and paginating the results.
With a little pre-knowledge about the possible values of your keys, I think this could be done using with the help of the token function. Take a look at [this answer](https://stackoverflow.com/a/11889327/2459609). Is that what you are looking for? Also, native pagination seems to be [an upcoming feature for 2.0](https...
The bad news is that for now (August 2013) you have to select the entire primary key, not just the partition key, to paginate through them. With a compound PK, this may involve a lot of duplicate partition keys. The good news is that <https://issues.apache.org/jira/browse/CASSANDRA-4536> is open to allow `SELECT DISTI...
Using CQL to walk partition keys of a Cassandra table
[ "", "sql", "cassandra", "partitioning", "cql", "cql3", "" ]
This is my assignment: > Write a program which reads in text from the keyboard until an > exclamation mark ('!') is found. > > Using an array of integers subscripted by the letters 'A' through 'Z', > count the number occurrences of each letter. In a separate counter, > also count the total number of "other" characters...
In the block ``` for character in msg.upper(): if count_character[ord(character)] > max_letter: max_letter = count_character[ord(character)] count_hi = count_hi + 1 ``` count\_hi will be the number of times a different letter was selected as the one with the highest count, not the index of the let...
The most-occuring item is finding the mode. The following will work assuming the list is sorted: ``` def get_mode(list): current_mode = list[0] new_mode = current_mode mode_count = 1 top_count = 1 for idx in range(0, len(list)): if list[idx] == modeChar: mode_count += 1 else: ...
How to Count Most & Least Common Characters in Input?
[ "", "python", "arrays", "counter", "subscript", "" ]
Yes, I know about [IronPython 3 compatibility](https://stackoverflow.com/questions/7751767/ironpython-3-compatibility), but that is from two years ago. I was searching on the internet but couldn't find any information on this that is up-to-date. So does IronPython support Python 3? If not, how many of the future impor...
IronPython 3 is once again alive. An alpha for Python 3.4 was released in April 2021. It is a very active effort which is being supported by the .NET Foundation. More here: [Python 3.4 Release Notes](https://github.com/IronLanguages/ironpython3/releases/tag/v3.4.0-alpha1)
Currently it doesn't support Python3. [IronPython3 Todo](http://blog.jdhardy.ca/2013/06/ironpython-3-todo.html). All future imports supported by the standard Python 2.7 interpreter should be supported by the newest version of IronPython. And there are no Iron-specific ways to make it seem more like Python3 as far as I...
IronPython 3 support?
[ "", "python", "python-3.x", "ironpython", "" ]
So I have the following: ``` myString = "This is %s string. It has %s replacements." myParams = [ "some", "two" ] # This is a function which works (and has to work) just like that myFunction(myString, myParams) ``` Now when I debug, I do the following: ``` print("Debug: myString = " + myString) print("Debug: myPara...
You need to use a *tuple*; cast your list into a tuple and that works just fine: ``` >>> myString = "This is %s string. It has %s replacements." >>> myParams = [ "some", "two" ] >>> myString % tuple(myParams) 'This is some string. It has two replacements.' ``` Define `myParams` to be a tuple to start with: ``` >>> m...
I'm using python 2.7 but this is quite close and tidy to what you're seeking I am using the `*` or splat operator to unpack the list into positional arguments (or a tuple) and feeding that tuple into `format()` and using format on the `myString` variable is possible by changing the `%s` to `{index}`. ``` >> myString ...
Insert replacements into %-string subsequently
[ "", "python", "" ]
I have a list of dictionaries. e.g: ``` list = [ {list1}, {list2}, .... ] ``` One of the key-value pair in each dictionary is another dictionary. Ex ``` list1 = { "key1":"val11", "key2":"val12", "key3":{"inkey11":"inval11","inkey12":"inval12"} } list2 = { "key1":"val21", "key2":"val22", "key3":{"inkey21":"inval21","...
I think a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) would work well here: ``` [innerdict["key3"] for innerdict in list] ```
Try this: ``` list1["key3"] ``` Notice that `list1` and `list2` as you defined them are dictionaries, not lists - and the value of `"key3"` is a *set*, not a list. You're confounding `{}` with `[]`, they have different meanings.
Get a list from the dictionary key in a list of dictionaries
[ "", "python", "" ]
I currently get output like this: <http://www.site.com/prof.php?pID=478http://www.site.com/prof.php?pID=693> after using suggestion from commenter below I have: ``` urls = [el.url for el in domainLinkOutput] return HttpResponse(urls) ``` How do I turn this output into a python dictionary like: ``` urls = { '0': 'h...
I don't believe you need regex here - just use attribute access on the `Link` objects you have... If you have a list of `Link` objects, then use something like: ``` urls = [el.url for el in list_of_objects] ``` You should just be able to get the url by `Link_object.url`...
Use this regex for matching the urls: ``` url='([^']+)' ``` Sample output: ``` [0] => http://www.somesite.com/prof.php?pID=478 [1] => http://www.somesite.com/prof.php?pID=527 [2] => http://www.somesite.com/prof.php?pID=645 ``` If you want to exclude the parameters, use ``` url='([^'?]+) ``` Sample out...
Grab Strings with Python Attribute Access Link Access into Dictionary
[ "", "python", "" ]
I have 3 tables. The `user_sticker` holds all sent stickers between users. When the profile view screen is loaded, i need to display which is the most common sticker that has been given to the user. **user** * id\_user * name **sticker** * id\_sticker * name **user\_sticker** * id\_user\_sticker * id\_sticker * i...
Ok, lets see In principal, you need to use the user\_sticker table. So: ``` SELECT * FROM user_sticker us ``` Then, match with the user table for user\_to ``` SELECT * FROM user_sticker us JOIN user u ON us.id_user_to = u.id_user ``` Then, you want the name and the stickers the user you want recieve ``` SELECT us...
this would be the select: ``` select id_user_to, count(id_sticker) quant from user_sticker group by id_sticker order by quant desc limit 1; ``` now with the info of the user: JOIN ``` select us.id_user_to, u.name, count(us.id_sticker) quant from user_sticker us join user u on u.id_user=us.id_user_to group by us....
Returning most common linked ID for a user
[ "", "mysql", "sql", "" ]
I really dont get this, tried with coalesce() but with no result... I have one select (very simplified to understand the problem): ``` select col1, col2 from table1 t1 where table1.col1='value' and table1.col2='value2' and table1.col3='value3' ``` And i really need a result so if this se...
Something like: ``` ; WITH Base AS ( select col1, col2 from table1 t1 where table1.col1='value' and table1.col2='value2' and table1.col3='value3' ) , Base2 AS ( select col1, col2 from table1 t1 where table1.col1='another_value' ...
It could benefit us a little better if you had a little more information in your example. Is there a common value between the two tables that a JOIN can be established? ``` SELECT col1 ,col2 FROM Table1 t1 WHERE table1.col1='value' and table1.col2='value2' and table1.col3='value3' UNION SELE...
Select only when first select is null
[ "", "sql", "select", "conditional-statements", "" ]
I have problem when executing this code: ``` SELECT * FROM tblpm n WHERE date_updated=(SELECT MAX(date_updated) FROM tblpm GROUP BY control_number HAVING control_number=n.control_number) ``` Basically, I want to return the most recent date for each control number. The query above returns correct output but it take...
Putting the subquery in the WHERE clause and restricting it to n.control\_number means it runs the subquery many times. This is called a *correlated subquery*, and it's often a performance killer. It's better to run the subquery once, in the FROM clause, to get the max date per control number. ``` SELECT n.* FROM tb...
There's no need to group in that subquery... a where clause would suffice: ``` SELECT * FROM tblpm n WHERE date_updated=(SELECT MAX(date_updated) FROM tblpm WHERE control_number=n.control_number) ``` Also, do you have an index on the 'date\_updated' column? That would certainly help.
GROUP BY having MAX date
[ "", "mysql", "sql", "optimization", "greatest-n-per-group", "" ]
I want to display the date in below format ``` July 23, 2011 SELECT REG_NO, FORMAT(DOB ,'YYYY/MM/DD') FROM Students ; ``` I tried below ``` SELECT REG_NO, FORMAT(DOB ,'MON DD,YYYY') FROM Students ; ``` It seems not working
use **to\_char** The syntax is `to_char( value, [ format_mask ], [ nls_language ] )` ``` SELECT REG_NO, TO_CHAR(DOB ,'MONTH DD,YYYY') FROM Students ; ```
How about trying this one: ``` SELECT REG_NO, to_char(DOB, 'FMMonth DD, YYYY') FROM Students; ``` [TO\_CHAR()](http://www.techonthenet.com/oracle/functions/to_char.php)
Displaying date in Month DD,YYYY format
[ "", "sql", "oracle", "" ]
How can i join a string that contains quotation marks? Here is an example, of a program to generate HTML image tags. But the program is not printing correctly. ``` import sys sys.stdout = open("/Users/kyle/images.html", "w") for x in xrange(100,490): site = "http://www.example.com/image"+str(x)+".jpg" print "...
Yes, you can use a single-quoted string for the `print` statement, and then include the double-quoted strings literally: ``` print '<img src="' + site + '">' ``` I generally prefer using `str.format()` for this kind of thing, though, because it makes the position of the output more obvious. ``` print '<img src="{0}"...
Python doesn't care which quotes you use. ``` print '<img src="' + site + '">' ```
Join string containg quotation marks
[ "", "python", "html", "join", "tags", "" ]
I have two lists: ``` list1 = [ set(['3105']), set(['3106', '3107']), set(['3115']), set(['3122']), set(['3123', '3126', '286']) ] ``` and ``` list2 = [ set(['400']), set(['3115']), set(['3100']), set(['3107']), set(['3123', '3126']) ] ``` How do I compare the intersection of...
You can flatten the two lists of sets into sets: ``` l1 = set(s for x in list1 for s in x) l2 = set(s for x in list2 for s in x) ``` Then you can compute the intersection: ``` common = l1.intersection(l2) # common will give common elements print len(common) # this will give you the number of elements in common. ```...
You'd have to merge all sets; take the unions of the sets in both lists, then take the intersection of these two unions: ``` sets_intersection = reduce(set.union, list1) & reduce(set.union, list2) if 3126 in sets_intersection: # .... ```
Python - Comparing two lists of sets
[ "", "python", "list", "intersection", "set", "" ]
Let's say I have a table like this: ``` |id|userID|email |website | -------------------------------------- |1 |user1 |user1@test.com|website.com| |2 |user2 |user2@test.com|website.com| |3 |user3 |user3@test.com|website.com| |4 |user1 |user1@test.com|foo.com | |5 |user2 |user2@test.com|foo.com | ``` A...
To get the user you can do ``` select userID from your_table where website in ('website.com', 'foo.com') group by userID having count(distinct website) = 2 ``` but if you need the complete row then do ``` select * from your_table where userID in ( select userID from your_table where website in ('website.com...
Here is one way: ``` select t.* from t where t.website = 'website.com' and exists (select 1 from t t2 where t2.userId = t.userId and t2.website = 'foo.com'); ``` EDIT: You can also express this as a join: ``` select distinct t.* from t join t2 on t2.userId = t.userId and t.website = 'website...
Get all rows with a matching field in a different row in the same table
[ "", "sql", "hive", "impala", "" ]
I'm having a difficult time extracting a value from a subquery. Suppose I have following tables: **D( fid , pid , r ),** **F( fid , t , j )** I need f.j from a subquery below at the first select. ``` SELECT pid -- Here I need f.j to show up FROM D WHERE r='something' AND fid IN ( SELECT f2....
Since there is no sample data it is not clear what should be the output, still you can try the following but this is not optimized. ``` SELECT pid , t.j -- Here I need f.j to show up FROM D INNER JOIN ( SELECT f2.fid , f2.j FROM F f2 , ...
I would create a temp table in this form **T( pid , j )**. Then you can insert all the pid and f.j data separately.
Extracting value from subquery to main query
[ "", "sql", "" ]
I have an array: ``` >>> data = np.ones((1,3,128)) ``` I save it to file using `savez_compressed`: ``` >>> with open('afile','w') as f: np.savez_compressed(f,data=data) ``` When I try to load it I don't seem to be able to access the data: ``` >>> with open('afile','r') as f: b=np.load(f) >>> b.file...
When using `numpy.load` you [can pass the file name](http://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html), and if the extension is `.npz`, it will first decompress the file: ``` np.savez_compressed('filename.npz', array1=array1, array2=array2) b = np.load('filename.npz') ``` and do `b['array1']` and s...
> You can also use the `f` attribute, which leaves you with a > `np.ndarray`: ``` images_npz = np.load('images.npz') images = images.f.arr_0 images_npz.close() ``` The name/key of the array inside the .npz-file (e.g. `arr_0`) can be found through ``` images.keys() ``` *Note*: The `f` attribute is not documented in ...
Load compressed data (.npz) from file using numpy.load
[ "", "python", "arrays", "numpy", "file-io", "" ]
I'm very new to Python (2.x) and trying to understand how to iterate over a dictionary containing multiple lists: ``` dict = {'list_1':[3, 'green', 'yellow', 'black'], 'list_2':[2, 'green', 'blue']} ``` I am trying to create a new list containing all of the unique values of these lists, but ignoring the first item (t...
Use `set.union`: ``` >>> dic = {'list_1':[3, 'green', 'yellow', 'black'], 'list_2':[2, 'green', 'blue']} >>> set().union(*(x[1:] for x in dic.itervalues())) set(['blue', 'black', 'green', 'yellow']) ``` If a list is required simply pass this set to `list()`. The working version of your attempt, though it is not effi...
One way using [`itertools.chain`](http://docs.python.org/2/library/itertools.html#itertools.chain) to flatten the dict values into a single list then [`list comprehension`](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) to filter out the non-string values and finally [`set`](http://docs.pyth...
Iterating over a dictionary of list elements
[ "", "python", "" ]
What is correct way to convert Python dict in single string? I have example program with code: ``` keywordsList = {u'roland.luethe1@gmail.com': 2, u'http://www.3ho.de/': 4, u'http://www.kundalini-yoga-zentrum-berlin.de/index.html': 1, u'ergo@ananda-pur.de': 3} keywordsCount = sorted(keywordsList.items(),key=lambda(k...
Use `str.join()` judiciously: ``` ', '.join([' : '.join((k, str(keywordsList[k]))) for k in sorted(keywordsList, key=keywordsList. get, reverse=True)]) ``` Outputs: ``` >>> ', '.join([' : '.join((k, str(keywordsList[k]))) for k in sorted(keywordsList, key=keywordsList. get, reverse=True)]) u'http://www.3ho.de/ : 4, ...
I'm not sure about the correct way but you could also do this: ``` ', '.join(' : '.join([a, str(b)]) for a, b in keywordsCount) ```
Python dict to string
[ "", "python", "string", "dictionary", "" ]
I have a text file sample.txt(space delimited) in this format ``` 12 john E 44 L 13 adam D 78 L 14 tue E 98 L ``` I want to to convert this file into a nested list ``` table_data = [ [12, 'john', 'E', 44, 'L'], [13, 'adam', 'D', 78, 'L'], [14, 'tue', 'E', 98, 'L'], ] ``` How can i do it ?
Use `str.split` and a list comprehension: ``` with open('filename') as f: table_data = [ line.split() for line in f] ``` If you want the numbers to be converted to integers then write an additional function that processes each item on a give line: ``` def func(x): try: ...
Use the inbuilt [`csv` package](http://docs.python.org/2/library/csv.html) ``` from csv import reader types = [int, str, str, int, str] with open('sample.txt', 'rb') as f: table_data = [[t(v) for v, t in zip(row, types)] for row in reader(f, delimiter=' ')] print table_data ``` Has the output: ``` [[12, 'john'...
use file content to create a nested list in python
[ "", "python", "list", "parsing", "nested-lists", "" ]
I read this: [Importing a CSV file into a sqlite3 database table using Python](https://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python) and it seems that everyone suggests using line-by-line reading instead of using bulk .import from SQLite. However, that will make t...
Divide your data into chunks on the fly using generator expressions, make inserts inside the transaction. Here's a quote from [sqlite optimization FAQ](https://web.archive.org/web/20140331055857/http://web.utk.edu/%7Ejplyon/sqlite/SQLite_optimization_FAQ.html): > Unless already in a transaction, each SQL statement has...
Since this is the top result on a Google search I thought it might be nice to update this question. From the [python sqlite docs](https://docs.python.org/2/library/sqlite3.html#sqlite3-controlling-transactions) you can use ``` import sqlite3 persons = [ ("Hugo", "Boss"), ("Calvin", "Klein") ] con = sqlite3....
Bulk insert huge data into SQLite using Python
[ "", "python", "sqlite", "" ]
I have an application where you write a short story (maximum 130 chars) and post it on the site. However, what I want to do is to add a specific hashtag in the end of the story and post it on a specific Twitter account in the same time as it's posted on the site. What is the best way to deal with this action? Is ther...
If you want something minimal, checkout <https://github.com/sixohsix/twitter>. Here is an example <https://gist.github.com/damilare/4435261>
do you mean that you don't want to import all of twython because you'd only be using some of it? If so then you could still used twython but only import some of it: ``` from twython import <thing you want> ``` I wasn't quite sure what you were asking, but other twitter API libraries for python include: * [tweepy](ht...
Posting to Twitter account from Django
[ "", "python", "django", "twitter", "" ]
I am fairly new to django and I am using it to make a website for an online game. The game already has it's own auth stuff so I am using that as a custom auth model for django. I created a new app called 'account' to put this stuff in and added the models. I added the router and enabled it in the settings and everythi...
I also had the same issue, you need to specify the correct database. For example, given your code: ``` $ ./manage.py dumpdata --database=auth_db account ```
I had similar problem. Creating an empty file called `models.py` solved the problem for me. Check if you have such a file in your app catalog and if not - create one.
django dumpdata empty array
[ "", "python", "django", "" ]
I have an error message that spans across multiple (2-3) lines. I want to catch it and embed in a warning. I think that substituting new-lines into spaces is ok. My question is, which method is the best practice. I know this is not the best kind of question, but I want to code it properly. I also might be missing some...
Just use the `replace` method: ``` >>> "\na".replace("\n", " ") ' a' >>> ``` It is the simplest solution. Using Regex is overkill and also means you have to import. `translate` is a little better, but still doesn't give anything that `replace` doesn't (except more typing of course). `replace` should run faster too.
If you want to leave all these implementation details up to the python implementation you could do: ``` s = "This\nis\r\na\rtest" print " ".join(s.splitlines()) # prints: This is a test ``` Note: > This method uses the *universal newlines* approach to splitting lines. Which means: > **universal newlines** A manner...
Good method to substitute end-lines '\n' into spaces in a string
[ "", "python", "string", "replace", "" ]
I'm using nested dictionaries as implemented using the AutoVivification class answer at [What is the best way to implement nested dictionaries?](https://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python); namely ``` class AutoVivification(dict): """Implementation of...
The problem you'll run into is that, in order to set an item on a nested dictionary, you must first be able to get all the parent items. For example: ``` d[1][2][3] = 42 ``` requires *getting* `d[1][2]` in order to *set* `d[1][2][3]`. There's no way to know whether an assignment is in process when you are accessing t...
I don't think there is any way to do exactly what you are trying to do, but if you are okay with a slight modification to how you set the keys you can get something pretty similar by just using regular dictionaries. ``` def nested_dict_set(d, keys, value): for k in keys[:-1]: d = d.setdefault(k, {}) d[...
Nested dictionaries in python with error when accessing non-existent key
[ "", "python", "dictionary", "nested", "" ]
I'm trying to capture the numbers in a decimal inches statement without catching the `"`. An expression that works well in Perl seems to fail in Python and I can't see why. In the following two expressions I expect to see `1` and `1.5` but in Python see instead `1"` and `1.5"` and I expect them to work the same. What ...
You can easily do.. ``` import re string = 'I have values "1" and "1.5" also "12.555"' m = re.findall(r'\"(\d+|\d+\.\d+)\"', string) print ", " . join(m) ``` Output: ``` 1, 1.5, 12.555 ```
Try: ``` re.search(r'^(?:(\d+(?:\.\d+)*)")', '1.5"').group(1) ``` See [re](http://docs.python.org/2/library/re.html#match-objects): > `group([group1, ...])` > > Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a t...
Perl regex vs. Python regex non-capture seems to work differently
[ "", "python", "regex", "" ]
I have a page to show 10 messages by each user (don't ask me why) I have the following code: `SELECT *, row_number() over(partition by user_id) as row_num FROM "posts" WHERE row_num <= 10` It doesn't work. When I do this: `SELECT * FROM ( SELECT *, row_number() over(partition by user_id) as row_num FROM ...
It seems to be the same "rule" as any query, column aliases aren't visible to the `WHERE` clause; This will also fail; ``` SELECT id AS newid FROM test WHERE newid=1; -- must use "id" in WHERE clause ```
SQL Query like: ``` SELECT * FROM table WHERE <condition> ``` will execute in next order: ``` 3.SELECT * 1.FROM table 2.WHERE <condition> ``` so, as Joachim Isaksson say, columns in `SELECt` clause are not visible in `WHERE` clause, because of processing order. In your second query, column `row_num` are fetched in...
Why do partitions require nested selects?
[ "", "sql", "postgresql", "" ]
I need to calculate the arcsine function of small values that are under the form of mpmath's "mpf" floating-point bignums. What I call a "small" value is for example e/4/(10\*\*7) = 0.000000067957045711476130884... Here is a result of a test on my machine with mpmath's built-in asin function: ``` import gmpy2 from m...
Actually binary splitting does work very well, if combined with iterated argument reduction to balance the number of terms against the size of the numerators and denominators (this is known as the bit-burst algorithm). Here is a binary splitting implementation for mpmath based on repeated application of the formula at...
Can you use the `mpfr` type that is included in gmpy2? ``` >>> import gmpy2 >>> gmpy2.get_context().precision = 3100000 >>> val = gmpy2.exp(1)/4/10**7 >>> from time import time >>> start=time();r=gmpy2.asin(val);print time()-start 3.36188197136 ``` In addition to supporting the GMP library, gmpy2 also supports the MP...
Fastest possible method for the arcsin function on small, arbitrary floating-point values
[ "", "python", "trigonometry", "bignum", "taylor-series", "mpmath", "" ]
I have a small problem with `True` or `False` Boolean. I have Defined a procedure `weekend` which takes a string as its input, and returns the Boolean `True if 'Saturday' or 'Sunday'` and `False` otherwise. Here is my `weekend` function: ``` def weekend(day): if day == 'Saturday' or day == 'Sunday': retu...
Try this: ``` def weekend(day): if day == 'Saturday' or day == 'Sunday': return True else: return False ``` Or this: ``` def weekend(day): return day == 'Saturday' or day == 'Sunday' ``` Or even simpler: ``` def weekend(day): return day in ('Saturday', 'Sunday') ``` Anyway: in Pyth...
This is the shortest way to write the function and output a boolean ``` def weekend(day): return day == 'Saturday' or day == 'Sunday' ``` or ``` def weekend(day): return day in ('Saturday', 'Sunday') ```
Return a Boolean instead of a string containing True or False in Python
[ "", "python", "python-2.7", "boolean", "" ]
Why is it that some objects keep their identities while others change at each initialization like so? ``` >>> id(2 ** 850) 26826480 >>> id(2 ** 850) 26826480 >>> id(2 ** 850) 26826480 >>> id(2 ** 850) 26826480 >>> id(2 ** 851) 26826624 >>> id(2 ** 851) 26826480 >>> id(2 ** 851) 26826624 >>> id(2 ** 851) 26826480 >>> i...
It's an implementation detail. The `id` in CPython is basically the memory address of the object. Sometimes temporary objects that are created and destroyed in the same line of execution (like the result of `2**850`) will have the same address in the next line of execution. Don't rely on the value! Here's an interesti...
Quoting the [docs](http://docs.python.org/2/library/functions.html#id) for `id`: > Two objects with non-overlapping lifetimes may have the same id() value. When you get the same `id()` results, it doesn't mean you have the same object. In fact, two unequal numbers may have the same ID if one of the objects is dealloc...
Can anyone define internals of this magic behavior of int objects in python
[ "", "python", "python-3.x", "" ]
I have duplicate rows in my table, how can I delete them based on a single column's value? Eg ``` uniqueid, col2, col3 ... 1, john, simpson 2, sally, roberts 1, johnny, simpson delete any duplicate uniqueIds to get 1, John, Simpson 2, Sally, Roberts ```
You can `DELETE` from a cte: ``` WITH cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY uniqueid ORDER BY col2)'RowRank' FROM Table) DELETE FROM cte WHERE RowRank > 1 ``` The `ROW_NUMBER()` function assigns a number to each row. `PARTITION BY` is used to start the numbering over for each item in that grou...
You probably have a row id that *is* assigned by the DB upon insertion and is actually unique. I'll call this rowId in my example. ``` rowId |uniqueid |col2 |col3 ----- |-------- |---- |---- 1 10 john simpson 2 20 sally roberts 3 10 johnny simpson ``` You can remove duplicates...
SQL Server 2008: delete duplicate rows
[ "", "sql", "sql-server-2008", "duplicates", "" ]
I've got these tables in my database: **Tourist** - this is the first table ``` Tourist_ID - primary key name...etc... ``` **EXTRA\_CHARGES** ``` Extra_Charge_ID - primary key Extra_Charge_Description Amount ``` **Tourist\_Extra\_Charges** ``` Tourist_Extra_Charge_ID Extra_Charge_ID - foreign key Tourist_ID - fo...
You can use two options, both are pretty much the same, but [one may perform better than the other](https://stackoverflow.com/questions/2246772/whats-the-difference-between-not-exists-vs-not-in-vs-left-join-where-is-null) depending on your DBMS. The principal of both is the same, get a cross join of tourist and extra ...
You may include the tourist name (for Tourist\_ID=86) as a subquery in the select statement: ``` SELECT (SELECT Tourist.Name FROM Tourist WHERE Tourist_ID=86) TouristName, e.* FROM EXTRA_CHARGES e WHERE e.Extra_Charge_ID NOT IN (SELECT Extra_Charge_ID FROM TOURIST_EXTRA_CHARGES te WHERE t...
sql subquery issue with inner join
[ "", "sql", "" ]
In Python I am trying to figure out how to evaluate commands given as strings in a program. For example, consider the built in math functions `sin`, `cos` and `tan` Say I am given these functions as a list; ``` li = ['sin', 'cos', 'tan'] ``` Now, I want to iterate over each element in the list and apply each functio...
Just use the functions themselves: ``` from math import sin, cos, tan li = [sin, cos, tan] ``` If you really need to use strings, create a dict: ``` funcs = {'sin': sin, 'cos': cos, 'tan': tan} func = funcs[string] func(x) ```
There are a several options here, I've listed some of the better options below: * If all of the functions come from the same module, you can use `module.getattr(func)` to access the function. In this case sin, cos, and tan are all functions from math so you could do the following: ``` import math li = ['sin', ...
python evaluate commands in form of strings
[ "", "python", "functional-programming", "symbols", "evaluation", "" ]