Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How can I can remove all NewLine from a variable in SQL Server? I use SQL Server 2008 R2. I need remove all NewLine in a variable in a T-Sql Command. For example: ``` Declare @A NVarChar(500) Set @A = ' 12345 25487 154814 ' Print @A ``` And it printed like this: ``` 12345 25487 1...
You must use this query ``` Declare @A NVarChar(500); Set @A = N' 12345 25487 154814 '; Set @A = Replace(@A,CHAR(13)+CHAR(10),' '); Print @A; ```
If you want it to look exactly like in your sample output, use [this hack](https://stackoverflow.com/questions/2455750/replace-duplicate-spaces-with-a-single-space-in-t-sql): ``` DECLARE @A nvarchar(500) SET @A = ' 12345 25487 154814 ' SET @A = replace( replace( replace( replace(...
How I can remove all NewLine from a variable in SQL Server?
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I am new to SQL Server and trying to create a query for following scenario using SQL Server. I have a table named `GenericLabels` containing list of all the labels (`varchar(30)`) that can be used. They are used in table called `UserDeviceStatus`. I want list of labels which are in `GenericLabels` but not used in `Use...
Try this instead: ``` select label from GenericLabels where label not in (select customlabel from UserDeviceStatus where userid = 40) ```
You have to link on label and customlabel: ``` select label from GenericLabels where not exists ( select 1 from UserDeviceStatus where customlabel = label and userid = 40 ) ```
'select not in' query with subquery selecting varchar(30)
[ "", "sql", "sql-server", "" ]
I want to delete only the rows that the following statement returns, how can I do that? ``` select usersernum,username,useremail from core.appuser where usersernum in ( select ch.usersernum from core.appusersession ch where ch.usersernum not in ( ...
Sometimes it helps to take a step back and ask yourself, What is the real goal here, in "business terms" or every-day language rather than SQL. Your query looks like it has a bunch of unnecessary layers. It appears that what you really want to do is remove any inactive users, meaning those who have not started a sessi...
You could use ``` DELETE FROM core.appuser WHERE usersnum IN ( select usersernum from core.appuser where usersernum in ( select ch.usersernum from core.appusersession ch where ch.usersernum not in ( select usersernum from ( ...
How to delete rows from a table with multiple select in DB2
[ "", "sql", "database", "db2", "delete-row", "" ]
I would like to perform a SQL query across a very large table. However, I only need to look through the last 100,000 rows. Currently: ``` SELECT * FROM bigtable WHERE columna='foobar' ORDER BY id DESC LIMIT 10 ``` I would like to do the same but make it only look in the last X ids. **EDIT:** Selecting 100k rows firs...
In a database you cannot do a query that checks the "last x rows". A relational database does not guarantee that the rows are physically stored in a specific order. And therefore SQL will not allow you to express that. If you can translate that into an actual constraint based on the data contained in the rows then that...
Try ``` select * from ( SELECT * FROM bigtable ORDER BY id DESC LIMIT 100000 ) x where columna = 'foobar' order by id desc limit 10 ``` ## [SQLFiddle demo](http://sqlfiddle.com/#!2/84b58/2) And if your query is slow then add an index on `columna`.
Optimizing a SQL query by only looking in the last X rows (Not simply LIMIT)
[ "", "mysql", "sql", "" ]
I have the following code ``` --first statement ALTER TABLE [nameOfMyTable] WITH CHECK ADD CONSTRAINT [nameOfMyConstraint] FOREIGN KEY([myFK]) REFERENCES [tableReference] ([myFK]) GO --second statement ALTER TABLE [nameOfMyTable] CHECK CONSTRAINT [nameOfMyConstraint] GO ``` First, i define a CHECK constraint on a t...
The 2nd statement is redundant, the only time it would be needed is if the first statement had `WITH NOCHECK`. By default `WITH CHECK` is added if you don't explicitly state `CHECK` or `NOCHECK` in the `ADD CONSTRAINT` statement. > [sql server management studio generate this code by default – Mikhail](https://stackove...
From the docs: > Specifies that constraint\_name is enabled or disabled. This option can only be used with FOREIGN KEY and CHECK constraints. When NOCHECK is specified, the constraint is disabled and future inserts or updates to the column are not validated against the constraint conditions. DEFAULT, PRIMARY KEY, and ...
What does second check constraint mean?
[ "", "sql", "" ]
I am attempting to build a view which selects from an active and archive table, but only returns a record from the archive folder when the record does not exist in the active folder. It must also only return the archive record with the latest timestamp. Thank you Example: **Active:** ``` *ID ItemID Price* 1 0...
So you need to get everthing from ACTIVE [First part of the UNION below[, then append the records from ARCHIVE [Second part of the UNION[. For the Archive records, exlcude those that dont exist in the ACTIVE table [The NOT EXISTS clause] and only get the record that has the latest date [THE MAX(ArchiveDate)] clause. `...
You can use the following: ``` SELECT ItemID, Price FROM ( -- All of the active records SELECT ItemID, Price FROM Active UNION ALL -- combined with the latest archive records for missing actives SELECT ItemID, Price FROM Archive AS A1 WHERE ArchiveDate=(SELECT MAX(ArchiveDate) FROM Archive ...
Displaying a sorted dataset from two tables
[ "", "sql", "sql-server", "t-sql", "" ]
I'm happy to accept that this might not be possible, let alone sensible, but is it possible to keep a persistent reference to an object I have created? For example, in a few of my views I have code that looks a bit like this (simplified for clarity): ``` api = Webclient() api.login(GPLAY_USER,GPLAY_PASS) url = api.ge...
You can't have anything that's instantiated once per application, because you'll almost certainly have more than one server process, and objects aren't easily shared across processes. However, one per process is definitely possible, and worthwhile. To do that, you only need to instantiate it at module level in the rele...
You can't persist the object reference, but you can store something either in memory django cache or in memcached django cache. Django Cache <https://docs.djangoproject.com/en/dev/topics/cache/> See also [Creating a Persistent Data Object In Django](https://stackoverflow.com/questions/2345257/creating-a-persistent-da...
Django: Keep a persistent reference to an object?
[ "", "python", "django", "" ]
I have two files 'seen.txt' and 'members.txt'. First file 'seen.txt' lists the people who have seen a post. The file is structured like following: ``` Friend/Not Friend Name #1 Number of mutual friends Friend/Not Friend Name #2 Number of mutual friends ``` Second file 'members.txt' lists the details of the all the p...
I would probably use sets instead of dictionaries because it seems like you're throwing away a lot of the stored info in the files and just care about the names. I first restructured the way you import the names from the files. I used `izip_longest` to read the files 4 lines at a time (3 lines of text plus a blank lin...
`members_list` is a dict, so is `seen_list`. Apparently they carry only one value, 1, and each key has the same value. You can simplify that by using a `set`. ``` members_list = set() ``` and adding items to it: ``` members_list.add(lines.strip()) ``` you then have several useful functions on sets, including `diff...
Finding out matches between two dictionaries in Python
[ "", "python", "dictionary", "" ]
I have two list: ``` a = [1, 2, 3, 4] b = [5, 6, 7, 8] ``` I need to get something like this: ``` c = [1, 5, 2, 6, 3, 7, 4, 8] ``` I use this solution: ``` c = list(reduce(lambda x, y: x + y, zip(a, b))) ``` Is there a better way to do this?
Using *List Comprehension*: ``` >>> [x for tup in zip(a, b) for x in tup] [1, 5, 2, 6, 3, 7, 4, 8] ``` The above nested list comprehension is equivalent to following nested for loops (Just in case you get confused): ``` result = [] for tup in zip(a, b): for x in tup: result.append(x) ```
Using `chain`: ``` from itertools import chain, izip interweaved = list(chain.from_iterable(izip(a, b))) # [1, 5, 2, 6, 3, 7, 4, 8] ```
Python two list lists shuffle
[ "", "python", "list", "" ]
I came across the website rubular.com, and their example regex was : ``` (?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4}) ``` where the months, day, and year encased in the < > tags each group with that name. I'm wondering if there's a way to do that in Python since I couldn't find it in the documentation.
You do that using `(?P<group_name>...)`: ``` (?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<year>\d{4}) ``` See [documentation](http://docs.python.org/2/library/re.html#regular-expression-syntax)
To do so in Python, you would prefix the named group with the letter 'P' like so: ``` import re match = re.search('(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<year>\d{4})', '01/02/2000') print match.group('day') print match.group('month') print match.group('year') ``` The [documentation page for Regex](http://docs.py...
Naming regex groups in Python
[ "", "python", "regex", "" ]
How python recognize class and instance level variables ? are they different ? ``` For example, class abc: i = 10 def __init__(self, i): self.i = i a = abc(30) b = abc(40) print a.i print b.i print abc.i output -------- 30 40 10 ``` Means, in above example when I access `a.i (or b.i)` and `abc.i` ...
First, your sample is wrong for you can not init the instance if there is only a self in the `__init__`. ``` >>> class abc: ... i = 10 ... j = 11 ... def __init__(self, x): ... self.i = x ``` Then, when you access the attribute on the instance, it will check the instance variables first. Refer...
> in above example when I access a.i (or b.i) and abc.i are they > referring to completely different variables? Yes. abc.i is a [Class Object](http://docs.python.org/2/tutorial/classes.html#class-objects) reference. a.i and b.i are each [Instance Object](http://docs.python.org/2/tutorial/classes.html#instance-object...
python: class variables and instance variables
[ "", "python", "static-members", "instance-variables", "" ]
I've got the following tables which im querying: ``` categories -id -name -parent_id -last products2categories -id -product_id -category_id ``` What im trying to do is to get the record's `category name` and `category id` which the `product_id` in the table `products2categories` is 10 and `last` in the...
You are delimiting fields incorrectly. Delimit the table name and column name separately: ``` SELECT `categories`.`id`,`categories`.`name` FROM `categories` JOIN `products2categories` ON `categories`.`id` = `products2categories`.`category_id` WHERE `categories`.`last` = 1 AND `products2categories`.`product_id`= 10...
Replace ``` WHERE `categories.last` = 1 ``` with ``` WHERE `categories`.`last` = 1 ``` Backticks for escaping column and table names can't be used to escape the combination of table and column. It must be applyed on both.
SQL query is producing an error which I can't solve
[ "", "mysql", "sql", "" ]
In the Python Guide's chapter on [project structure](http://docs.python-guide.org/en/latest/writing/structure.html), the term "top-level statement" is brought up a few times. I'm not sure exactly what this refers to. My guess is it's any variable declarations that happen outside of any functions or class methods that f...
It's not just variable declarations (and there aren't any variable declarations anyway). It's pretty much anything that starts at indentation level 0. ``` import sys # top-level 3 + 4 # top-level x = 0 # top-level def f(): # top-level import os # not top-level! ...
Here's the first mention of "top-level statement": > Once modu.py is found, the Python interpreter will execute the module in an isolated scope. Any top-level statement in modu.py will be executed, including other imports if any. Function and class definitions are stored in the module’s dictionary. This makes it clea...
What is a top-level statement in Python?
[ "", "python", "" ]
How do I set up argparse as follows: ``` if -2 is on the command line, no other arguments are required if -2 is not on the command line, -3 and -4 arguments are required ``` For example, ``` -2 [good] -3 a -4 b [good] -3 a [not good, -4 required] -2 -5 c [good] -2 -3 a [good] ``` There are a number of similar quest...
A subparser (as suggested in comments) might work. Another alternative (since `mutually_exclusive_group` can't quite do this) is just to code it manually, as it were: ``` import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-2', dest='two', action='store_true') parser.add_...
I think it is pretty hard to achieve that (including a nice help message) while only using the standard argparse functions. You can however easily test it yourself after parsing the arguments. You can describe the extra requirements in the epilogue or so. Note that it is unusual to use numbers as options, I had to use ...
Python argparse conditional requirements
[ "", "python", "python-2.7", "argparse", "" ]
I want to do hierarchical key-value storage in Python, which basically boils down to storing dictionaries to files. By that I mean any type of dictionary structure, that may contain other dictionaries, numpy arrays, serializable Python objects, and so forth. Not only that, I want it to store numpy arrays space-optimize...
After asking this two years ago, I starting coding my own HDF5-based replacement of pickle/`np.save`. Ever since, it has matured into a stable package, so I thought I would finally answer and accept my own question because it is by design exactly what I was looking for: * <https://github.com/uchicago-cs/deepdish>
I recently found myself with a similar problem, for which I wrote a couple of functions for saving the contents of dicts to a group in a PyTables file, and loading them back into dicts. They process nested dictionary and group structures recursively, and handle objects with types that are not natively supported by PyT...
Saving dictionaries to file (numpy and Python 2/3 friendly)
[ "", "python", "python-3.x", "numpy", "hdf5", "pytables", "" ]
According to the [Python documentation](http://docs.python.org/2/library/stdtypes.html#string-methods): > str.endswith(suffix[, start[, end]]) > > Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at...
> or am I missing something? You're missing a comma after the `';'` in your tuple: ``` >>> "hello;".endswith(('.', ',', ':', '-', ';' '?', '!')) # ^ # comma missing False ``` Due to this, `;` and `?` are concatenated. So, the string...
It has already been pointed out that adjacent string literals are concatenated, but I wanted to add a little additional information and context. This is a feature that is shared with (and borrowed from) C. Additionally, this is doesn't act like a concatenation operator like '+', and is treated identically as if they ...
Have I found a bug in Python's str.endswith()?
[ "", "python", "string", "" ]
I have a MapReduce job defined in **`main.py`**, which imports the `lib` module from **`lib.py`**. I use Hadoop Streaming to submit this job to the Hadoop cluster as follows: ``` hadoop jar /usr/lib/hadoop-mapreduce/hadoop-streaming.jar -files lib.py,main.py -mapper "./main.py map" -reducer "./main.py reduce" ...
I posted the question to Hadoop user list and finally found the answer. It turns out that Hadoop doesn't really copy files to the location where the command runs, but instead creates **symlinks** for them. Python, in its turn, can't work with symlinks and thus doesn't recognize `lib.py` as Python module. Simple **work...
When Hadoop-Streaming starts the python scripts, your python script's path is where the script file really is. However, hadoop starts them at './', and your lib.py(it's a symlink) is at './', too. So, try to add 'sys.path.append("./")' before you import lib.py like this: `import sys sys.path.append('./') import lib`
How to import a custom module in a MapReduce job?
[ "", "python", "mapreduce", "hadoop-streaming", "" ]
I'm pretty new to Sybase and am writing a query to return results after a specified date, and also before a specified date. MM/DD/YYYY format At the moment im doing.. ``` SELECT * From aTable WHERE afterDate >= 08/07/2013 AND beforeDate <= 08/08/2013 ``` I'm getting records back, but as I'm a Syba...
You'll need to convert the dates into DATETIME and tell sybase what the format is to be sure. According to [this documentation](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc38151.1540/doc/html/san1278453000116.html "Chapter 4: SQL Functions - CONVERT function [Data type conversion]") the...
For any date-time field in sybase, instead of going through the convert function, there is a more direct approach. ``` SELECT * From aTable WHERE afterDate >= '2013-08-07' AND beforeDate <= '2013-08-08' ``` The date has to be in the form **'YYYY-MM-DD'** If you want to add a time, it can be included along wit...
Sybase date comparison - Correct format?
[ "", "sql", "database", "sybase", "mybatis", "" ]
I'm trying to make a function in Python that takes a list of integers as input and returns a greater list containing all positive and negative possibilities of those numbers. Pretend '+' is a positive number and '-' is a negative number The output should match up with: ``` foo([-4]) >>> [ [4], [-4] ] foo([+, +]) >>...
For just numbers, you can use `itertools.product` to create all combos, after generating a list with both positive and negative numbers: ``` from itertools import product def foo(nums): return list(product(*((x, -x) for x in nums))) ``` Demo: ``` >>> foo([-4]) [(4,), (-4,)] >>> foo([-1, 3]) [(1, 3), (1, -3), (-...
``` list(itertools.product(*([x, -x] for x in input))) ``` You want every possible way to pick either a number or its negative, for each number in the input. That's the [Cartesian product](http://en.wikipedia.org/wiki/Cartesian_product) of `{x[i], -x[i]}` for each `x[i]` in the input. [`itertools.product`](http://docs...
python positive and negative number list possibilities
[ "", "python", "list", "" ]
I have many databases in my SQL Server. I have to just search for database names containg particular table name `Heartbitmaster` I have many databases such as `Gotgold`, `DVD`, etc and I just want to find database names from query that contain this table `Heartbitmaster`. I searched I tried for query: ``` SELECT ...
I got it done through following query: ``` SELECT name FROM sys.databases WHERE CASE WHEN state_desc = 'ONLINE' THEN OBJECT_ID(QUOTENAME(name) + '.[dbo].[heartbit]', 'U') END IS NOT NULL ```
``` sp_MSforeachdb 'SELECT "?" AS DB, * FROM [?].sys.tables WHERE name like ''%tablename%''' ``` try this one
Display all the names of databases containing particular table
[ "", "sql", "sql-server", "database", "sql-server-2008", "" ]
I have followed instructions out lined here: <http://forums.nuand.com/forums/viewtopic.php?f=9&t=2804> and installed GNU Radio from GIT repo (scroll down to the section that says "Building GNURADIO from GIT". I used the ./build-gnuradio.sh script to do this and it took a while, but it appeared to build successfully, ...
There is a section later in the instructions with this boldface label: **Now for some voodoo to get the new program installed into system libraries and python paths and executable path.** Those instructions lead you through modifying your PYTHONPATH to pick up the gnuradio module, among other things. If you have foll...
One of the reason for this error is, when the default python is selected incorrectly. To see which python is selected type the following command in the Terminal: ``` "sudo port select python" ``` it will display all the python available on your mac. like: ``` python26 python27-apple(Active) pytho...
"ImportError no module named gnuradio" when trying to execute ./uhd_fft
[ "", "python", "gnuradio", "" ]
I'm trying to install tastypie for Django. I also have South installed. But when I migrate I get some weird type error. ``` ./manage.py migrate tastypie Running migrations for tastypie: - Migrating forwards to 0002_add_apikey_index. > tastypie:0001_initial TypeError: type() argument 1 must be string, not unicode ```...
It's a bug in the latest version (`0.10.0`). A bug report has been submitted. <https://github.com/toastdriven/django-tastypie/issues/1005>. You can fix it by installing a previous version: `pip install django-tastypie==0.9.16`
I had the same issue (in the 0.11.0 version) and I solved it removing 'tastypie' from INSTALLED\_APPS (settings.py).
Tastypie migration error
[ "", "python", "tastypie", "" ]
I am very new to SQL and I wanted some help in writing this SQL query. I have a movie table like this: ``` Movie_id Actor_name Director_name 1 a AA 1 b AA 2 b BB 2 d BB ``` Now I want to print out all the pairs of actors and directors w...
You can do it like this: ``` SELECT a.Actor_name, d.Director_name FROM ( (SELECT DISTINCT Actor_name from movie) a CROSS JOIN (SELECT DISTINCT Director_name from movie) d ) WHERE NOT EXISTS ( SELECT * FROM movie m WHERE m.Actor_name=a.Actor_name AND m.Director_name=d.Director_name ) ``` The idea is to p...
I would do this by first developing all pairs of actors and directors with a cross join (i.e. [Cartesian product](http://en.wikipedia.org/wiki/Cartesian_product)), and then filter this list down using the table of observed relationships. ``` SELECT * FROM ( -- cross join SELECT a.actor_name, d.director_name ...
MySQL - how do I write this Query
[ "", "mysql", "sql", "" ]
Been experiencing this weirdness in my program. Here is a snippet of the part that is giving trouble: ``` #!/usr/bin python def test_func( newList, myList=[] ): for t in newList: for f in t: myList.append(f) return myList print test_func([[3, 4, 5], [6, 7, 8]]) print test_func([[9, 10, 11]...
Don't use mutable as keyword arguments. ``` def test_func( newList, myList=None ): myList = [] if myList is None else myList ```
Although an answer has been accepted, it is interesting as well as important to understand why this happens, so as to avoid not-so-obvious pitfalls. An excerpt from the [Python documentation for compound statements](http://docs.python.org/2/reference/compound_stmts.html#function) : > Default parameter values are eval...
Python function with default list argument
[ "", "python", "default-value", "" ]
The model Price has an attribute data, so ``` Price.pluck(:data) ``` results in something like [3.99,4.55,5.44] And Price belongs to Vendor So I want to select the best price for each vendor, something like ``` Vendor.all.pluck(prices.order("data ASC").first.data) ``` How can I go about extracting the lowest pric...
For each vendor, use `minimum(:data)` on its associated prices: ``` Vendor.includes(:prices).map { |v| v.prices.minimum(:data) } ```
Here's another approach which puts more work on the database and less on Ruby. (I'm pretty sure the code in @meagar 's answer will issue a select for each vendor during the map). Which way is better (faster) may depend on how big your tables are… You could do something like this, which will issue one SQL statement: `...
Pluck last value of an association in rails
[ "", "sql", "ruby-on-rails", "ruby", "activerecord", "" ]
``` select Year(Creation_Date) from Asset_Creation where Creation_Date = @Creation_Date ``` I am executing this query where I am getting year as `2013` when supplied today's date. I want the query to return only 13 of 2013. How can I achieve that?
Try ``` SELECT RIGHT(YEAR(Creation_Date), 2) YY FROM Asset_Creation WHERE ... ``` Sample output: ``` | YY | ------ | 10 | | 11 | | 13 | ``` Here is **[SQLFiddle](http://sqlfiddle.com/#!3/cfa46/1)** demo
For SQL Server 2012: ``` SELECT FORMAT(@Creation_Date, 'yy') ```
How to get year in format YY in SQL Server
[ "", "sql", "sql-server", "datetime", "" ]
I have function that appends the substrings of a string to a list. When the input string is large a `MemoryError exception` is thrown. Is there any length limit for the 1 dimensional list?.If yes how can I extend it?
Besides making more memory, you have several other options. 1. Try to change your algorithm so it is less memory-intensive. For example, if you don't need all these substrings at once, you could create and use them successively using a generator function or a generator expression. 2. If you need them, try to just hold...
Yes. Available memory. Make more memory available to the process, either by adding more swap, adding more RAM, or moving to an architecture with a larger memory limit.
Extend of size of a list in python
[ "", "python", "python-2.7", "" ]
I have about 50 CSV files with 60,000 rows in each, and a varying number of columns. I want to merge all the CSV files by column. I've tried doing this in MATLAB by transposing each csv file and re-saving to disk, and then using the command line to concatenate them. This took my computer over a week and the final resul...
> [...] transposing each csv file and re-saving to disk, and then using the command line to concatenate them [...] Sounds like Transpose-Cat-Transpose. Use [paste](http://en.wikipedia.org/wiki/Paste_%28Unix%29) for joining files horizontally. ``` paste -d ',' a.csv b.csv c.csv ... > result.csv ```
The Python [`csv`](http://docs.python.org/2/library/csv.html) module can be set up so that each record is a dictionary with the column names as keys. You should that way be able to read in all the files as dictionaries, and write them to an out-file that has all columns. Python is easy to use, so this should be fairly...
What's the fastest way to merge multiple csv files by column?
[ "", "python", "csv", "merge", "" ]
How do you get the total size of the files in a torrent? And is there any way to get the number of files in a torrent and the size of each one?
Using torrent\_parser: ``` import torrent_parser as tp torrent_metadata = tp.parse_torrent_file("file.torrent") totalsize = 0 for file in torrent_metadata['info']['files']: totalsize += file['length'] print(totalsize) ```
``` h = ses.add_torrent(params) s = h.status() while (not h.is_seed()): print s.total_wanted # prints total size wanted after meta data is obtained, before that 0 is printed. ```
How do you get the total size of a torrent in libtorrent?
[ "", "python", "libtorrent", "" ]
I have a table with an int valued column, which has values between 0 and 43 (both included). I would like a query that returns the min value of the range [0,44) which is not in the table. For example: if the table contains: 3,5, 14. The query should return 0 if the table contains: 0,1, 14. The query should return...
Since the value you want is either `0` or 1 greater than a value that exists in the table, you can just do; ``` SELECT MIN(value) FROM (SELECT 0 value UNION SELECT value+1 FROM MyTable) a WHERE value < 44 AND value NOT IN (SELECT value FROM MyTable) ``` [An SQLfiddle to test with](http://sqlfiddle.com/#!2/ab2a6/1).
One way would be to create another table that contains the integers in `[0,43]` and then left join that and look for NULLs, the NULLs will tell you what values are missing. Suppose you have: ``` create table numbers (n int not null); ``` and this table contains the integers from 0 to 43 (inclusive). If your table is...
select min value of range [0,44) not in a column
[ "", "mysql", "sql", "" ]
I am learning Python and am trying to use it to perform sentiment analysis. I am following an online tutorial from this link: <http://www.alex-hanna.com/tworkshops/lesson-6-basic-sentiment-analysis/>. I have taken a piece of code as a mapper class, an excerpt of which looks like this: ``` sentimentDict = { 'positi...
The loop creates a nested dictionary, and sets all values to 1, presumably to then just use the keys as a way to weed out duplicate values. You could use sets instead and avoid the `= 1` value: ``` sentimentDict = {} def loadSentiment(): with open('Sentiment/positive_words.txt', 'r') as f: sentimentDict[...
The point is that this is a *nested* dict. `sentimentDict` is a dictionary, and `sentimentDict['positive']` and `sentimentDict['negative']` are dictionaries as well. In the `loadSentiment()` function those inner dicts get populated with items. The words are the keys, the values are always `1`. So you get something li...
What is this dictionary assignment doing?
[ "", "python", "mapreduce", "nltk", "sentiment-analysis", "" ]
Hi i am struging to get my head round indentaion levels with this code- ``` def getSolarFlowtemperature(): #Open the temperature sensor, read it and process the result tfile = open("/sys/bus/w1/devices/28-000003086819/w1_slave") text = tfile.read() tfile.close() temperature_data = text.split()[-1]...
The if/else should be in the while and their code should be indented, **break does not make sense outside of a loop** ``` def getSolarFlowtemperature(): #Open the temperature sensor, read it and process the result tfile = open("/sys/bus/w1/devices/28-000003086819/w1_slave") text = tfile.read() tfile.cl...
``` if count > 10: break else: return(temperature) ``` if-else conditions need to be indented as well. It should be ``` if count > 10: break else : return temperature ``` Some other notes: `return temperature` does not need parenthesis like you have. Also, to open a file, read it and the close it, you can just...
Python indentation newbie
[ "", "python", "indentation", "" ]
Is there a way that I can get all the columns and tables referenced in all the stored procedures in all the databases in an instance? The output should be: ``` Database Procedure Table Column -------- --------- ----- ------ ```
This will get the list you're after, however it won't help you if you have such column references embedded in dynamic SQL (and may not find references that rely on deferred name resolution). SQL Server doesn't parse the text of the stored procedure to come up with the DMV output. Try now with `COLLATE` clauses to deal...
To list all SP Name have contain the specified column name: ``` SELECT OBJECT_NAME(M.object_id), M.* FROM sys.sql_modules M JOIN sys.procedures P ON M.object_id = P.object_id WHERE M.definition LIKE '%ColumnName%' ```
List all columns referenced in all procedures of all databases
[ "", "sql", "sql-server", "sql-server-2008", "stored-procedures", "" ]
Looking for a way to get items in between tabs ``` \t_e\t1\t_ ``` I need to get the 1 but in other cases it will be a longer string. ``` re.search("\t_e\t(.*)\t_", string).group(1) ``` 9 times out of 10 that line returns the string/value i want but not always, just to be clear after the underscore it could be any a...
Try making the regex lazy by adding a `?` character after `*`, like so: ``` re.search("\t_e\t(.*?)\t_", string).group(1) ^ ``` This makes the `.*` match as little as possible until the next `\t` (and thus prevents `.` to eat up a `\t`).
Try this: ``` re.findall(r"(?s)(?<=\t)(.*?)(?=\t)", "\t_e\t1\t_") ``` output: ``` ['_e', '1'] ``` Basically, it is using positive lookahead and lookbehind assertion. Also, the `(?s)` sets the "dotall" flag, allowing it to match whitespace.
get string in between with python
[ "", "python", "regex", "tabs", "" ]
I have a regex like this `'^(a|ab|1|2)+$'` and want to get all sequence for this... for example for re.search(reg, 'ab1') I want to get ('ab','1') Equivalent result I can get with `'^(a|ab|1|2)(a|ab|1|2)$'` pattern, but I don't know how many blocks been matched with (pattern)+ Is this possible, and if yes - how?
Your original expression does match the way you want to, it just matches the entire string and doesn't capture individual groups for each separate match. Using a repetition operator ('+', '\*', '{m,n}'), the group gets overwritten each time, and only the final match is saved. This is alluded to in the [documentation](h...
try this: ``` import re r = re.compile('(ab|a|1|2)') for i in r.findall('ab1'): print i ``` The `ab` option has been moved to be first, so it will match `ab` in favor of just `a`. findall method matches your regular expression more times and returns a list of matched groups. In this simple example you'll get back...
Python regexp: get all group's sequence
[ "", "python", "regex", "" ]
i have this following code in python/Django ``` movie_obj = Movies.objects.all() //assume there are 2 movies for movie in movie_obj movie.genre //genre = models.CharField(max_length = 100, blank=True) ``` will print like ``` Drama, Sci-Fi, Thriller //genre of movie_1 Biography, Drama, Music...
``` >>> a = unicode('bla, blee, bla, blue') >>> a u'bla, blee, bla, blue' >>> a.split(', ') [u'bla', u'blee', u'bla', u'blue'] >>> set(a.split(', ')) set([u'blee', u'blue', u'bla']) ``` For each genre, you can split them on the coma, and then have a list to do what you want, then you can convert it into a set, if you'...
I don't understand your issue. But this should work: ``` genre_groups = Movies.objects.values_list('genre', flat = True) #output: ['Drama, Sci-Fi, Thriller', 'Biography, Drama, Music'] genres = [ agroup.split(",") for agroup in genre_groups ] #output: ['Drama', 'Sci-Fi', 'Thriller', 'Biography', 'Drama', 'Music'] genr...
python: How to create set out of unicode objects
[ "", "python", "" ]
> The ORDER BY clause is invalid in views, inline functions, derived > tables, subqueries, and common table expressions, unless TOP, OFFSET > or FOR XML is also specified. I am getting the above said error while trying to execute the following query. Can anyone please have a look and tell me what am I doing wrong here...
You do not need to use `ORDER BY` in inner query after `WHERE` clause because you have already used it in `ROW_NUMBER() OVER (ORDER BY VRDATE DESC)`. ``` SELECT * FROM ( SELECT Stockmain.VRNOA, item.description as item_description, party.name as party_name, stockmain.vrdat...
``` ORDER BY column OFFSET 0 ROWS ``` Surprisingly makes it work, what a strange feature. A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later: ``` ;WITH cte AS ( SELECT .....long select statement here.... ) SELECT * FROM ( SELECT * FROM ( -- necessary to nest ...
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions
[ "", "sql", "sql-server", "database", "sql-server-2012", "sql-query-store", "" ]
I want to return only one column from table. This is my DAO: ``` @SuppressWarnings("unchecked") public String getUri() { return sessionFactory.getCurrentSession() .createQuery("uri from Templates WHERE state=1").toString(); } ``` Uri is a column. Domain: ``` public String getUri(...
Your SELECT clause is missing: ``` @SuppressWarnings("unchecked") public String getUri() { Query q = sessionFactory.getCurrentSession() .createQuery("SELECT uri FROM Templates WHERE state=1"); List l = q.list(); //guess you know there's only one result? return l.g...
You need to use the class/field names, not the table/column names. Also, the query won't return a list of instances of your class for that table, but rather an array. Also, put a `select` in your query. I believe that exception means your hql is broken.
How to return only one column in Hibernate?
[ "", "sql", "spring", "hibernate", "" ]
When iterating through a dictionary, I want to skip an item if it has a particular key. I tried something like `mydict.next()`, but I got an error message `'dict' object has no attribute 'next'` ``` for key, value in mydict.iteritems(): if key == 'skipthis': mydict.next() # for others do some complicat...
Use [`continue`](http://docs.python.org/2/reference/simple_stmts.html#the-continue-statement): ``` for key, value in mydict.iteritems(): if key == 'skipthis': continue ``` Also see: * [Are `break` and `continue` bad programming practices?](https://softwareengineering.stackexchange.com/questions/58237/are...
I think you want to call `mydict.iteritems().next()`, however you should just filter the list before iterating. To filter your list, you could use a generator expression: ``` r = ((k, v) for k, v in mydict.iteritems() if k != 'skipthis') for k,v in r: #do something complicated to filtered items ``` Because t...
Skipping to Next item in Dictionary
[ "", "python", "python-2.7", "dictionary", "" ]
I wanted to remove 'a' tag (link) from all the images found. Hence for performance I made a list of all images in the html and look for wrapping a tag and simply remove the link. I am using BeautifulSoup and not sure what I am doing wrong, instead of removing the a tag it is removing the inside content. **This is wha...
The `unwrap()` function *returns the tag that has been removed*. The tree itself has been properly modified. Quoting from the [`unwrap()` documentation](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#unwrap): > Like `replace_with()`, `unwrap()` returns the tag that was replaced. In other words: it works correc...
I'm not sure what output you are looking for. Is this it? ``` from bs4 import BeautifulSoup html = '''<div> <a href="http://somelink"><img src="http://imgsrc.jpg" /></a> <a href="http://somelink2"><img src="http://imgsrc2.jpg" /></a> ''' soup = BeautifulSoup(html) for img in soup.find_all('img'): img.parent.unwr...
Unwrap "a" tag from image, without losing content
[ "", "python", "html-parsing", "beautifulsoup", "" ]
So, I'm trying to be a good Python programmer and duck-type wherever I can, but I've got a bit of a problem where my input is either a `dict` or a `list` of `dict`s. I can't distinguish between them being iterable, because they both are. My next thought was simply to call `list(x)` and hope that returned my list inta...
Really, there is no obvious pythonic way to do this, because it's an unreasonable input format, and the obvious pythonic way to do it is to fix the input… But if you can't do that, then yes, you need to write an adapter (as close to the input edge as possible). The best way to do that depends on the actual data. If it...
Accessing a `dict` using a non-`int` key will get you either an item, or a `KeyError`. It will get you a `TypeError` with a `list`. So you can use exception handling: ``` def list_dicts(dict_or_list): try: dict_or_list[None] return [dict_or_list] # no error, we have a dict except TypeError: ...
What's the pythonic way to distinguish between a dict and a list of dicts?
[ "", "python", "list", "dictionary", "" ]
so the code is intended to increase the value of count every time it meet the requirement of the if statement and in the end it gives the count of how many times one particular item has appeared in the list, here is the code ``` x = ["fizz", "fizz", "fizz"] def fizz_count(x): count = 0 for fizz in x: ...
You are returning from the for loop on the very first iteration, that is why you get `count = 1`. You should increment the `count` in loop, and return it at the end of the function. --- However, your for loop is not doing what you want it to do. It will not search for `fizz` in the list. The loop variable `fizz` will...
The issue here is that the `return` statement will exit out of the function, so you will only loop once, and always return `count + 1`, which is `0 + 1 = 1`. You can fix this by not returning `count+1`, but rather by returning the total: ``` def fizz_count(x): count = 0 for fizz in x: count = count+1 ...
for statement does not work as intended
[ "", "python", "for-loop", "" ]
I have a string that contains letters and punctuation. I'm trying to replace only the letters in this string with other letters. The function I have developed only works for strings that contain letters. If numbers are included it produces a logic error and if punctuation is included then it produces a run-time error. ...
For one, there are some faster/simpler ways of doing the shifting you want. But to answer your question, you could simply add: ``` if not letter.isalpha(): continue ``` `str.isalpha()` returns `True` if the string is composed only of alphabetic letters.
Try this one: ``` textObject = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." smalltext = 'abcde' alphabet = list(['a','b','c','d','e','f','g','h','i','j','k',...
How can I get a loop to ignore non-letter elements in a list?
[ "", "python", "string", "list", "function", "" ]
Currently developping a RPG, I'm asking how could I protect the saved data so that the player/user can't read or modify it easily. I mean yes a person that is experienced with computers and programming could modify it but I don't want the lambda user to be able to modify it, as easily as one could modify a plaintext xm...
It sounds like you need a cryptography library. This will help you encrypt or decrypt a file using a key. Good thing there is already one called PyCrypto. You can download it [here](http://www.voidspace.org.uk/python/modules.shtml#pycrypto). To use it, once you have downloaded it [It is documented here](http://pythonh...
Just `pickle` or `cpickle` a configuration object with the compression set to max is a quick and easy option.
Protecting a Save file from modification in a game?
[ "", "python", "pygame", "" ]
**Update:** Following @dtmilano's suggestion, I added ``` import sys print(sys.path) ``` to the beginning of my MonkeyRunner script. This results in ``` ['e:/path/android-sdk/tools/lib/monkeyrunner.jar:e:\\path\\bbct\\android\\functional-tests', 'E:\\path\\android-sdk\\tools\\lib\\Lib', '/E:/path/android-sdk/tools/l...
For your reference, the android SDK does appear to have a bug in it where the first item on sys.path is the monkeyRunner lib and the working directory mashed together. I added the following to fix. ``` import sys sys.path.append(sys.path[0].split(':',1)[1]) import util ```
You need to add the module to the search path (you are cwd is not in the same dir?) <http://docs.python.org/2/tutorial/modules.html> import sys sys.path.append('/path/to/your/module')
How does Python (or MonkeyRunner) locate imported modules?
[ "", "android", "python", "module", "monkeyrunner", "" ]
I use this python scripts: python2.6 and 2.7 ``` for i in xrange(1000000):print i ``` python3.3 ``` for i in range(1000000):print(i) ``` Results: python 2.7 ``` real 1m15.973s user 0m3.392s sys 0m6.384s ``` python 2.6 ``` real 1m15.860s user 0m3.064s sys 0m6.296s ``` With python 3.3 I test the scr...
There are several ways to benchmark Python programs. At least, I can come with two serious ways. You can find an expanded version of what I say in these slides [here](https://docs.google.com/file/d/0B2opoqYF5uR8U2dHOHpmdS1LNlE/). You also may benefit from this [video](http://pyvideo.org/video/1770/python-profiling) fro...
Use the [`timeit` module](http://docs.python.org/2/library/timeit.html) to compare small Python snippets. It avoids the common pitfalls, making timing values comparable. However, you are mostly timing write speed to `sys.stdout` when timing `print i` (and in Python 3, encoding to the terminal codec).
python 3.3 ,2.7 and 2.6 - benchmark inconsistent results. how fix that?
[ "", "python", "" ]
I am trying to print this code but I keep getting errors when I use the print command in Python 2.7 So I pretty much understand how the interpreter reads and executes this program. What would be the ideal location to put *"print s"* to see the results on the screen? Thank you very much. ``` n = raw_input('input ...
From my experience, you probably want something closer to this: ``` def f(n): if n==0: return 1 else: m = f(n-1) s = n * m return s if __name__ == '__main__': n = raw_input('input an integer value to compute its factorial:\n') n = int...
I'd move the definition of `f` to the top, above your call to `raw_input`. Then at the very end, you can call `f` with `n` and print the result: ``` print f(n) ``` If you wanted to, you could store the result in a variable, although there's no advantage here: ``` result = f(n) print result ```
How to print out the results:
[ "", "python", "python-2.7", "" ]
when connecting to mysql database in Django ,I get the error. 1. I'm sure mysql server is running. 2. /var/run/mysqld/mysqld.sock doesn't exist. 3. When I run `$ find / -name *.sock -type s`, I only get /tmp/mysql.sock and some other irrelevant output. 4. I added `socket = /tmp/mysql.sock` to /etc/my.cnf. And then res...
Use "127.0.0.1", instead of "localhost" ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } } ```
For me this worked add OPTIONS attribute with read\_default\_file and give it the path of my.cnf file ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbname', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', '...
OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
[ "", "python", "mysql", "django", "mysql.sock", "" ]
I have a list of lists that contains users and scores as follows: ``` [["user1", 100], ["user2", 234], ["user3", 131]...] ``` I want to produce a list that sorts the users by score in declining order: ``` [["user2", 234], ["user3", 131], ["user1", 100]...] ``` How might I go about doing this kind of sort?
``` >>> li = [["user1", 100], ["user2", 234], ["user3", 131]] >>> >>> import operator >>> >>> sorted(li, key=operator.itemgetter(1)) # Ascending order [['user1', 100], ['user3', 131], ['user2', 234]] >>> sorted(li, key=operator.itemgetter(1), reverse=True) # Reverse Sort [['user2', 234], ['user3', 131], ['user1',...
You can custom the sort behaviour by pass a key and reverse. `sorted` will return a new list. If in-place sort wanted, use `list.sort`. ``` >>> a = [["user1", 100], ["user2", 234], ["user3", 131]] >>> sorted(a, key=lambda x: x[1], reverse=True) [['user2', 234], ['user3', 131], ['user1', 100]] ```
Sort a list of lists by an item in the sublist
[ "", "python", "list", "sorting", "" ]
I think this should be a simple question... but it's been holding me up for some time now :( I wish to create a list of numbers, centred (as it were) on zero, from an input that specifies the maximum and the increment. So, ``` max = 100 increment = 1 ``` would return ``` [-100,-99,-98,...,-1,0,1,...,99,100] ``` an...
If you want it to be strictly mirrored around `0`, (i.e. always include 0 and the endpoints, and be perfectly symmetric about 0) you'll need a couple of steps. First off, be aware of @NPE's comment above. Floating point math is not the same as decimal math!! This may seem beside the point, but it *will* bite you in ce...
It is quite easy using [`numpy.arange`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html): ``` >>> import numpy as np >>> max_val = 100 >>> increment = 1 >>> a = np.arange(start=-max_val, stop=max_val+increment, step=increment) >>> print a array([-100, -99, -98, -97, -96, -95, -94, -93, -9...
Create list of numbers mirrored around zero (python)
[ "", "python", "list", "numpy", "" ]
I'm trying to figure out how to combine these two queries. ``` SELECT `o`.`Order_ID` FROM `Orders` `o` JOIN `CustomerDetails` `cd` ON `cd`.`Customer_ID` = `o`.`Customer_ID` WHERE `o`.`OrderPlaceServerTime` >= '2013-06-01 00:00:00' AND `o`.`OrderPlaceServerTime` <= '2013-06-31 23:59:59' AND `cd`.`SalesRep_ID` = 6 ``` ...
A solution with proper `UPDATE` syntax with `JOIN` for MySql ``` UPDATE Orders o JOIN CustomerDetails d ON d.Customer_ID = o.Customer_ID SET o.SalesRep_ID = 6 WHERE o.OrderPlaceServerTime >= '2013-06-01 00:00:00' AND o.OrderPlaceServerTime <= '2013-06-31 23:59:59' AND d.SalesRep_ID = 6 ``` Here is **[S...
You can do it in a single query by just simply combining them: ``` UPDATE Orders SET SalesRep_ID = '6' WHERE Order_ID IN ( SELECT `o`.`Order_ID` FROM `Orders` `o` JOIN `CustomerDetails` `cd` ON `cd`.`Customer_ID` = `o`.`Customer_ID` WHERE `o`.`OrderPlaceServerTime` >= '2013-06-01 00:00:00' AND `o`.`...
Update multiple rows from results from a SELECT query to the same table
[ "", "mysql", "sql", "" ]
I'm new to python (and programming in general) and I can't seem to find a solution to this by myself. I want to check the first letter of a string is equal to any letter stored in an array, something like this: ``` letter = ["a", "b", "c"] word = raw_input('Enter a word:') first = word[0] if first == letter: prin...
You need to use the `in` operator. Use `if first in letter:`. ``` >>> letter = ["a", "b", "c"] >>> word = raw_input('Enter a word:') Enter a word:ant >>> first = word[0] >>> first in letter True ``` And one False test, ``` >>> word = raw_input('Enter a word:') Enter a word:python >>> first = word[0] >>> first in let...
The hint is in your question. Use [`any`](http://docs.python.org/2/library/functions.html#any). This uses a generator expression to check if it is True or False. ``` any(first == c for c in letter) ```
Checking if a value is equal to any value in an array
[ "", "python", "" ]
I have a text file containing simulation data (60 columns, 100k rows): ``` a b c 1 11 111 2 22 222 3 33 333 4 44 444 ``` ... where in the first row are variable names, and beneath (in columns) is the corresponding data (float type). I need to use all these variables with their data in Python for further cal...
Instead of trying to assign names, you might think about using an [associative array](http://en.wikipedia.org/wiki/Associative_array), which is known in Python as a [`dict`](http://docs.python.org/3/library/stdtypes.html#mapping-types-dict), to store your variables and their values. The code could then look something l...
The answer is: **you don't want to do that**. Dictionaries are designed for exactly this purpose: the data structure you *actually* want is going to be something like: ``` data = { "a": [1, 2, 3, 4], "b": [11, 22, 33, 44], "c": [111, 222, 333, 444], } ``` ... which you can then easily access using e.g. `...
Importing data and variable names from a text file in Python
[ "", "python", "variables", "dynamic", "variable-assignment", "genfromtxt", "" ]
Using python and argparse, the user could input a file name with -d as the flag. ``` parser.add_argument("-d", "--dmp", default=None) ``` However, this failed when the path included spaces. E.g. ``` -d C:\SMTHNG\Name with spaces\MORE\file.csv ``` NOTE: the spaces would cause an error (flag only takes in 'C:SMTHNG\N...
Simple solution: argparse considers a space filled string as a single argument if it is encapsulated by quotation marks. This input worked and "solved" the problem: ``` -d "C:\SMTHNG\Name with spaces\MORE\file.csv" ``` NOTICE: argument has "" around it.
For those who can't parse arguments and still get "error: unrecognized arguments:" I found a workaround: ``` parser.add_argument('-d', '--dmp', nargs='+', ...) opts = parser.parse_args() ``` and then when you want to use it just do ``` ' '.join(opts.dmp) ```
Handle spaces in argparse input
[ "", "python", "command-line-arguments", "user-input", "argparse", "spaces", "" ]
I have a variable "myvar" that when I print out its `type(myvar)` the output is: ``` <class 'my.object.kind'> ``` If I have a list of 10 variables including strings and variables of that kind.. how can I construct an if statement to check whether an object in the list "mylist" is of `<type 'my.object.kind'>`?
Use [`isinstance`](http://docs.python.org/3/library/functions.html#isinstance), this will return true even if it is an instance of the subclass: ``` if isinstance(x, my.object.kind) ``` Or: ``` type(x) == my.object.kind #3.x ``` If you want to test all in the list: ``` if any(isinstance(x, my.object.kind) for x in...
``` if any(map(lambda x: isinstance(x, my.object.kind), my_list_of_objects)): print "Found one!" ```
How to check if variable is a specific class in python?
[ "", "python", "" ]
I apologize for asking such a noobish question, but I'm having an issue writing a very basic program in Python to check whether or not a number is prime. Here's my code: ``` def is_prime(x): if x < 2: print ('Please enter a number >= 2.') else: if x == 2 or x == 3 or x == 5: return...
Your code just checks for `num % 2` and returns `True` or `False` depending on the result. So, it returns `True` for all odd numbers. You should just `return True` if the loop does not encounter a `return False`, see the code. ``` def is_prime(x): if x < 2: print ('Please enter a number >= 2.') else: ...
Checking if a number is prime (efficiently) is a really hard task to accomplish, since the primes don't really follow any distinct patterns: <http://en.wikipedia.org/wiki/Primality_test> In your code, which is the most intuitive (but inefficient) algorithm, you make the mistake of returning `true` as soon as you see t...
Having issues with an is_prime(x) program in Python?
[ "", "python", "" ]
I've got (e.g.) the following MySQL row: ``` firstname | lastname | anotherCol1 | anotherCol2 | anotherCol3 -------------------------------------------------------------- John | Smith | Football | Fast cars | 18 Fools ``` and for instance the following strings: ``` oh, xxx, foo, 41 ``` I am looking for...
A possible solution ``` SELECT q.keyword FROM Table1 t CROSS JOIN ( SELECT 'oh' keyword UNION ALL SELECT 'xxx' UNION ALL SELECT 'foo' UNION ALL SELECT '41' ) q WHERE INSTR(CONCAT_WS(' ', firstname, lastname, anotherCol1, ...
If your table is `MyISAM`, you can make use of [Full-Text Search](http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html) Create an `index` on your table with the following command: ``` ALTER TABLE <TABLE_NAME> ADD FULLTEXT(firstname, lastname, anotherCol1, anotherCol2, anotherCol3 ); ``` Now, run your queries ...
MySQL: Given a row and multiple strings. Find the string(s) that are contained in the row
[ "", "mysql", "sql", "database", "select", "" ]
If I explain what I think I am doing, I hope someone can explain where I am going wrong. I have the following dictionary: ``` ls = [{ 'The Wolf Gift (13)': { 'cover': 'V:\\Books\\Anne Rice\\The Wolf Gift (13)\\cover.jpg', 'author': 'Anne Rice', 'year': '1988' }, 'Mummy (14)': { ...
It's a list containing a single dictionary. You can do something like: ``` >>> books = ls[0] >>> for book, details in books.iteritems(): print book,'-->', details['cover'] ... Mummy (14) --> V:\Books\Anne Rice\Mummy (14)\cover.jpg The Wolf Gift (13) --> V:\Books\Anne Rice\The Wolf Gift (13)\cover.jpg ```
Her is an example that could be used if `ls` contained more than one dictionary. ``` for dic in ls: for key in dic: print 'Book Name: %s' % (key) for value in dic[key]: print '\t%s: %s' % (value, dic[key][value]) ``` This will produce the following output: ``` Book Name: Mummy (14) ...
Python - Looping through a multidimensional dictionary
[ "", "python", "python-2.7", "" ]
Say I have two tables: Table 1: ``` number 1 2 3 ``` and Table 2: ``` letter a b c d e f g ``` how can i produce ``` number letter a 1 a 2 a 3 b 1 b 2 b 3 c 1 c 2 c 3 ``` all the way to g -...
While the query suggested like: ``` SELECT number, letter FROM Table1, Table2 ``` will work the same, and even might look simpler - [DON'T USE IT.](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) It is an old style syntax outdated more then 20 years ago with the introduction of ANSI-92 standa...
Cross join: ``` select Table1.number, Table2.letter from Table1 CROSS JOIN Table2 ```
SQL Joining Values to A Set Of Values
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Coming from a file I have something like the following string: ``` var1 : data1 var2 : data2 dict1 { var3 : data3 dict2 { var4 : data4 } var5 : data5 } dict3 { var6 : data6 var7 : data7 } ``` and so on. (end of lines are \n, indents are \t each) And I try to convert it...
``` import re # key : value regexp KV_RE = re.compile(r'^\s*(?P<key>[^\s]+)\s+:\s+(?P<value>.+?)\s*$') # dict start regexp DS_RE = re.compile(r'^\s*(?P<key>[^\s]+)\s+{\s*$') # dict end regexp DE_RE = re.compile(r'^\s*}\s*$') def parse(s): current = {} stack = [] for line in s.strip().splitlines(): ...
your format is close enough to the yaml one (easy\_install pyyaml): <http://pyyaml.org/wiki/PyYAML> ``` x = """var1 : data1 var2 : data2 dict1 { var3 : data3 dict2 { var4 : data4 } var5 : data5 } dict3 { var6 : data6 var7 : data7 }""" x2 = x.replace('{', ':').replace('}'...
Python: How do I parse a string into a recursive dictionary
[ "", "python", "python-2.7", "" ]
I have a list of dicts that looks like this: ``` [{TYPE, OBJECT_ID, ACTOR, EXTRA_FIELDS}, ...] ``` I'd like to go through and aggregate the duplicates of {TYPE, OBJECT\_ID} and make ACTOR a list so: start with: ``` [ {'type': 'LOVE', 'obj_id': 1242, 'actor': 'bob', {..}}, {'type': 'LOVE', 'obj_id': 1242, ...
Here's how I'd do it: ``` def merge_dicts(list_of_dicts): lookup = {} results = [] for d in list_of_dicts: key = (d['type'], d['obj_id']) try: # it's easier to ask forgiveness than permission lookup[key]['actor'].append(d['actor']) except KeyError: val = {'ty...
Assuming that `input` is the list of tuples (not sets), what about ``` TYPE= 0 OBJECT_ID= 1 ACTOR= 2 EXTRA_INFO= 3 keys= set( [ ( e[TYPE] , e[OBJECT_ID] ) for e in input ] ) output= { k: [ ( e[ACTOR] , e[EXTRA_INFO] ) for e in input if ( e[TYPE] , e[OBJECT_ID] ) == k ] for k in keys } ``` Or, if you like one-liners: ...
Grouping data in a list of of dicts
[ "", "python", "" ]
I am trying to write a code that would analyze if a word is a palindrome. BTW a palindrome is a word that is read the same backward and forward. Example are "madam" or "noon" Here is a try: ``` x = raw_input("please enter a word:\n") L = len(x) # this part returns the first letter of the word def first(word): ...
Personally, I would prefer separating the check and the output. So `is_palindrome()` should just return the answer and not be responsible for telling the user. That makes it more reusable. ``` def is_palindrome(word): # handle the base case if len(word) <= 1: return True elif first(word) != last(wo...
To accomplish your goal, why don't just use: ``` string[::-1] == string ``` And the reason for your answer is when there is only 1 letter, `middle` will return an empty string and then `''[0]` will cause the error.
Recursive Program: What am I doing wrong?
[ "", "python", "python-2.7", "recursion", "" ]
Hello everyone i am new here so please be kind. I have been using scapy lately in order to send and recieve ipv6 packets to selected ipv6 enabled servers. The gist of the code is here: ``` text = line[:-1] #destination=getIPv6Addr(line[:-1]) destination="2607:f1c0:1000:60e0:7992:97f7:61b2:2814...
The ethernet adapter indeed has both an IPv6 address and a default gateway. You could * Try to `ping -6 ipv6.google.com` to see if there is any IPv6 connectivity. I think there must be, since I can ping your IPv6 address just fine, unless it has been reassigned to somebody else now. * Inspect the routing tables to see...
I observed that in "layers/inet6.py" there is function call to getmacbyip6, in which they are trying to get the interface info based on the scapy routing table. ``` iff,a,nh = conf.route6.route(ip6, dev=conf.iface6) ``` As conf.iface6 is set to "lo" by default it always return loopback interface. ``` iff,a,nh = conf...
Scapy fails to send ipv6 packets
[ "", "python", "http", "ipv6", "wireshark", "scapy", "" ]
I'm writing a Python program for running user-uploaded arbitrary (and thus, at the worst case, unsafe, erroneous and crashing) code on a Linux server. The security questions aside, my objective is to determine, if the code (that might be in any language, compiled or interpreted) writes the correct things to `stdout`, `...
Have you noticed that raw\_input writes the prompt string into stderr if stdout is terminal (isatty); if stdout is not a terminal, then the prompt too is written to stdout, but stdout will be in fully buffered mode. **With stdout on a tty** ``` write(1, "Hello.\n", 7) = 7 ioctl(0, SNDCTL_TMR_TIMEBASE...
Pexpect worked for me In your case here's what you could do : ``` import pexpect import time # Start the other program child = pexpect.spawn("python your_program.py", encoding='utf-8', timeout=None) while True: #pexpect will "wait" until this line is displayed in the child program #so if you know what will ...
Detecting when a child process is waiting for input
[ "", "python", "linux", "subprocess", "pty", "unbuffered-output", "" ]
I have this query, which returns days of the week. The days of the week are 0-6(Mon-Fri). ``` select ID, DayOfWeek from MyTable ID DayOfWeek 1 0 2 0 3 4 ``` Is there a way to substitute an alias for each int DayOfWeek? The enum isn't stored in the database so I can't join. I want to be able to write ...
You should consider storing the lookup in a new table... but just so you're aware of your options, you can also use the [`DATENAME(WEEKDAY)`](http://technet.microsoft.com/en-us/library/ms174395.aspx) function: ``` SELECT DATENAME(WEEKDAY, 0) ``` Returns: ``` Monday ``` [SQL Fiddle](http://sqlfiddle.com/#!3/6ca74/2)
If you can't store a table to join on, you can use a `CASE`: ``` SELECT ID, CASE DayOfWeek WHEN 0 THEN 'Monday' WHEN 1 THEN 'Tuesday' ... END AS DayOfWeek FROM MyTable ```
How to replace an int with text in a query
[ "", "sql", "sql-server", "" ]
There is this code: ``` class MyException(Exception): pass def gen(): for i in range(3): try: yield i except MyException: print("MyException!") a = gen() next(a) a.throw(MyException) ``` Running this code: ``` $ python3.3 main.py MyException! $ python3.3 main.py MyException! Exception Typ...
You are seeing a `__del__` hook misbehaving somewhere. The `TypeError` is being thrown while *shutting down*, as the Python interpreter is exiting everything is deleted and any exceptions thrown in a `__del__` deconstructor hook are being ignored (but *are* printed). On exit, Python clears everything in the namespace...
I was having this same error in Python 3.3 on Windows, with the difference that I was defining the exception in its own file. These were my code files: ``` $ cat FooError.py class FooError(Exception): pass $ cat application.py import FooError try: raise FooError('Foo not bar!') Except FooError as e: prin...
Exception TypeError warning sometimes shown, sometimes not when using throw method of generator
[ "", "python", "python-3.x", "exception", "generator", "" ]
I have an xml file I need to open and make some changes to, one of those changes is to remove the namespace and prefix and then save to another file. Here is the xml: ``` <?xml version='1.0' encoding='UTF-8'?> <package xmlns="http://apple.com/itunes/importer"> <provider>some data</provider> <language>en-GB</langua...
Replace tag as Uku Loskit suggests. In addition to that, use [lxml.objectify.deannotate](http://lxml.de/objectify.html#xml-schema-datatype-annotation). ``` from lxml import etree, objectify metadata = '/Users/user1/Desktop/Python/metadata.xml' parser = etree.XMLParser(remove_blank_text=True) tree = etree.parse(metada...
We can get the desired output document in two steps: 1. Remove namespace URIs from element names 2. Remove unused namespace declarations from the XML tree **Example code** ``` from lxml import etree input_xml = """ <package xmlns="http://apple.com/itunes/importer"> <provider>some data</provider> <language>en-GB...
Remove namespace and prefix from xml in python using lxml
[ "", "python", "xml", "namespaces", "lxml", "" ]
So currently, my code looks like this (thanks to help in another post I made) ``` phrase = raw_input("Enter text to Cipher: ") shift = int(raw_input("Please enter shift: ")) result = ("Encrypted text is: ") for character in phrase: #Loops through phrase and shows ascii numbers, example: hello is: 104,101,108,10...
You can just skip the space: ``` for character in phrase: x = ord(character) if character == ' ': result += ' ' else: result += chr(x + shift) ``` Your shift won't restrict the output to just ASCII. If you want to ensure that, you should use the modulo operator: ``` chr(32 + (x + shift) ...
You can add a space like this: ``` if character.isspace(): result += ' ' ``` or split the string at white-spaces: **Example:** ``` >>> "hello world".split() ['hello', 'world'] ``` **code:** ``` new_strs = [] result = ("Encrypted text is:") for word in phrase.split(): new_word = [] for character in wo...
Caesar Cipher Python - Additional Features
[ "", "python", "ascii", "shift", "" ]
I have an objects ``` >>> L[0].f.items() dict_items([('a', 1)]) >>> a3.f.items() dict_items([('a', 1), ('c', 3)]) ``` I want to test if L[0].f.items() is a subset of a3.f.items(). So I did the following: ``` >>> L[0].f.items() in a3.f.items() False ``` But I expect that L[0].f.items() is a subset of a3.f.items(). W...
You can make sets from the lists and see if one set is a subset of another: ``` >>> list1 = [('a', 1), ('c', 3)] >>> list2 = [('a', 1)] >>> set(list2).issubset(list1) True ``` Or, in your case: ``` set(L[0].f.items()).issubset(set(a3.f.items())) ```
`in` tests whether the left operand is an element of the right. Since dict item views are set-like, you want `<=`, which tests whether one is a subset of another: ``` >>> L[0].f.items() <= a3.f.items() True ``` If you want to do this with lists or other non-set-like iterables, you can build a set out of one and use `...
How to check if a dictionary is in another dictionary in python
[ "", "python", "python-3.x", "dictionary", "" ]
As an intellectual challenge, I'm trying to do what is described in the title. I am stuck, and wondering if anyone had any helping ideas..? ``` def main(): my_list = [1,2,3,4,5,6,3,4,63,3] sort(my_list) def sort(my_list): n=0 m=1 for number in my_list: if my_list[n] < my_list[m]: ...
There are many sorting algorithms, such as `bubble`, `quick sort` and so on, and here is a reference <http://www.sorting-algorithms.com/>, you can implement any of them according to the descriptioin. The following is bubble sort ``` def main(): my_list = [1,2,3,4,5,6,3,4,63,3] sort(my_list) def sort(my_list)...
*Most* python implementations use the [`mergesort` algorithm](http://en.wikipedia.org/wiki/Merge_sort)1. A quick google search will turn up an implementation, but the algorithm is simple enough that it's worth trying to code it yourself. 1 (Actually, they use Tim sort which is a hybrid between mergesort and insertion...
Sorting A List From Least to Greatest Without list.sort( )
[ "", "python", "list", "sorting", "" ]
I am writing the output of a function to a file, how ever if the number that is written has an e+01 at the end it writes one of the numbers on to the next line. for example ``` 0.12605695 1.64761066 1.55001798 0.01785089 15.80005801 0.12231149 1.65899943 1.56369755 0.01511221 10.45653689 0.1238494 1...
This was the answer, I just didnt realize it was a numpy array. ``` kop=open('new.txt', 'w') results=PCA(kk) res=results.mu res=np.ndarray.tolist(res) print results.mu kop.write(str(res)+'\n') kop.close() ```
Assuming `results.mu` is something that can be iterated like a normal list, this snippet should do what you need by utilizing the [`csv` module](http://docs.python.org/2/library/csv.html): ``` import csv with open('new.txt', 'w') as f: writer = csv.writer(f, delimiter="\t") writer.writerows(results.mu) ```
writing results to a file, some go on to the next line. python
[ "", "python", "" ]
I want to check if a boolean is true, then decide in the WHERE clause what condition to use. Say the boolean variable is @checkbool: ``` SELECT * FROM TableA A WHERE --if @checkbool is true, run this A.Id = 123 --if @checkbool is false, run this A.Id <> 123 ``` Is there a way to negate a condition? ...
SQL's equivalent of `!` in C is `NOT`. However, in your case you want something else: you need to build a condition that decides between the two choices based on the value of `@checkbool`, like this: ``` SELECT * FROM TableA A WHERE ( (@checkbool) AND (A.Id = 123)) OR ((NOT @checkbool) AND (A.Id <> 123)) ```
Here is one solution: ``` IF @Checkbool = 1 SELECT * FROM Table A WHERE A.Id = 123 ELSE SELECT * FROM Table A WHERE A.Id <> 123 ``` Here is another using just the WHERE Clause: ``` SELECT * FROM Table A WHERE (@Checkbool = 1 AND A.Id = 123) OR (@Checkbool = 0 AND A.Id <> 123) ``` Everythi...
SQL: Can I negate a condition in a where clause?
[ "", "sql", "conditional-statements", "where-clause", "" ]
I was just wondering how I could find out what the last character of the user input was using Python. I need to know whether it was an S or not. Thanks in advance.....
You can use the built-in function [`str.endswith()`](http://docs.python.org/2/library/stdtypes.html#str.endswith): ``` if raw_input('Enter a word: ').endswith('s'): do_stuff() ``` Or, you can use [Python's Slice Notation](https://stackoverflow.com/questions/509211/the-python-slice-notation): ``` if raw_input('En...
Use [`str.endswith`](http://docs.python.org/2/library/stdtypes.html#str.endswith): ``` >>> "fooS".endswith('S') True >>> "foob".endswith('S') False ``` help on `str.endswith`: ``` >>> print str.endswith.__doc__ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwi...
Python: Last character of user input
[ "", "python", "input", "" ]
I have a table like: ``` create table myTab( id integer primary key, is_available boolean not null default true ); ``` I need to do a query that returns only the first encountered row that has `is_available` set to false.
something like ``` select * from myTab where not is_available order by id asc limit 1 ```
Alternatively, you could use `NOT EXISTS` to find the *first* tuple, in most cases this is the fastest solution, too: ``` SELECT * FROM myTab mt WHERE mt.is_available = False AND NOT EXISTS ( SELECT * FROM myTab nx WHERE nx.is_available = False AND nx.id < mt.id ); ```
Return only one row of a select that would return a set of rows
[ "", "sql", "postgresql", "sql-limit", "" ]
``` if n == 1: return [(-1,), (1,)] if n == 2: return [(-1,0), (1,0), (0,-1), (0,1)] if n == 3: return [(-1,0,0), (1,0,0), (0,-1,0), (0,1,0), (0,0,-1), (0,0,1)] ``` Basically, return a list of `2n` tuples conforming to the above specification. The above code works fine for my purposes but I'd like to see a fu...
``` def faces(n): def iter_faces(): f = [0] * n for i in range(n): for x in (-1, 1): f[i] = x yield tuple(f) f[i] = 0 return list(iter_faces()) ``` --- ``` >>> faces(1) [(-1,), (1,)] >>> faces(2) [(-1, 0), (1, 0), (0, -1), (0, 1)] >>> fac...
``` [tuple(sign * (i == p) for i in range(n)) for p in range(n) for sign in (-1, 1)] ``` Plain `for`, no implicit `bool`→`int` equivalent: ``` for p in range(n): for sign in (-1, 1): yield tuple((sign if i == p else 0) for i in range(n)) ```
What is the pythonic way of generating this type of list? (Faces of an n-cube)
[ "", "python", "list", "geometry", "tuples", "" ]
I am facing problem with sorting according to AM / PM. Here is my table data ``` login_time 1:30 PM 2:00 AM 8:00 AM 9:30 PM 10:00 PM 11:10 AM ``` I want result as: ``` login_time 2:00 AM 8:00 AM 11:10 AM 1:30 PM 9:30 PM 10:00 PM ``` How can I do this?
You could use [STR\_TO\_DATE](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date) function, and you could also extract only the time part with [TIME()](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_time) if you wish: ``` SELECT login_time FROM ta...
If you already have your date as a `VARCHAR`, I suggest you to refactor that to a `TIME` column. This could be easily done online: ``` UPDATE tablename SET login_time = STR_TO_DATE(login_time, '%l:%i %p'); ALTER TABLE tablename CHANGE login_time login_time TIME; ``` I use the type `TIME` here since your data *apparen...
How to sort time ( In AM / PM ) in SQL?
[ "", "mysql", "sql", "" ]
I know this is a really bad description but how can i get this to work: ``` class Test1(): def test_p1(): print("This is part 1 of Test1") def Test2(): return test_p1() ``` Thanks in advance!
Well, there are several options. The most basic are: ## Create instance first ``` class Test1(): def test_p1(self): print("This is part 1 of Test1") def Test2(): return Test1().test_p1() ``` However, you should use it when having new instance makes sense (depends on your API). ## Make it class met...
Tadeck gave a detailed answer while I was typing mine, but here is my initial solution to what I believe you are trying to accomplish. I'm adding my input simply because I'm new to Python and I think a beginner's perspective may be beneficial for OP. ``` class Test1(): def test_p1(self): print "This is part 1 ...
how to return a function in a different class in python 3.3
[ "", "python", "function", "" ]
I have the following query: ``` profiles = session.query(profile.name).filter(and_(profile.email == email, profile.password == password_hash)) ``` How do I check if there is a row and how do I just return the first (should only be one if there is a match)?
Use [`query.one()`](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.one) to get one, and *exactly* one result. In all other cases it will raise an exception you can handle: ``` from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound try: user...
You can use the [`first()`](http://docs.sqlalchemy.org/en/rel_0_8/orm/query.html#sqlalchemy.orm.query.Query.first) function on the Query object. This will return the first result, or None if there are no results. ``` result = session.query(profile.name).filter(...).first() if not result: print 'No result found' `...
Getting first row from sqlalchemy
[ "", "python", "sqlalchemy", "flask", "flask-sqlalchemy", "" ]
I have a file containing duplicate timestamps, maximum two for each timestamp, actually they are not duplicate, it is just the second timestamp needs to add a millisecond timestamp. For example, I am having these in the file, ``` .... 2011/1/4 9:14:00 2011/1/4 9:15:00 2011/1/4 9:15:01 2011/1/4 9:15:01 2011...
Setup ``` In [69]: df = DataFrame(dict(time = x)) In [70]: df Out[70]: time 0 2013-01-01 09:01:00 1 2013-01-01 09:01:00 2 2013-01-01 09:01:01 3 2013-01-01 09:01:01 4 2013-01-01 09:01:02 5 2013-01-01 09:01:02 6 2013-01-01 09:01:03 7 2013-01-01 09:01:03 8 2013-01-01 09:01:04 9 2013-01-01 09:01:04 ``` ...
So this algorithm should work very well... I'm just having a hell of a time with numpy's datetime datatypes. ``` In [154]: df Out[154]: 0 0 2011/1/4 9:14:00 1 2011/1/4 9:15:00 2 2011/1/4 9:15:01 3 2011/1/4 9:15:01 4 2011/1/4 9:15:02 5 2011/1/4 9:15:02 6 2011/1/4 9:15:03 7 2011/1/4 9:15:03 8 ...
Python pandas change duplicate timestamp to unique
[ "", "python", "duplicates", "pandas", "" ]
I have table like ``` table_id item_id vendor_id category_id 1 1 33 4 2 1 33 4 3 1 33 2 4 2 33 4 5 2 33 2 6 3 33 4 7 3 33 4 ...
### Please always take backup before running any deletion query. Try using `LEFT JOIN` like this: ``` DELETE my_table FROM my_table LEFT JOIN (SELECT MIN(table_id) AS IDs FROM my_table GROUP BY `item_id`, `vendor_id`, `category_id` )A ON my_table.table_id = A.IDs WHERE A.ids IS NULL; ``` Result after...
What about this: ``` DELETE FROM my_table WHERE table_id NOT IN (SELECT MIN(table_id) FROM my_table GROUP BY item_id, vendor_id, category_id) ```
Deleting duplicate entries with search criteria
[ "", "mysql", "sql", "duplicates", "" ]
I wanted to start by asking here about this. This was given to me as part of an exercise at codeacademy.com and confused me for the better part of an hour. Take a look at the following code block: ``` bool_one = 40 / 20 * 4 >= -4**2 ``` Now, I evaluated that as being "8 >= 16" which is False. However, the codeacade...
If you have -4 without parentheses, the negative sign is considered a unary operator which is essentially "multiply by negative one." `(-4)**2` will be 16, because that is actually negative 4 squared, but `-4**2` uses the normal order of operations (exponentiation before multiplication) and treats it as `-(4**2)`. Hop...
From the doc of [Power Operator](http://docs.python.org/2/reference/expressions.html#the-power-operator): > The power operator binds more tightly than unary operators on its > left; it binds less tightly than unary operators on its right. The > syntax is: > > ``` > power ::= primary ["**" u_expr] > ``` > > Thus, in a...
Need some clarification on the ** operator in Python
[ "", "python", "operators", "" ]
So I have a string which is converted into a dictionary called test and takes the form: ``` {"a":"1","b":"2","c":"3"} ``` Now while creating the dictionary, the availablilty of the `"c":"3"` key-pair, depends on a some condition; so there are cases when the dictionary simply reads as: ``` {"a":"1","b":"2"} ``` I ha...
Use `in` to check if the key is in the dictionary: ``` if "c" in test: ... ```
Instead of `test['c']` try to use `test.get('c')`
If conditions for Python dictionaries
[ "", "python", "if-statement", "dictionary", "" ]
Im trying to join three tables in the following format. ``` select * from A inner join B (inner join (C on C.id=B.c_id)) on A.id=B.a_id; ``` Ive never used a lookup table to perform a join (in this case B). Oracle throws an error saying ``` ORA-00905: missing keyword 00905. 00000 - "missing keyword" *Cause: ...
Rather try something like ``` SELECT * FROM A INNER JOIN B ON A.id = B.a_id INNER JOIN C ON C.id = B.c_id ```
It should be written like this, which is clearer: ``` select * from A inner join B on A.id=b.a_id inner join C on C.id=B.c_id ``` You can see how this shows the intent of your statement (the join clause is very explicit about how you want to join the tables) Vs joining 2 tables by expressing the join condition in ...
Am I doing this join right? Three way table join
[ "", "sql", "oracle", "inner-join", "" ]
I've got a small problem. I've written a module to parse a configuration file (wvdial's wvdial.conf) using regex. File contains strings like `"Init1 = AT"` and I've used a following regex: ``` match = re.match(r'(.*)=(.*)', line) ``` Everything worked until following line: ``` #Init3 = AT+CPIN="0000" ``` Which got ...
You need to mark your first `*` quantifier as non-greedy by appending `?`: ``` match = re.match(r'(.*?)=(.*)', line) ``` Demo: ``` >>> line = '#Init3 = AT+CPIN="0000"' >>> re.match(r'(.*?)=(.*)', line).group() '#Init3 = AT+CPIN="0000"' ``` By making the quantifier non-greedy, the regular expression engine will matc...
No python re doesn't parse from right to left **but** .\* is by default *greedy* it will look for the longest match it can get, you can get your regex to work in a couple of ways easiest is: ``` re.match(r'([^=]+)=(.*)', line) ``` This will match anything but = as the first part of the match then = then anything afte...
Python re.search - searching from left to right
[ "", "python", "regex", "parsing", "" ]
``` global $wpdb; $sql = "SELECT * FROM $wpdb->postmeta"; $sql .= " INNER JOIN $wpdb->posts ON $wpdb->postmeta.post_id = $wpdb->posts.ID"; $sql .= " WHERE $wpdb->posts.post_type = 'task'"; $sql .= " AND $wpdb->posts.post_parent IN ( SELECT `ID` FROM $wpdb->posts WHERE `post_type` = 'task_list' AND `post_parent` IN ( S...
``` "ORDER BY CASE WHEN CAST( $wpdb->postmeta.meta_value AS DATE ) '' THEN 1 ELSE 0 END,CAST( $wpdb->postmeta.meta_value AS DATE )ASC, $wpdb->posts.ID ASC"; ```
You can add the function isnull to your order by clause: ``` $sql .= " ORDER BY $wpdb->posts.ID ASC, ISNULL($wpdb->postmeta.meta_value),CAST( $wpdb->postmeta.meta_value AS DATE ) ASC"; ```
ORDER BY date ASC placing records with no dates before records with dates?
[ "", "mysql", "sql", "wordpress", "" ]
``` SELECT alert, (select created_at from alerts WHERE alert = @ALERT ORDER BY created_at desc LIMIT 1) AS latest FROM alerts GROUP BY alert; ``` I am having an issue with the above query where I would like to pass in each alert into the subquery so that I have a column called latest which displays the...
If you are trying to get the latest created\_at date for each group of alerts, there is a simpler way. ``` SELECT alert, max (created_at) AS latest FROM alerts GROUP BY alert; ```
This is called a correlated subquery. To make it work, you need table aliases: ``` SELECT a1.alert, (select a2.created_at from alerts a2 WHERE a2.alert = a1.alert ORDER BY a2.created_at desc LIMIT 1 ) AS latest FROM alerts a1 GROUP BY a1.alert; ``` Table aliases are a ...
Passing query result into subquery
[ "", "mysql", "sql", "" ]
So now, I have a python program which I would like to convert into an executable(preferably a single file). Right now the target systems are only RedHat(and CentOS) and Debian(and Ubuntu). First, I've tried the PyInstaller but after running it, it creates a **.spec** file and 2 folders called build and dist. I have no...
If you want to make it executable, you have to `chmod +x /path/to/script.py`. This gives anybody permission to run the file. Then you can `python /path/to/script.py`. You still need to start the command with python, that is ugly. If you add this line `#!/usr/bin/env python` to the first line of your script. This is ca...
You might wish to investigate [Nuitka](http://nuitka.net/pages/overview.html). It takes python source code and converts it in to C++ API calls. Then it compiles into an executable binary (ELF on Linux). It has been around for a few years now and supports a wide range of Python versions. You will probably also get a pe...
converting python program into executable
[ "", "python", "pyinstaller", "" ]
I am fairly new to python so I apologies if this is quite a novice question, but I am trying to extract text from parentheses that has specific format from a raw text file. I have tried this with regular expressions, but please let me know if their is a better method. To show what I want to do by example: ``` s = "Te...
Assuming that you will have **no** nested brackets, you could use something like so: `(\([^()]+?, [0-9]{4}\))`. This will match any non bracket character which is within a set of parenthesis which is followed by a comma, a white space four digits and a closing parenthesis.
Using `[^()]` instead of `.`. This will make sure there is no nested (). ``` >>> re.findall("(\([^()]+[,] [0-9]{4}\))", s) ['(Stackoverflow, 2013)', '(Stackoverflow, 1999)'] ```
Extracting parenthesis with a specific format with Python
[ "", "python", "regex", "" ]
I have a million integers in sorted order and I would like to find the longest subsequence where the difference between consecutive pairs is equal. For example ``` 1, 4, 5, 7, 8, 12 ``` has a subsequence ``` 4, 8, 12 ``` My naive method is greedy and just checks how far you can extend a subsequence from ea...
**Update:** First algorithm described here is obsoleted by [Armin Rigo's second answer](https://stackoverflow.com/a/18247391/1009831), which is much simpler and more efficient. But both these methods have one disadvantage. They need many hours to find the result for one million integers. So I tried two more variants (s...
We can have a solution `O(n*m)` in time with very little memory needs, by adapting yours. Here `n` is the number of items in the given input sequence of numbers, and `m` is the range, i.e. the highest number minus the lowest one. Call A the sequence of all input numbers (and use a precomputed `set()` to answer in cons...
Longest equally-spaced subsequence
[ "", "python", "algorithm", "" ]
I am stuck in this issue: I have two models: Location and Rate. each location has its rate, possibly multiple rates. i want to get locations ordered by its rates, ascendingly. obvouisly, `order_by` and `distinct()` dont work together: ``` locations = Location.objects.filter(**s_kwargs).order_by('locations_rate__r...
Well the issue is not how to make query in Django for the problem you described. It's that your problem is either incorrect or not property thought through. Let me explained with an example: Suppose you have two `Location` objects, `l1` and `l2`. `l1` has two `Rate` objects related to it, `r1` and `r3`, such that `r1....
Possibly you want something like this: ``` locations = (Location.objects.filter(**s_kwargs) .values('locations_rate__rate') .annotate(Count('locations_rate__rate')) .order_by('locations_rate__rate')) ``` You need the `Count()` since you actually need a `GROUP BY` query, and `GRO...
django - annotate() instead of distinct()
[ "", "python", "django", "django-queryset", "" ]
I'm attempting to apply a bandpass filter with time-varying cutoff frequencies to a signal, using Python. The routine I am currently using partitions my signal into equal-length time segments, then for each segment I apply a filter with time-specific parameters, before merging the signal back together. The parameters a...
[AudioLazy](https://github.com/danilobellini/audiolazy) works natively with time varying filters ``` from audiolazy import sHz, white_noise, line, resonator, AudioIO rate = 44100 s, Hz = sHz(rate) sig = white_noise() # Endless white noise Stream dur = 8 * s # Some few seconds of audio freq = line(dur, 200, 800) # A...
If you're extracting portions of your signal using slices, then you're effectively windowing your data with a rectangular window, which "rings" at the edges due to the sudden discontinuities. One way to fix this is by using a window that rings less, like a hanning window : ``` import numpy as np signal = np.random.ra...
Applying time-variant filter in Python
[ "", "python", "filtering", "signal-processing", "" ]
Using SqlBulkCopy and getting this exception: > Received an invalid column length from the bcp client for colid 30. I've been banging my head against this one for hours. I know what row is having the issue, but I don't know which column "colid 30" is. There are 178 columns in the data table. All values seem to be cor...
I hope this helps solve someone else's issues as well. The error was because one of the string/varchar fields in the datatable had a semicolon ";" in it's value. Apparently you need to manually escape these before doing the insert! I did a loop through all rows/columns and did: ``` string.Replace(";", "CHAR(59)"); `...
Check the size of the columns in the table you are doing bulk insert. the varchar or other string columns might need to be extended. e.g, Increase size 30 to 50 => ``` ALTER TABLE [dbo].[TableName] ALTER COLUMN [ColumnName] Varchar(50) ```
SqlBulkCopy exception, find the colid
[ "", "sql", "sqlbulkcopy", "" ]
I have a list of list of lists like this ``` matches = [[['rootrank', 'Root'], ['domain', 'Bacteria'], ['phylum', 'Firmicutes'], ['class', 'Clostridia'], ['order', 'Clostridiales'], ['family', 'Lachnospiraceae'], ['genus', 'Lachnospira']], [['rootrank', 'Root'], ['domain', 'Bacteria'], ['phylum', '"Proteob...
The issue is that `node` is always the bottommost node in the tree, and you are always appending to that node. You need to store the root node. Since `['rootrank', 'Root']` appears at the beginning of each of the lists, I'd recommend pulling that out and using it as the root. So you can do something like: ``` rootnode...
I would highly recommend using a phylogenetics library like [Dendropy](http://pythonhosted.org/DendroPy/). The 'standard way of writing phylogenetic trees is with the Newick format (parenthetical statements like ((A,B),C)). If you use Dendropy, reading that tree would be as simple as ``` >>> import dendropy >>> tree1...
Constructing a phylogentic tree
[ "", "python", "tree", "bioinformatics", "phylogeny", "" ]
first off do you see a problem with this code; ``` SELECT num, surname, firstname, ward FROM doctor, ward WHERE num != consultant; NUM SURNAME FIRSTNAME W ---------- ---------- ---------- - 203 Black Peter A 574 Bisi Mavis B 461 Boyne Steve B ...
**[Here is the SQLFiddel Demo](http://www.sqlfiddle.com/#!2/cef82/2)** I think the best way to achive your output is using `not exsits`. **Below is the query which you can try** ``` SELECT * FROM doctor WHERE not exists (select 1 from ward where num = consultant) ``...
You need a left outer join: ``` SELECT num,surname, firstname,ward FROM doctor left outer join ward on num = consultant WHERE num is null; ``` The problem with your query is that you are doing a Cartesian product (all combinations) between `doctor` and `ward`. Then you are choosing the rows where the t...
Not Equals (!=) not operating as expected
[ "", "sql", "oracle", "" ]
I'm learning MySQL and PHP (running XAMPP and also using HeidiSQL) but have a live project for work that I'm trying to use it instead of the gazillion spreadsheets in which the information is currently located. I want to import 1,000+ rows into a table (tbl\_searches) where one of the columns is a string (contract\_no...
You can do it like this ``` LOAD DATA LOCAL INFILE '/path/to/your/file.csv' INTO TABLE table1 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' -- or '\r\n' if the file has been prepared on Windows (@field1, @contract_no, @field2, @field3,...) SET column1 = @field1, con...
try something like this: (I am assuming that you have data in tbl\_contracts) ``` <?php $handle = fopen("data_for_table_searches.csv", "r"); while (($data = fgetcsv($handle,",")) !== FALSE) { // get CSV data from you file $contract_id = query("SELECT contract_id FROM tbl_contracts WHERE contract_number = " ...
Import CSV Pulling One Column Field from Existing Table
[ "", "mysql", "sql", "" ]
For a programming language documentation project written in reStructuredText and rendered to HTML with Sphinx, I want to group my functions into logical groups like: String (all string functions), Web (all web-related functions), List (anything to do with list handling), etc.. Now, since functions can be members of sev...
I've solved this with some custom preprocessing and a custom directive. My personal website is made with Sphinx, as is my weblog. And a weblog means tags. First the **custom Sphinx directive** "tags" that I use like this: ``` My blog entry header ==================== .. tags:: python, django Bla bla bla bla ``` Th...
You can make use of indexing feature of sphinx. ReST: ``` .. index:: BNF, grammar, syntax, notation Some rest goes here. ``` conf.py: ``` html_use_index = True ```
How to add blog style tags in reStructuredText with Sphinx
[ "", "python", "python-sphinx", "restructuredtext", "" ]
I have a Python module that uses the argparse library. How do I write tests for that section of the code base?
You should refactor your code and move the parsing to a function: ``` def parse_args(args): parser = argparse.ArgumentParser(...) parser.add_argument... # ...Create your parser as you like... return parser.parse_args(args) ``` Then in your `main` function you should just call it with: ``` parser = pa...
"argparse portion" is a bit vague so this answer focuses on one part: the `parse_args` method. This is the method that interacts with your command line and gets all the passed values. Basically, you can mock what `parse_args` returns so that it doesn't need to actually get values from the command line. The `mock` [pack...
How do you write tests for the argparse portion of a python module?
[ "", "python", "unit-testing", "argparse", "" ]
I'm trying to use regex to parse an `XML` file (in my case this seems the simplest way). For example a line might be: ``` line='<City_State>PLAINSBORO, NJ 08536-1906</City_State>' ``` To access the text for the tag City\_State, I'm using: ``` attr = re.match('>.*<', line) ``` but nothing is being returned. Can so...
You normally don't want to use `re.match`. [Quoting from the docs](http://docs.python.org/2/library/re.html#re.match): > If you want to locate a match anywhere in string, use [search()](http://docs.python.org/2/library/re.html#re.search) instead (see also [search() vs. match()](http://docs.python.org/2/library/re.html...
Please, just use an XML parser like ElementTree ``` >>> from xml.etree import ElementTree as ET >>> line='<City_State>PLAINSBORO, NJ 08536-1906</City_State>' >>> ET.fromstring(line).text 'PLAINSBORO, NJ 08536-1906' ```
Parsing XML in Python with regex
[ "", "python", "xml", "regex", "" ]
I have a data/character\_data.py: ``` CHARACTER_A = { 1: {"level": 1, "name":"Ann", "skill_level" : 1}, 2: {"level": 2, "name":"Tom", "skill_level" : 1}} CHARACTER_B = { 1: {"level": 1, "name":"Kai", "skill_level" : 1}, 2: {"level": 2, "name":"Mel", "skill_level" : 1}} ``` In main.py, ...
How about this ``` In [38]: from data import character_data as character_data In [39]: character_type = "CHARACTER_A" In [40]: character_id = 1 In [41]: getattr(character_data, character_type)[character_id]["name"] Out[41]: 'Ann' ```
You can use [locals()](http://docs.python.org/2/library/functions.html#locals): ``` >>> from data.character_data import CHARACTER_A, CHARACTER_B >>> character_id = 1 >>> character_type = "CHARACTER_A" >>> locals()[character_type][character_id]["name"] Ann ``` Though, think about merging `CHARACTER_A` and `CHARACTER_B...
Get information from different dict by dict name
[ "", "python", "django", "" ]
So my problem is that I want to have a website that has a single navbar.html file. That I can use to add to the other pages in my website. I figured the best way to do this without javascript which I am trying to avoid because of compatibility issues (school website so I am trying to get best compatibility). I am writi...
I see a lot of people criticizing what you are trying to do, and I'm going to join them. This is a horrible way to implement a navbar, and a horrible procedural call for 'updating' a web site. I would be very adamant with your school that this isn't a wise decision, and more time is going to be wasted in the end doing ...
Use a templating engine when creating your web pages / website: an example is `Jinja` you can use a [base html template](http://jinja.pocoo.org/docs/templates/). You can do similar things in other engines as well and there are many many options: <http://wiki.python.org/moin/Templating> if you're determined not to use...
Parse HTML files then edit them in python
[ "", "python", "html", "parsing", "replace", "navbar", "" ]