Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I want to create a table with a subset of records from a master table. for example, i have: ``` id name code 1 peter 73 2 carl 84 3 jack 73 ``` I want to store peter and carl but not jack because has same peter's code. I need hight performance because i have 20M records. I try this: ``` SELECT id, nam...
Assuming you want to pick the row with the maximum `id` per `code`, then this should do it: ``` insert into new_tab (id, name, code) (SELECT id, name, code FROM ( SELECT id, name, code, rank() as rnk OVER (PARTITION BY code ORDER BY id DESC) FROM old_tab WHERE rnk = 1 ) ) ``` and for the minimum `id` per...
Using a derived table, you can find the minID for each code, then join back to that in the outer to get the rest of the columns for that ID from oldTab. ``` select id,name,code insert into newTabFROM from old_tab t inner join (SELECT min(id) as minId, code from old_tab group by code) x on t.id = x.minId WHERE ...
how to insert many records excluding some
[ "", "sql", "performance", "postgresql", "" ]
I created the simple code: ``` name = raw_input("Hi. What's your name? \nType name: ") age = raw_input("How old are you " + name + "? \nType age: ") if age >= 21 print "Margaritas for everyone!!!" else: print "NO alcohol for you, young one!!!" raw_input("\nPress enter to exit.") ``` It works great until I g...
It should be something like this: ``` name = raw_input("Hi. What's your name? \nType name: ") age = raw_input("How old are you " + name + "? \nType age: ") age = int(age) if age >= 21: print "Margaritas for everyone!!!" else: print "NO alcohol for you, young one!!!" raw_input("\nPress enter to exit.") ``` Y...
Firstly `raw_input` returns a string not integer, so use `int()`. Otherwise the if-condition `if age >= 21` is always going to be False.: ``` >>> 21 > '' False >>> 21 > '1' False ``` **Code:** ``` name = raw_input("Hi. What's your name? \nType name: ") age = int(raw_input("How old are you " + name + "? \nType age: "...
Simple raw_input and conditions
[ "", "python", "if-statement", "conditional-statements", "raw-input", "" ]
This is the Query I am using on the `product` table `LEFT JOIN` on the `page` table `ON` the `productid` column in `page` being the `id` in `product`.. pretty straightforward. ``` SELECT COUNT(DISTINCT `p`.`id`) as `quantity`, DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day` FROM `product` AS `p` LEFT JOIN `page`...
I found the solution to my query: ``` SELECT COUNT(`p`.`id`) as `quantity`, DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day` FROM `product` AS `p` INNER JOIN ( SELECT `productid` AS `id`, count(id) AS pagesNR FROM `page` GROUP BY `productid` HAVING COUNT(`id`) >= 10 ) AS `pg` USING (`id`) WHER...
I think that is because you are leaving `p.id` in the `group by` clause. Try this: ``` SELECT COUNT(DISTINCT `p`.`id`) as `quantity`, DATE_FORMAT(`p`.`created_time`,'%Y-%m-%d') AS `day` FROM `product` AS `p` LEFT JOIN `page` AS `pg` ON `p`.`id` = `pg`.`productid` WHERE `p`.`created_time` BETWEEN '20...
SQL query resultset, I need SUM(quantity) COLUMN grouped by DAY
[ "", "sql", "count", "sum", "having", "" ]
I've got a list of things, of which some can also be functions. If it is a function I would like to execute it. For this I do a type-check. This normally works for other types, like str, int or float. But for a function it doesn't seem to work: ``` >>> def f(): ... pass ... >>> type(f) <type 'function'> >>> if ty...
Don't check types, check actions. You don't actually care if it's a function (it might be a class instance with a `__call__` method, for example) - you just care if it can be called. So use `callable(f)`.
``` import types if type(f) == types.FunctionType: print 'It is a function!!' ```
How to check for a function type in Python?
[ "", "python", "function", "types", "" ]
It seems their only value is storing attributes. Even then, those can't be changed or the changes get reflected across all instances! If I have a class here: ``` # Vertex class Vertex: label = str() ID = int() outEdges = list() inEdges = list() ``` make a new vertex object: ``` v = Vertex() ``` and add...
The attributes you are declaring are class-level, and are shared by all instances of the class. You need to use a proper initializer/constructor function if you want those values to be specific to an instance: ``` # Vertex class Vertex: def __init__(self): self.label = str() self.ID = int() self.o...
You'll need an [instantiation method](http://docs.python.org/2/reference/datamodel.html#object.__init__) if you want different instances of the class. ``` class Vertex: def __init__(self): self.label = str() .... ```
What good are python classes?
[ "", "python", "class", "copy", "alias", "" ]
I have a "sessions" table that among other field has the following fields: ``` int int(11), user_id int(11), login_date timestamp, ip varchar(15) ``` I want to select for each user the last login\_date and the last three unique ips. How can I do this in an elegant way? I found a solution but it's very very very ugly...
Took a lot of time to convert in `MYSQL` from `SQL SERVER` I have work on my Query for **better Performance**. ``` select user_id, max(cast(login_date as datetime)), group_concat(distinct ip order by login_date desc SEPARATOR ' , ') from ( SELECT user_id, login_date, ip, CASE user_id WHEN @curType ...
This would get you the last date for each user\_id ``` SELECT s1.* FROM sessions s1 LEFT OUTER JOIN sessions s2 ON s1.user_id = s2.user_id AND s1.login_date < s2.login_date WHERE s2.user_id IS NULL ``` and this will get you the unique IPs used for each user\_id `SELECT user_id, GROUP_CONCAT(DISTINCT(ip)) FROM sessi...
Select last N unique records mysql
[ "", "mysql", "sql", "" ]
I'm trying to add on to an existing database where we have a tblUsers table. As of right now, we're storing user images in a file system, and now we're moving away from that by storing User images in the database in a new tblUserImages table. Here's what the two tables look like. ![Table Structure](https://i.stack.im...
If you are using SQL Server 2008, you can create a filtered unique index like the following: ``` create unique index uniqueUserActiveImages ON tblUserImage(UserID, Active) WHERE Active = 1; ``` This allows the user to have multiple inactive images but only one active image.
I'd recommend you consider having a separate entity (a separate table) for inactive images. That way you won't need an "active" attribute in tblUserImages, all images in this table will be active. You would only reference the inactive image table if you wanted to query the image history. The active image table would ei...
Sql Server only allow one active image per user
[ "", "sql", "sql-server", "" ]
I want to sort through lists of floats and take out all the values = 0, and keep the elements of the list as floats. Is this possible to do? --- I have tried `a[:] = [x for x in a if x != 0]` but this gives me this error: ``` a[:] = [x for x in a if x != 0] TypeError: 'float' object is not iterable ``` So then I t...
``` blacklist = [0] blacklist = set(blacklist) myList = [e for e in myList if int(e) not in blacklist] ``` Better yet, make your blacklist a collection of `float`s: ``` blacklist = [0] blacklist = set([float(i) for i in blacklist]) myList = [e for e in myList if int(e) not in blacklist] ```
you `a` object is a float, not a list ``` >>> a=[1,2,3,0,4] >>> a=[x for x in a if x!=0] >>> a [1, 2, 3, 4] ```
Remove all occurrences of an integer from a list of floats
[ "", "python", "list", "floating-point", "element", "" ]
Is there a way in python to store the part I sliced and print only the part I sliced? Meaning on the example below I sliced out "school". I want to just print "school". I will be trying to work on a text file later, where I will just need part of each sentence, but just trying to figure out if its doable with slicing. ...
why not slice it directly, then ? ``` a = word[-6:] ``` will give you `'school'`
``` print a ``` I'm not sure what your confusion is. **Update**: `"school"` is the part you *didn't* slice. If `"school"` is the part you're interested in, you want ``` a = word[-6:] ``` If you want both parts, slice them separately: ``` notschool, school = word[:-6], word[-6:] ```
Python Slicing Newbie
[ "", "python", "slice", "" ]
heya I am making a Project using scrapy in which I need to scrap the business details from a business directory <http://directory.thesun.co.uk/find/uk/computer-repair> the problem I am facing is: when I am trying to crawl the page my crawler fetches the details of only 1st page whereas I need to fetch the details of ...
Following is the working code. Scrolling the pages should be taken by studying the website and its scroll structure and apply them acccordingly. In this case, the website has given it "/page/x" where x is the page number. ``` from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from proje...
if you check the paging links they look like this: <http://directory.thesun.co.uk/find/uk/computer-repair/page/3> <http://directory.thesun.co.uk/find/uk/computer-repair/page/2> You could loop pages using urllib2 with a variable ``` import urllib2 response = urllib2.urlopen('http://directory.thesun.co.uk/find/uk/comp...
Scrapy Crawls only 1st page and not the rest
[ "", "python", "django", "scrapy", "" ]
So, I have a list of regex patterns, and a list of strings, what I want to do is to say within this list of strings, are there any strings which do not match any of the regexes. At present, I'm pulling out the regexes, and the values to be matched by the regex from two dictionaries: I've made two lists, one of patter...
``` [key for key in keys if not any(re.match(pattern, key) for pattern in patterns)] ```
Regexps are optimized for searching large blocks of text, not sequences of small blocks. So, you may want to consider searching `'\n'.join(keys)` instead of searching each one separately. Or, alternatively, instead of moving the loops from Python to regexp, move the implicit "or"/"any" bit from Python to regexp: ``` ...
Python list of strings and list of regexes, clean way to find strings which don't match anything?
[ "", "python", "regex", "" ]
I was wandering if there was a way to perform an action before the program closes. I am running a program over a long time and I do want to be able to close it and have the data be saved in a text file or something but there is no way of me interfering with the `while True` loop I have running, and simply saving the da...
Your `atexit` usage is wrong. It expects a function and its arguments, but you're just calling your function right away and passing the result to `atexit.register()`. Try: ``` atexit.register(saveFile, list) ``` Be aware that this uses the `list` reference as it exists at the time you call `atexit.register()`, so if ...
You could use the `handle_exit` context manager from this ActiveState recipe: <http://code.activestate.com/recipes/577997-handle-exit-context-manager/> It handles `SystemExit`, `KeyboardInterrupt`, `SIGINT`, and `SIGTERM`, with a simple interface: ``` def cleanup(): print 'do some cleanup here' def main(): ...
Performing an action upon unexpected exit python
[ "", "python", "terminate", "" ]
I've seen two different Python objects used to group arbitrary data together: empty classes and functions. ``` def struct(): pass record = struct record.number = 3 record.name = "Zoe" class Struct: pass record = Struct() record.number = 3 record.name = "Zoe" ``` Even if the class isn't empty, it seems to ...
The difference is that both function objects and your Struct object have a `__dict__` attribute, but `set` instances and built-in functions do not: ``` >>> def struct(): ... pass ... >>> record = struct >>> record.number = 2 >>> struct.__dict__ {'number': 2} >>> class Struct: ... pass ... >>> record = Struct()...
Built-in types are written in C and cannot be modified like that. But after the [type/class unification](http://www.python.org/download/releases/2.2/descrintro/) introduced in py2.2 you can now inherit from a built-in types and override or add your own attributes to that subclass. You can use the [forbiddenfood](https...
Why do Python's empty classes and functions work as arbitrary data containers, but not other objects?
[ "", "python", "" ]
I'm new at Python and tried writing a basic script. I'm trying to print out all the letters of the alphabet, and I keep getting Invalid Syntax. ``` letter = ord('a') while letter != ord('z') print(chr(letter)) letter = letter + 1 ``` Here's the first error log: ``` while letter != ord('z') ...
You want a colon at the end of your while loop, to let Python know it's a block. ``` while letter != ord('z'): <rest of your code here> ``` Also, right now you seem to have the start of the while loop indented and none of the rest, when you want the opposite: all the code to be run in the while loop should be ind...
Missing the colon in end `while` loop. ``` letter = ord('a') while letter != ord('z'): print(chr(letter)) letter += 1 ```
Invalid Syntax error?
[ "", "python", "" ]
The following iframe will not render in an ipython-notebook ``` from IPython.display import HTML HTML('<iframe src=http://stackoverflow.com width=700 height=350></iframe>') ``` but, this one will render (note, .com versus .org) ``` from IPython.display import HTML HTML('<iframe src=http://stackoverflow.org width=700...
You have a "Refused to display document because display forbidden by X-Frame-Options." in javascript console. Some sites explicitly refuse to be displayed in iframes.
IPython now supports IFrame directly: ``` from IPython.display import IFrame IFrame('http://stackoverflow.org', width=700, height=350) ``` For more on IPython embeds check out this [IPython notebook.](http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Part%205%20-%20Rich%20Display%20Sys...
iframe not rendering in ipython-notebook
[ "", "python", "iframe", "ipython", "jupyter-notebook", "" ]
I have 2 scripts. ``` Main.py Update.py ``` I have a function in **Main.py** which basically does the following: ``` def log(message): print(message) os.system("echo " + message + " >> /logfile.txt") ``` And in the **Update.py** file I have a single function which basically does the update. However throughout...
*Don't* import `log` from `Main`. That'll rerun the code in Main.py, since running Main.py as a script and importing it as a module aren't equivalent. Other modules should not depend on functions defined in the main script. Instead, put your `log` function in another module and import that, or have Main.py explicitly p...
Just add in **Update.py** the line ``` from Main import log ``` and you will be able to call `log()` from Update.py.
Python - How to allow the use of a function in different modules?
[ "", "python", "function", "module", "package", "" ]
Is there any way to do something like : ``` SELECT * FROM TABLE WHERE COLUMN_NUMBER = 1; ``` ?
If your table has a column named `COLUMN_NUMBER` and you want to retrieve rows from the table where that column contains a value of '1', that query should do the trick. I suspect that what you are trying to do is reference an expression in the select list with an alias. And that is not supported. An expression in the ...
No, you can't. Column order doesn't really matter in MySQL. See the below question for more details. [mysql - selecting values from a table given column number](https://stackoverflow.com/questions/4492035/mysql-selecting-values-from-a-table-given-column-number)
SELECT in mysql using column number instead of name
[ "", "mysql", "sql", "ordinal", "" ]
I've been kluding around with this and thought someone might have a clever way to solve my problem. I'm querying sales by category membership and need to aggregate ALL sales if a customer is a member of a single sales category. For example: ``` Cust Category Sale A Pie 3 A Cake 5 B Pi...
You can use the EXISTS operator with correlated subquery in the WHERE clause ``` SELECT t1.Cust, SUM(t1.Sale) AS Sale FROM dbo.test134 t1 WHERE EXISTS ( SELECT 1 FROM dbo.test134 t2 WHERE t1.Cust = t2.Cust AND t2.Category = 'Cake' ) GROUP BY t1.Cu...
``` Select A.Cust, A.Category, B.SumSale from Sales A Where A.Category like '%Cake%' Left Join (Select Cust, Category, Sum(Sale) as SumSale from Sales Group By Cust, Category) B On B.Cust = A.Cust ```
SQL To Aggregate by Category Membership
[ "", "sql", "" ]
The sequence I would like to accomplish: 1. A user clicks a button on a web page 2. Some functions in model.py start to run. For example, gathering some data by crawling the internet 3. When the functions are finished, the results are returned to the user. Should I open a new thread inside of model.py to execute my f...
1. Yes it can multi-thread, but generally one uses Celery to do the equivalent. [You can read about how in the celery-django tutorial.](http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html) 2. It is rare that you *actually* want to force the user to wait for the website. While it's better than ri...
As shown in [this answer](https://stackoverflow.com/a/21945663/8894424) you can use the threading package to perform an asynchronous task. Everyone seems to recommend Celery, but it is often overkill for performing simple but long running tasks. I think it's actually easier and more transparent to use threading. Here'...
Can you perform multi-threaded tasks within Django?
[ "", "python", "django", "multithreading", "" ]
I'm looking for an sql answer on how to merge two tables without anything in common. ``` So let's say you have these two tables without anything in common: Guys Girls id name id name --- ------ ---- ------ 1 abraham 5 sarah 2 isaak 6 rachel 3 jac...
You can do this by creating a key, which is the row number, and joining on it. Most dialects of SQL support the `row_number()` function. Here is an approach using it: ``` select gu.id, gu.name, gi.id, gi.name from (select g.*, row_number() over (order by id) as seqnum from guys g ) gu full outer join ...
Just because I wrote it up anyway, an alternative using CTEs; ``` WITH guys2 AS ( SELECT id,name,ROW_NUMBER() OVER (ORDER BY id) rn FROM guys), girls2 AS ( SELECT id,name,ROW_NUMBER() OVER (ORDER BY id) rn FROM girls) SELECT guys2.id guyid, guys2.name guyname, girls2.id girlid, girls2.name girlname FRO...
sql merge tables side-by-side with nothing in common
[ "", "sql", "" ]
First off, I did google this but sites are flooded with advice on how to deal with "host name is blocked" issues. (<https://www.google.com/search?q=mysql+block+a+host>). My issue is a little bit the opposite of that. With me, I am running a MySQL database and no PHP is involved. I need to block a certain host-name/IP...
You can use GRANT to give a non-privileged entry for a user connecting from a specific host, even if you have GRANTed privileges to a wildcard including that host. When authenticating, the most specific host match takes precedence. For example, suppose you enabled a user to connect from a range of hosts on your local ...
You can revoke privileges as mentioned above, but this will still allow a user to make a connection to your MySQL server - albeit this will prevent that user from authenticating. If you really want to block/allow connections to your MySQL server based on IP, use iptables.
How do I manually block and then unblock a specific IP/Hostname in MYSQL
[ "", "mysql", "sql", "privileges", "" ]
I just finished installing my `MySQLdb` package for Python 2.6, and now when I import it using `import MySQLdb`, a user warning appear will appear ``` /usr/lib/python2.6/site-packages/setuptools-0.8-py2.6.egg/pkg_resources.py:1054: UserWarning: /home/sgpromot/.python-eggs is writable by group/others and vulnerable to...
You can change `~/.python-eggs` to not be writeable by group/everyone. I think this works: ``` chmod g-wx,o-wx ~/.python-eggs ```
You can suppress warnings using the [`-W ignore`](http://docs.python.org/2/using/cmdline.html#cmdoption-W): ``` python -W ignore yourscript.py ``` [If you want to supress warnings in your script (quote from docs):](http://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings) > If you are using co...
Remove Python UserWarning
[ "", "python", "" ]
i have a table main: ``` ( time date, qty int ) ``` i want to create a query so for each day i get the sum of qty on that day and all days before that so for this data ``` ----------------------- time | qty 01/09/2009 | 3 02/09/2009 | 8 03/09/2009 | 2 04/09/2009 | 5 ``` i get: ``` --...
This should give you a faster result ``` SELECT time , @tot_qty := @tot_qty+qty AS tot_qty FROM Table1 JOIN (SELECT @tot_qty := 0) d order by time ``` **[SQL FIDDLE](http://www.sqlfiddle.com/#!2/0b3e2/7)**
``` SELECT TIME, (SELECT SUM(QTY) FROM main m2 WHERE m2.ITME <= mt1.TIME) AS sum FROM main m1 ORDER BY TIME ``` This should do the trick, though it might not be the fastest solution.
sql query for each day
[ "", "mysql", "sql", "mariadb", "" ]
I want to append rows of digits in the form of one long string to be appended to a list inside of a list based upon their row. For example, I know ahead of time that each row has 4 digits that can only go up to 99 from 01, and there is a total of 3 rows. How would you got through the string, turn each number into an in...
``` myStr = "01 02 03 04 11 12 13 14 21 22 23 24" myStr= [int(n) for n in myStr.split()] myList=[] for i in xrange(0,len(myStr),4): myList.append(myStr[i:i+4]) ``` Or, instead of the for loop, you can use list comprehension again. ``` myList=[myStr[i:i+4] for i in xrange(0,len(myStr),4)] ```
This is what I would do... ``` numDigits = 4 #Number of digits per row a = [int(val) for val in myStr.split()] myList = [] for i in arange(0, len(a), numDigits): myList.append(a[i:i+numDigits]) ``` Hope this helps!
What is the easiest but not fastest way to format this string into a list? Python
[ "", "python", "string", "list", "int", "append", "" ]
Python beginner here. I have a dictionary with a key and its value is an object (dict) who also has a key value pair. I want to add a key value pair to the 'child' object. given: ``` {"foo" : {"bar" : "bars value"} } ``` I want to add: ``` {"foo" : {"bar" : "bar value", "baz" : "baz value" } } ...
``` somedict = {"foo" : {"bar" : "bars value"} } somedict['foo']['baz'] = 'baz value' ``` When Python encounters `somedict['foo']['baz']` it first looks-up the value of the bare name `somedict`. It finds it is a `dict`. Then it evaluates `somedict['foo']` and finds it is another dict. Then it assigns to this dic...
You can just do ``` mydict["foo"]["baz"] = "baz value" ``` as in ``` >>> mydict = {"foo" : {"bar" : "bars value"}} >>> mydict["foo"]["baz"] = "baz value" >>> mydict {'foo': {'baz': 'baz value', 'bar': 'bars value'}} ```
add a new key value pair to existing key value pair object in python
[ "", "python", "" ]
I'm new to programming, hoping someone can help clarify some concept to help me learn. I think I understand \*\* , the \*\* convert kwarg into keyword and then pass to function. I'm not really sure why I need to use \*\* twice though. Specifically, why do I need to explicitly pass in \*\*param (vs just param) when it...
The trick is that though the symbol (`**`) is the same, the [*operator*](http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments) is different: ``` def print_kwargs(**all_args): # Here ** marks all_args as the name to assign any remaining keyword args to print all_args an_argument = {"test": 1} ...
Let's say you have a method like this... ``` >>> def fuct(a, b, c): ... print a ... print b ... print c ``` and you have got dictionary with required params to sent to method ``` d = {'a': 1, 'b': 2, 'c': 3} ``` so by using \*\* (double asteric) you can unpack the dictionary and send to function ``` >>> fuct...
Confuse about how to use **kwarg
[ "", "python", "keyword-argument", "" ]
I am working with webservices, and I need to get a dump of all the HTTP requests and responses, so that I can debug the interoperability between the devices. I have a small pc with 3 nics that are bridged, so that it acts as an hub and I can tap the traffic. I am looking for a way to easily dump the HTTP traffic, so t...
I finally solved my problem by using tshark in pipe and by parsing its output with a python script. Most of the decoding activity is performed by the following command ``` tshark -l -f "tcp port 80" -R "http.request or http.response " -i br0 -V ``` which outputs the decoded HTTP packets. and my script performs all th...
There are some respectable traffic sniffers around already, so you probably have no need to implement one of your own. [Wireshark](https://www.wireshark.org/ "Wireshark") is amongst the most popular. Not only it allows you to capture traffic, but also has some great tools for filtering and analyzing the packets. [shar...
how to dump http traffic?
[ "", "python", "http", "scapy", "sniffing", "" ]
I have django [custom user model](https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#extending-the-existing-user-model) `MyUser` with one extra field: ``` # models.py from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): age = models.PositiveIntegerField(_("age")) # settings...
Though it is a bit late but in case it helps someone. You need to create your own Custom AccountAdapter by subclassing DefaultAccountAdapter and setting the ``` class UserAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=True): """ This is called when saving u...
# Side note With Django 1.5 custom user model, the best practice is to use the `get_user_model` function: ``` from django.contrib.auth import get_user_model # forms.py class SignupForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) age = forms.IntegerF...
Saving custom user model with django-allauth
[ "", "python", "django", "django-models", "django-allauth", "" ]
Very basic question. We have the code: ``` a = input("how old are you") if a == string: do this if a == integer (a != string): do that ``` Obviously it doesn't work that way. But what is the easiest way to do this. Thanks for any answers in advance. We could also say: ``` if string in a: do this ```
You can use `str.isdigit` and `str.isalpha`: ``` if a.isalpha(): #do something elif a.isdigit(): #do something ``` help on `str.isdigit`: ``` >>> print str.isdigit.__doc__ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. ``` help on ...
You can use a.isalpha(), a.isdigit(), a.isalnum() to check if a is composed of letters, numbers, or a combination of numbers and letters, respectively. ``` if a.isalpha(): # a is made up of only letters do this if a.isdigit(): # a is made up of only numbers do this if a.isalnum(): # a is made up numbers and ...
python if user input contains string
[ "", "python", "string", "if-statement", "input", "python-3.x", "" ]
I want to play with [turtle](http://docs.python.org/2/library/turtle.html) module in Python. But when i do import turtle module, i've the following error: ``` $ python Python 2.7.3 (default, Sep 26 2012, 21:51:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import ...
You've called a script `turtle.py`, which is shadowing the `turtle` module in the standard library. Rename it.
You can fix this problem by installing the `python-tk` package. ``` sudo apt-get install python3-tk ```
Can't import turtle module in Python 2.x and Python 3.x
[ "", "python", "user-interface", "turtle-graphics", "" ]
I would like to operate on lists element by element without using numpy, for example, i want `add([1,2,3], [2,3,4]) = [3,5,7]` and `mult([1,1,1],[9,9,9]) = [9,9,9]`, but i'm not sure which way of doing is it considered 'correct' style. The two solutions i came up with were ``` def add(list1,list2): list3 = [] ...
The normal way to do this would be to use `map` or `itertools.imap`: ``` import operator multiadd = lambda a,b: map(operator.add, a,b) print multiadd([1,2,3], [2,3,4]) #=> [3, 5, 7] ``` Ideone: <http://ideone.com/yRLHxW> `map` is a c-implemented version of your `elementwiseoperation`, with the advantage of having th...
This could be done with just using `map` and `operator` module: ``` >>> from operator import add,mul >>> map(add, [1,2,3], [2,3,4]) [3, 5, 7] >>> map(mul, [1,1,1],[9,9,9]) [9, 9, 9] ```
correct style for element-wise operations on lists without numpy (python)
[ "", "python", "list", "coding-style", "functional-programming", "higher-order-functions", "" ]
I have this table ``` NAME TYPE codigo numeric referencia varchar codigo referencia 3018 7898379460494 3062 7897840302639 3064 7897840300154 ``` i want to write a select like this : ``` select CODIGO, REFERENCIA, DESCRICAO fr...
``` select CODIGO, REFERENCIA, DESCRICAO from ESTOQUE where convert(varchar(max),CODIGO) = REFERENCIA ```
You should be able to do: ``` select CODIGO, REFERENCIA, DESCRICAO from ESTOQUE where convert(varchar, CODIGO) = REFERENCIA ```
Same value in two columns of same table
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Consider: ``` >>> timeit.timeit('from win32com.client import Dispatch', number=100000) 0.18883283882571789 >>> timeit.timeit('import win32com.client', number=100000) 0.1275979248277963 ``` It takes significantly longer to import only the Dispatch function rather than the entire module, which seems counter intuitive. ...
That's because: ``` from win32com.client import Dispatch ``` is equivalent to: ``` import win32com.client #import the whole module first Dispatch = win32com.client.Dispatch #assign the required attributes to global variables del win32com #remove the reference to module object ``` ...
The entire module still has to be imported to get the name you want from it...You'll also find that the OS is caching the module so subsequent access to the `.pyc` file will be quicker.
Why does it take longer to import a function from a module than the entire module itself?
[ "", "python", "performance", "python-import", "python-internals", "" ]
I am using MS SQL Server 2008 and I have an sql table with some data that is inserted daily at 6 am by an sql job. The problem I have is that some data has been inserted separately into the job and I need to know when this data was added. Is there a query I can run that will show me this?
I think the short answer is NO, there's no magic, ad hoc SQL query that will let you go back after the fact and find out when a row was inserted. If you want to know when a row is inserted, the easiest thing would be to simply add a date or timestamp field with a default value (like getDate()) that automatically fills...
Add a date field to the table. You can give it a default value of `GETDATE()` Then `ORDER BY` that field. ``` SELECT Column1, Column2, NewDateColumn FROM YourTable ORDER BY NewDateColumn ```
Can you tell me when data was inserted into a table
[ "", "sql", "sql-server", "database", "sql-server-2008", "" ]
I am trying to extract the string enclosed by the span with id="titleDescription" using BeautifulSoup. ``` <div class="itemText"> <div class="wrapper"> <span class="itemPromo">Customer Choice Award Winner</span> <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16819116501" title="View D...
``` spans = soup.find_all('span', attrs={'id':'titleDescriptionID'}) for span in spans: print span.string ``` In your code, `wrapper_href.descendants` contains at least 4 elements, 2 span tags and 2 string enclosed by the 2 span tags. It searches its children recursively.
`wrapper_href.descendants` includes any [`NavigableString` objects](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring), which is what you are tripping over. `NavigableString` are essentially string objects, and you are trying to index that with the `child['id']` line: ``` >>> next(wrapper_href.desc...
BeautifulSoup: <div class <span class></span><span class>TEXT I WANT</span>
[ "", "python", "" ]
I need to write a query that returns a single row or record per group. For example I have a table 'employee' with columns: ``` id, name, type 1, John, full-time 2, Mike, full-time 3, Alex, part-time 4, Jerry, part-time ``` I need to return something like ``` 1, John, full-time 4, Alex, part-time ``` Thanks
You could use "group by" in your SQL request. Let's say you have a table EMPLOYEES : ``` ID | NAME | TYPE 1 | 'John' | 'full-time' 2 | 'Mike' | 'full-time' 3 | 'Alex' | 'part-time' 4 | 'Jerry' | 'part-time' ``` You can run: ``` Select * from employees group by type ``` This would return: ``` ID | NAME |...
You will want to apply an aggregate function with a GROUP BY: ``` select min(id) id, min(name) name, type from yourtable group by type; ``` See [SQL Fiddle with Demo](http://sqlfiddle.com/#!2/11243/1). The above works if you don't care what id/name is returned for each type. If you do then you can use: ``` sel...
SQL to return single row per group
[ "", "mysql", "sql", "" ]
I have a small max\_min program I am writing in python 2.7 on Ubuntu 13.04. The code takes a user input inside an infinite loop that breaks on two conditions. I noticed that when I enter a number greater than 9 the program returns the incorrect results. What I want to do is for every time a user inputs a number, compar...
You get a string from `raw_input`, ``` >>> x = raw_input("Enter number: ") Enter number: 10 >>> type(x) <type 'str'> ``` Using the following code ``` for i in inp: if largest is None or i > largest: largest = i print 'Largest',largest # Gets smallest number for i in inp: if smallest is None or i < sm...
Perhaps I don't understand what this is supposed to do, but you are iterating over the number and comparing 1 and than 0. Shouldn't this ``` for i in inp: if largest is None or i > largest: largest = i ``` and the corresponding smallest one, be something like this instead? ``` if largest is None or inp ...
Iterative Comparison of raw_input
[ "", "python", "python-2.7", "" ]
Here's a list of strings. ``` '"5" is a magic number.' '"6" is a magic number.' '"7" is a magic number.' 'This line is extra...' 'This line is extra...' '"8" is a magic number.' ``` What is the most efficient way to pick out those like "\*\* is a magic number" in python?
Use a list comprehension: ``` mylist = ['"5" is a magic number.', ..., '"8" is a magic number.'] print [i for i in mylist if "is a magic number" in i] ``` Prints: ``` ['"5" is a magic number.', '"6" is a magic number.', '"7" is a magic number.', '"8" is a magic number.'] ``` A regex solution, using re.findall: ```...
Suppose you have an unsorted block of strings as you describe: ``` strs='''\ "17" is a magic number. "6" is a magic number. "5" is a magic number. This line is extra... This line is extra... "8" is a magic number.''' ``` Now you want to parse and sort those on number in the string: ``` import re out=sorted([s for s ...
What‘s the best way to pick out string of a specific pattern in python?
[ "", "python", "string", "" ]
I'm wondering what peoples thoughts are on this..... I have a list of names (e.g. company names), and want to display them as a list on a webpage. I'd like for users to be able to find a group of names by alphabetical letter. So if they click on 'M' then it will show company names that begin with the letter M. This so...
If you want to be able to put any name in any "letter category" arbitrarily, then adding a column is your only option. If you can define a specific set of rules that determine which letter category the name must be sorted by, then you can write a sorting function in CF (or JS).
Considering that these are company names, you could rely on their capital letter being either at the beginning of their name or prepended with a white space in the middle of the description: ``` SELECT * WHERE Name LIKE 'M%' OR Name LIKE '% M%'; ``` In this way "University of Michigan" will be listed under letter U a...
Categorising Database Data
[ "", "sql", "sql-server-2008", "coldfusion", "sql-server-2012", "" ]
given a dict what contains n number of dictionaries which contain n number of dictionaries etc. ``` foo = dict({"foo" : {"bar": {"baz": "some value"}}} ``` assuming `baz` could be anywhere in `foo` but that it will only occur once, is it possible without iterating to find if the value of the key "baz"? I'm thinking s...
I don't think you can do it without iteration/recursion. ``` >>> def search(d, baz): ... if baz in d: ... return d[baz] ... for value in d.values(): ... if isinstance(value, dict): ... ret = search(value, baz) ... if ret: ... return ret ... >>> >>> foo = ...
With a standard dictionary, and not iterating? No.
is it possible to get a grandchild dict key's value without iterating
[ "", "python", "xpath", "" ]
I am trying to do an insert *into table2* based on a select *from table1*, but I can not get the correct syntax. The column names from table1 will drive the value being inserted into the PD\_NO column in table2, as shown in the example below. Can anyone help with this? Table1: ``` (1) (2) (3) (4)...
This is a typical problem for which Oracle 11 provides UNPIVOT clause for use in queries: ``` insert into table2(seq, pd_no, amt) select seq, pd_no, amt from ( select * from table1 unpivot (amt for pd_no in (pd_01 as 1, pd_02 as 2, pd_03 as 3, pd_04 as 4, pd_05 as 5, pd_06 as 6)) )...
In pure sql it can be done in this way: ``` INSERT INTO table2 ( SEQ , PD_NO, AMT ) SELECT SEQ, 1 as pd_no, PD_01 FROM Table1 UNION ALL SELECT SEQ, 2 as pd_no, PD_02 FROM Table1 UNION ALL SELECT SEQ, 3 as pd_no, PD_03 FROM Table1 UNION ALL SELECT SEQ, 4 as pd_no, PD_04 FROM Table1 UNION ALL SELECT SEQ, 5 as pd_no, PD...
SQL - Insert Using Column Name as Value
[ "", "sql", "oracle", "select", "insert", "pivot-table", "" ]
I've got a model with many fields. I'd like to build a queryset that selects the objects which have blank fields from a predefined list of fields. (Any of the fields, not all) Say: ``` fields=['a','b','c','d','e','f','g','h','i','j','k'] ``` I could write ``` model.objects.filter(Q(a==Null) | Q(b==Null) | Q(c==Null...
How about this? ``` qObj = None for field in fields: newQ = Q(**{field : Null}) if qObj is None: qObj = newQ else: qObj = qObj | newQ ``` I don't love the `qObj = None` and following check, but I don't know of a way around it when building up Q objects. The `Q(**{field: Null})` might be w...
I think this should do it: ``` query_terms = {} for fieldname in fields: query_terms['%s__isnull' % fieldname] = False model.objects.exclude(**query_terms) ``` Or if you're on 2.7 or later, use a dictionary comprehension to build `query_terms`. Your original query is awkward because it needs to be or'd together ...
Django, build long queryset automatically
[ "", "python", "django", "" ]
I am trying to implement a simple database program in python. I get to the point where I have added elements to the db, changed the values, etc. ``` class db: def __init__(self): self.database ={} def dbset(self, name, value): self.database[name]=value def dbunset(self, name): ...
A simple approach is to keep a "transaction" list containing all the information you need to be able to roll-back pending changes: ``` def dbset(self, name, value): self.transaction.append((name, self.database.get(name))) self.database[name]=value def rollback(self): # undo all changes while self.tran...
If you are doing this as an academic exercise, you might want to check out the [Rudimentary Database Engine](http://code.activestate.com/recipes/577825) recipe on the *Python Cookbook*. It includes quite a few classes to facilitate what you might expect from a SQL engine. * **Database** is used to create database inst...
python database implementation
[ "", "python", "python-2.7", "" ]
I have following tables structure, cust\_info: ``` cust_id cust_name 1 nikhil 2 sam ``` bill\_info: ``` bill_id cust_id bill_amount 7 1 10000 8 1 15000 9 2 6000 10 2 4000 ``` paid\_info: ``` paid_id cust_id pa...
``` SELECT cust_info.cust_id, cust_name, bill_amount, paid_amount, bill_amount - paid_amount AS balance FROM cust_info INNER JOIN ( SELECT cust_id, SUM(bill_amount) bill_amount FROM bill_info GROUP BY cust_id ) bill_info ON bill_info.cust_id = cust_info.cust_id INNER JOIN ( SELECT c...
``` SELECT c.cust_id, SUM(b.total_bill), SUM(p.total_paid), SUM(c.total_bill) - SUM(p.total_paid) FROM cust_info c LEFT JOIN bill_info b ON (c.cust_id = b.cust_id) LEFT JOIN paid_info p ON (c.cust_id = p.party_id) GROUP BY cust_info.cust_id ```
sql join query for multiple tables
[ "", "sql", "" ]
i know that it is good style to define a main() method for "script-style" python programs so it can optionally be included as a module later on. so let's assume this code (random snippet): ``` a = 5 if a > 0: print a ``` becomes ``` def main(): a = 5 if a > 0: print a if __name__ == "__main__":...
Nope, not possible, really. When `__name__` is **not** `'__main__'` your module was imported by another piece of code, as a regular module. You cannot bail out early in that case. And what's wrong with a **one time** extra indentation level? Just hit tab in the editor, and be done with it? Personally, I find that usi...
You *can* do this: ``` if __name__ != "__main__": throw TypeError("Attempted to import command-line only script") # Your code here ``` However, I would advise against this pattern - most of the time it should be pretty obvious that a script is command-line only. And if someone has a use case for something that y...
no additional indentation with if __name__ == "__main__":
[ "", "python", "program-entry-point", "idioms", "" ]
I have the following query that SHOULD update 716 records: ``` USE db1 GO UPDATE SAMP SET flag1 = 'F', flag2 = 'F' FROM samp INNER JOIN result ON samp.samp_num = result.samp_num WHERE result.status != 'X' AND result.name = 'compound' AND result.alias = '1313' AND sample.standard = 'F' AND sample.flag...
This is likely caused by a trigger on the [samp] table. If you go to Query -> Query Options -> Execution -> Advanced and check SET STATISTICS IO, you will see which other tables are being updated when you run the query.
You can also use the object browser in SSMS to look for the triggers. Open the Tables Node, find the table, open the table node and then open the triggers. The nice thing about this method is that you can script the trigger to a new query window and see what the trigger is doing.
Multiple success messages from SQL Server Update statement
[ "", "sql", "sql-server", "sql-update", "message", "" ]
I have this huge list ( `mylist` ) that contains strings like this: ``` >>> mylist[0] 'Akaka D HI -1 -1 1 1 1 -1 -1 1 1 1 1 1 1 1 -1 1 1 1 -1 1 1 1 1 1 -1 1 -1 -1 1 1 1 1 1 1 0 0 1 -1 -1 1 -1 1 -1 1 1 -1' ``` now, I want to take those 0, 1 and -1 and make a list with them, so I can make a list with the name at the fi...
One way to do this: ``` dictionary = {} for x in mylist: p = x.find('1') if p > 0 and x[p-1] == '-': p -= 1 dictionary[x[0:p].strip()] = x[p:].split() ```
You could use a regex: ``` import re st='Akaka D HI -1 -1 1 1 1 -1 -1 1 1 1 1 1 1 1 -1 1 1 1 -1 1 1 1 1 1 -1 1 -1 -1 1 1 1 1 1 1 0 0 1 -1 -1 1 -1 1 -1 1 1 -1' dic={} m=re.match(r'([a-zA-Z\s]+)\s(.*)',st) if m: dic[m.group(1)]=m.group(2).split() ``` result: ``` {'Akaka D HI': ['-1', '-1', '1', '1', '1', '-1', '...
Why am I getting an "Unhashable type: 'list' " error?
[ "", "python", "" ]
I want to reorder dimensions of my numpy array. The following piece of code works but it's too slow. ``` for i in range(image_size): for j in range(image_size): for k in range(3): new_im[k, i, j] = im[i, j, k] ``` After this, I vectorize the new\_im: ``` new_im_vec = new_im.reshape(image_size...
Check out [rollaxis](http://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html#numpy.rollaxis), a function which shifts the axes around, allowing you to reorder your array in a single command. If `im` has shape *i, j, k* ``` rollaxis(im, 2) ``` should return an array with shape *k, i, j*. After this, y...
``` new_im = im.swapaxes(0,2).swapaxes(1,2) # First swap i and k, then i and j new_im_vec = new_im.flatten() # Vectorize ``` This should be much faster because swapaxes returns a view on the array, rather than copying elements over. And of course if you want to skip `new_im`, you can do it in one line, and still only...
reordering of numpy arrays
[ "", "python", "numpy", "" ]
I'm able to run my Google App Engine webapp2 app using [Python Tools for Visual Studio](http://pytools.codeplex.com/) 2012 without issues after following [this tutorial](http://4a47.blogspot.ca/2012/11/debugging-python-in-google-app-engine.html), and even step through the server initialization code, but I can't get it ...
### UPDATE#2 ### `gcloud preview` deprecated it's back to original method ### UPDATE#1 ### `gcloud preview` (it's newer and simpler), replace this: *General->Startup File:* ``` C:\Program Files\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\gcloud\gcloud.py ``` *Debug->Script Arguments:* ``` preview app ...
There's a workaround, but I don't know about getting this working for python tools for vs. In theory it should be possible. <https://groups.google.com/forum/#!topicsearchin/google-appengine/Boa/google-appengine/-m00Qz4Vc7U> You'd probably need this guide to get it working: <https://docs.google.com/document/d/1CCSaRi...
Debugging GAE in Python Tools for Visual Studio
[ "", "python", "visual-studio", "google-app-engine", "webapp2", "ptvs", "" ]
I need to get the value of the previous line in a file and compare it with the current line as I'm iterating through the file. The file is HUGE so I can't read it whole or randomly accessing a line number with `linecache` because the library function still reads the whole file into memory anyway. **EDIT** I'm so sorry...
Just save the previous when you iterate to the next ``` prevLine = "" for line in file: # do some work here prevLine = line ``` This will store the previous line in `prevLine` while you are looping **edit** apparently OP needs to read this file backwards: aaand after like an hour of research I failed multip...
@Lim, here's how I would write it (reply to the comments) ``` def do_stuff_with_two_lines(previous_line, current_line): print "--------------" print previous_line print current_line my_file = open('my_file.txt', 'r') if my_file: current_line = my_file.readline() for line in my_file: previous_li...
Read previous line in a file python
[ "", "python", "file", "loops", "" ]
Can anyone please advise on how to go about writing a SQL query to include the sum for multiple fields across multiple rows by group. I'm using the below query, but it keeps saying that the fields "in the select line are invalid because it is not contained in either an aggregate function or the GROUP BY clause." ``` ...
Depending on what you really want, you have two options: **OPTION #1: Remove the `BilledAmt` from the `SELECT`** ``` Select ClaimId,InternalICN, Sum(PayAmt) as TotPayAmt,Sum(COBAmt) as TotCOBAmt,Sum(PrePayAmt) as TotPrePayAmt from CAIDEnc.IntEncTracking.EncounterList where BypassFlag...
BilledAmt is not in the group by clause. You must put it there, or aggregate it with a sum, average or other function.
How to sum across multiple rows for multiple fields
[ "", "sql", "group-by", "sum", "" ]
I am attempting to parse a space delimited text file in python 2.7.5 which looks kind of like: ``` variable description useless data a1 asdfsdf 2342354 Sometimes it goes into further detail about the variable/description here a2 asdsfda ...
You want to filter out lines that start with spaces, and split all other lines to get the first two columns. Translating those two rules into code: ``` with open('Myfile.txt') as f: for line in f: if not line.startswith(' '): variable, description, _ = line.split(None, 2) print(var...
Assuming no spaces in your variables or descriptions, this will work ``` with open('path/to/file') as infile: answer = [] for line in file: if not line.strip(): continue if line.startswith(' '): # skipping descriptions continue splits = line.split() var, ...
Skipping lines and splitting them into columns in python text parser
[ "", "python", "" ]
I am pulling rows from a MySQL database as dictionaries (using SSDictCursor) and doing some processing, using the following approach: ``` from collections import namedtuple class Foo(namedtuple('Foo', ['id', 'name', 'age'])): __slots__ = () def __init__(self, *args): super(Foo, self).__init__(self, *...
First, you have to override `__new__` in order to customize `namedtuple` creation, because a `namedtuple`'s `__new__` method checks its arguments before you even get to `__init__`. Second, if your goal is to accept and filter keyword arguments, you need to take `**kwargs` and filter and pass that through, not just `*a...
A `namedtuple` type has an attribute `_fields` which is a tuple of the names of the fields in the object. You could use this to dig out the required fields from the database record.
Creating a namedtuple object using only a subset of arguments passed
[ "", "python", "arguments", "decorator", "namedtuple", "" ]
Given a sparse matrix listing, what's the best way to calculate the cosine similarity between each of the columns (or rows) in the matrix? I would rather not iterate n-choose-two times. Say the input matrix is: ``` A= [0 1 0 0 1 0 0 1 1 1 1 1 0 1 0] ``` The sparse representation is: ``` A = 0, 1 0, 4 1, 2 1, 3 ...
You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn. As of version 0.17 it also supports sparse output: ``` from sklearn.metrics.pairwise import cosine_similarity from scipy import sparse A = np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1],[1, 1, 0, 1, 0]]) A_sparse = sparse.c...
The following method is about 30 times faster than `scipy.spatial.distance.pdist`. It works pretty quickly on large matrices (assuming you have enough RAM) See below for a discussion of how to optimize for sparsity. ``` import numpy as np # base similarity matrix (all dot products) # replace this with A.dot(A.T).toa...
What's the fastest way in Python to calculate cosine similarity given sparse matrix data?
[ "", "python", "numpy", "pandas", "similarity", "cosine-similarity", "" ]
I have two databases, one is called `Natalie_playground` and one is called `LiveDB`. Since I want to practice insert, update things, I want to copy some of the tables from the `LiveDB` to `Natalie_playground`. The tables I want to copy are called: `Customers, Computers, Cellphones, Prices` What I tried to do is that ...
Assuming that you have two databases, for example A and B: * If target table not exists, the following script will create (I do not recommend this way): ``` SELECT table_A.FIELD_1, table_A.FIELD_2,......, table_A.FIELD_N INTO COPY_TABLE_HERE FROM A.dbo.table_from_A table_A ``` * If target table exists, t...
Right click on your database -> under **Tasks** choose **Generate scripts**, follow the wizard, choose your tables and check the check box that says **'script table data'** (or similar) generate it to an SQL script and execute it on your other DB.
SQL Server Copying tables from one database to another
[ "", "sql", "sql-server", "data-migration", "" ]
Im trying to get an output like: ``` KPLR003222854-2009131105131 ``` in a text file. The way I am attempting to derive that output is as such: ``` with open('Processed_Data.txt', 'r') as file_P, open('KIC_list.txt', 'w') as namelist: nameData = [] for line in file_P: splt_file_P = line.spl...
Your code looks like it's working as one would expect: `"".join(str(w) for w in nameData)` makes a string composed of the concatenation of every item in `nameData`. Chances are you want; ``` for key in nameData: namelist.write('\n' 'KPLR00' + key + '-2009131105131') ``` Or even better: ``` for key in nameData: ...
You can change this: ``` "".join(str(w) for w in nameData) ``` to this: ``` ",".join(str(w) for w in nameData) ``` Basically, the "," will comma delimit the elements in your `nameData` list. If you use `""`, then there will be nothing to separate the elements, so they appear all at once. You can change the delimite...
Looping a write command to output many different indices from a list separately in Python
[ "", "python", "list", "" ]
I want to cleanse data on the postcode column. So far I have ``` declare @postcode table ( letter1 varchar(4) ,number1 varchar(4) ,number2 varchar(4) ,letter3 varchar(4) ) insert into @postcode values ('a','1','1','a'), ('b','2','2','b'), ('c','3','3','c') ``` All the way down the alphabet to ``` (null,'37','37',n...
Not sure this is exactly what you need, but assuming the formula needed is "letter-digit-digit-space-digit-letter-letter" (according to picture), data can be generated e.g. with the following statement: ``` ;with A as (select cast(char((rand(checksum(newid())) * 26) + ascii('A')) as varchar(10)) A), D as (sele...
Some things that may help: To get a random integer between 1 and 37: `CONVERT(int, RAND() * 37) + 1` To get a random letter: `CHAR((RAND() * 26) + ASCII('A'))` If you want a random row, you could try this, though it wouldn't be particularly speedy: ``` declare @rowCount int , @randomRow int select @rowCount ...
Select Random value from columns
[ "", "sql", "sql-server", "" ]
I'm new to this, hope someone can help with my basic question to help clarify my concept. I was playing around to shorten the code, but the 2nd case didn't work. I think it didn't work because remove() doesn't return anything. Is that correct? This got me wondering. When do you want write function that doesn't retur...
This is a matter of style. I, and plenty of others, agree that in general it is much more useful to have a function return something - in particular, methods of an object which return `self` rather than `None` allow chaining. Unfortunately, that's not what most people in the Python community do, and it's not what the ...
Many programmers are proponents of what is known as the [Command-query separation](http://en.wikipedia.org/wiki/Command%E2%80%93query_separation "Command-query separation - Wikipedia, the free encyclopedia"). Functions that return values (*queries*) will in general not have side effects, while functions that have side ...
When do you write function that doesn't return anything
[ "", "python", "return", "" ]
Below is a table which stores the value of personal\_id and date: ``` Person_ID Effective_Date End Effective_Date 1)6335 24/02/1999 2)6335 09/07/1998 3)6335 26/06/1998 ``` and the output table should be like ``` Person_ID Effective_Date End Effective_Date 1)6335 ...
Hope this helps you out. Run the query and check the results. ``` DECLARE @tbl table (ID int, D1 DATETIME, D2 DATETIME) INSERT INTO @tbl select 1,'2/28/2013','2/28/2013' union all select 2,'3/2/2013','3/2/2013' union all select 3,'4/2/2013','4/2/2013' union all select 4,'4/6/2013','4/6/2013' union all select 5,'5/21/...
You can use the `lead` function to look ahead to the next row and get its effective date: ``` select person_id, effective_date, lead(effective_date) over (partition by person_id order by effective_date) as lead_date from t42; PERSON_ID EFFECTIVE_DATE LEAD_DATE ---------- -------------- --------- 6335 26-...
Sorting Data By SQL Statement
[ "", "sql", "oracle-sqldeveloper", "" ]
This works in the Python 3.3.2 Shell # Inside the Python 3.3.2 Shell ``` >>> import datetime >>> print(datetime.datetime.utcnow()) 2013-07-09 19:40:32.532341 ``` That's great! I then wrote a simple text file named "datetime.py" # Inside Datetime.py ``` #Date time import datetime print(datetime.datetime.utcnow()) #...
The problem is that file is recursively importing itself, instead of importing the built-in module `datetime`: **Demo:** ``` $ cat datetime.py import datetime print datetime.__file__ $ python datetime.py /home/monty/py/datetime.pyc /home/monty/py/datetime.pyc ``` This happens because the [module is searched](http://...
As @Sukrit Kalra says, don't use `datetime.py` as your file name. Python is getting confused with which `datetime` is which (and is importing itself!). Maybe; ``` $ mv datetime.py my_datetime.py ```
Why does this work in the Python IDLE shell but not when I run it as a Python script from the command prompt?
[ "", "python", "python-3.x", "" ]
My current format string is: ``` formatter = logging.Formatter('%(asctime)s : %(message)s') ``` and I want to add a new field called `app_name` which will have a different value in each script that contains this formatter. ``` import logging formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s') sys...
# Python3 As of Python3.2 you can now use [LogRecordFactory](https://docs.python.org/3/library/logging.html#logrecord-objects) ``` import logging logging.basicConfig(format="%(custom_attribute)s - %(message)s") old_factory = logging.getLogRecordFactory() def record_factory(*args, **kwargs): record = old_factor...
You could use a [LoggerAdapter](http://docs.python.org/2/library/logging.html#loggeradapter-objects) so you don't have to pass the extra info with every logging call: ``` import logging extra = {'app_name':'Super App'} logger = logging.getLogger(__name__) syslog = logging.StreamHandler() formatter = logging.Formatter...
How do I add custom field to Python log format string?
[ "", "python", "logging", "python-logging", "" ]
I have a MYSQL Database with one table that is growing by 5,000 rows a second. I expect this table to get into the Billions of records. I have a query function in php right now: ``` $result =mysqli_query($con, "SELECT * FROM table WHERE `data`='".$input."' LIMIT 0 , 30"); ``` The problem is obvious the bigger the t...
Indexes are very important here. Makes huge difference. Also make sure it is normalized correctly. Another, more hands on idea, is to not have one big db. But separate it into many smaller, based on a criteria that you know when querying it later. Like, date, first letter, etc. It is not practical to have this big db ...
If you have such a big table and the values you are interested in are "latest" the you could improve performance using MySQL [partitioning](http://dev.mysql.com/doc/refman/5.5/en/partitioning.html). More you can check this [article](http://www.chrismoos.com/2010/01/31/mysql-partitioning-tables-with-millions-of-rows).
MYSQL query a billion records and timeout issues
[ "", "mysql", "sql", "performance", "" ]
I'm learning python, and I have a novice question about initializing sets. Through testing, I've discovered that a set can be initialized like so: ``` my_set = {'foo', 'bar', 'baz'} ``` Are there any disadvantages of doing it this way, as opposed to the standard way of: ``` my_set = set(['foo', 'bar', 'baz']) ``` o...
There are two obvious issues with the set literal syntax: ``` my_set = {'foo', 'bar', 'baz'} ``` 1. It's not available before Python 2.7 2. There's no way to express an empty set using that syntax (using `{}` creates an empty dict) Those may or may not be important to you. The section of the docs outlining this syn...
Compare also the difference between `{}` and `set()` with a single word argument. ``` >>> a = set('aardvark') >>> a {'d', 'v', 'a', 'r', 'k'} >>> b = {'aardvark'} >>> b {'aardvark'} ``` but both `a` and `b` are sets of course.
Use curly braces to initialize a Set in Python
[ "", "python", "python-2.7", "set", "" ]
I've got the following minimal code for a CGI-handling HTTP server, derived from several examples on the inner-tubes: ``` #!/usr/bin/env python import BaseHTTPServer import CGIHTTPServer import cgitb; cgitb.enable() # Error reporting server = BaseHTTPServer.HTTPServer handler = CGIHTTPServer.CGIHTTPRequestHandler ...
My suspicions were correct. The examples from which this code is derived showed the wrong way to set the default directory to be the same directory in which the server script resides. To set the default directory in this way, use: ``` handler.cgi_directories = ["/"] ``` **Caution: This opens up potentially huge secur...
The solution doesn't seem to work (at least for me) if the .cgi\_directories requires multiple layers of subdirectories ( `['/db/cgi-bin']` for instance). Subclassing the server and changing the `is_cgi` def seemed to work. Here's what I added/substituted in your script: ``` from CGIHTTPServer import _url_collapse_pat...
Python CGIHTTPServer Default Directories
[ "", "python", "cgi", "httpserver", "cgihttpserver", "cgihttprequesthandler", "" ]
I have a table that uses UUIDs as primary keys. New rows are inserted like this ``` INSERT INTO a ( id, ... ) VALUES ( uuid_generate_v4(), ...) ``` Now I actually only want to generate the UUID when no ID is provided in the insert (either `NULL` or an empty string) Is it possible to write something like this? ``` I...
The [coalesce() function](http://www.postgresql.org/docs/current/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL) will use the first non-null. If $1 is null, coalesce() will use uuid\_generate\_v4(). Otherwise, it will try to use $1. ``` insert into a (id, ... ) values (coalesce($1, uuid_generate_v4()...
Check the IF function, available in some RDBMS. ``` IF( $1 = NULL, $1, uuid_generate_v4()) ``` `$1` being a placeholder. Also you could set a trigger, if you like them, but mostly they are frowned upon. And also there are `IFNULL( $1, uuid_generate_v4() )`. Update: I'm quite surprised that PostgreSQL doesn't supor...
Conditional Value
[ "", "sql", "postgresql", "" ]
Ok, so I want/need to use the "|: operator Say I have a list: ``` list = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}] ``` I need to find the intersection of the list without using: set.intersection(\*L) Ideally I'd like to use a function with a for loop (or nested for loops) to get return the intersections of all of the sets ...
Try this, using list comprehension ``` list = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}] b = [] [b.append(x) for c in list for x in c if x not in b] print b # or set(b) ``` Output: ``` [1, 2, 3, 4, 5, 6] ``` If you are keen on having the output as a set, try this: ``` b = set([]) [b.add(x) for c in list for x in c if x not...
``` >>> L=[{1,2,3},{2,3,4},{3,4,5},{4,5,6}] >>> from itertools import chain >>> set(chain.from_iterable(L)) {1, 2, 3, 4, 5, 6} ```
intersection of multiple sets in a list
[ "", "python", "python-3.x", "set", "intersection", "" ]
I have python 3.3.2 installed on windows 8 x64. I am trying to install webpy framework. What I tried: Downloaded latest webpy. Extracted to python directroy. in command promp I cd {python\_dir/webpy\_sub\_dir}, then python setup.py install I get this error: ``` Traceback .... File "setup.py", line 6 .... from w...
In the end the problem was that webpy is not compatible with python 3.x. I went with a similar alternative - bottle py.
You might need to download the utils package from pypi <https://pypi.python.org/pypi/python-utils/>
How to install webpy framework on Windows
[ "", "python", "web.py", "" ]
Here's the table in sql server.. and below is what I want to do. TABLE: ``` Area (column 1) ----- Oregon California California California Oregon Washington Idaho Washington ``` I want ALL the cities that *are* duplicates to be returned, but not the distinct ones. Just the duplicates. Is there a select statement that...
``` Select State FROM Area GROUP BY State Having COUNT(*) > 1 ``` Try this Update the query with your own column and table names
While the `GROUP BY .. HAVING` approach is probably better here, this case - "more than one" - can also be answered with a `JOIN` *assuming* that there is a column (or set of columns) that form a Key. The requirement of a Key is that it must *uniquely* identify a record. ``` SELECT DISTINCT a1.State FROM AREA a1 JOIN ...
How to select only duplicate records?
[ "", "sql", "sql-server", "" ]
Hi I have the following table struct: ``` Person Date1 Date2............Daten ------ ----- ----- ----- 1 2001-01-01 2002-01-01 2 2003-01-01 2000-01-01 ``` and i want to choose the minimum Date between Date1 and Date(n) (20 dates in my case). So fo...
``` SELECT person AS the_person , LEAST(date1 ,date2, date3, date4, date5, ..., dateN ) AS the_date FROM the_table ; ``` `Least()` should ignore NULLs, if present. (the above works for Postgres) UPDATE (thanks to @WarrenT) apparently **DB2** does not have `LEAST()`, but it does have `MIN()` instead (having more tha...
Without commenting on the really bad schema (it violates on of normal form rules - I think it's called *no repeating groups*), The only way I know is to use case statement ``` Select case When Date1 < Date2 And Date1 < date3 and date1 < date4 and ... Then date1 When Date2 < Date1 And Date2 < date3 an...
choose minimum date from a record out of multiple columns
[ "", "sql", "db2", "" ]
Kind of a strange request. Let's say I have the following list: ``` [1,2,3] ``` And I want something, say, the number 9, to pass through every index, to get the following list of lists: ``` [[9,1,2,3], [1,9,2,3], [1,2,9,3], [1,2,3,9]] ``` Any idea how to do this easily? Also, is there a name for this sort of th...
You could do something like ``` l = [1,2,3] new_l = [l[:i] + [9] + l[i:] for i in range(len(l) + 1)] ```
How about a for loop: ``` l = [1,2,3] res = [] for i in xrange(len(l)+1): l2 = l[:] l2.insert(i,9) res.append(l2) ``` Here is another thing I thought of: ``` l = [1,2,3] q = [l[:] for _ in range(len(l)+1)] map(lambda(x):x.insert(q.index(x),9), q) ``` Then `q` will contain your list: ``` print q [9, 1, ...
Getting lists where an element passes through every index in python?
[ "", "python", "list", "permutation", "" ]
let's say we have two functions: ``` def ftpConnect(): ftp = FTP('server') ftp.login() ftp.cwd('/path') def getFileList(): ftpConnect() files = ftp.nlst() print(files) ``` If I call the getFileList() function it won't work because it doesn't know the ftp var. I know that if I declare the ft...
In my opinion, the most elegant solution would be to make a FTP-class, which would have the `ftp`-variable as a private attribute. ``` class FTPConnection(object): def __init__(self, server): self._ftp = FTP(server) def connect(self): self._ftp.login() self._ftp.cwd('/path') def g...
Functions can return values. Return values are cool! Return `ftp` from `ftpConnect()`: ``` def ftpConnect(): ftp = FTP('server') ftp.login() ftp.cwd('/path') # return the value of `ftp` to the caller return ftp def getFileList(): # assign the return value of `ftpConnect` to a new local varia...
Function variable scope in python
[ "", "python", "function", "variables", "scope", "" ]
I know that **a[end:start:-1]** slices a list in a reverse order. **For example** ``` a = range(20) print a[15:10:-1] # prints [15, ..., 11] print a[15:0:-1] # prints [15, ..., 1] ``` but you cannot get to the first element (0 in the example). It seems that -1 is a special value. ``` print a[15:-1:-1] # prints [] `...
You can assign your variable to `None`: ``` >>> a = range(20) >>> a[15:None:-1] [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> ```
Omit the end index: ``` print a[15::-1] ```
Reverse Indexing in Python?
[ "", "python", "" ]
I have a string: ``` """Hello. It's good to meet you. My name is Bob.""" ``` I'm trying to find the best way to split this into a list divided by periods and linebreaks: ``` ["Hello", "It's good to meet you", "My name is Bob"] ``` I'm pretty sure I should use regular expressions, but, having no experience with them...
You don't need regex. ``` >>> txt = """Hello. It's good to meet you. ... My name is Bob.""" >>> txt.split('.') ['Hello', " It's good to meet you", '\nMy name is Bob', ''] >>> [x for x in map(str.strip, txt.split('.')) if x] ['Hello', "It's good to meet you", 'My name is Bob'] ```
For your example, it would suffice to split on dots, optionally followed by whitespace (and to ignore empty results): ``` >>> s = """Hello. It's good to meet you. ... My name is Bob.""" >>> import re >>> re.split(r"\.\s*", s) ['Hello', "It's good to meet you", 'My name is Bob', ''] ``` In real life, you'd have to han...
Divide string by line break or period with Python regular expressions
[ "", "python", "regex", "string", "split", "" ]
I have a definition that builds a string composed of UTF-8 encoded characters. The output files are opened using `'w+', "utf-8"` arguments. However, when I try to `x.write(string)` I get the `UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 1: ordinal not in range(128)` I assume this is ...
Are you using [`codecs.open()`](http://docs.python.org/2/library/codecs.html#codecs.open)? Python 2.7's built-in `open()` does not support a specific encoding, meaning you have to manually encode non-ascii strings (as others have noted), but `codecs.open()` does support that and would probably be easier to drop in than...
In python 2.x there are two types of string: byte string and unicode string. First one contains bytes and last one - unicode code points. It is easy to determine, what type of string it is - unicode string starts with `u`: ``` # byte string >>> 'abc' 'abc' # unicode string: >>> u'abc абв' u'abc \u0430\u0431\u0432' ``...
Python, Encoding output to UTF-8
[ "", "python", "python-2.7", "encoding", "utf-8", "" ]
``` select C.customerId,(C.lastName+', '+C.firstName) as CustomerName, C.companyName, D.companyName+' ('+D.lastName+','+D.firstName+')' as "Parent CompanyName(Last, First)",S.siteId, S.nickName as siteName, dbo.GetSiteTelemetryBoxList(s.siteId) as "DeviceId's", dbo.GetSiteTelemetryBoxSKUList(S.siteId,0) as SKU from...
I did some digging and found a few ways to implement it. Basically, the simple solution for this is using mysql's group\_concat function. These links discuss how the group\_concat can be implemented for SQL server. You can choose one based on your requirements. 1. [Simulating group\_concat MySQL function in Microsoft ...
You can convert the rows with something like this to transform the rows into a concatenated string: ``` select distinct stuff(( select ',' + u.username from users u where u.username = username order by u.username for xml path('') ),1,1,'') as userlist from users group by username ```
Trying to combine multiple rows of result set into single row
[ "", "sql", "sql-server-2008", "sql-server-2008-r2", "" ]
For example, when I calculate `98/42` I want to get `7/3`, not `2.3333333`, is there a function for that using Python or `Numpy`?
The `fractions` module can do that ``` >>> from fractions import Fraction >>> Fraction(98, 42) Fraction(7, 3) ``` There's a recipe over [here](https://stackoverflow.com/questions/15569429/numpy-gcd-function) for a numpy gcd. Which you could then use to divide your fraction ``` >>> def numpy_gcd(a, b): ... a, b =...
Addition to John's answer: **To get simplified fraction from a decimal number (say 2.0372856077554062)** Using Fraction gives the following output: ``` Fraction(2.0372856077554062) #> Fraction(4587559351967261, 2251799813685248) ``` **To get simplified answer** : ``` Fraction(2.0372856077554062).limit_denominator(...
Does Python have a function to reduce fractions?
[ "", "python", "python-2.7", "numpy", "numerical", "fractions", "" ]
So me and my buddy are helping each other learn about programming, and we have been coming up with challenges for ourselves. He came up with one where there are 20 switches. We need to write a program that first hits every other switch, and then every third switch, and then every fourth switch and have it output which ...
Use [Python's List Slicing Notation](https://stackoverflow.com/questions/509211/the-python-slice-notation): ``` start_list[::2] ``` Slicing goes as `[start:stop:step]`. `[::2]` means, from the beginning until the end, get every second element. This returns every second element. I'm sure you can figure out how to get...
Every other switch: ``` mylist[::2] ``` Every third: ``` mylist[::3] ``` You can assign to it too: ``` mylist=[1,2,3,4] mylist[::2]=[7,8] ```
Can't figure out how to increment certain values in a list
[ "", "python", "list", "increment", "" ]
I am trying to replace single `$` characters with something else, and want to ignore multiple `$` characters in a row, and I can't quite figure out how. I tried using lookahead: ``` s='$a $$b $$$c $d' re.sub('\$(?!\$)','z',s) ``` This gives me: ``` 'za $zb $$zc zd' ``` when what I want is ``` 'za $$b $$$c zd' ``` ...
notes, if not using a callable for the replacement function: * you would need look-ahead because you must not match if followed by `$` * you would need look-behind because you must not match if preceded by `$` not as elegant but this is very readable: ``` >>> def dollar_repl(matchobj): ... val = matchobj.group(0...
Hmm. It looks like I can get it to work if I used both lookahead and lookbehind. Seems like there should be an easier way, though. ``` >>> re.sub('(?<!\$)\$(?!\$)','z',s) 'za $$b $$$c zd' ```
replacing only single instances of a character with python regexp
[ "", "python", "regex", "" ]
I have a small code producing the following picture with this code: Code 1: ``` hist, rhist = np.histogram(r, bins=40, range=(0, 0.25)) hist = -hist/np.trapz(rhist[:-1],hist) plt.plot(rhist[:-1], hist) ``` Output of code 1: ![enter image description here](https://i.stack.imgur.com/ws65v.png) Then I try setting the ...
I'm pretty sure it's just not plotting those values because they are zero. Log(0) = -Infinity. Plotting that is going to make your graph look pretty rubbish...
Issue `plt.yscale('symlog')` at the end of your plotting. See [here](https://stackoverflow.com/questions/3305865/what-is-the-difference-between-log-and-symlog) for a description of `'symlog'`.
Matplotlib/Pylab - part of plot disappears after setting log scale
[ "", "python", "graph", "matplotlib", "plot", "" ]
This is from django's documentation: > Field.unique > > If True, this field must be unique throughout the table. > > This is enforced at the database level and by model validation. > If you try to save a model with a duplicate value in a unique field, a django > .db.IntegrityError will be raised by the model’s save() ...
**For django 1.9+** Running `makemigrations` then `migrate` applies the unique constraint to sqlite3 **For django < 1.9** Since you are using django 1.5, this solution will apply. If you added the `unique=True` after the table was already created, then even if you do `syncdb` later, the unique condition will not ...
Running sql scripts directly on the db can be avoided. Rather add the sql execution in your migration: ``` from __future__ import unicode_literals from django.db import migrations, connection def alter_table(apps, schema_editor): query ="ALTER TABLE <your table> ADD UNIQUE (unique_col);" cursor = connection....
Django unique=True not working
[ "", "python", "django", "" ]
I'm currently have a few tables with `InnoDB Engine`. 10-20 connections are constantly inserts data into those tables. I use `MySQL RDS` instance on AWS. Metric shows about 300 Write IOPS (counts/second). However, INSERT operations lock the table, and if someone want to perform a query like `SELECT COUNT(*) FROM table;...
SELECT COUNT(\*) without WHERE is bad query for InnoDB, as it does not cache the row count like MyISAM do. So if you have issue with this particular query, you have to cache the count somewhere - in a stats table for example. After you remove this specific type of query, you can talk about InnoDB vs MyISAM read perfor...
I think you should stick with your current setup. InnoDB is supposed not to lock the table when inserting rows, since it uses the MVCC technique. On the other hand, MyISAM locks the entire table when new rows are inserted. So, if you have many writes, you should stick with InnoDB.
Will switch to MyISAM Engine help to improve the speed of reading operations?
[ "", "mysql", "sql", "innodb", "myisam", "" ]
I have dictionary structure. For example: ``` dict = {key1 : value1 ,key2 : value2} ``` What I want is the string which combines the key and the value Needed string -->> key1\_value1 , key2\_value2 Any Pythonic way to get this will help. Thanks ``` def checkCommonNodes( id , rs): for r in rs: for k...
A `list` of key-value `str`s, ``` >>> d = {'key1': 'value1', 'key2': 'value2'} >>> ['{}_{}'.format(k,v) for k,v in d.iteritems()] ['key2_value2', 'key1_value1'] ``` Or if you want a single string of all key-value pairs, ``` >>> ', '.join(['{}_{}'.format(k,v) for k,v in d.iteritems()]) 'key2_value2, key1_value1' ``` ...
Assuming Python 2.x, I would use something like this ``` dict = {'key1': 'value1', 'key2': 'value2'} str = ''.join(['%s_%s' % (k,v) for k,v in dict.iteritems()]) ```
Python getting a string (key + value) from Python Dictionary
[ "", "python", "string", "dictionary", "" ]
I have a dictionary ``` d = {'a':1, 'b':2, 'c':3} ``` I need to remove a key, say **c** and return the dictionary without that key in one function call ``` {'a':1, 'b':2} ``` d.pop('c') will return the key value - 3 - instead of the dictionary. *I am going to need one function solution if it exists, as this will g...
How about this: ``` {i:d[i] for i in d if i!='c'} ``` It's called [Dictionary Comprehensions](https://www.python.org/dev/peps/pep-0274/) and it's available since Python 2.7. or if you are using Python older than 2.7: ``` dict((i,d[i]) for i in d if i!='c') ```
Why not roll your own? This will likely be faster than creating a new one using dictionary comprehensions: ``` def without(d, key): new_d = d.copy() new_d.pop(key) return new_d ```
Remove key from dictionary in Python returning new dictionary
[ "", "python", "methods", "dictionary", "" ]
Hey guys I need help on this past test question. Basically I am given two list of objects, and I am suppose to find the number of items that appear in the same position of the first list and the second. I have an example that was provided. ``` >>> commons(['a', 'b', 'c', 'd'], ['a', 'x', 'b', 'd']) 2 >>> commons(['a',...
This is not a simple problem for a beginner. A more straightforward approach would use functions like `sum` and `zip` with a list comprehension like so: ``` def commons(L1, L2): return sum(el1 == el2 * 1 for el1, el2 in zip(L1, L2)) ``` A more typical but error prone approach taken by beginners is: ``` def comm...
I think a more straightforward solution would be: ``` def commons(L1,L2): return len([x for x in zip(L1,L2) if x[0]==x[1]]) ```
Finding the common item between two list in python
[ "", "python", "python-3.x", "" ]
I'm trying to get the number from a string and then remove that number. For instance, I'm going to have a string like '42Xmessage' where 42 is the number I want (it could be any number of digits) and it's terminated by an X. How can I get the number in a variable and then get the message part (without the number and X...
You can do ``` '42Xmessage'.split('X') ``` to return ``` ['42', 'message'] ``` This isn't very general, but you can get more information from the [string](http://docs.python.org/2/library/string.html) or [re](http://docs.python.org/2/library/re.html) module documentation.
Use [`partition`](http://docs.python.org/2/library/stdtypes.html#str.partition): ``` >>> s = '42Xmessage' >>> s.partition('X') ('42', 'X', 'message') >>> s.partition('X')[0] '42' ```
How can I capture a value from a string and then remove it?
[ "", "python", "regex", "string", "" ]
How can I get all the text content of an XML document, as a single string - [like this Ruby/hpricot example](https://stackoverflow.com/questions/1243817/hpricot-get-all-text-from-document) but using Python. I'd like to replace XML tags with a single whitespace.
**EDIT:** This is an answer posted when I thought one-space indentation is normal, and as the comments mention it's not a *good* answer. Check out the others for some better solutions. This is left here solely for archival reasons, do **not** follow it! You asked for lxml: ``` reslist = list(root.iter()) result = ' '...
Using stdlib `xml.etree` ``` import xml.etree.ElementTree as ET tree = ET.parse('sample.xml') print(ET.tostring(tree.getroot(), encoding='utf-8', method='text')) ```
Get all text from an XML document?
[ "", "python", "xml", "lxml", "" ]
After following this article: [How do I install pip on Windows?](https://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows) on my Windows system using Enthought Canopy 64 Bit system, I cannot get pip or easy\_install to work due to error: ``` pip install requests failed to create process ``` I tried r...
When I encountered this, it was because I'd manually renamed the directory python was in. This meant that both setuptools and pip had to be reinstalled. Or, I had to manually rename the python directory to what it had been previously.
It will help after changing the PATH to python in environment variables: `python -m pip install --upgrade pip --force-reinstall`
pip/easy_install failure: failed to create process
[ "", "python", "pip", "easy-install", "" ]
I forked the Flask example, Minitwit, to work with MongoDB and it was working fine on Flask 0.9, but after upgrading to 0.10.1 I get the error in title when I login when I try to set the session id. It seems there was [changes](http://lucumr.pocoo.org/2013/6/13/werkzeug-and-flask-releases/) in Flask 0.10.1 related to ...
EDIT: Even easier fix. You don't even need to do any JSON encoding/decoding. Just save the session['\_id'] as a string: ``` user = db.minitwit.user.find_one({'username': request.form['username']}) session['_id'] = str(user['_id']) ``` And then everywhere you want to do something with the session['\_id'] you have to ...
JSON only supports serializing (encoding/decoding) a limited set of objects types by default. You could extend python JSON's decoder/encoder's to handle this situation though. In terms of encoding an object which contains on ObjectID, for example, when ObjectIds are created client side, which will be passed along to s...
Getting 'TypeError: ObjectId('') is not JSON serializable' when using Flask 0.10.1
[ "", "python", "json", "flask", "pymongo", "" ]
I just want to change a list (that I make using range(r)) to a list of strings, but if the length of the string is 1, tack a 0 on the front. I know how to turn the list into strings using ``` ranger= map(str,range(r)) ``` but I want to be able to also change the length of those strings. Input: ``` r = 12 ranger = r...
Use [`string formatting`](http://docs.python.org/2/library/string.html#formatspec) and list comprehension: ``` >>> lst = range(11) >>> ["{:02d}".format(x) for x in lst] ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10'] ``` or [`format`](http://docs.python.org/2/library/functions.html#format): ``` >>...
`zfill` does exactly what you want and doesn't require you to understand an arcane mini-language as with the various types of string formatting. There's a place for that, but this is a simple job with a ready-made built-in tool. ``` ranger = [str(x).zfill(2) for x in range(r)] ```
Convert range(r) to list of strings of length 2 in python
[ "", "python", "python-3.x", "string", "list", "range", "" ]
My stored procedure implementation is simple: ``` create Procedure [dbo].[GetNegotiationInfo] ( @negotiationId uniqueidentifier ) As select NegotiationId, SellerId from NegotiationMaster where negotiationId = @negotiationId ``` Then I expected to be to write the following code after updating my model. ``` ...
Its all about editing the "Function Import" in the Visual Studio Model Browser and creating a complex type for the return record set. Note, temp Tables in your stored procedure will be difficult for Entity Framework to inspect. see [MSDN](http://msdn.microsoft.com/en-us/library/bb896231.aspx)
Stored procedures always return an integer. This is the status of the stored procedure call and will be set to `NULL` if not specified in the code. The general approach is that `0` indicates success and any other value indicates an error. [Here](http://msdn.microsoft.com/en-us/library/ms190778%28v=sql.105%29.aspx) is s...
Entity Framework generated representation of a stored procedure signature is an Int instead of a record set
[ "", "sql", "linq", "sql-server-2008", "entity-framework", "" ]
Is there any way to make the tkinter `label widget` vertical? Something like this ![sample label](https://i.stack.imgur.com/NrqM7.gif) or is it just simply impossible? I have already look around and can't seems to find how to do it.By the way, i have tried `orient='vertical'` but `label widget` doesn't seems to suppo...
No, there is no way to display rotated text in the tkinter Label widget.
You can achieve vertical display, without the text rotation, by using the wraplength option which set to 1 will force the next char into a new line: ``` Label( master_frame, text="Vertical Label", wraplength=1 ).grid( row=0, column=0 ) ```
Python tkinter label orientation
[ "", "python", "tkinter", "label", "" ]
I am trying to get some test data inserted into a MySQL database, which has a mixture of reference ID's and variable values. My statement, rejected by MySQL with it's generic (and patently next to worthless) "syntax error near xxx" error is: ``` INSERT INTO TimeSlotWorker (TimeSlotId, WorkerId, PostCode, CitySuburbNam...
Every one of the UNION-ed together SELECT statements has the same syntax error and cannot be parsed. Consider the first one in isolation ``` SELECT TimeSlotId FROM TimeSlot WHERE (DayCode = 'MON' AND SequenceNbr = 1), '2914' AS PostCode, '' AS CitySuburbName ``` Those extra column names must all be before the ...
To make your current code to work change it to ``` INSERT INTO TimeSlotWorker (TimeSlotId, WorkerId, PostCode, CitySuburbName) SELECT TimeSlotId, 1 , PostCode, CitySuburbName FROM ( SELECT (SELECT TimeSlotId FROM TimeSlot WHERE DayCode = 'MON' AND SequenceNbr = 1) TimeSlotId, '2...
Inserting Test Data into SQL Table
[ "", "mysql", "sql", "" ]
I want to know if it is possible to use the pandas `to_csv()` function to add a dataframe to an existing csv file. The csv file has the same structure as the loaded data.
You can specify a python write mode in the pandas [`to_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html) function. For append it is 'a'. In your case: ``` df.to_csv('my_csv.csv', mode='a', header=False) ``` The default mode is 'w'. If the file initially might be missing, you ...
You can *append* to a csv by [opening the file](http://docs.python.org/2/library/functions.html#open) in append mode: ``` with open('my_csv.csv', 'a') as f: df.to_csv(f, header=False) ``` If this was your csv, `foo.csv`: ``` ,A,B,C 0,1,2,3 1,4,5,6 ``` If you read that and then append, for example, `df + 6`: ``...
How to add pandas data to an existing csv file?
[ "", "python", "pandas", "csv", "dataframe", "" ]
I want to find the sub-image from large image using PIL library. I also want to know the coordinates where it is found ?
``` import cv2 import numpy as np image = cv2.imread("Large.png") template = cv2.imread("small.png") result = cv2.matchTemplate(image,template,cv2.TM_CCOEFF_NORMED) print np.unravel_index(result.argmax(),result.shape) ``` This works fine and in efficient way for me.
I managed to do this only using PIL. Some caveats: 1. This is a pixel perfect search. It simply looks for matching RGB pixels. 2. For simplicity I remove the alpha/transparency channel. I'm only looking for RGB pixels. 3. This code loads the entire subimage pixel array into memory, while keeping the large image out o...
How to find subimage using the PIL library?
[ "", "python", "python-imaging-library", "" ]
The things I've googled haven't worked, so I'm turning to experts! I have some text in a tab-delimited text file that has some sort of carriage return in it (when I open it in Notepad++ and use "show all characters", I see [CR][LF] at the end of the line). I need to remove this carriage return (or whatever it is), but...
Technically, there is an answer! ``` with open(filetoread, "rb") as inf: with open(filetowrite, "w") as fixed: for line in inf: fixed.write(line) ``` The b in `open(filetoread, "rb")` apparently opens the file in such a way that I can access those line breaks and remove them. This answer actua...
Depending on the type of file (and the OS it comes from, etc), your carriage return might be `'\r'`, `'\n'`, or `'\r'\n'`. The best way to get rid of them regardless of which one they are is to use [`line.rstrip()`](http://docs.python.org/2/library/stdtypes.html#str.rstrip). ``` with open(infile, "r") as f: for li...
How can I remove carriage return from a text file with Python?
[ "", "python", "unicode", "csv", "" ]
I see I can override or define `pre_save, save, post_save` to do what I want when a model instance gets saved. Which one is preferred in which situation and why?
I shall try my best to explain it with an example: [`pre_save`](https://docs.djangoproject.com/en/dev/ref/signals/#pre-save) and [`post_save`](https://docs.djangoproject.com/en/dev/ref/signals/#post-save) are [signals](https://docs.djangoproject.com/en/dev/ref/signals/#signals) that are sent by the model. In simpler w...
``` pre_save ``` it's used before the transaction saves. ``` post_save ``` it's used after the transaction saves. You can use `pre_save` for example if you have a `FileField` or an `ImageField` and see if the `file` or the `image` really exists. You can use `post_save` when you have an `UserProfile` and you want t...
when to use pre_save, save, post_save in django?
[ "", "python", "django", "django-models", "django-signals", "" ]
I am using pyserial and need to send some values less than 255. If I send the int itself the the ascii value of the int gets sent. So now I am converting the int into a unicode value and sending it through the serial port. ``` unichr(num_less_than_255); ``` However it raises this Exception: > ``` > 'ascii' codec can...
Just use `chr(somenumber)` to get a 1 byte value of an int as long as it is less than 256. pySerial will then send it fine. If you are looking at sending things over pySerial it is a *very* good idea to look at the struct module in the standard library it handles endian issues an packing issues as well as encoding for...
In Python 2 - Turn it into a string first, then into unicode. ``` str(integer).decode("utf-8") ``` Best way I think. Works with any integer, plus still works if you put a string in as the input. Updated edit due to a comment: For Python 2 and 3 - This works on both but a bit messy: ``` str(integer).encode("utf-8")....
Convert an int value to unicode
[ "", "python", "character-encoding", "ascii", "pyserial", "" ]
I am having an issue when I try to run: ``` pip install numpy ``` I get: ``` unable to find vcvarsall.bat. ``` I followed this procedure: [How to use MinGW's gcc compiler when installing Python package using Pip?](https://stackoverflow.com/questions/3297254/how-to-use-mingws-gcc-compiler-when-installing-python-pack...
I am using the same setup and installing visual studio 2010 express was the easiest solution for me. <http://www.microsoft.com/visualstudio/eng/downloads#d-2010-express> Python 3.3 was built using VS 2010. <http://blog.python.org/2012/05/recent-windows-changes-in-python-33.html>
As other people have already mentioned, it appears that you do not have Microsoft Visual Studio 2010 installed on your computer. Older versions of Python used Visual Studio 2008, but now the 2010 version is used. The 2010 version in particular is used to compile some of the code (not 2008, 2013, or any other version). ...
Unable to find vcvarsall.bat using Python 3.3 in Windows 8
[ "", "python", "visual-studio", "python-3.x", "mingw", "pip", "" ]
got a simple question, I believe, but it got me stuck anyways. Say I have a simple model: ``` class myModel(models.Model): expires = models.DateTimeField(...) ``` and I want, say on the specified time do something: send an email, delete model, change some of the models fields... Something. Is there a tool in dja...
I think the best is a background-task the reads the datime and executes a task if a datetime is or has been reached. See the solution given here for a [scheduled task](https://stackoverflow.com/questions/573618/django-set-up-a-scheduled-job) So the workflow would be: * Create the task you want to apply on objects wh...
1. Write a [custom management command](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) to do the task that you desire. When you are done, you should be able to run your task with `python manage.py yourtaskname`. 2. Use `cron`, `at`, [periodic tasks in `celery`](http://docs.celeryproject.org/en/...
Django execute task on time specified in model datetime field
[ "", "python", "django", "django-models", "django-celery", "" ]
I want to initialize a multidimensional list. Basically, I want a 10x10 grid - a list of 10 lists each containing 10 items. Each list value should be initialized to the integer 0. The obvious way to do this in a one-liner: `myList = [[0]*10]*10` won't work because it produces a list of 10 references to one list, so c...
You can do it quite efficiently with a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions): ``` a = [[0] * number_cols for i in range(number_rows)] ```
This is a job for...the nested [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)! ``` [[0 for i in range(10)] for j in range(10)] ```
How to create a multi-dimensional list
[ "", "python", "list", "" ]