Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have following function defined ``` alter FUNCTION [dbo].[GetXMLValues](@business_id int, @id varchar(30)) RETURNS varchar(30) AS BEGIN declare @xmlValue varchar(30) set @xmlValue = (SELECT top 1000 T.Content.value('(/XmlDataPairDocument/dataitem[@id=sql:variable("@id")]/@value)[1]', 'VARCHAR(100)') ...
This is a **Scalar** function, not a **Table-Valued** function. ``` select dbo.[GetXMLValues](1,'sadfj') ``` should work. You can't treat this like a table, i.e. `select * ...`, you need to just select the result directly as above. See [Types of Functions](http://msdn.microsoft.com/en-us/library/ms177499%28v=sql.10...
As mentioned by t-clausen.dk and Ian Preston, it's because you have a Scalar function and not a table valued function. I just wanted to extend on t-clausen.dk's post which switches your function to a **multi-statement** table valued function. I would take this a step further and actually use an **inline** table valued...
Invalid Object Name Error in Function in SQL
[ "", "asp.net", "sql", "sql-server", "" ]
For example [1,2,3,4,1,2] has min element 1, but it occurs for the last time at index 4.
``` a = [1,2,3,4,1,2] a.reverse() print len(a) - a.index(min(a)) - 1 ``` Update after comment: The side effect can be removed by reversing again (but of course that is quite inefficient). ``` a.reverse() ```
``` >>> values = [1,2,3,4,1,2] >>> -min((x, -i) for i, x in enumerate(values))[1] 4 ``` No modification to the original list, works for arbitrary iterables, and only requires one pass. This creates an iterable of tuples with the first value being the original element from the list, and the second element being the ne...
Python: Finding the last index of min element?
[ "", "python", "list", "min", "" ]
If I have a dictionary ``` d = {'a':1, 'b':2 , 'c': 3} ``` with `d['a']` or `d.get('a')` I get `1`. How can I get the values in the dictionary from a list of keys? Something like ``` d[['a','b']] ```
Use list comprehension: ``` >>> d = {'a':1, 'b':2 , 'c': 3} >>> [d[k] for k in ['a','b']] [1, 2] ```
I would use [`map`](http://docs.python.org/2/library/functions.html#map): ``` >>> d = {'a': 1, 'b': 2, 'c': 3} >>> map(d.get, ['a','b']) [1, 2] ```
Get values in Python dictionary from list of keys
[ "", "python", "dictionary", "" ]
I'm transferring over some queries from MySQL to PostgreSQL and I'm stumped on how to rewrite the following query to work in PostgreSQL: `SUM(phoneid IN (1, 2, 6, 8)) AS completedcalls` I originally thought I could just do `SUM(SELECT phoneid FROM myTable WHERE phoneid = 1 OR phoneid = 2` etc etc, but I do not believ...
how about using `CASE` ``` SUM(CASE WHEN phoneid IN (1, 2, 6, 8) THEN 1 ELSE 0 END) ```
``` count(phoneid in (1,2,6,8) or null) ```
MySQL to PostgreSQL query rewrite using "IN"?
[ "", "mysql", "sql", "postgresql", "" ]
Consider this table: ``` Declare @Content table (id int, ParentId int, CreatedOn DateTime, LastCommentOn DateTime) insert into @Content values (1, null, GETDATE() - 10, '2001-12-01'), (2, 1, GETDATE() - 9, GETDATE() - 8), (3, 1, GETDATE() - 8, GETDATE() - 7), (4, 1, GETDATE() - 7, GETDATE() - 6), (5, null, GETDATE()...
Have you tried? ``` update @Content set LastCommentOn = (select MAX(CreatedOn) from @Content c where c.ParentId = m.Id) from @Content m where ParentId is null and LastCommentOn = '2001-12-01' ```
Your SQL should be ``` update @Content m set LastCommentOn = (select MAX(CreatedOn) from @Content c where c.ParentId = m.Id) where ParentId is null and LastCommentOn = '2001-12-01' ``` Assuming max works on DateTime
How to update a value in a table to MAX of other rows?
[ "", "sql", "sql-server", "" ]
I'm learning python on codecademy and my current task is this: > Write a function, shut\_down, that takes one parameter (you can use > anything you like; in this case, we'd use s for string). The shut\_down > function should return **"Shutting down..."** when it gets **"Yes"**, **"yes"**, > or **"YES"** as an argument...
You forgot to write `s == "no"` in your first `elif:` ``` def shut_down(s): if s == "Yes" or s == "yes" or s == "YES": return "Shutting down..." elif s == "No" or "no" or "NO": # you forgot the s== in this line return "Shutdown aborted!" else: return "Sorry, I didn't un...
Instead of checking for different combinations of capitalization you could uses the `lower` function to return a copy of `s` in lowercase and compare against that. ``` def shut_down(s): if s.lower() == "yes": return "Shutting down..." elif s.lower() == "no": return "Shutdown aborted!" ...
Python testing whether a string is one of a certain set of values
[ "", "python", "string", "equality", "" ]
I'm trying to upgrade `Scipy` from `0.9.0` to `0.12.0`. I use the command: ``` sudo pip install --upgrade scipy ``` and I get all sorts of errors which can be seen [in the pip.log file here](http://pastebin.com/09JRVDhH) and I'm unfortunately not python-savvy enough to understand what's wrong. Any help will be apprec...
The error messages all state the same: You lack BLAS (Basic Linear Algebra Subroutines) on your system, or scipy cannot find it. When installing packages from source in ubuntu, as you are effectively trying to do with pip, one of the easiest ways to make sure dependencies are in place is by the command ``` $ sudo apt-...
I had the same problem upgrading from scipy 0.9 to 0.13.3, and I solved it using the following [answer](https://stackoverflow.com/a/22336915/2548301 "this") and installing: sudo apt-get install libblas-dev sudo apt-get install liblapack-dev sudo apt-get install gfortran
Can't upgrade Scipy
[ "", "python", "scipy", "upgrade", "" ]
``` #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() name = form.getvalue('name') age = int(form.getvalue('age')) + 1 print "Content-type: text/html" print print "<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:...
Your quotes are conflicting (notice how the syntax highlighting breaks after that line). Either use single quotes: ``` print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' ``` Or triple quote it: ``` print """<!DOCTYPE html PUBLIC "-//W3C//D...
Use different quotes: ``` print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' ``` Print statement sees the quotes in the middle as ending quotes. You need to escape out of quotes by using /" or using different quotes. ``` print '<!DOCTYPE html PUBLIC \...
Python DOCTYPE Syntax Error
[ "", "python", "" ]
I have used backticks (`) in some SELECT queries to escape fields such as 'first-name'. This will work on MySQL. These queries are run through a DBO class in a php application and I would like the application to be able to use other database servers, such as MSSQL and Posgres. What is the best approach for allowing pr...
The cross-DBMS mechanism (as defined in SQL-92 and other standards) is using double-quoted delimited identifiers. According to [this reference](http://en.wikibooks.org/wiki/SQL_Dialects_Reference/Data_structure_definition/Delimited_identifiers) it's widely supported. It's worth nothing that MySQL allows to [enable/dis...
The solution is very simple: do not use reserved words as identifiers. It makes the code more difficult to read anyways. If you really *need* to use such words (as in "there is some obscure reason beyond your control"), you can just prefix all your identifiers by an arbitrary character, such as `_` for example.
Using reserved words in queries that can run on different database servers
[ "", "mysql", "sql", "database", "postgresql", "" ]
Could any one provide an example sql script that generates Could anyone help me out. Is there a way to create a script that will generate insert statements for the table with already existing data? There is a table with such a structure -> **Country [id (int pk), name(nvarchar)]** How will the script for generating s...
This will do what you wanted: ``` select concat ("insert into `Country` (`country`) values (\"", country, "\");") from Country order by id; ``` Sample: <http://sqlfiddle.com/#!2/efb4c/2> However you need to tune it for your schema of course.
If you want to insert the existing data again into your table (as you have mentioned in the question) then, you can write an sql like: ``` INSERT INTO country (NAME) SELECT NAME FROM COUNTRY; ```
How to create sql script that generates insert statements with tables data in mysql/mssql
[ "", "mysql", "sql", "t-sql", "" ]
Sample Data: ``` LogID OrderNo MaxDate AnotherDate Status NULL 1 2013-07-30 12:01:00 NULL Pending NULL 1 2013-07-30 12:01:01 NULL Pending NULL 1 2013-07-30 12:01:02 NULL Pending NULL 2 2013-07-30 12...
I think what you're looking for is something like this: ``` SELECT [LOGID], [ORDERNO], Max([MAXDATE]) MaxDate, [ANOTHERDATE], [STATUS] FROM Logs GROUP BY [LOGID], [ORDERNO], [ANOTHERDATE], [STATUS] ``` Take a look at this [SQL Fiddle](http://sqlfidd...
I think `select distinct * from <your table>` will work for you In your case with different times, you could use: ``` select distinct LogID, OrderNo, cast(MaxDate as date) as MaxDate, AnotherDate, Status from <your table> ```
SQL: Display Distinct Record From A Column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am having some trouble making dictionaries based on multiple matches in a list. Here is a sample list: ``` items = [["1.pdf", "123", "train", "plaza"], ["2.pdf","123", "plane", "town"], ["3.pdf", "456", "train", "plaza"], ["4.pdf", "123", "plane", "city"], ["5.pdf", "123", "train...
Might I suggest a different output data format? ``` from collections import * d = defaultdict(list) for item in items: d[tuple(item[1:])].append(item[0]) ``` This results in a dict like: ``` { ('123', 'train', 'plaza'): ['1.pdf', '5.pdf'], ('123', 'plane', 'town'): ['2.pdf', '6.pdf'], ('123', 'plan...
Ignore my bad naming schemes. ``` items = [["1.pdf", "123", "train", "plaza"], ["2.pdf","123", "plane", "town"], ["3.pdf", "456", "train", "plaza"], ["4.pdf", "123", "plane", "city"], ["5.pdf", "123", "train", "plaza"], ["6.pdf","123", "plane", "town"]] final = dict() for ...
Make a dictionary on matching values
[ "", "python", "" ]
How would I delete everything after a certain character of a string in python? For example I have a string containing a file path and some extra characters. How would I delete everything after .zip? I've tried `rsplit` and `split` , but neither included the .zip when deleting extra characters. Any suggestions?
Just take the first portion of the split, and add `'.zip'` back: ``` s = 'test.zip.zyz' s = s.split('.zip', 1)[0] + '.zip' ``` Alternatively you could use slicing, here is a solution where you don't need to add `'.zip'` back to the result (the `4` comes from `len('.zip')`): ``` s = s[:s.index('.zip')+4] ``` Or anot...
`str.partition`: ``` >>> s='abc.zip.blech' >>> ''.join(s.partition('.zip')[0:2]) 'abc.zip' >>> s='abc.zip' >>> ''.join(s.partition('.zip')[0:2]) 'abc.zip' >>> s='abc.py' >>> ''.join(s.partition('.zip')[0:2]) 'abc.py' ```
How to delete everything after a certain character in a string?
[ "", "python", "string", "character", "python-3.3", "" ]
Does the use of fully qualified table names in SQL Server have any affect on performance? I have a query where I am joining two tables in different databases. A DBA has suggested to omit the database name on the host query, which I am guessing is either for performance or a convention. **All tables fully qualified** ...
Fully qualified names are usually preferred, but some considerations apply. I will say it depends a lot on the requirements and a single answer may not suffice all scenarios. Note that this is just a compilation binding, not an execution one. So if you execute the same query thousand times, only the first execution wi...
> Does the use of fully qualified table names in SQL server have any affect on performance? There's a trivial penalty because the query text is longer so there's more bytes to be sent to SQL Server and parsed. The penalty is academic, honesty it will not be better or worse because of the prefixes. If you observe a d...
Does using fully qualified names affect performance?
[ "", "sql", "sql-server", "t-sql", "" ]
Imagine I have two or more apps in my django project, I was able to successfully write and execute custom manage.py commands when I had only one app, `A`. Now I have a new app, `B`, and as mentioned in <https://docs.djangoproject.com/en/dev/howto/custom-management-commands/> I created directory structure of `B/manange...
As @Babu said in the comments, It looks like you may not have added your app to `INSTALLED_APPS` in your `settings.py`. It's also possible that you're missing the `__init__.py` files (that are required in python modules) from the `management` and `commands` folders. Alternatively, (sorry to say this) you may have mis...
Most likely, you did not include app B in your settings.py If you just run `python manage.py` with no command specified, it will print the list of commands Django can find. This can help rule out misspelling the command name, but doesn't answer the question of whether or not you made `management` and `commands` both ...
How to write custom django manage.py commands in multiple apps
[ "", "python", "django", "django-admin", "manage.py", "" ]
I have an SQL query ``` SELECT c,d FROM tableX where a='str' AND b=var1 ; ``` I would like to substitute the var1 with a variable. I tried to use plpgsql. ``` CREATE OR REPLACE FUNCTION foo (var1 integer) RETURNS TABLE (c integer, d varchar) AS $BODY$ DECLARE aa varchar = 'str'; BEGIN RETURN QUERY EXECUTE '...
First - the correct way to specify parameters is `$1`, not `@1`. Second - you do not need dynamic sql to pass parameters to the query. Just write something like: ``` CREATE OR REPLACE FUNCTION foo (var1 integer) RETURNS TABLE (c integer, d varchar) AS $BODY$ DECLARE aa varchar = 'str'; BEGIN RETURN QUERY SEL...
Just to practice in PostgreSQL, as a\_horse\_with\_no\_name said, it's possible to write function in plain SQL, here's my attempt: ``` CREATE FUNCTION foo1 (var1 integer) RETURNS TABLE(c int, d text) AS $$ SELECT c,d FROM tableX where a='str' AND b=$1 $$ LANGUAGE SQL; ``` [**SQL FIDDLE EXAMPLE**](http://sqlf...
SQL query with variables in Postgresql
[ "", "sql", "postgresql", "plpgsql", "" ]
I want a MS Access query that can add a column to my current table. Query should include `NOT NULL` constraint, `DEFAULT` value as `''` i.e. 2 single quotes and the data type. I tried this query in Access 2007 but this is not working: ``` ALTER TABLE Demo ADD COLUMN LName TEXT NOT NULL DEFAULT ('') ```
``` ALTER TABLE {TABLENAME} ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE} ``` OR TRY ``` ALTER TABLE TestTable ADD NewCol VARCHAR(50) CONSTRAINT DF_TestTable_NewCol DEFAULT '' NOT NULL GO ```
Try this query: ``` ALTER TABLE TableName ADD ColumnName(50) NOT NULL ```
Alter table query in MS Access 2007
[ "", "sql", "vb.net", "ms-access", "visual-studio-2008", "ms-access-2007", "" ]
**The question:** Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. (the numbers are given later) This is my code for the question: ``` f = open("euler13.txt", "r") nums = f.readlines(50) ints1 = map(int, nums) total = sum(ints1) print total[:10] #The error occurs when running...
``` b = sum(a) ``` At this point in your program `a` is a number, not a list. I'm not sure what you are trying to do, because: ``` b = sum(42) ``` doesn't really make sense. If you are trying to add up all of the numbers in the file, try replacing your loop with this: ``` b = sum(int(x) for x in nums) ``` Or, ge...
Long is a very long integer python makes big ints into long's since an int isn't iterable neither is a long the only way to iterate numbers is do: ``` for i in xrange(number): ``` or ``` for i in range(0, number): ``` and what that will do it repeat the for loop `number` amount of times but i dont think you want...
Python error: ' Long' object is not subscriptable [Project Euler 13] (Simplifying the code)
[ "", "python", "" ]
any idea what I'm doing wrong? I'm creating a table called General: ``` conn = sqlite3.connect(self.dbLocation) c = conn.cursor() sql = "create table if not exists General (id integer NOT NULL,current char[20] NOT NULL,PRIMARY KEY (id))" c.execute(sql) c.close() conn.close() ``` I'm t...
You have to commit the changes before closing the connection: ``` conn.commit() ``` check the example in the docs : <http://docs.python.org/2/library/sqlite3.html>
You need to commit changes in the database with ``` conn.commit() ``` This will write on the disk changes you made in your database. If you close your database without doing it, you lost your modification (INSERT/UPDATE/DELETE)
python sqlite3 insert command
[ "", "python", "insert", "sqlite", "" ]
I am using `django_countries` to show the countries list. Now, I have a requirement where I need to show currency according to country. Norway - NOK, Europe & Afrika (besides UK) - EUR, UK - GBP, AMERICAS & ASIA - USDs. Could this be achieved through django\_countries project? or are there any other packages in python...
There are several modules out there: * [pycountry](https://pypi.python.org/pypi/pycountry): ``` import pycountry country = pycountry.countries.get(name='Norway') currency = pycountry.currencies.get(numeric=country.numeric) print currency.alpha_3 print currency.name ``` prints: ``` NOK Norwe...
`django-countries` just hands you a field to couple to your model (and a static bundle with flag icons). The field can hold a 2 character ISO from the list in `countries.py` which is convenient if this list is up-to-date (haven't checked) because it saves a lot of typing. If you wish to create a model with verbose dat...
django countries currency code
[ "", "python", "django", "python-2.7", "django-1.5", "django-countries", "" ]
If i have a list in python say ``` thing = [[20,0,1],[20,0,2],[20,1,1],[20,0],[30,1,1]] ``` I would want to have a resulting list ``` thing = [[20,1,1],[20,0,2],[30,1,1]] ``` That is if the first element is the same, remove duplicates and give priority to the number 1 in the second element. Lastly the 3rd element m...
I am not sure you would like this, but it works with your example: ``` [list(i) + j for i, j in dict([(tuple(x[:2]), x[2:]) for x in sorted(thing, key=lambda x:len(x))]).items()] ``` EDIT: Here a bit more detailed (note that it fits better to your description of the problem, sorting ONLY by the length of each sublis...
You might want to try using the `unique_everseen` function from the [itertools recipes](http://docs.python.org/3/library/itertools.html#itertools-recipes). As a first step, here is a solution excluding `[20, 0]`: ``` from itertools import filterfalse def unique_everseen(iterable, key=None): "List unique elements...
Unique items in a list with condition
[ "", "python", "" ]
I am new to python programming and using scrapy. I have setup my crawler and so far it was working until I got to the point where I wanted to figure out how to download images. The error I am getting is cannot import name NsiscrapePipeline. I dont know what I am doing wrong and I dont understand some of the documentati...
Heres my final code thats working. There was two issues 1: I was missing the second backslash that needede to be in the request --> //td[1]/a[3]/img/@data-original 2: I had to check the full URL in which the image would be displayed and join them together which was the main URL or the allowed URL and the image URL. ...
You tried to pass list, but this function accepts only string. Pass only one element from list (for example list[0]).
Scrapy pipeline error cannot import name
[ "", "python", "scrapy", "" ]
I tried to execute the following code on a Python IDLE ``` from __future__ import braces ``` And I got the following error: ``` SyntaxError: not a chance ``` What does the above error mean?
You have found an easter egg in Python. It is a joke. It means that delimiting blocks by braces instead of indentation will never be implemented. *Normally*, imports from the [special `__future__` module](http://docs.python.org/2/library/__future__.html) enable features that are backwards-incompatible, such as the `p...
The `__future__` module is normally used to provide features from future versions of Python. This is an easter egg that summarizes its developers' feelings on this issue. There are several more: `import this` will display the zen of Python. `import __hello__` will display `Hello World...`. In Python 2.7 and 3.0, `...
SyntaxError: not a chance — What is this error?
[ "", "python", "syntax-error", "curly-braces", "" ]
I can make simple for loops in python like: ``` for i in range(10): ``` However, I couldn't figure out how to make more complex ones, which are really easy in c++. How would you implement a for loop like this in python: ``` for(w = n; w > 1; w = w / 2) ``` The closest one I made so far is: ``` for w in reversed(r...
First and foremost: Python `for` loops are not really the same thing as a C `for` loop. They are [For Each loops](http://en.wikipedia.org/wiki/Foreach_loop) instead. You iterate over the elements of an iterable. `range()` generates an iterable sequence of integers, letting you emulate the most common C `for` loop use c...
``` for i in range(0, 10, 2): print(i) >>> 0 >>> 2 >>> 4 >>> 6 >>> 8 ``` <http://docs.python.org/2/library/functions.html> ``` >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> range(0, 30, 5) [0, 5, 10, 15, 20, 25] >>> range(0, 10, 3) [0, 3, 6, 9] ```
For loop with custom steps in python
[ "", "python", "for-loop", "" ]
I want to include the date on to this file so it would be unity20130723.txt How do I go about it. I have this so far: ``` dt =datetime.datetime.now() f=open('unity.txt', 'w') for issue in data["issues"]: f.write(issue ['key']) f.write(issue['fields']['summary']) f.write('\n') f.close() ``` I love the Answ...
You can access the different fields of `dt` using `dt.year`, `dt.month`, `dt.day`. So if you wanted to put the date in the name of the file you could do ``` f=open('unity{}{}{}.txt'.format(dt.year, dt.month, dt.day), 'w') ``` EDIT: [Brien's answer](https://stackoverflow.com/a/17811993/2452770) is really elegant, I wo...
An easy way is using [`time.strftime`](http://docs.python.org/2/library/time.html#time.strftime). ``` >>> import time >>> time.strftime('%Y%m%d') '20130723' >>> time.strftime('unity%Y%m%d.txt') 'unity20130723.txt' ```
Include a date in a txt file
[ "", "python", "" ]
I have these 3 queries ``` select tab_ug.cod from tab_ug select coalesce(sum(valor),0) from contas where contas.conta_monitorada = 'Sim' group by ug select coalesce(sum(valor_justificativa),0) from contas, justificativas where contas.cod = justificativas.cod_contas and contas.conta_monitorada = 'Sim' gro...
Try this: ``` select t.cod, coalesce(sum(c.valor), 0) As [ValorSum], coalesce(sum(j.valor_justificativa), 0) As [ValorJustSum] from tag_ug t inner join contas c On c.ug = t.cod inner join justificativas j On j.cod_contas = c.cod where c.conta_monitorada = 'Sim' group by t.cod, c.ug ```
I think you can do it this way : ``` select contas.ug, coalesce(sum(valor),0), coalesce(sum(valor_justificativa),0) from tab_ug, contas, justificativas where contas.conta_monitorada = 'Sim' and contas.ug = tab_ug.cod and contas.cod = justificativas.cod_contas group by contas.ug ```
Trouble using join on SQL with 3 tables
[ "", "sql", "select", "join", "" ]
I recently started learning python and decided to try and make my first project. I'm trying to make a battleship game that randomly places two 3 block long ships on a board. But it doesn't work quite right. I made a while loop for ship #2 that's supposed to check and see if two spaces next to it are free, then build it...
I'd recommend allowing your placing code to run through simply and without if statements, it will be much cleaner. Then, at the end, you can check to see if any of the pieces overlap, and if they do reset. Depending on how you end up deciding to store the points that the individual ships lie in, maybe a list of tuples...
Assigning to `row_2` and `col_2` in `make_it_different` doesn't assign to the global variables by those names. Python's rule for determining a function's local variables is that anything a function assigns to without a `global` declaration is local; assigning to `row_2` and `col_2` creates new local variables instead o...
Simple Python Battleship game
[ "", "python", "" ]
I currently have a table `Telephone` it has entries like the following: ``` 9073456789101 +773456789101 0773456789101 ``` What I want to do is remove only the 9 from the start of all the entries that have a 9 there but leave the others as they are. any help would be greatly appreciated.
While all other answer are probably also working, I'd suggest to try and use [`STUFF`](http://msdn.microsoft.com/en-us/library/ms188043.aspx) function to easily replace a part of the string. ``` UPDATE Telephone SET number = STUFF(number,1,1,'') WHERE number LIKE '9%' ``` **[SQLFiddle DEMO](http://sqlfiddle.com/#!3/1...
Here is the code and a [SQLFiddle](http://sqlfiddle.com/#!3/d26ab/1) ``` SELECT CASE WHEN substring(telephone_number, 1, 1) <> '9' THEN telephone_number ELSE substring(telephone_number, 2, LEN(telephone_number)) END FROM Telephone ```
How to remove the first character if it is a specific character in SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have table : ``` id | name 1 | a,b,c 2 | b ``` i want output like this : ``` id | name 1 | a 1 | b 1 | c 2 | b ```
If you can create a numbers table, that contains numbers from 1 to the maximum fields to split, you could use a solution like this: ``` select tablename.id, SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name from numbers inner join tablename on CHAR_LENGTH(tablename.name) -CHAR...
If the `name` column were a JSON array (like `'["a","b","c"]'`), then you could extract/unpack it with [JSON\_TABLE()](https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html) (available since MySQL 8.0.4): ``` select t.id, j.name from mytable t join json_table( t.name, '$[*]' columns (name varchar(50) p...
SQL split values to multiple rows
[ "", "mysql", "sql", "delimiter", "csv", "" ]
I am passing in a string into a stored procedure to be used in a select statement using dynamic sql: ``` @groups as nvarchar(1000) = 'group1,group10,group8' ``` I might just pass in string of numbers, eg, '1,2,3,4' I want to split these values and then concatenate them so that they end up in the following manner : ...
``` declare @groups nvarchar(1000) ='group1,group10,group8' set @groups = 'rmc.' + replace(@groups, ',', ',rmc.') select @groups ``` Result: ``` rmc.group1,rmc.group10,rmc.group8 ```
[**Sql Fiddle Demo**](http://sqlfiddle.com/#!2/42eb9/2) ``` Select Replace('group1,group10,group8','group','rmc.group') ```
how to split and concatenate in sql server?
[ "", "sql", "sql-server", "t-sql", "" ]
How can I concat two fields and text in between? I've tried all of the following and nothing has worked... ``` ([fldCode1] || ':' ||[fldCode2]) AS Method ([fldCode1] + ':' + [fldCode2]) AS Method ([fldCode1] & ':' & [fldCode2]) AS Method *** & cannot be used with varch...
This should work ``` select [fldCode1] + ':' + [fldCode2] from tab ``` or if the columns are numeric ``` select cast([fldCode1] as varchar(100)) + ':' + cast([fldCode2] as varchar(100)) from tab ```
The first and last forms are not valid, but the second is certainly ok, assuming the columns are strings. If the columns are numeric, date etc. you will need to convert them first: ``` SELECT Method = CONVERT(VARCHAR(255), fldCode1) + ':' + CONVERT(VARCHAR(255), fldCode2) FROM ... ``` If they're strings and t...
Concatenate two SQL fields with text
[ "", "sql", "sql-server-2008", "concatenation", "" ]
I'm running Oracle SQL developer and I've got the following Stored Procedure. I'm quite new to this but really not sure why this isn't working: ``` CREATE OR REPLACE PROCEDURE CHECKDUPLICATE( username1 IN USERS.USERNAME%TYPE, o_username OUT USERS.USERNAME%TYPE ) IS BEGIN SELECT USERNAME INTO o_user...
Once you quote 'Jacklin' so that it's treated as a string literal rather than an identifier, your SQL statement doesn't look right. ``` SELECT USERNAME INTO o_username FROM USERS WHERE username1 = o_username; ``` My wager is that you want to use the input parameter in your `WHERE` clause, not the output para...
You need to put Jacklin within quotes for it to be treateed as a string. Otherwise the parser thinks it's a field name.
Why does this basic 'Select Into' stored procedure not work?
[ "", "sql", "oracle", "stored-procedures", "procedure", "declare", "" ]
I am reading in a file using ``` for line in fin: process(line) ``` However, I would sometimes like skip back some lines in the file and just carry on from there. I won't know the number of lines in advance as it depends on calculations in the code. So I would like it to be something like ``` for line in fin: ...
Another approach: ``` In [11]: from collections import deque In [12]: cache = deque(maxlen=max_skip_back) In [13]: for line in fin: ....: line = line.strip() ....: cache.append(line) ....: x = process(line) ....: if x == 23: ....: for line in cache[-this_skip_back:]: ....: ...
Try something like ``` lines = fin.readlines() i = 0 while i < len(lines): x = process(lines[i]) if x == 23: i -= num_lines else: i += 1 ```
Skip back in a file in python
[ "", "python", "" ]
After CSV import, I have following dictionary with keys in different language: ``` dic = {'voornaam': 'John', 'Achternaam': 'Davis', 'telephone': '123456', 'Mobielnummer': '234567'} ``` Now I want to change keys to English and (also to all lowercase). Which should be: ``` dic = {'first_name': 'John', 'last_name': '...
you have dictionary type, it fits perfectly ``` >>> dic = {'voornaam': 'John', 'Achternaam': 'Davis', 'telephone': '123456', 'Mobielnummer': '234567'} >>> tr = {'voornaam':'first_name', 'Achternaam':'last_name', 'telephone':'phone', 'Mobielnummer':'mobile'} >>> dic = {tr[k]: v for k, v in dic.items()} {'mobile': '2345...
``` name_mapping = { 'voornaam': 'first_name', ... } dic = your_dict # Can't iterate over collection being modified, # so change the iterable being iterated. for old, new in name_mapping.iteritems(): value = dic.get(old, None) if value is None: continue dic[new] = value del dic[old] `...
replace dictionary keys (strings) in Python
[ "", "python", "dictionary", "" ]
I have a list of instances of MC and I want to subset all the instances which attribute equals 2. Can you help me creating the function "superfunction" that does either subset according to a value to accept or to reject. ``` class MC(object): def __init__(self,smth): self.smth=smth l = [MC(2),MC(4),MC(1...
For your specific example, you could use a list comprehension like so: ``` return [x for x in a_list if x.smth == 2] ``` For your general example, you could do a similar thing: ``` if value_to_accept is not None: return [x for x in a_list if x.smth == value_to_accept] if value_to_reject is not None: return [...
You don't necessarily need a separate function to do this. List comprehensions are pretty straightforward: ``` [mc from l if mc.smth == value_to_accept] [mc from l if mc.smth != value_to_reject] ```
Python: Subsetting a list according to the attribute
[ "", "python", "class", "attributes", "subset", "" ]
I'm looking for a function that operates on a python arbitrarily nested dict/array in JSON-esque format and returns a list of strings keying all the variable names it contains, to infinite depth. So, if the object is... ``` x = { 'a': 'meow', 'b': { 'c': 'asd' }, 'd': [ { "e...
``` def dot_notation(obj, prefix=''): if isinstance(obj, dict): if prefix: prefix += '.' for k, v in obj.items(): for res in dot_notation(v, prefix+str(k)): yield res elif isinstance(obj, list): for i, v in enumerate(obj): for res in dot_no...
This is a fun one. I solved it using recursion. ``` def parse(d): return parse_dict(d) def parse_dict(d): items = [] for key, val in d.iteritems(): if isinstance(val, dict): # use dot notation for dicts items += ['{}.{}'.format(key, vals) for vals in parse_dict(val)] ...
Return a list of all variable names in a python nested dict/json document in dot notation
[ "", "python", "json", "dictionary", "nested-lists", "" ]
This works (using Pandas 12 dev) ``` table2=table[table['SUBDIVISION'] =='INVERNESS'] ``` Then I realized I needed to select the field using "starts with" Since I was missing a bunch. So per the Pandas doc as near as I could follow I tried ``` criteria = table['SUBDIVISION'].map(lambda x: x.startswith('INVERNESS')) ...
You can use the [`str.startswith`](https://pandas.pydata.org/pandas-docs/dev/user_guide/basics.html#vectorized-string-methods) DataFrame method to give more consistent results: ``` In [11]: s = pd.Series(['a', 'ab', 'c', 11, np.nan]) In [12]: s Out[12]: 0 a 1 ab 2 c 3 11 4 NaN dtype: object In [...
To retrieve all the rows which **startwith** required string ``` dataFrameOut = dataFrame[dataFrame['column name'].str.match('string')] ``` To retrieve all the rows which **contains** required string ``` dataFrameOut = dataFrame[dataFrame['column name'].str.contains('string')] ```
pandas select from Dataframe using startswith
[ "", "python", "numpy", "pandas", "" ]
New to WPF. I want to edit the values of a database row that are displayed in textboxes. At the moment I am getting an error: "ExecuteNonQuery:Connection property has not been initialized". When I remove the where clause all rows are updated and not just the selected item. ``` private void btnEDIT_Click(object sender,...
You haven't set the [`Connection`](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection.aspx) property of `SqlCommand`. So the command does not know where to connect. Use the [constructor overload](http://msdn.microsoft.com/en-us/library/877h0y3a.aspx) from `SqlCommand` or set it separate...
``` cmd = new SqlCommand("Update Rewards set Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'where Name = '" + this.txtName.Text +"'",sc); // add connection here ``` also You should use parametrized queries or Stored Procedures that will prevent SQL Injection attacks. ``` SqlCommand cmd = new Sq...
edit the values of a database row that are displayed in textboxes
[ "", "sql", "wpf", "sqlconnection", "" ]
So I have recently installed Python Version 2.7.5 and I have made a little loop thing with it but the problem is, when I go to cmd and type `python testloop.py` I get the error: > 'python' is not recognized as an internal or external command I have tried setting the path but no avail. Here is my path: > C:\Program ...
You need to add that folder to your Windows Path: <https://docs.python.org/2/using/windows.html> Taken from this question.
Try "py" instead of "python" from command line: > C:\Users\Cpsa>py > Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>
'python' is not recognized as an internal or external command
[ "", "python", "cmd", "" ]
Today I am reading in a file, and extracting information. I've figured out pretty much everything, but for some reason I am having a very, very annoying problem! I read in an entire line and use the .split() command to break the 'sentence' into 'words' right? And then I alias the 'words' as such: ``` startAddress = li...
You have to parse the string as a base-16 int ``` >>> int("0x00230008", 16) 2293768 ``` Add the ints ``` >>> int("0x00230008", 16) + 4 2293772 ``` And convert it back to a hex string: ``` >>> hex(int("0x00230008", 16) + 4) '0x23000c' ``` You'll have to use some string formatting instead of `hex` to pad it with ze...
`int` takes an optional parameter specifying the base of integer you want to convert it into. So you could simple call something like: ``` proper_int = int(number, 16) ``` To get a proper representation. For example: ``` int("10", 16) = 16 int("F0", 16) = 240 int("0x10", 16) = 16 ``` If you want to add zero paddin...
Python 2.7 Reading Hex and Dec as Str and then adding them
[ "", "python", "" ]
I could not find the meaning of the following SQL command: > where date between to\_date('2013-03-01', 'yyyy-mm-dd') and trunc(sysdate, 'mm') **-1** What does the "**-1**" mean / does? The other example is > trunc(months\_between(date1, date2))**+1** I have searched for this, but could not find a thing. Thank you...
As others have answered, "date - 1" subtracts one day from the date. Here's more detail on your specific SQL snippets: ``` where date between to_date('2013-03-01', 'yyyy-mm-dd') and trunc(sysdate, 'mm') -1` ``` This evaluates to "date between 3/1/2013 and the end of last month" * `TRUNC(`*some date*, `'MM')` chops t...
`+1` is way to add a day to the date `-1` is way to remove a day to the date In your specific case: the instruction `trunc(sysdate, 'mm') -1` remove one month to the date, in this case is one month before the current date. the instruction `trunc(months_between(date1, date2))+1` compute the difference in month betwe...
SQL +/- number meaning?
[ "", "sql", "oracle", "" ]
There are [a few articles](http://undocumentedmatlab.com/blog/matrix-processing-performance/) that show that MATLAB prefers column operations than row operations, and that depending on you lay out your data the performance [can vary significantly](http://undocumentedmatlab.com/blog/matrix-processing-performance/). This...
Like many benchmarks, this really depends on the particulars of the situation. It's true that, by default, numpy creates arrays in C-contiguous (row-major) order, so, in the abstract, operations that scan over columns should be faster than those that scan over rows. However, the shape of the array, the performance of t...
As other replies pointed out, using numpy functions tend not to have a dramatic performance difference, however if you are doing some sort of manual indexing (which you should typically avoid if all possible), it can matter a lot. Here is a "toy" example to demonstrate this effect: ``` import numpy as np from time imp...
Performance of row vs column operations in NumPy
[ "", "python", "numpy", "benchmarking", "row-major-order", "column-major-order", "" ]
Hey I'm trying to install some packages from a `requires` file on a new virtual environment (2.7.4), but I keep running into the following error: ``` CertificateError: hostname 'pypi.python.org' doesn't match either of '*.addvocate.com', 'addvocate.com' ``` I cannot seem to find anything helpful on the error when...
The issue is being documented on the python status site at <http://status.python.org/incidents/jj8d7xn41hr5>
When I try to connect to pypi I get the following error: ``` pypi.python.org uses an invalid security certificate. The certificate is only valid for the following names: *.addvocate.com , addvocate.com ``` So either pypi is using the wrong ssl certificate or somehow my connection is being routed to the wrong serve...
CertificateError when trying to install packages on a virtualenv
[ "", "python", "virtualenv", "" ]
I am trying to output a rotated version of a string. I have taken a string, `z="string"`, and created a deque out of it, `y=collections.deque(z) (deque(['S','t','r','i','n','g'])`, and rotated it using the rotate method. How do I "convert" that deque object I rotated back to a string?
Answer to your question: Since a deque is a [sequence](https://docs.python.org/3/glossary.html#term-sequence), you can generally use [str.join](https://docs.python.org/3/library/stdtypes.html#str.join) to form a string from the ordered elements of that collection. `str.join` works more broadly on any Python [iterable](...
Just use [str.`join()`](http://docs.python.org/2/library/stdtypes.html#str.join) method: ``` >>> y.rotate(3) >>> y deque(['i', 'n', 'g', 's', 't', 'r']) >>> >>> ''.join(y) 'ingstr' ```
How to "convert" a dequed object to string in Python?
[ "", "python", "collections", "rotation", "deque", "" ]
I am creating an import data tool from several vendors. Unfortunately the data is not generated by me, so i have to work with it. I have come across the following situation. I have a table like the following: ``` ID |SartDate |Availability ======================================== H1 |20130728 |YYYYYYNNNNQ...
This can be done in SQL Server, using recursive CTEs. Here is an example: ``` with t as ( select 'H1' as id, cast('20130728' as date) as StartDate, 'YYYYYYNNNNQQQQQ' as Availability union all select 'H2' as id, cast('20130728' as date) as StartDate, 'NNNNYYYYYYY' as Availability union all...
As SQL Server is not the best tool, If I had to do this, I would probably set up an Integration Services package where I would use a script component to code the generate the several records from one in C#.
Group characters of varchar field
[ "", "sql", "sql-server", "sql-server-2008-r2", "sql-server-express", "" ]
In SQL Server, I got this error: > `There are no primary or candidate keys in the referenced table 'BookTitle' that match the referencing column list in the foreign key 'FK__BookCopy__Title__2F10007B'.` I first created a relation called the `BookTitle` relation. ``` CREATE TABLE BookTitle ( ISBN CHAR(17) ...
Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index. At the moment, the only unique index you have is a compound one on `ISBN, Title` which is your primary key. There are a number of...
Another thing is - if your keys are very complicated sometimes you need to replace the places of the fields and it helps: if this doesn't work: ``` foreign key (ISBN, Title) references BookTitle (ISBN, Title) ``` Then this might work (not for this specific example but in general): ``` foreign key (Title,ISBN) refer...
There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key
[ "", "sql", "sql-server", "key", "candidate", "" ]
I've got a really simple question, but I can't figure it out how to do it. The problem I have is that I want to send the following payload using Python and Requests: ``` { 'on': true } ``` Doing it like this: ``` payload = { 'on':true } r = requests.put("http://192.168.2.196/api/newdeveloper/lights/1/state", data = ...
You need to json encode it to get it to a string. ``` import json payload = json.dumps({"on":True}) ```
should be {'on': True}, capital T
Using python 'requests' to send JSON boolean
[ "", "python", "rest", "python-requests", "" ]
I've looked all over the place and am not finding a solution to this issue. I feel like it should be fairly straightforward, but we'll see. I have a .FITS format data cube and I need to collapse it into a 2D FITS image. The data cube has two spacial dimensions and one spectral/velocity dimension. Just looking for a s...
OK, this seems to work: ``` import pyfits import numpy as np hdulist = pyfits.open(filename) header = hdulist[0].header data = hdulist[0].data data = np.nan_to_num(data) new_data = data[0] for i in range(1,84): #this depends on number of layers or pages new_data += data[i] hdu = pyfits....
[This tutorial on pyfits](http://www.astropython.org/tutorial/2010/10/PyFITS-FITS-files-in-Python#getting-data-from-fits-files) is a little old, but still basically correct. The key is that the output of opening a FITS cube with pyfits (or [astropy.io.fits](https://astropy.readthedocs.org/en/stable/io/fits/index.html))...
Collapsing / Flattening a FITS data cube in python
[ "", "python", "astronomy", "fits", "pyfits", "" ]
Here are my criteria: 1. Get a copy of the text of the whole bible 2. This should be ready to open, read, split up into fields 3. Use this to create a persistent dictionary variable called bible 4. Set up your python program so when you type as I have shown, the program will know what you entered on the command line. ...
``` Here is what I was trying to get out of this #!/usr/bin/python import shelve # we will use the persistent dictionary import sys bible = shelve.open("bible.db") try: k = bible['rev 22:21'] # try this, if it fails then build the database except: print "Building..." m=open("kjv.txt").read().split("\n"...
EDIT: ``` import csv import string reader = csv.reader(open('bible.txt','rb'),delimiter="|") bible = dict() for line in reader: chapter = line[1].split()[0] key = line[1].split()[1] linenum = line[0].strip() bible[chapter] = bible.get(chapter,dict()) bible[chapter].update({key:line[2],linenum:lin...
How to sort through a bible.txt by entering the name, verse etc.?
[ "", "python", "python-2.7", "text-processing", "" ]
I'd like to update a table in dynamic sql. ``` declare x varchar2(10) := 'table_n'; begin execute immediate 'update :1 set column_n = 12345' using x; end; ``` I get ORA-00903: invalid table name But ``` declare x varchar2(10) := 'table_n'; begin execute immediate 'update ' || x || ' set column_n = ...
you cannot use bind variables for table names in pl/sql
Dynamic sql: ``` 1.It generally uses the SQL statements at run time. (for the time which we don't have data at the compilation time). 2. The bind variable , in your query, `x`, uses it on runtime and execute the dynamic on run time. 3. the bind variable refered by colon is used after USING clause. ``` For more click...
Dynamic sql - update table using table variable
[ "", "sql", "oracle", "dynamic-sql", "" ]
This is what the file looks like ``` 5.0000E+02 5.23744E-06 0.0006 1.0600E+03 2.15119E-06 0.0023 1.6900E+03 1.83529E-06 0.0035 2.4000E+03 1.76455E-06 0.0044 3.1900E+03 1.78831E-06 0.0050 4.0800E+03 1.86632E-06 0.0056 5.0800E+03 1.91086E-06 0.0061 6.1900E+03 1.97899E-06 0.0066 <--- Get data fr...
``` import numpy data = numpy.loadtxt('filename.txt') print(data[7:,1].sum()) ``` It's possible that I have the indexes transposed, in which case it would be data[1,7:].sum()
First you need to open the file. The best way to do this is: ``` with open("myfile.txt","r") as f: # do stuff with file f here ``` Then you need to get the individual lines. If the file isn't too large (as in very large) you can store it all in memory. Get the lines as a list by calling `list(f)`, eg. `list_of_f...
Python find sum of column in table in text file
[ "", "python", "python-3.x", "" ]
There are a lot of good getattr()-like functions for parsing nested dictionary structures, such as: * [Finding a key recursively in a dictionary](https://stackoverflow.com/questions/14962485/finding-a-key-recursively-in-a-dictionary) * [Suppose I have a python dictionary , many nests](https://stackoverflow.com/questio...
I have separated this out into two steps. In the first step, the query string is broken down into a series of instructions. This way the problem is decoupled, we can view the instructions before running them, and there is no need for recursive calls. ``` def build_instructions(obj, q): """ Breaks down a query ...
``` >>> class D(dict): ... def __missing__(self, k): ... ret = self[k] = D() ... return ret ... >>> x=D() >>> x['f'][0]['a'] = 'whatever' >>> x {'f': {0: {'a': 'whatever'}}} ```
Python recursive setattr()-like function for working with nested dictionaries
[ "", "python", "algorithm", "recursion", "nested", "setattr", "" ]
I am trying to write up a pixel interpolation(binning?) algorithm (I want to, for example, take four pixels and take their average and produce that average as a new pixel). I've had success with stride tricks to speed up the "partitioning" process, but the actual calculation is really slow. For a 256x512 16-bit graysca...
Without diving into your code, I think what you what is just to resize the image with interpolation. You should use an image library for this operation, as it will have heavily optimized code. Since you are using SciPy, you might want to start with PIL, the Python Imaging Library. Use the resize method, were you can p...
For the average look at scipy.ndimage.filters.uniform\_filter, in scipy.ndimage.filters, you have lots kernels for convolution that are much faster than a direct convolution with scipy.convolve.
Pixel interpolation(binning?)
[ "", "python", "image-processing", "filtering", "" ]
I've a table like this which contains links : ``` key_a key_b -------------- a b b c g h a g c a f g ``` not really tidy & infinite recursion ... key\_a = parent key\_b = child Require a query which will recompose and attribute a number for each hiera...
The problem is that you aren't really dealing with strict hierarchies; you're dealing with directed graphs, where some graphs have cycles. Notice that your nbgroup #1 doesn't have any canonical root-- it could be a, b, or c due to the cyclic reference from c-a. The basic way of dealing with this is to think in terms o...
You should use a recursive query. In the first part we select all records which are top level nodes (have no parents) and using `ROW_NUMBER()` assign them group ID numbers. Then in the recursive part we add to them children one by one and use parent's groups Id numbers. ``` with CTE as ( select t1.parent,t1.child, ...
Retrieve hierarchical groups ... with infinite recursion
[ "", "sql", "sql-server-2008", "" ]
I have object Reports and ReportSubscriber and I want to count number of subscribers of a Report. One solution is annotating. I have lots of reports so annotating all of them takes ~6 seconds, so I thought maybe it's better to annotate after paginating: ``` filter_search = ReportFilter(request.GET, queryset=Report.ob...
I can't give you a definitive answer, I believe your problem is that even when paginated, your entire query must be executed so that the paginator knows how many pages there are. I should think you'll be better off getting rid of the annotation before pagination: ``` filter_search = ReportFilter(request.GET, queryset=...
OK, got it. I was selecting wrong table. So I changed .extra() and it's only COUNTing per page now: ``` result = filter_search.qs.extra( select={ 'sub_count': 'SELECT COUNT(*) FROM report_subscribers \ WHERE report_subscribers.report_id = reports.id\ ...
Django filter, paginate and annotate paginated results
[ "", "python", "django", "postgresql", "" ]
I am writing a script that searches through text files in a directory for certain words. If "True" is returned, then it will print the text file it found it in. Is there a way to return/print the keyword it actually found? Thank you! ``` from glob import glob def main(): directory = "C:\\Files Folder\\*.txt" ...
``` for line in f: for s in keywords: if s in line: print 'Key word found!', f.name, s ```
Not with that. You will have to expand the `any()` call into a `for` loop in order to get the specific keyword found.
Obtaining keyword for matching string in Python
[ "", "python", "string", "text-files", "glob", "" ]
i'm trying to get simple python script to call another script, just in order to understand better how it's working. The 'main' code goes like this: ``` #!/usr/bin/python import subprocess subprocess.call('kvadrat.py') ``` and the script it calls - `kvadrat.py`: ``` #!/usr/bin/python def kvadriranje(x): kvadrat =...
you need to give it the full path to the script that you are trying to call, if you want to do this dynamically (and you're in the same directory), you can do: ``` import os full_path = os.path.abspath('kvadrat.py') ```
Have you tried: ``` from subprocess import call call(["python","kvadrat.py"]) #if in same directory, else get abs path ``` You should also check if your file is there: ``` import os print os.path.exists('kvadrat.py') ```
calling python script from another script
[ "", "python", "" ]
I have a `subject` table that is recursive because a subject can be a prerequisite of another subject: * A subject can have no prerequisites * A subject can have 1 prerequisite * A subject can have 2 prerequisites Since there are subjects with 2 prerequisites, I made the `prerequisite_1` and the `prerequisite_2` colu...
You need to split them into two separate foreign keys, and you should probably (but don't have to) name them; ``` CREATE TABLE subject( subject_code CHAR(7), subject_desc VARCHAR(255) NOT NULL, no_of_units TINYINT UNSIGNED NOT NULL CHECK(no_of_units >= 0 AND no_of_units < 13), prerequisite_1 CH...
Instead of putting prerequisites in the `subject` table, use a many-to-many relation table: ``` CREATE TABLE prerequisite ( subject_code CHAR(7), prerequisite CHAR(7), PRIMARY KEY (subject_code, prerequisite), FOREIGN KEY (subject_code) REFERENCES subject(subject_code), FOREIGN KEY (prerequisite) R...
SQL DDL: Recursive table with two foreign keys (MySQL)
[ "", "mysql", "sql", "foreign-keys", "ddl", "recursive-query", "" ]
I'm stuck in this logical issue and I don't know how to proceed. I have two columns: ID and FOLDERID. As a folder can be subfolder too, I want to order my result by first selecting the folders that has no folderid (root folder), and then their subfolders and on. So this way I will not have any problem like "folder **X...
Using a simple recursive query you can get these results. ``` ;WITH CTE AS (SELECT *, 1 RN FROM TABLE1 WHERE FOLDERID = 0 UNION ALL SELECT T1.*, T2.RN + 1 FROM TABLE1 T1 INNER JOIN CTE T2 ...
You can use `CASE` statements to `ORDER`, for your example this would work, but it sounds like you might be after a recursive heirarchy, for which the syntax will vary by RDBMS: ``` ORDER BY CASE WHEN FolderID = 0 THEN 0 ELSE 1 END, ID ```
Ordering a SELECT - Logical issue (SQL)
[ "", "sql", "sql-server", "logic", "" ]
I need to do multiple counts. I have about 6 columns. Something like this: ``` SELECT COUNT(C.ID) as 'Column 1', COUNT(C.ID) as 'Column 2', COUNT(C.ID) as 'Column 3', COUNT(C.ID) as 'Column 4', FROM CONTACT C ``` I need to be able to run different counts using different queries but unsure how to apply queries counts...
You have several options here. 1) use subqueries as @TheSoultion proposed 2) use use UNION ``` SELECT 'A' NAME, COUNT(c.ID) [COUNT] FROM Contact c WHERE ... UNION SELECT 'B' NAME, COUNT(c.ID) [COUNT] FROM Contact c WHERE ... ``` 3) in case it is really the same subset but you want to sum based on some con...
If I understand what you're trying to do, I usually end up doing it this way: ``` SELECT SUM(CASE WHEN Condition1 THEN 1 END) AS Column1, SUM(CASE WHEN Condition2 THEN 1 END) AS Column2 FROM Contact ```
multiple SQL counts using multiple queries using SQL
[ "", "sql", "sql-server", "" ]
I'm having difficulty getting my sizers to work properly in wxpython. I am trying to do a simple one horizontal bar at top (with text in it) and two vertical boxes below (with gridsizers \* the left one should only be 2 columns!! \* inside each). I want the everything in the image to stretch and fit my panel as well (w...
Is this what you're after? ![enter image description here](https://i.stack.imgur.com/dodoe.png) ``` import wx class Frame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent) self.panel = wx.Panel(self) main_sizer = wx.BoxSizer(wx.VERTICAL) # Title sel...
something like this?? ``` import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self,None,-1,"Test Stretching!!") p1 = wx.Panel(self,-1,size=(500,100)) p1.SetMinSize((500,100)) p1.SetBackgroundColour(wx.GREEN) hsz = wx.BoxSizer(wx.HORIZONTAL) ...
wxpython layout with sizers
[ "", "python", "layout", "wxpython", "sizer", "" ]
Example: ``` a = ['abc123','abc','543234','blah','tete','head','loo2'] ``` So I want to filter out from the above array of strings the following array `b = ['ab','2']` I want to remove strings containing 'ab' from that list along with other strings in the array so that I get the following: ``` a = ['blah', 'tete', ...
You can use a list comprehension: ``` [i for i in a if not any(x in i for x in b)] ``` This returns: ``` ['blah', 'tete', 'head'] ```
``` >>> a = ['abc123','abc','543234','blah','tete','head','loo2'] >>> b = ['ab','2'] >>> [e for e in a if not [s for s in b if s in e]] ['blah', 'tete', 'head'] ```
How to remove an array containing certain strings from another array in Python
[ "", "python", "" ]
I'm trying to create a simple app that lists recent photos posted to Flickr based on geography. I've created the query using flickerapi, but struggling with the API notes as to how to actually return the results so I can actually parse the attributes I actually want. This is my query: ``` import flickrapi api_key = ...
In your case what you might want is: > ``` > "flickr = flickrapi.FlickrAPI(api_key) > photos = flickr.photos_search(user_id='73509078@N00', per_page='10') > sets = flickr.photosets_getList(user_id='73509078@N00')" > ``` > > - [flickrapi docs](http://stuvel.eu/media/flickrapi-docs/apidoc/) So what it does is ge...
If you want to see what a given object has I would advise one of the following: ``` vars(item) # To see all the variable associated with it ``` or ``` dir(item) # To see all of the methods associated with it ``` To be more precise `dir()` returns all of the variables in scope, but for your object, and given that ...
How to parse Flickr using flickrapi in Python
[ "", "python", "flickr", "" ]
I can't figure out how to `SUM` up and down votes on a certain item while also returning whether or not a given user voted on this item. Here's my Votes table: ``` item_id vote voter_id 1 -1 joe 1 1 bob 1 1 tom 3 1 bob ``` For `item_id=1` here's the data I want to show:...
``` SELECT item_id, MAX(CASE WHEN voter_id = 'Joe' THEN vote ELSE NULL END) AS my_vote, sum(vote= 1) AS yes_votes, sum(vote=-1) AS no_votes FROM Votes WHERE item_id = 1 GROUP BY item_id ``` Or, possibly more flexible... ``` SELECT Votes.item_id, MAX(CASE WHEN Users.user_id IS NOT NULL THEN Vot...
My answer's pretty much the same, but for those of us who love stored procs I've cleaned it up a little: ``` declare p_item_id int; declare p_voter_id varchar(10); select sum(vote = 1) as TotalUpVotes , sum(vote = -1) as TotalDownVotes , sum(vote) as TotalScore , sum(case when p_voter_id = voter_id t...
Using SELECT CASE and SUM: MYSQL
[ "", "mysql", "sql", "case", "" ]
I am doing a project in *python-django,* i would like to know whether there is any built-in library or something like that, that can convert text to pdf. Something similar to pyTeaser for converting image to text Thanks in Advance
There are several options out there: * [reportlab](http://www.reportlab.com/software/opensource/) (suggested by [django docs](https://docs.djangoproject.com/en/dev/howto/outputting-pdf/)) * [PDFMiner](http://www.unixuser.org/~euske/python/pdfminer/index.html) (or +[slate](https://pypi.python.org/pypi/slate) wrapper) *...
I have been using [django-webodt](https://github.com/NetAngels/django-webodt) for a few days now to convert OpenOffice template (.odt) dynamically into PDF filling placeholders with database models. test.odt could be... > Hello {{ first\_name }} ``` import webodt template = webodt.ODFTemplate('test.odt') context = d...
django-python how to convert text to pdf
[ "", "python", "django", "pdf", "" ]
I wonder if it is possible to create a table that has a created date and updated date every time a record is created or updated. For example, when I insert a record into that table, the created date will auto generated in the table same with the update date. When I modify this record, the create date won't change but...
``` CREATE TABLE dbo.foo ( ID INT IDENTITY(1,1), CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, UpdatedDate DATETIME NULL ); GO CREATE TRIGGER dbo.foo_ForUpdate ON dbo.foo FOR UPDATE AS BEGIN SET NOCOUNT ON; UPDATE f SET UpdatedDate = CURRENT_TIMESTAMP FROM dbo.foo AS f INNER JOIN inse...
You can set the default value for the column to be equal to GetDate() and this will set the Created Date to the time when the record was created. This will not work for UpdatedDate because default values will be used when the record is created. For this column you can use after update trigger. Here is a link that shows...
Create a Table that has Created Date and Update Date (Read Only)
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have what seems to be a common business request but I can't find no clear solution. I have a daily report (amongst many) that gets generated based on failed criteria and gets saved to a table. Each report has a type id tied to it to signify which report it is, and there is an import event id that signifies the day th...
Something like this? <http://www.sqlfiddle.com/#!3/81945/14> ``` SELECT [final].*, [last].total_rows FROM tblEventInfo AS [final] INNER JOIN ( SELECT [first_of_last].type_id, [first_of_last].invoice, MAX([all_of_last].event_date) AS event_date, COUNT(*) AS total_rows ...
I had a similar requirement not long ago getting a "Top 5" ranking with a consecutive number of periods in Top 5. The only solution I found was to do it in a cursor. The cursor has a `date = @daybefore` and inside the cursor if your data does not match quit the loop, otherwise set `@daybefore = datediff(dd, -1, @daybef...
Calculating current consecutive days from a table
[ "", "sql", "sql-server", "sql-server-2000", "" ]
I have a table as below ``` ID | CID 1 | 3 2 | 0 3 | 4 4 | 0 5 | 0 6 | 3 ``` Below is the SQL query I use which is SELF JOIN. ``` SELECT t1.ID FROM `tbl_a` AS t1 JOIN `tbl_a` AS t2 ON t1.ID = t2.CID ``` Which gives me O/P as below. ``` ID | CID 3 | 4 4 | 0 ``` But what I want as an O/P is `1,3,4,6`. L...
Not sure what you're trying to do. I think you are saying you want the ID of rows that have a non-zero CID or that are referenced by the CID column. (?) Try this: ``` SELECT ID FROM tbl_a AS t1 WHERE CID <> 0 OR EXISTS(SELECT * FROM tbl_a AS t2 WHERE t2.CID = t1.ID) ORDER BY ID ```
Try this ``` SELECT t2.ID FROM `tbl_a` AS t1 JOIN `tbl_a` AS t2 ON t1.ID = t2.CID OR t2.ID = t1.CID GROUP BY t2.ID ```
SELF JOIN Unique Resultset Issue - MySQL
[ "", "mysql", "sql", "self-join", "" ]
I have a for loop that looks like this, and am looking to make it faster. mylist = range(100) ``` def normalrandom(): for a in range(100): b = random.getrandbits(1) if b==1: #do something with mylist[a] ``` My list has ~100 elements, and I know calls to random are expensive. Is there a faster way...
Here are some timings for different methods: code: ``` from random import getrandbits, randint, random, sample s = list(range(100)) def loop_bits(): res = [] b = getrandbits(len(s)) for i in s: if b % 2 == 0: res.append(i) b >>= 1 def comp_bits(): res = [i for i in s if ...
This seems to work pretty nicely. It returns a generator object, so the only memory usage is the `n`-bit integer `r`. *Edit: Don't use this!* ``` import random def rand_bools(n): r = random.getrandbits(n) return ( bool((r>>i)&1) for i in xrange(n) ) ``` Usage: ``` >>> for b in rand_bools(4): print b ... Fa...
Generate Sequence of Booleans Quickly in Python
[ "", "python", "random", "" ]
I am using jquery+ajax to transfer a file to the server. In the server I have a python script which I copy below which simply gets the file and writes it on disk. The script works perfect for bytes smaller than 1 Kby but for bigger files it throws an exception: OSError: [Errno 13] Permission denied Why does this happe...
The problem was that the server was not configured to accept files with a size larger than 1 Kby. The solution was asking the server administrator to change this configuration.
you don't have permission to open (or write?) whatever file you are trying to work with. Try running the script as super user or change permissions on the directory where you are trying to read/write from
OSError: [Errno 13] Permission denied in Python script when passing files > 1 Kb
[ "", "python", "permissions", "cgi", "" ]
I have a table with a column which contains strings like below. ``` RTSPP_LZ_AEN RTSPP_LZ_CPS RTSPP_LZ_HOUSTON RTSPP_LZ_LCRA RTSPP_LZ_NORTH RTSPP_LZ_RAYBN RTSPP_LZ_SOUTH RTSPP_LZ_WEST RTSPP_BTE_CC1 RTSPP_BTE_PUN1 RTSPP_BTE_PUN2 ``` I need to get the substring from the second occurrence of `_` till the end of string...
You can use `CHARINDEX` in combination with [`REVERSE`](http://msdn.microsoft.com/en-us/library/ms180040.aspx) function to find last occurrence of `_`, and you can use [`RIGHT`](http://msdn.microsoft.com/en-us/library/ms177532.aspx) to get the specified number of characters from the end of string. ``` SELECT RIGHT([St...
You can try giving len([string]) as the last argument : ``` SELECT SUBSTRING([String],CHARINDEX('_',[String],(CHARINDEX('_',[String])+1))+1,len([string])) FROM [Table] ```
substring of variable length
[ "", "sql", "sql-server", "sql-server-2012", "substring", "" ]
Title question says it all. I was trying to figure out how I could go about integrating the database created by sqlite3 and communicate with it through Python from my website. If any further information is required about the development environment, please let me know.
I'm not sure if you are using JQuery at all but you should use AJAX to make calls to the python api. Jquery Method: <http://api.jquery.com/jQuery.ajax/> ``` $.ajax({ type: "POST", //OR GET url: yourapiurl, data: datatosend, success: success, //Callback when request is successful that contains the SQlite data dat...
Use XMLHttpRequest (<https://en.wikipedia.org/wiki/XMLHttpRequest>) to call your python script and put the results back in your webpage.
I have a static website built using HTML, CSS and Javascript. How do I integrate this with a SQLite3 database accessed with the Python API?
[ "", "python", "sqlite", "static-site", "" ]
I have a table and i need to present the output in the following fashion. ``` tb_a: col1 | reg_id | rsp_ind ``` Count of rows with rsp\_ind = 0 as 'New' and 1 as 'Accepted' The output should be ``` NEW | Accepted 9 | 10 ``` I tried using the following query. ``` select case when rsp_ind = 0 then count(reg...
``` SELECT COUNT(CASE WHEN rsp_ind = 0 then 1 ELSE NULL END) as "New", COUNT(CASE WHEN rsp_ind = 1 then 1 ELSE NULL END) as "Accepted" from tb_a ``` You can see the output for this request [HERE](http://sqlfiddle.com/#!2/84442/1)
Depending on you flavor of SQL, you can also [imply the else statement](https://dba.stackexchange.com/a/123668/31340) in your aggregate counts. For example, here's a simple table `Grades`: ``` | Letters | |---------| | A | | A | | B | | C | ``` We can test out each Aggregate counter syntax li...
using sql count in a case statement
[ "", "sql", "" ]
I'm trying to split my query results into 2 groups, ones that have a flag of Y and ones that have a flag N. I then need to sort the groups by the based on 2 things. Here's the query I've tried which doesn't work with the GROUP BY bit: ``` SELECT location, country FROM web_loc_info WHERE f...
It might be worth clarifying that a "GROUP" in Oracle (from a `GROUP BY` operation) is where one or more rows of raw data has been consolidated into a single row in the result. Recall that: ``` SELECT flag FROM web_loc_info GROUP BY flag ORDER BY flag ``` is equivalent to ``` SELECT DISTINCT flag FROM web_log_info ...
it doesn't seem like you need the group at all. ``` SELECT location, country FROM web_loc_info WHERE flag in ( 'Y' , 'N' ) AND available_online = 'Y' ORDER BY flag desc, country, location_desc ```
Oracle sql group by then sort
[ "", "sql", "oracle", "" ]
I was trying to implement a `lxml, xpath` code to parse html from link: `https://www.theice.com/productguide/ProductSpec.shtml?specId=251` Specifically, I was trying to parse the `<tr class="last">` table at near the end of the page. I wanted to obtain the text in that sub-table, for example: "New York" and the hours ...
Your `lxml` code is very close to working. The main problem is that the `table` tag is not the one with the `class="last"` attribute. Rather, it is a `tr` tag that has that attribute: ``` </tr><tr class="last"><td>TRADING HOURS</td>&#13; ``` Thus, ``` //table[@class="last"] ``` has no matches. There is also a minor...
I like css selectors much adaptive on page changes than xpaths: ``` import urllib from lxml import html url = 'https://www.theice.com/productguide/ProductSpec.shtml?specId=251' response = urllib.urlopen(url).read() h = html.document_fromstring(response) for tr in h.cssselect('#tradingHours tbody tr'): td = tr.c...
Parsing with lxml xpath
[ "", "python", "parsing", "lxml", "" ]
I'd like to rank some data If I used a rank function with ties, the same ranking is assigned and a gap appears in the sequence for each duplicate ranking. example : ``` Value | Ranking 1 1 1 1 1 1 1 1 1 1 2 6 ``` **EDIT** : I'd like to know if it's possible have these two ...
``` SELECT Value, count(*) over (partition by value)/2 + rank() over(order by value) as Ranking1, count(*) over (partition by value) + rank() over(order by value) -1 as Ranking2 FROM table ```
Try ``` select value, RANK() over (order by value) + COUNT(value) OVER (PARTITION BY value) / 2, RANK() over (order by value) + COUNT(value) OVER (PARTITION BY value) - 1 from yourtable t ``` If you're using SQL 2005, use ``` (select COUNT(*) from yourtable where value = t....
SQL ranking and ties
[ "", "sql", "sql-server", "ranking", "" ]
In `R` I can do this ``` > a = (10:19) > a [1] 10 11 12 13 14 15 16 17 18 19 > b = c(4,7) > b [1] 4 7 > > a[b] [1] 13 16 > > a[-b] [1] 10 11 12 14 15 17 18 19 ``` I suppose there is an equally elegant way of doing this to Python (2.7) lists, but haven't found yet. I'm particularly interested in the `a[-b]` bit. Any ...
You do this using list comprehensions ``` [n for n, i in enumerate(a) if i not in b] ``` Or using numpy: ``` x = np.arange(10, 20) y = [2, 7] x[y] ```
``` a=numpy.array(range(10,20)) b = [4,7] print a[b] print a[~numpy.in1d(a,a[b])] ``` not quite as elegent but meh ... it also wont work if there are duplicate elements in the list ... since its looking at the values in the negation step rather than the indices
Slicing Python lists vs Slicing R vectors
[ "", "python", "r", "" ]
I was thinking if is relevant to import just what i need from a module in order to reduce the memory consume of any script, or should i just import everything ? I believe if i start to write that way could consume more time write , but it worth it? I mean, could reduce the chance of more usage of the memory? With the ...
Importing the module doesn't waste *anything*; the module is always *fully* imported (into the `sys.modules` mapping), so whether you use `import ftplib` or `from ftplib import FTP` makes no odds. I elaborate on why this is and what importing a module really means over on Programmers, on a cross-site duplicate questio...
You should try and import as little as possible. i.e. ``` "from sys import a" is better than "from sys import *" ``` The rationale behind it, is so that we do not end up with duplicates and hence things not working as desired. There is already fair amount of module duplication present. so, there are changes that we m...
Import full module or just what i need in order to reduce memory
[ "", "python", "" ]
I have some strings and at some particular index i want to check if the next char is digit surrounded by one or more whitespaces. For example here is a string > 'some data \n 8 \n more data' lets say i am iterating the string and currently standing at index 8, and at that position i want to know that if the next ch...
Your original regex didn't work because the "\*" is saying "zero or more matches". Instead, you should use a "+", which means "one or more matches". See below: ``` >>> import re >>> s = 'some data \n 8 \n more data' >>> if re.search("\s+[0-9]+\s+", s): print True ... True >>> s = 'some data \n 8) \n more data' >>> if ...
Try this: ``` (?<=\s)[0-9]+(?=\s) ``` This regex uses a look-ahead and a look-behind, such that it matches the number only when the characters before and after it are whitespace characters. In verbose form: ``` (?<=\s) # match if whitespace before [0-9]+ # match digits (?=\s) # match if whitespace after ```
python regex, only digit between whitespaces
[ "", "python", "regex", "" ]
I would like to have my code bring up a window where you can select multiple files within a folder and it assigns these filenames to elements of a list. Currently, I can only select a single file at a time and it assigns the filename to a single variable. ``` from Tkinter import Tk from tkFileDialog import askopenfil...
You need to use the `askopenfilenames` method instead.
You can encapsulate all that in a function: ``` def get_filename_from_user(message): root = Tk() root.withdraw() filename = tkFileDialog.askopenfilename(title=message) return filename ``` Then you can call it as many times as you like: ``` filename1 = get_filename_from_user('select the first file!') filename...
Python; User Prompts; choose multiple files
[ "", "python", "file", "user-interface", "prompt", "" ]
I want to make 4 `imshow` subplots but all of them share the same colormap. Matplotlib automatically adjusts the scale on the colormap depending on the entries of the matrices. For example, if one of my matrices has all entires as 10 and the other one has all entries equal to 5 and I use the `Greys` colormap then one o...
To get this right you need to have all the images with the same intensity scale, otherwise the `colorbar()` colours are meaningless. To do that, use the `vmin` and `vmax` arguments of `imshow()`, and make sure they are the same for all your images. E.g., if the range of values you want to show goes from 0 to 10, you c...
When the ranges of data (data1 and data2) sets are unknown and you want to use the same colour bar for both/all plots, find the overall minimum and maximum to use as `vmin` and `vmax` in the call to `imshow`: ``` import numpy as np import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=1, ncols=2) # generate...
Imshow subplots with the same colorbar
[ "", "python", "matplotlib", "" ]
This has me stumped... I have a list of files in a folder. Eg. ``` myFiles = ["apple_d_v01.jpg", "apple_d_v02.jpg", "apple_d_v03.jpg", "something_d.jpg", "anotherthing_d.jpg"] ``` There are three versions of the file "apple\_d", using a version suffix of "\_vxx". I want to be able to modify the list to have only the...
Assuming that `d` is a version number in your question ``` latestVersion = max(int(fname.rsplit('.',1)[0].rsplit("_",1)[1].strip('v')) for fname in myFiles) ``` From your comments, I understand that you want to keep the latest versions of versioned files. For that, you'll need this: ``` answer = set() for fname in m...
This Method i made i think will do what you asked, It takes a List of file names and finds the latest version, It then searches for all files that contain a version tag and removes the ones that are not latest. It will not work if some files are only updated to a version 2 and others a 3. ``` def removePreviousVersion...
Determining the latest version of a file (python)
[ "", "python", "file", "versioning", "" ]
My objective is to find the line numbers of the start and the end of a loop statement in python. Example scenario ``` #A.py Line1: a=0 Line2: while a<5: Line3: print a Line4: a=a+1 Desired output: Start of a loop Line2 End of a loop Line4 ``` Current parser code ```...
A `While` node has its statements in its `node.body` list. The last line of the `while` loop is the last element of the list. I don't know why you are subtracting one (unless your file `a` has a comment that you want to pretend does not exist): ``` $ cat a.py a = 0 while a < 5: print a a += 1 for i in (1, 2, ...
It could be complecated but you can try following algorithm. ``` 1. Count the number of white spaces before while. say it ident(you can use something like this len(a) - len(a.lstrip()) ) 2. countinue reading the next line and counting the white spaces before the line say currIdent. 3. when ever currIdent = ident, then...
How to parse the starting and ending of a loop statements in python
[ "", "python", "parsing", "" ]
I am trying to create a dice game using a while loop and if's. I have done this successfully however I am trying to figure out how to program the game so that if numbers 4,6 or 12 are not input it will state invalid choice and will ask diceChoice again. Can anybody help? So far I have... ``` rollAgain = "Yes" or "yes...
Fixed While Loop, Tidied up all the repetition. Moved import statement to the top. Structured to allow more options for rollAgain and diceChoice. ``` import random rollAgain = "Yes" while rollAgain in ["Yes" , "yes", "y"]: diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?") ...
You should only import random once at the top ``` import random #put this as the first line ``` Your rollAgain declaration should only set it to one value ``` rollAgain = "yes" # the or statements were not necessary ``` You forgot to do `rollAgain ==` in your subsequent conditionals, here is a simpler way ``` wh...
Dice game query While loop
[ "", "python", "if-statement", "while-loop", "dice", "" ]
I am using the matrix (numpy) operations in Python and came across an interesting observation. If I have the following code: ``` x=matrix([[1,2],[3,4]]) y=matrix([[1.1,2.1],[3.1,4.1]]) x=y print x ``` then it prints `[[1.1,2.1],[3.1,4.1]]` However instead if I do ``` x=matrix([[1,2],[3,4]]) y=matrix([[1.1,2....
The names `x` and `y` are just labels you can asisgn to objects. They are not really "variables" as in other languages, and they don't have any type assigned to them. Executing the line ``` x = y ``` will simply attach the label `x` to the object `y` is currently pointing to, and drop the reference to the object it ...
your x matrix has a dtype of int32 Edit: A more interesting result is this: ``` >>> x = np.matrix([[1,2],[3,4]],dtype='f') >>> y = np.matrix([[1.1,2.1],[3.1,4.1]],dtype='f') >>> x[:,:] = y[:,:] >>> x matrix([[ 1.10000002, 2.0999999 ], [ 3.0999999 , 4.0999999 ]], dtype=float32) ``` But this is caused by the...
Python matrix manipulation
[ "", "python", "numpy", "" ]
I am trying to calculate the cost per square of a circular object, given its diameter and price. Here is what I got: ``` import math def main(): print("This program calculates the cost per square inch of a circular object.") diameter = eval(input("What is the diameter of the object? ")) price = eval(inp...
Yes, the formula for the area of a circle is A = π \* r \* r. But `price` should be in the numerator and `area` in the denominator. You've coded the *inverse* - square feet per unit cost. Think of the units you want: cost per square foot. That will guide you. I'd recommend dividing `diameter` by 2.0 rather than 2 to ...
I would also suggest to compute intermediate values with proper names first. This often prevents mistakes in the first place: ``` radius = diameter / 2.0 area = math.pi * radius**2 price_per_area = price / area ``` You also might have noticed that I preferred "price" before "cost" and "area" before "square". That's b...
Calculate the cost per square of a circular object
[ "", "python", "math", "python-3.x", "geometry", "" ]
I have a table that contains salary increase history (Oracle) `emp_id` - for employee identification, `inc_date` - the date that the salary was changed and inc\_amount - the amount of the change in salary. I would like to get the `inc_amount` for the last `inc_date.` ``` emp_pay_inc: ==============================...
You should be able use a subquery for this: ``` SELECT * FROM (SELECT epi.inc_amt FROM emp_pay_inc epi ORDER BY epi.inc_date DESC) WHERE ROWNUM = 1; ```
I guess you want this for each employee. ``` SELECT emp_id, inc_date, inc_amount FROM (SELECT emp_id, inc_date, inc_amount, ROW_NUMBER () OVER (PARTITION BY emp_id ORDER BY inc_date DESC) r FROM emp_pay_inc) WHERE r = 1; ```
Retrieve only the first row with ORDER BY
[ "", "sql", "oracle", "" ]
I'm very new to SQL so apologies in advance if I'm missing the obvious. My data consists of customer contract number, service date, and a list of prices. I need to be able to group by customer, pull the first price by service date and in another column have the sum of all prices. So I have something like: ``` SELECT...
Try: ``` -- @tmp represents your table declare @tmp table ( [Contract] int, [Prices] decimal(18,5), [ServiceDate] datetime ) -- some testing data - you may skip that insert into @tmp values(1, 100, '2011-01-01') insert into @tmp values(1, 200, '2011-01-02') insert into @tmp ...
You can use [`ROW_NUMBER`](http://msdn.microsoft.com/en-us/library/ms186734%28v=sql.110%29.aspx): ``` WITH CTE AS( SELECT CONTRACT, SUM(PRICES) OVER(PARTITION BY CONTRACT) as [TOTAL SPENT], PRICE as [FIRST PRICE], ROW_NUMBER()OVER(PARTITION BY Contract Order By ServiceDate) ...
SQL Select first price when grouping by customer
[ "", "sql", "sql-server", "" ]
I have the following query ``` DECLARE @onlymonth bit SET @onlymonth = 0 DECLARE @month int SET @month = 5 SELECT SUM(amount) amount FROM accounting ac WHERE DATEPART(mm,ac.date) <= @month ``` What I want is depending on the @onlymonth parameter remove the minor sign so... for example ...WHERE DATEPART(mm,ac.date...
Try this: ``` SELECT SUM(amount) amount FROM accounting ac WHERE (DATEPART(mm,ac.date) = @month and @onlymonth = 0) OR (DATEPART(mm,ac.date) <= @month and @onlymonth = 1) ```
This does what you want. ``` DECLARE @onlymonth bit SET @onlymonth = 0 DECLARE @month int SET @month = 5 if (@onlymonth = 0) begin SELECT SUM(amount) amount FROM accounting ac WHERE DATEPART(mm,ac.date) <= @month end else begin SELECT SUM(amount) amount FROM accounting ac WHERE...
SQL Case Statement with math in Where Clause
[ "", "sql", "sql-server", "" ]
``` TYPE ref_cur IS REF CURSOR; ref_cur_name ref_cur; TYPE tmptbl IS TABLE OF ref_cur_name%ROWTYPE; n_tmptbl tmptbl; ``` I tried this code but can't get it thru compiler . Is there a way to store the results of ref cursor into a table ? NOTE-I need a table because i need to access the column of ref cur...
As far as I understand what you're doing, you just need to parameterise the delete: ``` ... v_str3 VARCHAR2 (4000); v_rowid ROWID; BEGIN ... OPEN ref_cur_name FOR v_str1; LOOP FETCH ref_cur_name INTO v_rowid; EXIT WHEN ref_cur_name%NOTFOUND; IF v_cnt = 1 ...
By issuing `TYPE ref_cur IS REF CURSOR` you are declaring a weak cursor. Weak cursors return no specified types. It means that you cannot declare a variable that is of `weak_cursor%rowtype`, simply because a weak cursor does not return any type. ``` declare type t_rf is ref cursor; l_rf t_rf; type t_trf is t...
can TYPE be declared of ref cursor rowtype
[ "", "sql", "oracle", "plsql", "ref-cursor", "" ]
If I call os.urandom(64), I am given 64 random bytes. With reference to [Convert bytes to a Python string](https://stackoverflow.com/questions/606191/convert-byte-array-to-python-string) I tried ``` a = os.urandom(64) a.decode() a.decode("utf-8") ``` but got the traceback error stating that the bytes are not in utf-8...
The code below will work on both Python 2.7 and 3: ``` from base64 import b64encode from os import urandom random_bytes = urandom(64) token = b64encode(random_bytes).decode('utf-8') ```
You have random bytes; I'd be very surprised if that ever was decodable to a string. If you **have** to have a unicode string, decode from Latin-1: ``` a.decode('latin1') ``` because it maps bytes one-on-one to corresponding Unicode code points.
How can I convert a python urandom to a string?
[ "", "python", "string", "random", "python-3.x", "byte", "" ]
Here's how I would write it in C. ``` if(x < 50 && x < 0.125y) { return 0; } else if(x < 50 && x >= 0.125y) { if(z >= 2a) { return 50; } } else return b; ``` Here's my attempt, it's just a bunch of nested ifs... ``` IIf(([Est_Order_Qty]<50) And ([Est_Order_Qty]<0.125*[...
``` IIF((x < 50) AND (x < 0.125 * y), 0, IIF((x < 50) AND (x >= 0.125 * y) AND (z >= 2 * a), 50, b) ``` or with your attempt ``` IIf(([Est_Order_Qty] < 50) And ([Est_Order_Qty] < 0.125 * [Quantity On Hand]), "0", IIf(([Est_Order_Qty] < 50) And ([Est_Order_Qty] >= 0.125 * [Quantity On Hand...
Try [Switch](http://office.microsoft.com/en-us/access-help/switch-function-HA001228918.aspx) ``` SWITCH( x < 50 AND x < 0.125y, 0, x < 50 AND x >= 0.125y AND z >= 2a, 50, TRUE, b) ```
How would I write this in a MS Access query?
[ "", "sql", "ms-access", "if-statement", "" ]
Although I am using stackoverflow for a long time now, it's my first time posting a question. I hope someone can help me solve this problem. I am having this database structure (please have a look at the diagram below) in SQL Server 2005 and I am now working on reports using Crystal Reports. What I want to do is to g...
I hope I understood you correctly. For each Agency you want to know how many of each type of unit (learner, facilitator, course) there are. This query should do what you want to do: ``` ;WITH data AS (SELECT T1.*, T2.FULLNAME AS Facil_Name, T3.ID AS Learner_Name, ...
It looks like you want a combination of `group by` and `count distinct` ``` select implementingagencyid, count (distinct courses.id) as CourseCount, count (distinct learners.id) as LearnerCount, count (distinct facilitators.id) as FacilitatorCount courses inner join learners on courses.ID = learner...
Querying data from tables having one-to-many and many-to-one relationships based on the relationship
[ "", ".net", "sql", "sql-server", "sql-server-2008", "" ]
We have a need to store people, with their 'Person Number' in the format the business uses them. At the moment, they use a manual process with numbers for the person in the format of, for example FP123456. The next person added gets the next number, so FP123457. There is a search in the system based on that number. M...
I would certainly keep this *PersonNumber* separate from the [Primary Key](http://en.wikipedia.org/wiki/Primary_key). You will find folks who disagree, but in my experience using a [natural key](https://en.wikipedia.org/wiki/Natural_key) as the primary key *always* turns out to be a bad choice. Things change\*. * Tod...
Yes, you can use a [computed column](http://msdn.microsoft.com/en-us/library/ms191250%28v=sql.105%29.aspx). You can index a persisted computed column. ``` ALTER TABLE YourTable ADD PersonNumber AS 'FP' + CAST(ID AS VARCHAR(15)) PERSISTED NOT NULL go ``` [See SQL Fiddle](http://sqlfiddle.com/#!6/f1706/1)
Table design with "Person Number"
[ "", "sql", "identity", "uniqueidentifier", "" ]
Pardon me if this has been addressed before, but how do I organize data exchanged between client and server in python application (sockets)? Let's say I have some elements I have to send - strings, tuples, dicts: ``` "hello world", (1, 2, 3), {"k": "v"} ``` What I currently do is I simply convert everything to strin...
The easiest way is to [pickle](http://docs.python.org/3/library/pickle.html#module-pickle) them on the client side and unpickle them on the server side. However, to need to ensure that the data is coming from a trusted source as it is possible to force unpickle to execute arbitrary code. Make sure you use `cPickle` to ...
JSON is what you're looking for. If you have an object and you import the JSON functions: ``` from json import dumps, loads ``` you can use `dumps(obj)` to encode into JSON and `loads(str)` to convert a JSON string back to an object. For example: ``` dumps([[1,2,3],{"a":"b", "c":"d"}]) ``` yields `'[[1, 2, 3], {"a"...
Organize data sent between client-server
[ "", "python", "sockets", "python-2.7", "" ]
I have two different tables, Table1 & Table2 each with their own sets of values. I want to check a column to see if there are any differences from each other and `UPDATE` Table1 accordingly. I have this query that updates every row regardless if they differ in the value I'm checking for: ``` UPDATE Table1 SET value = ...
``` ... WHERE t1.value <> t2.value OR (t1.value IS NULL AND t2.value IS NOT NULL) OR (t1.value IS NOT NULL AND t2.value IS NULL); ```
You could just tack on `where t1.id is not null and t2.ID is not null` eg: ``` UPDATE Table1 SET value = t2.value FROM Table1 t1 INNER JOIN Table2 t2 ON t1.ID = t2.ID WHERE t1.value <> t2.value AND t1.id is not null AND t2.ID is not null ```
Check Differences between two Tables with allowed nulls in SQL
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-update", "" ]
Say I have a matrix: ``` > import numpy as nap > a = np.random.random((5,5)) array([[ 0.28164485, 0.76200749, 0.59324211, 0.15201506, 0.74084168], [ 0.83572213, 0.63735993, 0.28039542, 0.19191284, 0.48419414], [ 0.99967476, 0.8029097 , 0.53140614, 0.24026153, 0.94805153], [ 0.92478 ...
If you install the latest scikit-learn, version 0.14a1, you can use its shiny new `Imputer` class: ``` >>> from sklearn.preprocessing import Imputer >>> imp = Imputer(strategy="mean") >>> a = np.random.random((5,5)) >>> a[(1,4,0,3),(2,4,2,0)] = np.nan >>> a array([[ 0.77473361, 0.62987193, nan, 0.11367791, ...
You can do it with pure numpy, but its nastier. ``` from scipy.stats import nanmean >>> a array([[ 0.70309466, 0.53785006, nan, 0.49590115, 0.23521493], [ 0.29067786, 0.48236186, nan, 0.93220001, 0.76261019], [ 0.66243065, 0.07731947, 0.38887545, 0.56450533, 0.58647126], ...
Matrix completion in Python
[ "", "python", "numpy", "machine-learning", "scikit-learn", "mathematical-optimization", "" ]
I tried following in Sybase ``` SELECT ChrgAmt, REPLACE(convert(varchar(255),ChrgAmt), '.', '') AS Result FROM PaymentSummary ``` But it gives below error in isql ``` Incorrect syntax near the keyword 'REPLACE'. ``` What could be the possible reason Thanks
Assuming there is only one decimal point, you can do it this way: ``` stuff(convert(varchar(255), chrgamt), charindex('.', ChrgAmt), 1, NULL) ```
On Sybase ASE there is [str\_replace](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.blocks/html/blocks/blocks214.htm) funciotn ``` SELECT ChrgAmt, str_replace(convert(varchar(255),ChrgAmt), '.', '') AS Result FROM PaymentSummary ``` you can also use [cast](http://infocenter.sybase.com/he...
Replace doesn't work in Sybase
[ "", "sql", "sybase", "isql", "" ]
I'm using SQL Server 2008 R2 and have a `VARCHAR` column I want to convert to `DECIMAL(28,10)` using `CONVERT`. But many of those rows are badly formatted, so it is not possible to parse them to a number. In that case I just want to skip those by setting result to 0 or NULL. I know there is a new statement in SQL Serv...
Finally found out how to make it with the help from SO and Google. The update statement: ``` UPDATE PriceTerm SET PercentAddition = CONVERT(decimal(28,10), RTRIM(LTRIM(REPLACE(REPLACE(REPLACE(AdditionalDescription,'%',''), ',','.'), '&', '')))) WHERE AdditionalDescription LIKE '%[%]%' AND dbo.isreallynumeric(RTRIM(...
When using XML in SQL Server you can **try** to cast to a data type and receive null values where the cast fails. ``` declare @T table ( Col varchar(50) ) insert into @T values ('1'), ('1.1'), ('1,1'), ('1a') select cast('' as xml).value('sql:column("Col") cast as xs:decimal ?', 'deci...
Try_Convert for SQL Server 2008 R2
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I am trying to copy from one location to other as below and running into following error,can anyone provide inputs as to how to overcome this? ``` import argparse import shutil, errno def copystuff(src, dst): try: shutil.copytree(src, dst) except OSError as exc: # python >2.5 if exc.errno == e...
You need to use raw strings (or escape the slashes) when dealing with Windows paths: ``` source= r"\\Terminal\workspace\username\nfc\AU_LINUX_ANDROID_JB_3.2_RB2.04.03.00.129.005\\" ``` Otherwise, `\nfc` will be treated as `<newline>fc`.
Look at the path produced, shown in the error message. I think you forgot the backslash between the source and the item. ;) Just add an backslash at the end of `source` and `destination`, or add one in the begginning of the item in the `copy_list`.
copying from one location to other
[ "", "python", "" ]