Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How do I login to www.###.nl/admin and print the source? I've tried several things. Here's what I tried recently using requests: ``` import requests url = "http://www.###.nl/admin" r = requests.get(url, auth=('***', '***')) page = r.text print(page) ``` This code just prints out the code of the login page. Thank...
I got it working using [Splinter](http://splinter.cobrateam.info/). [Phantomjs](http://phantomjs.org/) (headless WebKit) is used as the browser. You can also use other browsers, check out the [documentation](http://splinter.cobrateam.info/docs/browser.html) for Splinter. This is the working code: ``` from splinter i...
Inspect the source of this page, and identify the form element that is being submitted (you can use Chrome Developer Tools for this purpose). You can then find the `input` elements and identify the required `name` attributes. An example (untested): ``` import requests payload = { 'username': 'USERNAME', 'password': ...
How do I login to a website and print the source?
[ "", "python", "python-3.x", "urllib", "python-requests", "" ]
Using pygame mixer, I open an audio file and manipulate it. I can't find a way to save the "Sound object" to a local file on disk. ``` sound_file = "output.mp3" sound = pygame.mixer.Sound(sound_file) ``` Is there any way to do this? I have been researching pygame mixer docs but I couldn't find anything related to t...
Your question is almost two years old, but in case people are still looking for an answer: You **can** save PyGame Sound instances by using the `wave` module (native Python). ``` # create a sound from NumPy array of file snd = pygame.mixer.Sound(my_sound_source) # open new wave file sfile = wave.open('pure_tone.wav',...
I've never tried this, so I'm only guessing that it might work. The `pygame.mixer.Sound` object has a function called `get_raw()` which returns an array of bytes in Python 3.x, and a string in Python 2.x. I think you might be able to use that array of bytes to save your sound. <http://www.pygame.org/docs/ref/mixer.htm...
pygame mixer save audio to disk?
[ "", "python", "audio", "python-2.7", "save", "pygame", "" ]
I'm running a query that breaks up percentages by country.. something like this: ``` select country_of_risk_name, (sum(isnull(fund_weight,0)*100)) as 'FUND WEIGHT' from OFI_Country_Details WHERE FIXED_COMP_FUND_CODE = 'X' GROUP BY country_of_risk_name ``` This returns me the right output. This can range anywhe...
``` SELECT rn, CASE WHEN rn <= 5 THEN x.country_of_risk_name ELSE 'Other' END AS country_of_risk_name, SUM(x.[FUND WEIGHT]) AS SumPerc FROM( SELECT country_of_risk_name, CASE WHEN ROW_NUMBER() OVER(ORDER BY SUM(ISNULL(fund_weight,0)*100) DESC) <= 5 THE...
Here's an ugly way to do this using just SQL: ``` select country, sum(perc) from ( select case when rn <= 5 then country else 'Other' end 'Country', case when rn <= 5 then rn else 6 end rn, perc from ( select *, row_number() over (order by perc desc) rn from yourresults ) t ) t group b...
Two levels of grouping on one set of data. Is it possible
[ "", "sql", "sql-server", "logic", "grouping", "" ]
I am a brand new programmer, and I have been trying to learn Python (2.7). I found a few exercise online to attempt, and one involves the creation of a simple guessing game. Try as i might, I cannot figure out what is wrong with my code. The while loop within it executes correctly if the number is guessed correctly th...
You've noticed that `raw_input()` returns a string (as I have noticed at the bottom of your code). But you forgot to change the input to an integer inside the while loop. Because it is a string, it will always be greater than a number ("hi" > n), thus that is why `"Too high. Try again:"` is always being called. So, j...
Try this: ``` guess = int(raw_input()) ``` As `raw_input.__doc__` describes, the return type is a `string` (and you want an `int`). This means you're comparing an `int` against a `string`, which results in the seemingly wrong result you're obtaining. See [this answer](https://stackoverflow.com/a/3270689/724361) for m...
Python While Loop woes
[ "", "python", "while-loop", "" ]
I need to gather counts from multiple tables (which are related by an ID column), all in a single query that I can parameterize for use in some dynamic SQL elsewhere. This is what I have so far: ``` SELECT revenue.count(*), constituent.count(*) FROM REVENUE INNER JOIN CONSTITUENT ON REVENUE.CONSTITUENTI...
This would work: ``` select MAX(case when SourceTable = 'Revenue' then total else 0 end) as RevenueCount, MAX(case when SourceTable = 'Constituent' then total else 0 end) as ConstituentCount from ( select count(*) as total, 'Revenue' as SourceTable FROM revenue union select count(*), 'Constituen...
maybe you need to union things... ``` select * from ( SELECT 'revenue' tbl, count(*), constituentid id FROM REVENUE union SELECT 'constituent', count(*), id FROM CONSTITUENT ) where id = ? ```
Gathering counts of multiple tables in a single query
[ "", "sql", "sql-server", "" ]
I busted through my daily free quota on a new project this weekend. For reference, that's .05 million writes, or 50,000 if my math is right. Below is the only code in my project that is making any Datastore write operations. ``` old = Streams.query().fetch(keys_only=True) ndb.delete_multi(old) try: ...
You are mixing two different things here: write API calls (what your code calls) and low-level datastore write operations. See the billing docs for relations: [Pricing of Costs for Datastore Calls](https://developers.google.com/appengine/docs/billing#Billable_Resource_Unit_Costs) (second section). This is the relevant...
It seems as though I've finally figured out what was going on, so I wanted to update here. I found this older answer: <https://stackoverflow.com/a/17079348/1452497>. I've missed somewhere along the line where the properties being indexed were somehow multiplying the writes by factors of at least 10, I did not expect t...
Why are my Datastore Write Ops so high?
[ "", "python", "google-app-engine", "google-cloud-datastore", "app-engine-ndb", "" ]
I create a function dynamically this way: ``` def create_function(value): def _function(): print value return _function f1 = create_func(1) f1() ``` which works fine and prints '1'. but my problem is slightly different, say there is a variable called no\_of\_arguments which contains the number of argume...
A function can be defined as taking any (minimum) number of arguments by preceding one with a `*`, which will then result in the name being bound to a tuple containing the appropriate arguments. ``` def foo(a, b, *c): print a, b, c foo(1, 2, 3, 4, 5) ``` You will need to limit/check the number of values passed thi...
Use `*` in the function arguments to make it accept any number of positional arguments. ``` def func(*args): if len(args) == 1: print args[0] else: print args ... >>> func(1) 1 >>> func(1,2) (1, 2) >>> func(1,2,3,4) (1, 2, 3, 4) ```
How can I create a Python function dynamically which takes a specified number of arguments?
[ "", "python", "python-2.7", "runtime", "" ]
In my case there are different database versions (SQL Server). For example my table `orders` does have the column `htmltext` in version A, but in version B the column `htmltext` is missing. ``` Select [order_id], [order_date], [htmltext] from orders ``` I've got a huge (really huge statement), which is required to ac...
Create a View in both the versions.. In the version where the column htmltext exists then create it as ``` Create view vw_Table1 AS select * from <your Table> ``` In the version where the htmlText does not exist then create it as ``` Create view vw_Table1 AS select *,NULL as htmlText from <your Table> ``` Now, i...
The "best" way to approach this is to check if the column exists in your database or not, and build your SQL query dynamically based on that information. I doubt if there is a more proper way to do this. Checking if a column exists: ``` SELECT * FROM sys.columns WHERE Name = N'columnName' AND Object_ID = Obj...
A not-existing column should not break the sql query within select
[ "", "sql", "sql-server", "" ]
I am attempting to validate that text is present on a page. Validating an element by *ID* is simple enough, buy trying to do it with text isn't working right. And, I can not locate the correct attribute for *By* to validate text on a webpage. Example that works for ID using *By* attribute ``` self.assertTrue(self.is_...
First of all, it's discouraged to do so, it's better to change your testing logic than finding text in page. Here's how you create you own `is_text_present` method though, if you really want to use it: ``` def is_text_present(self, text): try: body = self.driver.find_element_by_tag_name("body") # find bod...
From what I have seen, is\_element\_present is generated by a Firefox extension (Selenium IDE) and looks like: ``` def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException: return False return True ``` "By" is imported from selenium.webdriver...
Checking if element is present using 'By' from Selenium Webdriver and Python
[ "", "python", "webdriver", "" ]
Over simplifying here, but I need help. Let's say I have a SQL statement like this: ``` SELECT * FROM Policy p JOIN OtherPolicyFile o on o.PolicyId = p.PolicyId WHERE OtherPolicyFile.Status IN (9,10) ``` OK, so here is the story. I need to also pull any OtherPolicyFile where the Status = 11, but ONLY if there is a m...
Perform one extra left join and test the left joined table for NULL: ``` SELECT p.*, o.* FROM Policy p JOIN OtherPolicyFile o on o.PolicyId = p.PolicyId LEFT JOIN OtherPolicyFile o9or10 on o9or10.PolicyId = p.PolicyId and o9or10.Status IN (9,10) WHERE o.Status IN (9,10) OR o.Status = 11 AND o9or...
I would add a subquery to see if 9 or 10 exists. Here's the fiddle: <http://sqlfiddle.com/#!3/1a68c/2> ``` SELECT * FROM Policy p JOIN OtherPolicyFile o on o.PolicyId = p.PolicyId WHERE o.Status IN (9,10) OR (o.Status = 11 AND exists (select * from OtherPolicyFile innerO where innerO.PolicyId = p.P...
SQL - include this record if these other records are included
[ "", "sql", "sql-server", "t-sql", "" ]
I'm using **Eclipse+PyDev** to write code and often face unicode issues when moving this code to production. The reason is shown in this little example ``` a = u'фыва '\ 'фыва' ``` If Eclipse see this it creates unicode string like nothing happened, but if type same command directly to Python shell(Python 2.7.3) you'...
This happens because the encoding for the console is utf-8. There's currently no way to set that globally in the UI, although you can change it by editing: `\plugins\org.python.pydev_2.7.6\pysrc\pydev_sitecustomize\sitecustomize.py` And just remove the call to: (line 108) sys.setdefaultencoding(encoding)
This issue should be fixed in PyDev 3.4.0 (not released yet). Fabio (PyDev maintainer) says: *"from now on PyDev will only set the PYTHONIOENCODING and will no longer change the default encoding"*. And `PYTHONIOENCODING` is supported since Python 2.6. Here is the [commit on GitHub](https://github.com/fabioz/Pydev/comm...
unicode string tolerance in Eclipse+PyDev
[ "", "python", "eclipse", "unicode", "pydev", "" ]
I am wondering how I can access a function inside another function. I saw code like this: ``` >>> def make_adder(x): def adder(y): return x+y return adder >>> a = make_adder(5) >>> a(10) 15 ``` So, is there another way to call the `adder` function? And my second question is why in the last line I ...
No, you can't call it directly as it is a local variable to `make_adder`. You need to use `adder()` because `return adder` returned the function object `adder` when you called `make_adder(5)`. To execute this function object you need `()` ``` def make_adder(x): def adder(y): return x+y return...
You really don't want to go down this rabbit hole, but if you insist, it is possible. With some work. The nested function is created *anew* for each call to `make_adder()`: ``` >>> import dis >>> dis.dis(make_adder) 2 0 LOAD_CLOSURE 0 (x) 3 BUILD_TUPLE 1 ...
How to access a function inside a function?
[ "", "python", "function", "" ]
I have a pre-formatted text file with some variables in it, like this: ``` header one name = "this is my name" last_name = "this is my last name" addr = "somewhere" addr_no = 35 header header two first_var = 1.002E-3 second_var = -2.002E-8 header ``` As you can see, each score starts with the string...
I'd parse that with a generator, yielding sections as you parse the file. `ast.literal_eval()` takes care of interpreting the value as a Python literal: ``` import ast def load_sections(filename): with open(filename, 'r') as infile: for line in infile: if not line.startswith('header'): ...
Martijn Pieters is correct in his answer given your preformatted file, but if you can format the file in a different way in the first place, you will avoid a lot of potential bugs. If I were you, I would look into getting the file formatted as JSON (or XML), because then you would be able to use python's json (or XML) ...
How can I parse a formatted file into variables using Python?
[ "", "python", "parsing", "" ]
I’m having difficulty eliminating and tokenizing a .text file using `nltk`. I keep getting the following `AttributeError: 'list' object has no attribute 'lower'`. I just can’t figure out what I’m doing wrong, although it’s my first time of doing something like this. Below are my lines of code.I’ll appreciate any sugge...
You can use the `stopwords` lists from NLTK, see [How to remove stop words using nltk or python](https://stackoverflow.com/questions/5486337/how-to-remove-stop-words-using-nltk-or-python). And most probably you would also like to strip off punctuation, you can use `string.punctuation`, see <http://docs.python.org/2/li...
From the error message, it seems like you're trying to convert a list, not a string, to lowercase. Your `tokens = nltk.word_tokenize(s)` is probably not returning what you expect (which seems to be a string). It would be helpful to know what format your `sinbo.txt` file is in. A few syntax issues: 1. Import should b...
Getting rid of stop words and document tokenization using NLTK
[ "", "python", "nltk", "tokenize", "stop-words", "" ]
I'm currently trying to plot multiple date graphs using matplotlibs `plot_date` function. One thing I haven't been able to figure out is how to assign each graph a different color automatically (as happens with `plot` after setting `axes.color_cycle` in `matplotlib.rcParams`). Example code: ``` import datetime as dt i...
From [this discussion in `GitHub`](https://github.com/matplotlib/matplotlib/issues/2148) it came out a good way to solve this issue: ``` ax.plot_date(d, nv, ls='solid', fmt='') ``` as @tcaswell explained, this function set `fmt='bo'` by default, and the user can overwrite this by passing the argument `fmt` when calli...
Despite the possible bug you've found you can workaround that and create the plot like this: ![enter image description here](https://i.stack.imgur.com/z3iRQ.png) The code is as follows. Basically a `plot()` is added just after the `plot_date()`: ``` values = xrange(1, 13) dates = [dt.datetime(2013, i, 1, i, 0, 0, 0)...
Setting colors using color cycle on date plots using `plot_date()`
[ "", "python", "matplotlib", "" ]
Is this possible in mysql query.. I want to select distinct client name, group by client name.. then show the values in the group\_name.. ``` table 1 id client_name Group_id ------------------------------ 1 IBM 1 2 DELL 1 3 DELL 2 4 MICROSOFT ...
Try this one: ``` SELECT Client_name, GROUP_CONCAT(group_name) merge_group FROM Table1 t1 JOIN Table2 t2 ON t1.group_id = t2.id GROUP BY t1.Client_name ORDER BY t1.Id ``` Result: ``` ╔═════════════╦═══════════════╗ ║ CLIENT_NAME ║ MERGE_GROUP ║ ╠═════════════╬═══════════════╣ ║ IBM ║ Group1 ║ ║ DE...
Try this :: ``` Select tab1.id, GROUP_CONCAT(tab2.group_name SEPARATOR ',') as groupedColumn from table1 tab1 inner join table2 tab2 ON tab1.group_id = tab2.id GROUP BY tab1.Client_name ```
MYSQL Distinct and Show Group Values
[ "", "mysql", "sql", "select", "group-by", "distinct", "" ]
This is my code: ``` {names[i]:d.values()[i] for i in range(len(names))} ``` This works completely fine when using python 2.7.3; however, when I use python 3.2.3, I get an error stating `'dict_values' object does not support indexing`. How can I modify the code to make it compatible for 3.2.3?
In Python 3, `dict.values()` (along with `dict.keys()` and `dict.items()`) returns a `view`, rather than a list. See the documentation [here](http://docs.python.org/3/library/stdtypes.html#dictionary-view-objects). You therefore need to wrap your call to `dict.values()` in a call to `list` like so: ``` v = list(d.valu...
A simpler version of your code would be: ``` dict(zip(names, d.values())) ``` If you want to keep the same structure, you can change it to: ``` vlst = list(d.values()) {names[i]: vlst[i] for i in range(len(names))} ``` (You can just as easily put `list(d.values())` inside the comprehension instead of `vlst`; it's j...
Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3
[ "", "python", "python-3.x", "" ]
I have value like this ``` DECLARE @hex VARCHAR(64) = '00E0' ``` and I need to convert this value to a double. I have code in C language ``` double conver_str_to_temp(char *strTemp) { int iTemp; double fTemp; iTemp = strtoul(strTemp, 0, 16); //strTemp is the string get from the message. if (iTemp &...
There's no function to convert a string containing a hexadecimal value to a number directly. But you can use intermediate conversion to `varbinary`, which could then be easily converted to an integer. However, when converting to a `varbinary`, you will need to specify the correct format, so that the string is interpre...
try this-: ``` DECLARE @hex VARCHAR(64) = '00E0' SELECT CONVERT(VARBINARY, @hex) * 1 -- OR SELECT CONVERT(INT, CONVERT(VARBINARY, @hex)) ```
Convert Hex To unsigned long integer in SQL
[ "", "sql", "sql-server", "t-sql", "" ]
MATLAB throws an error for this: ``` >> a = [2,3,4] >> a(3:4) index out of bounds ``` If something similar is tried with Python, why isn't it illegal? ``` >>> a = [2,3,4] >>> a[2:3] [4] ``` Isn't the Index '3' in python out of bounds, considering Numbering starts from Zero in Python?
Slicing never raise error in python for out of bound indexes.. ``` >>> s =[1,2,3] >>> s[-1000:1000] [1, 2, 3] ``` From the [docs](http://docs.python.org/2/tutorial/introduction.html#strings) on string(applies to lists, tuples as well): > Degenerate slice indices are handled gracefully: an index that is too > large i...
As others answered, Python generally doesn't raise an exception for out-of-range slices. However, and this is important, your slice is **not** out-of-range. Slicing is specified as a closed-open interval, where the beginning of the interval is inclusive, and the end point is exclusive. In other words, `[2:3]` is a per...
Why doesn't Python throw an error for slicing out of bounds?
[ "", "python", "slice", "" ]
I created a 4D scatter plot graph to represent different temperatures in a specific area. When I create the legend, the legend shows the correct symbol and color but adds a line through it. The code I'm using is: ``` colors=['b', 'c', 'y', 'm', 'r'] lo = plt.Line2D(range(10), range(10), marker='x', color=colors[0]) ll...
# 2D scatter plot Using the `scatter` method of the `matplotlib.pyplot` module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use `scatterpoints=1` rather than `numpoints=1` in the legend call to have only one point for each legend en...
if you are using matplotlib version 3.1.1 or above, you can try: ``` import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap x = [1, 3, 4, 6, 7, 9] y = [0, 0, 5, 8, 8, 8] classes = ['A', 'B', 'C'] values = [0, 0, 1, 2, 2, 2] colors = ListedColormap(['r','b','g']) scatter = plt.scatter(x, y, c=val...
Matplotlib scatter plot legend
[ "", "python", "matplotlib", "legend", "scatter-plot", "" ]
Right now, I have a two-dimensional grid that shows the (1) requirements for a particular (2) service. It looks something like this on the front-end: ``` FEATURE TRAILER MARKETING DVD x Streaming x x Theatrical x ...
To answer your first question - how to store a four dimensional grid - just continue in the direction you're already headed, but normalize the `requirement_ids` column. So in the current schema, if you have ``` | service_id | requirement_ids | | 1 | 1,2,3 | | 2 | 2 | ``` In ...
``` CREATE TABLE requirement (service_id INT NOT NULL requirement_id INT NOT NULL content_type --type?? provider --type??, PRIMARY KEY ? (service_id,requirement_id,content_type,provider type)); ```
4-Dimensional database grid
[ "", "mysql", "sql", "database-design", "" ]
I am trying to sum the total price from invoices (named Total\_TTC in table FACT) depending on the code of the taker ( named N\_PRENEUR in the two concerned tables) and store the result in the DEBIT\_P column of the table table\_preneur. Doing so i get a syntax error (missing operator) In access and can't seem to under...
``` with cte as (select t.somePrice from table_preneur as P inner join (select SUM(Total_TTC) as somePrice from FACT group by N_PRENEUR) t on t.N_PRENEUR = p.N_PRENEUR) update P set DEBIT_P = cte.somePrice -- DO YOU NEED A WHERE CLAUSE? --or maybe update table_p...
You're missing the `as` keyword before your column alias `somePrice`: ``` UPDATE P SET DEBIT_P = t.somePrice FROM table_preneur AS P INNER JOIN ( SELECT N_PRENEUR, SUM(Total_TTC) as somePrice FROM FACT GROUP BY N_PRENEUR ) t ON t.N_PRENEUR = p.N_PRENEUR ```
Error with the sum function in sql with Access
[ "", "sql", "ms-access", "" ]
I've got the following exercise: *Write the function countA(word) that takes in a word as argument and returns the number of 'a' in that word.* Examples ``` >>> countA("apple") 1 >>> countA("Apple") 0 >>> countA("Banana") 3 ``` My solution is: ``` def countA(word): return len([1 for x in word if x is 'a']) ``` An...
use this ``` def countA(word): return word.count('a') ``` As another example, `myString.count('c')` will return the number of occurrences of c in the string
Assuming you're not just allowed to use `word.count()` - here's another way - possibly faster than summing a generator and enables you to do multiple letters if you wanted... ``` def CountA(word): return len(word) - len(word.translate(None, 'A')) ``` Or: ``` def CountA(word): return len(word) - len(word.repl...
Counting letters in a string with python
[ "", "python", "string", "" ]
I have a list called stock\_data which contains this data: ``` ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close\n2013-06-28', '874.90', '881.84', '874.19', '880.37', '2349300', '880.37\n2013-06-27', '878.80', '884.69', '876.65', '877.07', '1926500', '877.07\n2013-06-26', '873.75', '878.00', '870.57', '873...
It evidently does what you want in the first 7 iterations. But after completing the 7th iteration, the for loop will still only have traversed 7 of the many more elements in the list, and so it will then try to access `stock_data[10+6*7]`. What you probably meant is: ``` closing_prices = stock_data[10::6] ``` `stock_...
``` # for splitting adj-close/date @ the newlines stock_data = [ y for x in stock_data for y in x.split('\n') ] headers = { k:i for i,k in enumerate(stock_data[:7]) } # convert stock_data to a matrix stock_data = zip(*[iter(stock_data[7:])]*len(headers)) # chose closing column closing = [ r[headers['Close']] for r in s...
Adding specific items from a list to a new list, index out of range error
[ "", "python", "list", "" ]
I have to use only to use natural join it is not working in sql server,,, i have to select EmpName,EmpDOB and EMPDOB from employee table and just DEPTID from department table..please help ``` SELECT DEPARTMENT.DEPTID, EMPLOYEE.EmpID, EMPLOYEE.EMPName, EMPLOYEE.EMPDOB FROM DEPARTMENT NATURAL JOIN ...
When you use the '=' sign it is just a normal equi-join (explicit) while a natural join the predicates are figured out by the query engine (implicit). <http://en.wikipedia.org/wiki/Join_(SQL)#Natural_join>
If you must use a `NATURAL JOIN` then try this: ``` SELECT D.DEPTID, E.EmpID, E.EMPName, E.EMPDOB FROM DEPARTMENT D NATURAL JOIN EMPLOYEE E ``` As long as the column names `DEPTID` are the SAME on both tables. `NATURAL JOIN` Doesn't need to specify what fields are joined, it figures it out on it's own. Here's a grea...
Natural Join in related table
[ "", "sql", "sql-server", "" ]
Does cql has support python3? I tried to install with pip but it failed. ``` rabit@localhost:/usr/bin> pip-3.3 install cql ^CDownloading/unpacking cql Operation cancelled by user Storing complete log in /home/rabit/.pip/pip.log rabit@localhost:/usr/bin> sudo pip-3.3 install cql root's password: Downloading/unpacking ...
Thrift does indeed explicitly not support Python 3, it's metadata is marked as supporting Python 2 only, and installing it gives you a Syntax error. The solution is to contact the authors of Thrift and help them [port to Python 3](http://python3porting.com/). and once that is done, help port cql. Updating is usually e...
No, the `cql` library is **not** compatible with Python 3. It relies on `thrift`, a package that is *not* Python 3 compatible itself: ``` Traceback (most recent call last): File "<string>", line 16, in <module> File "/Users/mj/Development/venvs/stackoverflow-3.3/build/thrift/setup.py", line 45 except Distutils...
Does cql support python 3?
[ "", "python", "python-3.x", "cassandra", "thrift", "cql", "" ]
In the program I'm currently writing there is a point where I need to check whether a table is empty or not. I currently just have a basic SQL execution statement that is ``` Count(asterisk) from Table ``` I then have a fetch method to grab this one row, put the `Count(asterisk)` into a parameter so I can check again...
You are looking for an indication if the table is empty. For that SQL has the EXISTS keyword. If you are doing this inside a stored procedure use this pattern: ``` IF(NOT EXISTS(SELECT 1 FROM dbo.MyTable)) BEGIN RAISERROR('MyError',16,10); END; ``` IF you get the indicator back to act accordingly inside the app, us...
You could try something like this: ``` select count(1) where exists (select * from t) ``` Tested on [SQLFiddle](http://sqlfiddle.com/#!3/0490c/9/0)
How to efficiently check if a table is empty?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
This is a follow up to [this question](https://stackoverflow.com/questions/17395243/printing-stdout-in-realtime-from-subprocess), but if I want to pass an argument to `stdin` to `subprocess`, how can I get the output in real time? This is what I currently have; I also tried replacing `Popen` with `call` from the `subpr...
In order to grab stdout from the subprocess in real time you need to decide exactly what behavior you want; specifically, you need to decide whether you want to deal with the output line-by-line or character-by-character, and whether you want to block while waiting for output or be able to do something else while waiti...
something like this I think ``` from subprocess import Popen, PIPE, STDOUT p = Popen('c:/python26/python printingTest.py', stdout = PIPE, stderr = PIPE) for line in iter(p.stdout.readline, ''): print line p.stdout.close() ``` using an iterator will return live results basically .. in order to send inpu...
printing stdout in realtime from a subprocess that requires stdin
[ "", "python", "subprocess", "" ]
How to get the date and time only up to minutes, not seconds, from timestamp in PostgreSQL. I need date as well as time. For example: ``` 2000-12-16 12:21:13-05 ``` From this I need ``` 2000-12-16 12:21 (no seconds and milliseconds only date and time in hours and minutes) ``` From a timestamp with time zone field,...
There are plenty of date-time functions available with postgresql: See the list here <http://www.postgresql.org/docs/9.1/static/functions-datetime.html> e.g. ``` SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40'); Result: 16 ``` For formatting you can use these: <http://www.postgresql.org/docs/9.1/static/fu...
To get the `date` from a `timestamp` (or `timestamptz`) a simple **cast** is fastest: ``` SELECT now()::date ``` You get the `date` according to your *local time zone* either way. If you want `text` in a certain format, go with [`to_char()`](http://www.postgresql.org/docs/current/interactive/functions-formatting.htm...
How to get the date and time from timestamp in PostgreSQL select query?
[ "", "sql", "postgresql", "select", "timestamp", "" ]
I would like to modify a text file containing numbers. For example, I have this text file. ``` 1 2 3 4 5 2 5 6 7 8 3 2 6 3 8 4 4 4 5 6 5 3 5 7 8 6 8 7 5 4 7 2 6 8 4 8 5 6 9 7 ``` If you see the second column, there are three 2s. Then, I would like to change all the numbers of 10 in next rows like this. ``` 1 2 3 ...
Something like this: ``` with open('abc') as f, open('out.txt','w') as f2: seen = False #initialize `seen` to False for line in f: #iterate over each line in f spl = line.split() #split the line at whitespaces if seen: #if se...
How about this: ``` with open('out.txt', 'w') as output: with open('file.txt', 'rw') as f: prev2 = False for line in f: l = line.split(' ') if prev2: l[1] = 10 prev2 = False if l[1] == 2: prev2 = True output.write(' '.join(l)) ```
modifying a text file containing array with python
[ "", "python", "file", "text", "" ]
Is it possible to get the full follower list of an account who has more than one million followers, like McDonald's? I use Tweepy and follow the code: ``` c = tweepy.Cursor(api.followers_ids, id = 'McDonalds') ids = [] for page in c.pages(): ids.append(page) ``` I also try this: ``` for id in c.items(): id...
In order to avoid rate limit, you can/should wait before the next follower page request. Looks hacky, but works: ``` import time import tweepy auth = tweepy.OAuthHandler(..., ...) auth.set_access_token(..., ...) api = tweepy.API(auth) ids = [] for page in tweepy.Cursor(api.followers_ids, screen_name="McDonalds").pa...
Use the rate limiting arguments when making the connection. The api will self control within the rate limit. The sleep pause is not bad, I use that to simulate a human and to spread out activity over a time frame with the api rate limiting as a final control. ``` api = tweepy.API(auth, wait_on_rate_limit=True, wait_o...
Get All Follower IDs in Twitter by Tweepy
[ "", "python", "twitter", "tweepy", "" ]
i have this spell checker which i have writted: ``` import operator class Corrector(object): def __init__(self,possibilities): self.possibilities = possibilities def similar(self,w1,w2): w1 = w1[:len(w2)] w2 = w2[:len(w1)] return sum([1 if i==j else 0 for i,j in zip(w1,w2)])/...
Here you go.... ``` from operator import itemgetter from difflib import SequenceMatcher class Corrector(object): def __init__(self, possibilities): self.possibilities = possibilities self.sums = sum(self.possibilities.values()) def correct(self, word): corrections = {} sm = S...
You typically don't want to check the submitted token against *all* the tokens in your corpus. The "classic" way to reduce the necessary computations (and thus to reduce the calls in your `for` loop) is to maintain an index of all the (tri-)grams present in your document collection. Basically, you maintain a list of al...
Spell checker speed up
[ "", "python", "loops", "spell-checking", "" ]
I'm trying to match a pattern against strings that could have multiple instances of the pattern. I need every instance separately. `re.findall()` *should* do it but I don't know what I'm doing wrong. ``` pattern = re.compile('/review: (http://url.com/(\d+)\s?)+/', re.IGNORECASE) match = pattern.findall('this is the me...
Use this. You need to place 'review' outside the capturing group to achieve the desired result. ``` pattern = re.compile(r'(?:review: )?(http://url.com/(\d+))\s?', re.IGNORECASE) ``` This gives output ``` >>> match = pattern.findall('this is the message. review: http://url.com/123 http://url.com/456') >>> match [('h...
You've got extra /'s in the regex. In python the pattern should just be a string. e.g. instead of this: ``` pattern = re.compile('/review: (http://url.com/(\d+)\s?)+/', re.IGNORECASE) ``` It should be: ``` pattern = re.compile('review: (http://url.com/(\d+)\s?)+', re.IGNORECASE) ``` Also typically in python you'd a...
Python regex to match multiple times
[ "", "python", "regex", "multiple-matches", "" ]
I have a query like this: ``` $sql_place = "SELECT * FROM place INNER JOIN join_appointment_place ON join_appointment_place.id_place = place.id_place INNER JOIN join_event_appointment ON join_appointment_place.id_appointment = join_event_appointment.id_appointment WHERE join_event_appointment.id_event = " . $EVENT_I...
try to use GROUP BY place.title if you just want to get those title.
Yes, it will return a distinct on every column but that's no bad thing. For example a distinct query like that could return: ``` Col1 Col2 Col3 Col4 1 ABC XYZ Y 1 ABC XYZ N ``` While your question makes it sound like you are expecting it to only retrieve distinct values for each a...
SELECT DISTINCT one column but return all
[ "", "sql", "" ]
``` for tstep in arange (1,500,1): Intensity=np.sum(Itarray*detarray) print tstep*t*10**9, "\t", Intensity.real ``` For the above program how do I save the two arrays tstep\*t\*10\*\*9 and Intensity.real into a csv file as two colums with a tab so that I get all the values as the loop goes from 1 to 500
As far as I understand, it's as simple as; ``` myfile = open("test.out", "w") for tstep in arange (1,500,1): Intensity=np.sum(Itarray*detarray) myfile.write(str(tstep*t*10**9) + '\t' + str(Intensity.real) + '\n') myfile.close() ```
Instead of using a for-loop, use ``` tsteps = np.arange(1,500,1, dtype='int64')*t*10**9 ``` to build a NumPy array. Note carefully that NumPy arrays have a dtype. The dtype determines the range of numbers representable by the elements in the array. For example, with dtype `int64`, an array can represent all integers ...
saving a set of arrays from python output to csv file
[ "", "python", "numpy", "" ]
I'm using Microsoft's SQL Server 2008. I need to aggregate by a foreign key to randomly get a single value, but I'm stumped. Consider the following table: ``` id fk val ----------- ----------- ---- 1 100 abc 2 101 def 3 102 ghi 4 102 ...
I might think about it a little differently, using a special ranking function called `ROW_NUMBER()`. You basically apply a number to each row, grouped by `fk`, starting with 1, ordered randomly by using the `NEWID()` function as a sort value. From this you can select all rows where the row number was 1. The effect of ...
You can do this not with aggregation but with `row_number()`: ``` select id, fk, val from (select t1.*, row_number() over (partition by fk order by newid()) as seqnum from withTable t1 ) t1 where seqnum = 1 ```
Aggregate randomly?
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have written a function to check for the existence of a value in a list and return True if it exists. It works well for exact matches, but I need for it to return True if the value exists anywhere in the list entry (e.g. value <= listEntry, I think.) Here is the code I am using for the function: ``` def isValInLst(v...
If I understood your question then I guess you need `any`: ``` return any(val in x for x in lst) ``` **Demo:** ``` >>> lst = ['aaa','dfbbsd','sdfdee'] >>> val = 'bb' >>> any(val in x for x in lst) True >>> val = "foo" >>> any(val in x for x in lst) False >>> val = "fde" >>> any(val in x for x in lst) True ```
Mostly covered, but if you want to get the index of the matches I would suggest something like this: ``` indices = [index for index, content in enumerate(input) if substring in content] ``` if you want to add in the `true/false` you can still directly use the result from this list comprehension since it will return a...
How do I check existence of a string in a list of strings, including substrings?
[ "", "python", "string", "list", "" ]
I have been posting similar questions here for a couple of days now, but it seems like I was not asking the right thing, so excuse me if I have exhausted you with my XOR questions :D. To the point - I have two hex strings and I want to XOR these strings such that each byte is XORed separately (i.e. each pair of number...
Use [`binascii.unhexlify()`](http://docs.python.org/2/library/binascii.html#binascii.unhexlify) to turn your hex strings to binary data, then XOR that, going back to hex with [`binascii.hexlify()`](http://docs.python.org/2/library/binascii.html#binascii.hexlify): ``` >>> from binascii import unhexlify, hexlify >>> s1 ...
I found a very simple solution: ``` def xor_str(a,b): result = int(a, 16) ^ int(b, 16) # convert to integers and xor them return '{:x}'.format(result) # convert back to hexadecimal ``` It will xor the string until one of theme ends
How to XOR two hex strings so that each byte is XORed separately?
[ "", "python", "string", "hex", "encode", "xor", "" ]
What is the most efficient way to organise the following pandas Dataframe: data = ``` Position Letter 1 a 2 b 3 c 4 d 5 e ``` into a dictionary like `alphabet[1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e']`?
``` In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict() Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} ``` Speed comparion (using Wouter's method) ``` In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB')) In [7]: %timeit dict(zip(df.A,df.B)) 1000 loops, best of 3: 1.27 ms pe...
I found a faster way to solve the problem, at least on realistically large datasets using: `df.set_index(KEY).to_dict()[VALUE]` Proof on 50,000 rows: ``` df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB')) df['A'] = df['A'].apply(chr) %timeit dict(zip(df.A,df.B)) %timeit pd.Seri...
How to create a dictionary of two pandas DataFrame columns
[ "", "python", "dictionary", "pandas", "dataframe", "" ]
I have two different class ``` class ircChannel: NAME = "" def __init__(self): self.NAME = NAME class ircServer: HOST = "" PORT = 0 CHAN = [] def __init__(self, HOST, PORT): self.HOST = HOST self.PORT = PORT def addChan(self, CHANEL): self.CHAN.append(CHANEL) ``` I...
The problem is here: ``` class ircServer: HOST = "" PORT = 0 CHAN = [] ``` These are members of the entire class, not merely a single object (instance) of it. To fix it, move it to the constructor (`__init__`): ``` class ircServer: def __init__(self, HOST, PORT): self.HOST = HOST self.P...
Lose the class attributes. You are not using them anyway. In fact it's causing your bug because all the instances appear to share the same `CHAN` list ``` class ircServer: def __init__(self, HOST, PORT): self.HOST = HOST self.PORT = PORT self.CHAN = [] def addChan(self, CHANEL): self.C...
Python Object list keep changing when I change an other object list
[ "", "python", "list", "class", "" ]
I retrieved data from a sql query by using ``` bounds = cursor.fetchone() ``` And I get a tuple like: ``` (34.2424, -64.2344, 76.3534, 45.2344) ``` And I would like to have a string like `34.2424 -64.2344 76.3534 45.2344` Does a function exist that can do that?
Use [`str.join()`](http://docs.python.org/2/library/stdtypes.html#str.join): ``` >>> mystring = ' '.join(map(str, (34.2424, -64.2344, 76.3534, 45.2344))) >>> print mystring 34.2424 -64.2344 76.3534 45.2344 ``` You'll have to use map here (which converts all the items in the tuple to strings) because otherwise you wil...
You can also use [`str.format()`](https://docs.python.org/2/library/stdtypes.html#str.format) to produce any arbitrary formatting if you're willing to use `*` magic. To handle the specific case of this question, with a single separator, is actually a little cumbersome: ``` >>> bounds = (34.2424, -64.2344, 76.3534, 45....
How to transform a tuple to a string of values without comma and parentheses
[ "", "python", "" ]
I have a python script file that works perfectly when I use it from the terminal. Now I have created the following `.desktop` file in order to launch it easily: ``` [Desktop Entry] Name=Test GenericName=Test Comment=My test script Type=Application Exec=/opt/test.py Icon=/opt/test.png Categories=Utils; ``` When I lau...
Thanks anyone to have participate to this question. I have solved this issue by implemented use of `pkexec` instead of `gksudo`. `pkexec` seems to reuse the current user environment then I don't have this issue anymore. Thanks.
The problem is valid, but I think "replicating the terminal environment" is the wrong approach to solve it. Indeed, what makes the application work is not the fact that it's *launched from the terminal*, it's that the terminal *happens to have* some environment variables which matter to your application. Therefore, w...
Linux desktop file Exec doesn't used the user session
[ "", "python", "linux", "freedesktop.org", "" ]
I am following the book "how to think like a computer scientist" to learn python and am having some problems understanding the classes and object chapter. An exercise there says to write a function named moveRect that takes a Rectangle and 2 parameters named dx& dy. It should change the location of the rectangle by ad...
You must specify the members and methods you want to access and use in your class declaration. inside the class the Instance you are currently working on is refered to by the name `self` (see the link below!): ``` class Rectangle: def __init__(self): self.x = 0 self.y = 0 self.width = 50 ...
In your first example, you passed the *class* as an argument instead of the *instance* you created. Because there is no `self.x` in the class `Rectangle`, the error was raised. You could just put the function in the class: ``` class Rectangle: def __init__(self, x, y, width, height): self.x = x se...
Class declaration and action on class instances
[ "", "python", "" ]
Some of the value in two of my columns have decimal places for some reason, this is a bug in my code I need to sort out but its causing problems at the moment. How can I round numbers with decimal places? # Example Data ``` # Table: level_3 |---------------------| | day_start | day_end | |-----------|---------| | -1...
I have actually fixed my problem, I just changed the structure to **INT** and back which removed all the decimals! But thanks for the answers, they will help others looking for this!
Use either the PHP *`floor()`* function, or the mysql *`FLOOR()`* function PHP ``` <?php echo floor(44.62); // will output "44" ``` MySQL ``` SELECT FLOOR(44.62); -> 44 ``` HOWEVER ``` SELECT FLOOR(-44.62); -> -45 ``` So, you can try something like: ``` SELECT IF(day_start < 0, CEIL(day_start), FLOOR(day_s...
Round off values in 2 columns that have decimal places
[ "", "mysql", "sql", "phpmyadmin", "" ]
I am writing my first python script, and I am trying to connect it to a mysql db to insert rows. ``` import MySQLdb db = MySQLdb.connect("localhost","root","xxx","pytest" ) cursor = db.cursor() cursor.execute("INSERT INTO `first_table` (`name`) VALUES ('boop') ") ``` When I check the mysql db via phpmyadmin, it co...
In yuor case please use ``` import MySQLdb db = MySQLdb.connect("localhost","root","jimmypq79","pytest" ) cursor = db.cursor() cursor.execute("INSERT INTO `first_table` (`name`) VALUES ('boop') ") db.commit() ``` Please put this in top of the code like this-- ``` db = MySQLdb.connect("localhost","ro...
You can use ``` cursor.autocommit(True) ``` in the beginning of the code for automatically committing the changes .
Database Primary Key is incrementing, but no new rows are being added
[ "", "python", "mysql", "" ]
We have a table like this: ``` +----+--------+ | Id | ItemId | +----+--------+ | 1 | 1100 | | 1 | 1101 | | 1 | 1102 | | 2 | 2001 | | 2 | 2002 | | 3 | 1101 | +----+--------+ ``` We want to count how many items each guy has, and show the guys with 2 items or more. Like this: ``` +----+-----------+ | ...
``` SELECT id, COUNT(itemId) AS ItemCount FROM YourTable GROUP BY id HAVING COUNT(itemId) > 1 ```
``` SELECT id, count(1) FROM YOUR_TABLE GROUP BY id HAVING count(1) > 1; ```
Count rows grouped by condition in SQL
[ "", "sql", "" ]
I read some lines from a file in the following form: ``` line = a b c d,e,f g h i,j,k,l m n ``` What I want is lines without the ","-separated elements, e.g., ``` a b c d g h i m n a b c d g h j m n a b c d g h k m n a b c d g h l m n a b c e...
Using `regex`, `itertools.product` and some string formatting: This solution preserves the initial spacing as well. ``` >>> import re >>> from itertools import product >>> line = 'a b c d,e,f g h i,j,k,l m n' >>> items = [x[0].split(',') for x in re.findall(r'((\w+,)+\w)',line)] >>> strs = re.sub(r'((\w...
Your question is not really clear. If you want to **strip off** any part after commas (as your text suggests), then a fairly readable one-liner should do: ``` cleaned_line = " ".join([field.split(",")[0] for field in line.split()]) ``` If you want to **expand** lines containing comma-separated fields into multiple li...
Python: Split a mixed String
[ "", "python", "" ]
I've 2 tables Sales & Purchase, Sales table with fields SaleId, Rate, Quantity, Date, CompanyId, UserID. Purchase table with fields PurchaseId, Rate, Quantity, Date, CompanyId, UserID. I want to select a record from either table that have highest Rate\*Quantity. ``` SELECT SalesId Or PurchaseId FROM Sales,Purchase w...
Try: ``` select top 1 * from (select SalesId ID, Rate, Quantity, 'Sales' TransactionType from sales union all select PurchaseId ID, Rate, Quantity, 'Purchase' TransactionType from purchase) order by Rate * Quantity desc ```
You can do ``` SELECT TOP 1 * FROM ... ORDER BY Rate * Quantity DESC ``` or ``` SELECT ... WHERE Rate * Quantity = (SELECT max(Rate * Quantity) FROM ... ) ``` You might also consider if there are two equal 'max' records. (The second option would return both, the first just one - at random)
Select a record with highest amount by joining two tables
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am using below code (simplified for this question): ``` t1=['1.99','2','133.37'] t2=['4.98','5','11116.98'] t3=list(zip(t1,t2)) t4=[] for num1,num2 in t3: t4.append(float(num1)+float(num2)) print('The sum is='+ ":".join(map(str,t4))) # output is -> The sum is=6.970000000000001:7.0:11250.35 ``` But I want the outp...
Use `format`: ``` >>> format(5.2, '.6f') '5.200000' ``` The `.6` means “to six decimal places” and the `f` means a floating point number. To put this into your existing code, use a `lambda` as the argument to `map` rather than `str`: ``` print('The sum is=' + ":".join(map(lambda n: format(n, '.6f'), t4))) ``` You ...
``` print('The sum is={:.6f}:{:.6f}:{:.6f}'.format(*t4)) ```
Python print issue
[ "", "python", "python-3.x", "" ]
I'm a beginner at Python. I don't understand the Python function description. For example, the function `getopt` ``` getopt.getopt(args, options[, long_options]) ``` what does `options[, long_options]` mean?
It means that the part in square brackets is **optional**. From <http://docs.python.org/2/library/getopt.html>: > long\_options, **if specified**, must be a list of strings ... In case you add this optional parameter, you also need to add the comma - if you do not add it, you also must not add the comma. This notat...
You would be well served to learn about [EBNF](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form) syntax, which is a way to specify syntax for various languages or commands in a formal way. While many tools' syntax documentations dont use strict EBNF, they often *borrow* its symbols. E.g. square brackets ...
How to understand the python function description?
[ "", "python", "" ]
I'm looking for a way I can duplicate all the rows in my database, I tried exporting it and then importing but I get the duplicate key error. The reason is purely for testing purposes, I just want a load of dummy data in there to test the system I have out. Is there a direct statement for this? Or is there a way to e...
You can try this: ``` INSERT INTO your_table_name(parent_id,priority,text,shortname,weighting,g_or_a, dept,ksf,day_start,day_end,date_start,date_end,depends_on,is_question,budget, ccode,responsible,accountable,consulted,informed) (SELECT parent_id,priority,text,shortname,weighting,g_or_a,dept,ksf, day_st...
Put 1 record and then run: ``` insert into mytable select * from mytable ``` 10 times. This will give you 1024 records. Continue until satisfied.
Duplicate all data in the same table MYSQL
[ "", "mysql", "sql", "duplicate-data", "" ]
In SQL Server 2008 i want to set a default date value of every Friday to show up in the column when i insert a new record? ``` ALTER TABLE myTable ADD CONSTRAINT_NAME DEFAULT GETDATE() FOR myColumn ``` Whats the best way to show every Friday? I want the default value to be based on the now date then knowing that the...
``` SELECT DATEADD(day,-3, DATEADD(week, DATEDIFF(week, 0, current_timestamp)+1, 0)) AS LastFridayDateOfWeek ``` Gets the last date of current week (sunday) then subtracts 3 from that to get Friday. Replace `current_timestamp` if you need a different dates friday. EDIT: I thought about this a bit, and if the above (...
If your current query gives you *last* Friday, the easiest thing to do is simply to add 7 to it: ``` select dateadd(d, 7-((datepart(weekday, getdate()) + 1 + @@DATEFIRST) % 7), getdate()) ------------------^ ```
default date value of every Friday in SQL Server?
[ "", "sql", "sql-server", "" ]
I am trying to count frequencies of words in a text file using python. I am using the following code: ``` openfile=open("total data", "r") linecount=0 for line in openfile: if line.strip(): linecount+=1 count={} while linecount>0: line=openfile.readline().split() for word in line: if wo...
This loop `for line in openfile:` moves the file pointer at the end of the file. So, if you want to read the data again then either move the pointer(`openfile.seek(0)`) to the start of the file or re-open the file. To get the word frequency better use `Collections.Counter`: ``` from collections import Counter with op...
Add `openfile.seek(0)` right after you initialize `count`. That'll put the read pointer to the beginning of the file
word frequency in python not working
[ "", "python", "dictionary", "" ]
Suppose a table `fruits` that looks like this: ``` ------------------------------------------ | id | name | color | calories | ------------------------------------------ | 1 | apple | red | 20 | | 2 | orange | orange | 10 | | 3 | grapes | green | 5 | | 4 | ban...
You could use a join inequality to line up the rows you want to swap: ``` update fruit a inner join fruit b on a.id <> b.id set a.color = b.color, a.name = b.name, a.calories = b.calories where a.id in (2,5) and b.id in (2,5) ``` <http://sqlfiddle.com/#!18/27318a/5>
Since ID is unique, it is difficult to just swap the IDs, it's easier to swap the column contents. A query like this might be what you need: ``` UPDATE yourtable t1 INNER JOIN yourtable t2 ON (t1.id, t2.id) IN ((1,5),(5,1)) SET t1.color = t2.color, t1.name = t2.name, t1.calories = t2.calories ``` Please see...
Mysql: Swap data for different rows
[ "", "mysql", "sql", "" ]
(Sorry. The title's pretty unclear. I couldn't come up with a good one.) Say I have a url like so (it's root-relative): ``` "/forums/support/windows/help_i_deleted_sys32/6/" ``` and I'm trying to split this into a class structure like this: ``` class Forum_Spot: def __init__(self, url): parts = url.stri...
Use sequence unpacking: ``` >>> strs = "/forums/support/" >>> spl =strs.strip('/').split('/') >>> a,b,c,d,e = spl + [None]*(5-len(spl)) >>> a,b,c,d,e ('forums', 'support', None, None, None) >>> strs = "/forums/support/windows/" >>> spl =strs.strip('/').split('/') >>> a,b,c,d,e = spl + [None]*(5-len(spl)) >>> a,b,c,d...
You could add a setter method to your class that sets appropriate default values: ``` class Forum_Spot: def __init__(self, url): parts = url.split('/')[1:] # use function argument unpacking: self.set_url(*parts) def set_url(self, root, section=None, subsection=None, thread=None, post=N...
Elegantly Assign Variables of Unknown Length
[ "", "python", "" ]
I am trying to check whether the string starts and ends with the same word. eg`earth`. ``` s=raw_input(); m=re.search(r"^(earth).*(earth)$",s) if m is not None: print "found" ``` **my problem is when the string consists only of one word** eg: `earth` At present I have hard coded this case by ``` if m is not Non...
You can use backreference within regex ``` ^(\w+\b)(.*\b\1$|$) ``` This would match a string only if it * starts and ends with the **same** word * has a single word
Use the [`str.startswith`](http://docs.python.org/2/library/stdtypes.html#str.startswith) and [`str.endswith`](http://docs.python.org/2/library/stdtypes.html#str.endswith) methods instead. ``` >>> 'earth'.startswith('earth') True >>> 'earth'.endswith('earth') True ``` You can simply combine them into a single functio...
find whether the string starts and ends with the same word
[ "", "python", "regex", "" ]
I have been having a lot of trouble in creating a SQL query to show the categories and subcategories from one table. I have the following columns: ``` category_id category_name category_parent category_order ``` Basically what I want to produce as a result is something like this ``` parent category 1 sub category 1 ...
When the depth of the tree is limited to just 2: ``` select c1.*, c2.*, if (c2.category_parent is NULL, "parent category", "sub category") as text from cat c1 left join cat c2 on c1.category_id = c2.category_parent order by c1.category_id, c2.category_id ``` You may use the condition `c2.category_...
I think the ordering is the interesting part here. In particular, the ordering within a category is interesting. I made a fiddle illustrating this: <http://sqlfiddle.com/#!8/78059/3> Here's the query: ``` select * from ( select c.*, coalesce(nullif(c.parent, 0), c.id) as groupID, case when c.parent = 0 then 1 e...
show categories and subcategories in order
[ "", "mysql", "sql", "" ]
I am using SQL LOADER to load multiple csv file in one table. The process I found is very easy like ``` LOAD DATA INFILE '/path/file1.csv' INFILE '/path/file2.csv' INFILE '/path/file3.csv' INFILE '/path/file4.csv' APPEND INTO TABLE TBL_DATA_FILE EVALUATE CHECK_CONSTRAINTS REENABLE DISABLED_CONSTRA...
Solution 1: Can you concatenate the 1000 files into on big file, which is then loaded by SQL\*Loader. On unix, I'd use something like ``` cd path cat file*.csv > all_files.csv ```
Solution 2: Use external tables and load the data using a PL/SQL procedure: ``` CREATE PROCEDURE myload AS BEGIN FOR i IN 1 .. 1000 LOOP EXECUTE IMMEDIATE 'ALTER TABLE xtable LOCATION ('''||to_char(i,'FM9999')||'.csv'')'; INSERT INTO mytable SELECT * FROM xtable; END LOOP; END; ```
load multiple csv into one table by SQLLDR
[ "", "sql", "oracle", "sql-loader", "" ]
i currently do have a table called TempTable imported from excel sheet. However, how can i make use of vba code to remove the top four records as they are unnecessary data. i know "SELECT TOP 4 \* FROM TempTable" does the select job. But how do i do delete? Any help will be appreciated.
Try ``` DELETE FROM (SELECT TOP 4 * FROM TempTable) ``` *Just in case make sure you a backup before you delete*
In SQL server 2008 and later you can do it in this way same as select . ``` DELETE TOP(4) FROM TempTable ``` Thanks Manoj
SQL: Remove top 4 records from table
[ "", "sql", "ms-access", "" ]
I want to make (for fun) python print out 'LOADING...' to console. The twist is that I want to print it out letter by letter with sleep time between them of 0.1 seconds (ish). So far I did this: ``` from time import sleep print('L') ; sleep(0.1) print('O') ; sleep(0.1) print('A') ; sleep(0.1) etc... ``` However that ...
You can also simply try this ``` from time import sleep loading = 'LOADING...' for i in range(10): print(loading[i], sep=' ', end=' ', flush=True); sleep(0.5) ```
In Python2, if you put a comma after the string, print does not add a new line. However, the output may be buffered, so to see the character printed slowly, you may also need to flush stdout: ``` from time import sleep import sys print 'L', sys.stdout.flush() sleep(0.1) ``` So to print some text slowly, you could use...
Python: Print to one line with time delay between prints
[ "", "python", "console", "formatting", "format", "string-formatting", "" ]
So I have looked it up for the past 2 days almost and I can't seem to figure out what is it that mysql doesn't let me add a foreign key. When I run the code for the second table that includes the foreign key I get the following error: *#1072 - Key column 'album' doesn't exist in table* I'm pretty sure there isn't any...
First you don't need any quote mark because any reserved word is used. I tried to execute these sql queries without the quotes and it worked like a charm. ``` CREATE TABLE Album( id INT AUTO_INCREMENT PRIMARY KEY , name VARCHAR( 35 ) NOT NULL ) ENGINE = InnoDB; CREATE TABLE Picture( id_pk INT AUTO_INCREMENT PR...
I think you should index the column 'album' before declaring it as a foreign key Please check if this works ``` CREATE TABLE ‘Picture’( ‘id_pk’ INT AUTO_INCREMENT PRIMARY KEY , ‘album’ INT, ‘pictureURL’ VARCHAR( 270 ) NOT NULL , ‘name’ VARCHAR( 35 ) NOT NULL , INDEX (album), CONSTRAINT album_f...
Why mySql doesn't let me declare foreign key?
[ "", "mysql", "sql", "database-design", "foreign-keys", "syntax-error", "" ]
I'm having a brain lapse, but I just can't get this to work. I have an array of distances: ``` import numpy as np zvals = np.linspace(-5,5,10) d = np.array([(0,0,z) for z in zvals]) ``` I want to compute the square distance of the points in the array. The non-numpy way to make this work is: ``` d2 = np.array([np.dot...
Edit: As of NumPy 1.9, it appears inner1d may be faster. (Thanks to Nuno Aniceto for pointing this out): ``` In [9]: %timeit -n 1000000 inner1d(d,d) 1000000 loops, best of 3: 1.39 µs per loop In [14]: %timeit -n 1000000 einsum('ij,ij -> i', d, d) 1000000 loops, best of 3: 1.8 µs per loop ``` PS. Always test benchma...
Dot product functions are very fast, and for really simple stuff may even beat `np.einsum` (which is a terrific function you should definitely learn to use). Numpy has a hidden little gem, `inner1d`, which does the dot product, with broadcasting, over the last dimensions of its arguments. You can use it as follows: ``...
Compute square distances from numpy array
[ "", "python", "numpy", "" ]
For example, I have the string: ``` <Url class="class">http://www.ccc.com/Files/thumbnails/Gone Dark.jpg</Url> ``` I want to replace all spaces inside the url tag to %20 ``` <Url class="class">http://www.ccc.com/Files/thumbnails/Gone%20Dark.jpg</Url> ``` Notice that the space in `<Url class="class">` remained intac...
Here is one without using variables You can process all the records in the table at once ``` SELECT LEFT(url,CHARINDEX('>',url))+ REPLACE(SUBSTRING(url, CHARINDEX('>',url)+1, CHARINDEX('</',url)-CHARINDEX('>',url)-1), ' ', '%20') + RIGHT(url,LEN(url)...
You should be using the other method in the URLEncoder class: `URLEncoder.encode(String, String)`. The first parameter is the String to encode; the second is the name of the character encoding to use (e.g., "UTF-8"). or you should try something like this ``` String url = "http://example.com/query?q=" + URLEncoder.en...
Replace spaces that are between a specific pattern with some other character
[ "", "sql", "" ]
I have to build a string like this ``` { name: "john", url: "www.dkd.com", email: "john@fkj.com" } ``` where john, www.dkd.com and john@fkj.com are to be supplied by variables I tried to do the following ``` s1 = "{'name:' {0},'url:' {1},'emailid:' {2}}" s1.format("john","www.dkd.com","john@fkj.com") ``` I am gett...
Looks like you're trying to build (malformed) JSON or a weird way of just building a string of a dictionary... ``` d = {'name': 'bob', 'email': 'whatever', 'x': 'y'} print str(d) ``` Or: ``` import json print json.dumps (d) ```
You need to escape `{` and `}` by doubling them: ``` s1 = "{{'name:' {0},'url:' {1},'emailid:' {2}}}" print s1.format("john","www.dkd.com","john@fkj.com") ```
insert multiple elements in string in python
[ "", "python", "python-2.7", "" ]
The issue arises from the need to return values from need to return a single-row result set that will be used for a web service. For example, if I have a select statement which currently returns a result set with 3 columns and 1 row, is there a way to "append" a value to it in its own column? The new value could be th...
If you want a new select statement, you can do that in two ways. One is a `select` within a `select`: ``` select col1, col2, col3, (select 'NEW' from d limit 1) as col4 from d ``` The other is a `cross join`: ``` select d.col1, d.col2, d.col3, const.col4 from d cross join (select 'NEW' as col4 from d...
``` select a, b, c, (select smth from table2 limit 1) as col4 as col4 from d where a = 'id' ``` The second query should return exactly one row and one column
SQL how to append columns to a single-row result set?
[ "", "mysql", "sql", "sql-server", "oracle", "" ]
I have 4 .bat-files in the Windows autostart folder for starting the programs Sabnzbd, CouchPotato, SickBeard and Headphones together with Windows. In these batch files I run the Python .py file through a line like this: ``` start "SABnzbd" pythonw "C:\SABnzbd\SABnzbd.py" ``` After all 4 programs have been started an...
I just solved it myself. I've been stupid, I found out I can add colums to the processes tab in the Task manager. One of the columns available is `Command line` and that column shows exactly what I put in the .bat files including path and the path shows what program the process is. Because of @Ansgar Wiechers' answer...
I'd suggest using python's [WMI package](https://pypi.python.org/pypi/WMI/) (see [this answer](https://stackoverflow.com/a/1632274/1630171)): ``` import wmi c = wmi.WMI () for process in [p for p in c.Win32_Process () if p.Name == 'pythonw.exe']: print process.ProcessId, process.CommandLine ```
Indentify running pythonw programs through cmd start
[ "", "python", "windows", "batch-file", "cmd", "pythonw", "" ]
i have a mysql table with this sort of data ``` TACOMA, Washington, 98477 ``` Now i have thousands of such rows. I want the data to be manipulated in such a manner that it appears like: ``` TACOMA, Washington ``` Is it possible though mysql or do i have to manually do it.
You can use : ``` SELECT SUBSTRING_INDEX('TACOMA, Washington, 98477', ',', 2) ``` You can read more [here](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index). And the update statement : ``` UPDATE my_table SET my_col = SUBSTRING_INDEX(my_col, ',', 2) ``` Where you need to re...
Possibly this way. Count the number of commas (by checking the length against the length with all the commas removed) and then use SUBSTRING\_INDEX to get the string up to the number of commas:- ``` SELECT SUBSTRING_INDEX(col, ',', LENGTH(col) - LENGTH(REPLACE(col, ',', ''))) FROM SomeTable ```
query to remove all characters after last comma in string
[ "", "mysql", "sql", "" ]
My ajax always returns undefined on getting response data Here is my django view code: ``` value= {'response':'SUCCESS'} return render_to_response('topics.html', json.dumps(value), RequestContext(request) ) ``` And below is my jquery: ``` var ...
I think I got my problem. I didn't have to do ``` render_to_response('template.html'....) ``` Instead ``` HttpResponse(json.dumps(value)) ```
Why don't you put a console.log in your showResponse function for a start? So ``` function showResponse(data){ console.log(data); } ``` You will then see easily what to do.
Unable to get response object in ajax
[ "", "jquery", "python", "ajax", "django", "" ]
I have a table with two columns, Name (nvarchar(256)) and Score (int between 0 and 100). Each name can have more than one score. I know it should be simple, but I can't work out how to get one table containing each name only once, and the top score for that name. Can anyone help?
The simplest approach would be: ``` select [Name], max([Score]) from t1 group by [Name] ```
Something like: ``` SELECT Name, max(score) FROM Table GROUP BY Name ``` should do what you're after.
Select distinct value from one column, using another for ordering
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a column in python `pandas` DataFrame that has boolean `True`/`False` values, but for further calculations I need `1`/`0` representation. Is there a quick `pandas`/`numpy` way to do that?
A succinct way to convert a single column of boolean values to a column of integers 1 or 0: ``` df["somecolumn"] = df["somecolumn"].astype(int) ```
Just multiply your Dataframe by 1 (int) ``` [1]: data = pd.DataFrame([[True, False, True], [False, False, True]]) [2]: print data 0 1 2 0 True False True 1 False False True [3]: print data*1 0 1 2 0 1 0 1 1 0 0 1 ```
How can I map True/False to 1/0 in a Pandas DataFrame?
[ "", "python", "pandas", "dataframe", "numpy", "boolean", "" ]
I'm attempting to use sed to edit a text file. The text file is actually an sms text message that was sent to my email in a .txt format, but the formatting is not pretty. Thanks in advance for any assistance. For instance, a particular line: ``` TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from t...
Using `python`: ``` >>> import re >>> spl = "TO" >>> strs = "TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from the store. TO : Contact NameDate : 06/12/2013 10:00:10 AMI can in about 15 minutes. I'm still in a meeting." >>> lis = re.split(r'\bTO\b',strs)[1:] for x in lis: print "{}{}".forma...
This will insert a newline at the second occurrence of TO ``` sed 's/TO/\nTO/2' myFile.txt ``` test: ``` temp_files > cat myFile.txt TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from the store. TO : Contact NameDate : 06/12/2013 10:00:10 AMI can in about 15 minutes. I'm still in a meeting. te...
Edit a text file by starting each line with TO
[ "", "python", "unix", "sed", "awk", "" ]
Example will make that clearer I hope, (This is a Logistic Regression object, the Theano Tensor library is imported as T) ``` def __init__(self, input, n_in, n_out): #Other code... self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b) ``` Which is called down in main... ``` def main():...
so... Theano builds graphs for the expressions it computes before evaluating them. By passing a theano variable such as 'x' in the example to the initialization of the logistic regression object, you will create a number of expressions such as p\_y\_given\_x in your object which are theano expressions dependent on x. T...
This is a Python feature called [named parameters](http://www.diveintopython.net/power_of_introspection/optional_arguments.html). For functions with optional parameters or many parameters it is helpful to pass the parameters by name, instead of just relying on the order on which they were passed to the function. In you...
What is the prupose/meaning of passing "input" to a function in Theano?
[ "", "python", "theano", "" ]
I have two test methods with the same problem, here are the original methods in the main class: ``` def get_num_words(self, word_part): """ 1 as default, may want 0 as an invalid case """ if word_part[3] == '0a': self.num_words = 10 else: self.num_words = int(word_part[3]) return self.n...
Your `gen_num_pointers()` and `gen_num_words()` methods return an integer. `zip()` can only work with sequences (lists, sets, tuples, strings, iterators, etc.) You don't need to call `zip()` at all here; you are testing one integer against another: ``` def test_get_num_words(self): word_part = ['13797906', '23', ...
Your test should look like this: ``` def test_get_num_pointers(self): before_at = '13797906 23 n 04 flood 0 inundation 0 deluge 0 torrent 0 005' expected = 5 real = self.wn.get_num_pointers(before_at) self.assertEqual(real, expected) ``` It only makes sense to use a `for` loop when you're asserting mo...
How to solve error: Zip argument #1 must support iteration
[ "", "python", "unit-testing", "python-unittest", "" ]
I have one Change Report Table which has two columns ChangedTime,FileName ![enter image description here](https://i.stack.imgur.com/3OeWY.png) Please consider this table has over 1000 records Here I need to query all the changes based on following factors ``` i) Interval (i.e-1mins ) ii) No of files ``` It means wh...
You need to aggregate by the interval and then do the count. Assuming that an interval starting at time 0 is ok, the following should work: ``` declare @interval int = 1; declare @limit int = 10; select sum(cnt) from (select count(*) as cnt from t group by DATEDIFF(minute, 0, ChangedTime)/@interval )...
``` select count(*) from (select a.FileName, b.ChangedTime startTime, a.ChangedTime endTime, DATEDIFF ( minute , a.ChangedTime , b.ChangedTime ) timeInterval from yourtable a, yourtable b where a.FileName = b.FileName and a.ChangedTime > b.ChangedTime and DATEDIFF ( minute , a.ChangedTime , b.ChangedTime ) = 1) temp...
How to write SQL query for the following case.?
[ "", "sql", "" ]
Sorry about my english I have to get all the records what has the same date at least 2 times , i mean i want to know whos seller make at least 2 sales in the same date. **Table A** ``` id Name Lastname Seller Date Item 23456 Roberto Rodriguez jvazquez 01/01/2013 auto 23423 Roberto...
``` select id, Name, Lastname, Seller, Date, Item from ( select id, Name, Lastname, Seller, Date, Item, count(*) over (partition by date, seller) as cnt from the_table ) t where cnt >= 2; ``` SQLFiddle example: <http://www....
``` SELECT seller, Date, COUNT(*) "Sales" FROM TableA GROUP BY Date, seller HAVING COUNT(*) >= 2 ```
Postgresql At least 2 sales in the same day
[ "", "sql", "postgresql", "" ]
I am looking for simple solution for the following problem. Do we have a *for*-loop for this kind of usage in python? ``` [2,3,4,5,6,7,8,9,0,1] ``` I have an implementation using a *while*-loop: ``` i = 2 while True: i = i%9 if i == 1: break # payload code here i+=1 ```
``` for i in (2, 3, 4, 5, 6, 7, 8, 9, 0, 1): ``` ... ``` for i in range(2, 10) + range(2): ``` ... ``` for i in itertools.chain(xrange(2, 10), xrange(2)): ``` ... ``` for i in (x % 10 for x in xrange(2, 12)): ```
You can use `range`: ``` >>> for i in range(2,10) + range(0,2): ... print i ... 2 3 4 5 6 7 8 9 0 1 ``` Or using `itertools.chain`(works in both py2 and py3): ``` >>> from itertools import chain >>> for i in chain(range(2,10),range(0,2)): print (i) ... 2 3 4 5 6 7 8 9 0 1 ```
Python for loop which begin from 2 to 10 and then cover 0 and 1
[ "", "python", "list", "loops", "" ]
I have a csv file with mixed floats, a string and an integer, the formatted output from a FORTRAN file. A typical line looks like: ``` 507.930 , 24.4097 , 1.0253E-04, O III , 4 ``` I want to read it while keeping the float decimal places unmodified, and check to see if the first entry in each line is ...
If you need to keep precision exactly, you need to use the [`decimal` module](http://docs.python.org/2/library/decimal.html). Otherwise, [issues with floating point arithmetic limitations](http://docs.python.org/3/tutorial/floatingpoint.html) might trip you up. Chances are, though, that you don't really need that prec...
`loadtxt` appears to take a `converters` argument so something like: ``` from decimal import Decimal numpy.loadtxt(..., converters={0: Decimal, 1: Decimal, 2: Decimal}) ``` Should work. `Decimal`'s should work with whatever precision you require although ...
Python: read mixed float and string csv file
[ "", "python", "arrays", "floating-point", "" ]
First of all, I would like to point out that I am a python newbie and I am totally inexperienced at coding, so please be patient. I've already searched for an answer to my problem but with no success. I have a bunch of lines in text with names and teams in this format: ``` Team (year)|Surname1, Name1 ``` e.g. ``` Ya...
First, this line: ``` items = [line.split('|')] ``` should have been: ``` items = line.split('|') ``` Otherwise, it was creating a list made up of a list. --- Second, I changed this: ``` teams[team].add(name) ``` to this: ``` teams[team].add(name.strip()) ``` Otherwise, you'd get extra newlines and spaces in ...
For this case you should get familiar with Map-Reduce, research a little about it and that will help you, I'm sure I have some code around here and I'm trying to find it, in the meantime this is a good place to start: <http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/>
Aggregate text keys-values python defaultdict
[ "", "python", "text", "python-2.7", "" ]
I'm pretty new at python and I've been playing with argv. I wrote this simple program here and getting an error that says : > TypeError: %d format: a number is required, not str ``` from sys import argv file_name, num1, num2 = argv int(argv[1]) int(argv[2]) def addfunc(num1, num2): print "This function adds %d a...
`sys.argv` is indeed a list of strings. Use the `int()` function to turn a string to a number, provided the string *can* be converted. You need to *assign* the result, however: ``` num1 = int(argv[1]) num2 = int(argv[2]) ``` or simply use: ``` num1, num2 = int(num1), int(num2) ``` You did call `int()` but ignored ...
Assign the converted integers to those variables: ``` num1 = int(argv[1]) #assign the return int to num1 num2 = int(argv[2]) ``` Doing just: ``` int(argv[1]) int(argv[2]) ``` won't affect the original items as `int` returns a new `int` object, the items inside `sys.argv` are not affected by that. Yo modify the or...
Argv - String into Integer
[ "", "python", "argv", "" ]
When we write: ``` SELECT * FROM USERS WHERE Username in ('user1', 'user2', 'user3') ``` is this equivalent to: ``` SELECT * FROM USERS WHERE Username = 'user1' OR Username = 'User2' OR Username = 'User3' ``` Moreover, can we provide the `like` pattern functionality (`%`) to the `IN` clause?
``` Are they equivalent? ``` **Ans**: Yes But I would prefer using `IN` clause as it is more readable then `OR` clause in case of large number of values. > can we provide the like pattern functionality (%) to the IN clause **Ans**: No You can't use like operation with `IN` clause. If you want pattern option than y...
I would use "in" when dealing with multivalued parameters. Otherwise, there's not much of a difference, just preference. To your second question: No, you'll have to use ``` WHERE Username LIKE '%1' OR Username LIKE '%2' OR Username LIKE '%3' ... etc. ```
What is SQL Server 'IN' Clause Equivalent To
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "" ]
I was working on a game yesterday where I had to traverse a 2-D array and find the location of any cells marked "d" (where cells are represented as either "-" for blank or "d" for dirty). I did this using two for-loops: ``` def find_dirty_cells(board): dirty_cells = [] for enum, row in enumerate(board): ...
You need to list your `for` loops in the same order you nest them: ``` def find_dirty_cells(board): return ((enum, enumrow) for enum, row in enumerate(board) for enumrow, cell in enumerate(row) if cell == 'd') ``` You had swapped the `enumerate(board)` and `enumerate(row)` loops, which would only work if there wa...
To cleanly convert your original function into a generator, what you want is the [`yield`](http://docs.python.org/2/reference/simple_stmts.html#the-yield-statement) statement, rather than the `return` (or in your particular case, rather than the `append`). I'd prefer this version to the generator expression version, be...
Return generator instead of list of locations from a 2d Array
[ "", "python", "python-3.x", "generator", "" ]
I am tring to print out a load of lines in a few loops and I want to find a way of printing out the lines without using `\n` as that adds an empty line after each loop is completed. A sample of the code i have is as follows: ``` def compose_line6(self, pointers, pointers_synset_type): self.line6 = '' for A...
You need to close your quotes before you add newlines: ``` '''\ '''+line1+''' '''+line2+''' '''+line3+''' '''+line4+''' '''+line5+''' '''+line6+''' '''+line7+'''''' ``` You escaped the first newline, but it is still adding 4 spaces behind `line1`. Try this: `print("\n".join([line1, line2,...
use: ``` def compose_contents(self, line1, line2, line3, line4, line5, line6, line7): self.contents = '\n'.join([line1, line2, line3, line4, line5, line6, line7]) return self.contents ``` and: ``` print contents, ``` Note the comma at the end!
Printed lines acting strange in Python
[ "", "python", "loops", "" ]
I have a string like this: ``` a = '{CGPoint={CGPoint=d{CGPoint=dd}}}{CGSize=dd}dd{CSize=aa}' ``` Currently I am using this `re` statement to get desired result: ``` filter(None, re.split("\\{(.*?)\\}", a)) ``` But this gives me: ``` ['CGPoint={CGPoint=d{CGPoint=dd', '}}', 'CGSize=dd', 'dd', 'CSize=aa'] ``` which...
There's an alternative regex module for Python I really like that supports recursive patterns: <https://pypi.python.org/pypi/regex> ``` pip install regex ``` Then you can use a recursive pattern in your regex as demonstrated in this script: ``` import regex from pprint import pprint thestr = '{CGPoint={CGPoint=d{C...
As @m.buettner points out in the comments, Python's implementation of regular expressions can't match pairs of symbols nested to an arbitrary degree. (Other languages can, notably current versions of Perl.) The Pythonic thing to do when you have text that regexs can't parse is to use a recursive-descent parser. There'...
Regular expression curvy brackets in Python
[ "", "python", "regex", "" ]
I have some data that I usually plot in matplotlib. Certain values of the independent variable are resonances, and I want to label them with something resembling matplotlib's [annotate](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.annotate). Is there a way to have one annotation (one balloon that says so...
how about (basically ripped out of the docs <http://matplotlib.org/users/annotations_intro.html>) ``` import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = ax.plot(t, s, lw=2) coords_to_annote = [(2,1),(3,1),(4,1)]...
In this form is better to you? ``` import matplotlib.pyplot as plt import numpy as np a = np.ones(100) multi = np.arange(0,100,5) plt.ylim(-0.5,10) plt.text(50, 6.5,'a=5k',fontsize=20) for x in multi: plt.annotate("",xy=(x,1),xytext=(50,6), arrowprops=dict(facecolor='black', shrink=0.005)) plt.plo...
How can I have one annotation pointing to several points in matplotlib?
[ "", "python", "matplotlib", "" ]
Given a list of items in Python, how can I get all the possible combinations of the items? There are several similar questions on this site, that suggest using `itertools.combinations`, but that returns only a subset of what I need: ``` stuff = [1, 2, 3] for L in range(0, len(stuff)+1): for subset in itertools.co...
Use [`itertools.permutations`:](http://docs.python.org/library/itertools.html#itertools.permutations) ``` >>> import itertools >>> stuff = [1, 2, 3] >>> for L in range(0, len(stuff)+1): for subset in itertools.permutations(stuff, L): print(subset) ... () (1,) (2,) (3,) (1, 2) (1, 3) (2...
**You can generate all the combinations of a list in python using this simple code** ``` import itertools a = [1,2,3,4] for i in xrange(1,len(a)+1): print list(itertools.combinations(a,i)) ``` **Result:** ``` [(1,), (2,), (3,), (4,)] [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] [(1, 2, 3), (1, 2, 4), (1, 3, ...
Generating all possible combinations of a list, "itertools.combinations" misses some results
[ "", "python", "list", "combinations", "" ]
Just wondering what the significance of the 'u' before every line of my code is and how I would be able to remove them? I'm working in python. ``` Last login: Mon Jul 1 09:58:27 on ttys000 Samuel-Finegolds-MacBook-Pro:~ samuelfinegold$ /var/folders/jv/9_sy0bn10mbdft1bk9t14qz40000gn/T/Cleanup\ At\ Startup/tutor-394379...
`u` is used to create unicode strings: ``` >>> unicode_string = u'my unicode string' >>> type(unicode_string) <type 'unicode'> >>> ascii_string = 'my ascii string' >>> type(ascii_string) <type 'str'> ``` You can convert a unicode string using `str`: ``` >>> converted_string = str(unicode_string) >>> type(converted_s...
`u` means it's an unicode string, if the string contains only ASCII chacacters then there's no need of conversion to normal `str` as: ``` >>> "foo" == u"foo" True ``` But you can't compare a unicode string with a byte string that contains non-ASCII characters: ``` >>> u'ö' == 'ö' False >>> 'ö' #contains bytes ...
Why is there a 'u' before every line of my output?
[ "", "python", "json", "" ]
Given a Python list whose elements are either integers or lists of integers (only we don't know how deep the nesting goes), how can we find the sum of each individual integer within the list? It's fairly straightforward to find the sum of a list whose nesting only goes one level deep, e.g. ``` [1, [1, 2, 3]] # sum is...
You can use this recursive solution: ``` from collections import Iterable def flatten(collection): for element in collection: if isinstance(element, Iterable): for x in flatten(element): yield x else: yield element ``` **Demo:** ``` >>> lis = [1, [1, [2, [3]]]] >>> sum(flatten(lis)) 7 >...
Easiest way I can think of: ``` from compiler.ast import flatten sum(flatten(numbs)) ```
Sum a nested list of a nested list of a nested list of integers
[ "", "python", "list", "" ]
I want to pull all rows except the last one in Oracle SQL My database is like this ``` Prikey - Auto_increment common - varchar miles - int ``` So I want to sum all rows except the last row ordered by primary key grouped by common. That means for each distinct common, the miles will be summed (except for the last on...
**Note**: the question was changed after this answer was posted. The first two queries work for the original question. The last query (in the addendum) works for the updated question. This should do the trick, though it will be a bit slow for larger tables: ``` SELECT prikey, authnum FROM myTable WHERE prikey <> (SEL...
Looks like I am a little too late but here is my contribution, similar to Ed Gibbs' first solution but instead of calculating the max id for each value in the table and then comparing I get it once using an inline view. ``` SELECT d1.prikey, d1.authnum FROM myTable d1, (SELECT MAX(prikey) prikey myTable FROM myTa...
Select all but last row in Oracle SQL
[ "", "sql", "oracle", "" ]
``` Table: user Columns - id - username - full_name Table: pet Columns - id - pet_name - color_id Table: pet_color Columns - id - color Table: results Columns - id - user_id_1 - user_id_2 - user_id_3 - pet_id - date - some_text ``` This: ``` SELECT A.id, B.full_name, C.full_name, D.full_name, E.pet_name, A.date, A...
``` SELECT A.id, B.full_name, C.full_name, D.full_name, E.pet_name, A.date, A.some_text, pc.color FROM RESULTS AS A LEFT OUTER JOIN USER AS B ON A.USER_ID1 = B.ID LEFT OUTER JOIN USER AS C ON A.USER_ID2 = C.ID LEFT OUTER JOIN USER AS D ON A.USER_ID3 = D.ID LEFT OUTER JOIN PET AS E ON A.PET_ID = E.ID LEFT OUTER JOIN PE...
``` SELECT A.id, B.full_name, C.full_name, D.full_name, E.pet_name, A.date, A.some_text, PC.color FROM RESULTS AS A LEFT OUTER JOIN USER AS B ON A.USER_ID1 = B.ID LEFT OUTER JOIN USER AS C ON A.USER_ID2 = C.ID LEFT OUTER JOIN USER AS D ON A.USER_ID3 = D.ID LEFT OUTER JOIN PET AS E ON A.PET_ID = E.ID LEFT OUTER JOIN PE...
SQL query with deeper relationship
[ "", "mysql", "sql", "" ]
In python I have a string that is inputted is like this ``` var1,var2,var3,var4,var5,var6,var7 ``` I'm using split to split the variables up into their own independent variables like this ``` stringone = var1,var2,var3,var4,var5,var6,var7 var1, var2, var3, var4, var5, var6, var7 = stringone.split(',') ``` Then I'm ...
What you are searching for is the [`maxsplit` parameter of `split()`](http://docs.python.org/2/library/stdtypes.html#str.split). This should do the trick: ``` var1, var2, var3, var4, var5, var6, var7 = stringone.split(',', 6) ```
``` var1, var2, var3, var4, var5, var6, var7 = stringone.split(',', 6) ```
Python Split Ignore Comma
[ "", "python", "split", "" ]
I am trying to select the max value from one column, while grouping by another non-unique id column which has multiple duplicate values. The original database looks something like: ``` mukey | comppct_r | name | type 65789 | 20 | a | 7n 65789 | 15 | b | 8m 65789 | 1 | c | 1o ...
You have yourself a [greatest-n-per-group](/questions/tagged/greatest-n-per-group "show questions tagged 'greatest-n-per-group'") problem. This is one of the possible solutions: ``` select c.mukey, c.comppct_r, c.name, c.type from c yt inner join( select c.mukey, max(c.comppct_r) comppct_r from c group by ...
Any non-aggregate column should be there in Group By clause .. why?? ``` t1 x1 y1 z1 1 2 5 2 2 7 ``` Now you are trying to write a query like: ``` select x1,y1,max(z1) from t1 group by y1; ``` Now this query will result only one row...
Select multiple (non-aggregate function) columns with GROUP BY
[ "", "sql", "ms-access", "greatest-n-per-group", "" ]
I am developing my very first stored procedure in SQL Server 2008 and need advice concerning the errors message. > Procedure or function xxx too many arguments specified which I get after executing the stored procedure `[dbo].[M_UPDATES]` that calls another stored procedure called `etl_M_Update_Promo`. When calling ...
You invoke the function with 2 parameters (@GenId and @Description): ``` EXEC etl.etl_M_Update_Promo @GenID, @Description ``` However you have declared the function to take 1 argument: ``` ALTER PROCEDURE [etl].[etl_M_Update_Promo] @GenId bigint = 0 ``` SQL Server is telling you that `[etl_M_Update_Promo]` only...
Use the following command before defining them: ``` cmd.Parameters.Clear() ```
Procedure or function !!! has too many arguments specified
[ "", "sql", "database", "sql-server-2008", "t-sql", "stored-procedures", "" ]
I have 3 tables. Below is the structure: * `student` (`id int, name varchar(20)`) * `course` (`course_id int, subject varchar(10)`) * `student_course` (`st_id int, course_id int`) -> contains name of students who enrolled for a course Now, I want to write a query to find out students who did not enroll for any course...
The subqueries you use, whether it is `not in`, `minus` or whatever, are generally inefficient. Common way to do this is `left join`: ``` select name from student left join student_course on id = st_id where st_id is NULL ``` Using `join` is "normal" and preffered solution.
The canonical (maybe even *synoptic*) idiom is (IMHO) to use `NOT EXISTS` : ``` SELECT * FROM student st WHERE NOT EXISTS ( SELECT * FROM student_course WHERE st.id = nx.st_id ); ``` Advantages: * `NOT EXISTS(...)` is very old, and most optimisers will know how to handle it * , thus it will probably be prese...
Efficient way to select records missing in another table
[ "", "sql", "database", "join", "" ]
I have stored procedures with same parameters (server name and date). I want to write a stored procedure and Exec them in that SP (called it SP\_All). ``` CREATE PROCEDURE [dbo].[SP_All] AS BEGIN exec sp_1 @myDate datetime, @ServerName sysname exec sp_2 @myDate datetime, @ServerName sysname exec sp_3 @myDate dat...
I see two issues here: 1. Your procedure apparently takes two parameters, `@myDate` and `@ServerName`, which you have not declared yet. Do so by adding the names and the types between the procedure name and AS. 2. When calling sp\_1 to sp\_4, there is no need to specify the data type of the parameters again (that's be...
Try this one - ``` CREATE PROCEDURE [dbo].[SP_All] @myDate DATETIME , @ServerName SYSNAME AS BEGIN EXEC dbo.sp_1 @myDate, @ServerName EXEC dbo.sp_2 @myDate, @ServerName EXEC dbo.sp_3 @myDate, @ServerName EXEC dbo.sp_4 @myDate, @ServerName END ```
How to call Stored Procedures (with 2 parameters) in a Stored Procedure?
[ "", "sql", "sql-server", "stored-procedures", "parameters", "sqlparameter", "" ]
some one have asked me the output of below query. ``` Select * from TableA t1, TableB t2 where t1.Id *= t2.Id ``` Can anyone explain me, if such type of any query exists, if so then how its works. Because i have never seen such type of query Thanks. **UPDATE:** Also when i run this query in...
Using asterisk in a `WHERE` is an old `non-ANSI` compliant syntax for `OUTER JOIN`ing tables and therefore should not be used anymore. Here's the [link](http://sqlmag.com/sql-server/old-join-syntax-vs-new).
The asterisk in the where condition is actually part of a `non-ANSI outer join operator`, it is used to define an implicit outer join. It will cause trouble in modern databases as this operator has been obsolete since 1992. Essentially the below are the same: ``` SELECT * FROM TableA LEFT OUTER JOIN TableB ON t1.I...
What Does *= means in WHERE Clause in TSQL?
[ "", "sql", "sql-server", "t-sql", "" ]
I'm trying to install the new Regex module The readme.txt says::: ``` To build and install regex for your default Python run python setup.py install To install regex for a specific version run setup.py with that interpreter, e.g. python3.1 setup.py install ``` I type in `python setup.py install` and get ...
The implicit first step in these instructions is to download a tarball or zip file of regex, unpack it, go into that directory, and there run “python setup.py install”. See <http://docs.python.org/2/install/index.html#the-new-standard-distutils> If you have pip installed, you can avoid these manual steps by running “p...
It's Easy (On Mac): 1. Install easy\_install `curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python` 2. Install pip `sudo easy_install pip` 3. Install regex module `pip install regex`
Install new regex module with setup.py
[ "", "python", "regex", "installation", "setup.py", "" ]
I am looking for an alternative to Oracle's Toad for Mac OS X. I currently use this for work on a Windows machine, but I would like to use it natively in OSX. I am looking for something that specifically handles XMLTYPEs well.
No love for SQL Developer by Oracle?(Oops sorry didn't see it was mentioned earlier so I'll just second it.) We used to use TOAD exclusively but due to budgetary issues we reluctantly moved to SQL Developer. It was painful but after an adjustment period it is not bad. Does 95% of the functionality we used in TOAD. They...
Quest has released [Toad Mac Edition v1.0 Beta](http://www.toadworld.com/m/freeware/628.aspx) > Toad- Mac Edition is a native Mac application for database > development. Designed to help database developers be more productive, > the Toad - Mac Edition provides essential database tools for Oracle, > MySQL, and PostgreS...
What is a good alternative to Toad for Mac OSX?
[ "", "sql", "macos", "oracle", "xmltype", "" ]
Question: You are given a list of integer weights. You need to distribute these weights into two sets, such that the difference between the total weight of each set is as low as possible. Input data: A list of the weights. Output data: A number representing the lowest possible weight difference. I saw an answer,...
`bestval` is just set to -1 initially and is updated the first time around the loop to `d`. After that, `bestval` is updated again each time that `d` is a better value (aka smaller difference in weights) than the current `bestval`. The key code is here... ``` if bestval == -1 or d < bestval: bestval = d ``` So o...
It is a starting value the you **know** can not be right so it gets replaced by the first answer no matter how bad!
Minimal stone piles
[ "", "python", "" ]
I have information separated by semi-colon and I'm trying to place it all in a list: ``` txt = Alert Level: 3; Rule: 5502 - Login session closed.; Location: mycomputer->/var/log/secure;Jul 1 14:22:25 MYCOMPUTER sshd[6470]: pam_unix(sshd:session): session closed for user root ``` When I use this expression: ``` resu...
Why do you not use `split` instead? ``` result = txt.split(";") ``` Otherwise, if you absolutely want regex, I would use: ``` result = re.findall('[^;]+', str) ```
Try: ``` .*?(;|$) ``` `$` being the typical symbol for the end of the line, so `(;|$)` would be either a ';' or end of line.
re.findall not placing all information in a list
[ "", "python", "regex", "" ]
Given the following array: ``` complete_matrix = numpy.array([ [0, 1, 2, 4], [1, 0, 3, 5], [2, 3, 0, 6], [4, 5, 6, 0]]) ``` I would like to identify the row with the highest average, excluding the diagonal zeros. So, in this case, I would be able to identify `complete_matrix[:,3]` as being the row wit...
You don't need to worry about the `0`s, they shouldn't effect how the averages compare since there will presumably be one in each row. Hence, you can do something like this to get the index of the row with the highest average: ``` >>> import numpy as np >>> complete_matrix = np.array([ ... [0, 1, 2, 4], ... [...
Note that the presence of the zeros doesn't affect which row has the highest mean because all rows have the same number of elements. Therefore, we just take the mean of each row, and then ask for the index of the largest element. ``` #Take the mean along the 1st index, ie collapse into a Nx1 array of means means = np....
Finding the row with the highest average in a numpy array
[ "", "python", "arrays", "numpy", "" ]