Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I stored date as a varchar(256) latin1\_swedish\_ci which shows up as: 11/22/2012 Now I wanted to convert the existing data and column to a DATE What would be the easiest way to do this in SQL thanks
To be on the safe side I personally would add a new column, Transfer the data and then delete ``` update `table` set `new_col` = str_to_date( `old_col`, '%m/%d/%Y' ) ; ``` Check the data is OK before you delete the column.
**Edit** to convert the existing data use: ``` STR_TO_DATE(t.datestring, '%d/%m/%Y') ``` Source: [Convert String to Date](https://stackoverflow.com/questions/1861489/converting-a-date-in-mysql-from-string-field) You may need to create a temp table to hold your data for conversion: ``` CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,...) [table_options] [partition_options] ``` Then you can truncate the table: ``` TRUNCATE [TABLE] tbl_name ``` Then you can alter the column datatype: ``` ALTER TABLE tablename MODIFY columnname DATE; ``` Then you can reload from the temp table: ``` INSERT INTO table SELECT temptable.column1, temptable.column2 ... temptable.columnN FROM temptable; ```
convert the existing data varchar and column into a DATE
[ "", "mysql", "sql", "" ]
I am trying to create a stored procedure which will return records based on input. If all the input parameters are null, then return the entire table, else use the parameters and return the records: ``` create procedure getRecords @parm1 varchar(10) = null, @parm2 varchar(10) = null, @parm3 varchar(10) = null as declare @whereClause varchar(500) set @whereClause = ' where 1 = 1 ' if (@parm1 is null and @parm2 is null and @parm3 is null) select * from dummyTable else begin if (@parm1 is not null) set @whereClause += 'and parm1 = ' + '' + @parm1 + '' if (@parm2 is not null) set @whereClause += 'and parm2 = ' + '' + @parm2 + '' if (@parm3 is not null) set @whereClause += 'and parm3 = ' + '' + @parm3 + '' select * from dummyTable @whereClause <-- Error end ``` Error while creating this procedure is "An expression of non-boolean type specified in a context where a condition" Please comment if my approach is wrong in building the where clause? Thanks
The entire query should be in a varchar and can be executed using "EXEC" function. ``` SET @query = "SELECT * FROM dummyTable WHERE 1=1 " ... your IF clauses ... EXEC(@query) ``` HTH.
``` select * from dummyTable where (parm1 = @parm1 OR @parm1 IS NULL) and (parm2 = @parm2 OR @parm2 IS NULL) and (parm3 = @parm3 OR @parm3 IS NULL) ; ```
Building where clause based on null/not null parameters in sql
[ "", "sql", "sql-server", "stored-procedures", "" ]
If I have Table 1 ``` Column A, Column B, Column C, Type, ID 111 ABC NEW R 1 222 LMN NEW L 1 ``` What I want is the same value for one of the field. So the result should be like - ``` 111, ABC, NEW, R, 1 222, ABC, NEW, L, 1 ``` The ID is the common value between the two and can be used to link the two records. To clarify, above is a table I have and I have given the result I expect. Please refer to the column 2 of the result. I would want the value in the column 2 to be the same for the two rows, but rest of the values to reflect the actual value in the table. The common link between the two rows is the ID field. I think that I must clarify that I dont need the top 1 or the first value. The value in Column B should be the same in the result and must be the value where Type = R. The ID links the two rows and Type drives what value should be shown in Column B. Using SQL Server 2008.
I am not quite sure what you expect, but seem like you need something like ``` Select A,(SELECT TOP 1 B FROM #Temp WHERE ID=T.ID AND D='R') AS B,C,D,ID From #Temp T ```
Assuming you want the first value found in column B for a given id... ``` SELECT A, MIN(B) OVER(PARTITION BY ID) AS B, C, [Type], ID FROM Table1 ORDER BY ID, B ```
SQL - same value in one field in output
[ "", "sql", "sql-server", "" ]
Learning regex for python. I want to thank Jerry for his initial help on this problem. I tested this regex: ``` (\b\w+\b)?[^a-z]*(\b\w+\b)?[^a-z]*(\b\w+\b)?[^a-z]*(\b\w+\b)?[,;]\s*(\b\w+\b)?[^a-z]*(\b\w+\b)?[^a-z]*(\b\w+\b)?[^a-z]*(\b\w+\b)? ``` at <http://regex101.com/> and it finds what I am looking for, which is the four words that come before a comma in a sentence and the four words after a comma. If there are three two words before the comma at the beginning of the sentence it cannot crash. The test sentence I am using is: ``` waiting for coffee, waiting for coffee and the charitable crumb. ``` right now the regex returns: ``` [('waiting', 'for', 'coffee', '', 'waiting', 'for', 'coffee', 'and')] ``` I can't quite understand why the fourth member of the set is empty. What I want is for the regex to only return the 3 before the comma and the 4 after the comma in this instance, but in the event that there are four words before the comma, I want it to return four. I know that regex varies between languages, is this something I am missing in python?
You have *optional* groups: ``` (\bw+\b)? ``` The question mark makes that an optional match. But Python will always return *all* groups in the pattern, and for any group that didn't match anything, an empty value (`None`, usually) is returned instead: ``` >>> import re >>> example = 'waiting for coffee, waiting for coffee and the charitable crumb.' >>> pattern = re.compile(r'(\b\w+\b)?[^a-z]*(\b\w+\b)?[^a-z]*(\b\w+\b)?[^a-z]*(\b\w+\b)?[,;]\s*(\b\w+\b)?[^a-z]*(\b\w+\b)?[^a-z]*(\b\w+\b)?[^a-z]*(\b\w+\b)?') >>> pattern.search(example).groups() ('waiting', 'for', 'coffee', None, 'waiting', 'for', 'coffee', 'and') ``` Note the `None` in the output, that's the 4th word-group before the comma not matching anything because there are only 3 words to match. You must've used `.findall()`, which explicitly returns *strings*, and the pattern group that didn't match is thus represented as an empty string instead. Remove the question marks, and your pattern won't match your input example until you add that required 4th word before the comma: ``` >>> pattern_required = re.compile(r'(\b\w+\b)[^a-z]*(\b\w+\b)[^a-z]*(\b\w+\b)[^a-z]*(\b\w+\b)[,;]\s*(\b\w+\b)[^a-z]*(\b\w+\b)[^a-z]*(\b\w+\b)[^a-z]*(\b\w+\b)') >>> pattern_required.findall(example) [] >>> pattern_required.findall('Not ' + example) [('Not', 'waiting', 'for', 'coffee', 'waiting', 'for', 'coffee', 'and')] ``` If you need to match between 2 and 4 words, but do *not* want empty groups, you'll have to make *one* group match multiple words. You cannot have a variable number of groups, regular expressions do not work like that. Matching multiple words in one group: ``` >>> pattern_variable = re.compile(r'(\b\w+\b)[^a-z]*((?:\b\w+\b[^a-z]*){1,3})[,;]\s*(\b\w+\b)[^a-z]*(\b\w+\b)[^a-z]*(\b\w+\b)[^a-z]*(\b\w+\b)') >>> pattern_variable.findall(example) [('waiting', 'for coffee', 'waiting', 'for', 'coffee', 'and')] >>> pattern_variable.findall('Not ' + example) [('Not', 'waiting for coffee', 'waiting', 'for', 'coffee', 'and')] ``` Here the `(?:...)` syntax creates a *non*-capturing group, one that does not produce output in the `.findall()` list; used here so we can put a quantifier on it. `{1,3}` tells the regular expression we want the preceding group to be matched between 1 and 3 times. Note the output; the second group contains a variable number of words (between 1 and 3).
Since you've got an answer as to how to sort out your regex, I'd point out that in Python - stuff like this is normally much more easily done, and readable via using builtin string functions, eg: ``` s = 'waiting for coffee, waiting for coffee and the charitable crumb.' before, after = map(str.split, s.partition(',')[::2]) print before[-4:], after[:4] # ['waiting', 'for', 'coffee'] ['waiting', 'for', 'coffee', 'and'] ```
Empty grouping during Python regex evaluation
[ "", "python", "regex", "" ]
Using python 3.2. ``` import collections d = defaultdict(int) ``` run ``` NameError: name 'defaultdict' is not defined ``` Ive restarted Idle. I know collections is being imported, because typing ``` collections ``` results in ``` <module 'collections' from '/usr/lib/python3.2/collections.py'> ``` also help(collections) shows me the help including the defaultdict class. What am I doing wrong?
``` >>> import collections >>> d = collections.defaultdict(int) >>> d defaultdict(<type 'int'>, {}) ``` It might behoove you to read about [the `import` statement](http://docs.python.org/2/reference/simple_stmts.html#the-import-statement).
You're not importing `defaultdict`. Do either: ``` from collections import defaultdict ``` or ``` import collections d = collections.defaultdict(list) ```
defaultdict is not defined
[ "", "python", "python-3.x", "" ]
I have a rather gnarly bit of code that must more-or-less randomly generate a bunch of percentages, stored as decimal floats. That is, it decides that material one makes up 13.307 percent of the total, then stores that in a dict as 0.13307. The trouble is, I can never get those numbers to add up to exactly one. I'm not entirely certain what the problem is, honestly. It might be something to do with the nature of floats. Here's the offending code, in all its overcomplicated glory: ``` while not sum(atmosphere.values())>=1: #Choose a material randomly themat=random.choice(list(materials.values())) #If the randomly chosen material is gaseous at our predicted temperature... if themat.vapor < temp: #Choose a random percentage that it will make up of our planet's atmosphere, then put it in the atmos dict. atmosphere[themat]=round(random.uniform(0.001,0.5),5) #Find out if the fractions add up to more than 1 difference=(sum(atmosphere.values())-1) #If one does... while difference > 0: #Choose a random constituent themat=random.choice(list(atmosphere.keys())) #If that constituent has a higher fraction value than the amount we'd need to reduce the total to 1... if atmosphere[themat]>(sum(atmosphere.values())-1): #Subtract that much from it. atmosphere[themat]-=difference #Then break the loop, since we're done and otherwise we'd go on removing bits of the atmosphere forever. break else: #Otherwise, halve its percentage and reduce difference by the amount we reduced the atmosphere oldperc=atmosphere[themat] atmosphere[themat]=oldperc/2 difference-=oldperc/2 #Then, finally, we correct any overcorrections the previous block made. difference=(sum(atmosphere.values())-1) if difference < 0: #Choose a random mat themat=random.choice(list(atmosphere.keys())) #Then add enough to it that the total is 1. atmosphere[themat]+=difference ``` Sorry if I've missed something obvious, or am not providing an important bit of information, but I'm tired at the moment, and I've been trying to figure this out for days now.
From your code it looks like you're randomly generating planet atmospheres, presumably for some kind of game or something. At any rate, the randomness of it is convincing me it doesn't need to be too accurate. So i'd suggest you don't use floats, just use `int`s and go up to 100. Then you'll get your exact summing. For any maths you want to use them in just cast. Is this not an option? If you insist on using floats, then read on... The problem you have using floats is as follows: A floating point (in this case a double) is represented like this: ![enter image description here](https://i.stack.imgur.com/8uNdO.png) which corresponds to a `double` of value: ![enter image description here](https://i.stack.imgur.com/fyDGf.png) So, your number is `(1+M) * 2**(E)` (where `E` = `e-offset`) `1+M` is always in the range 1-2. So, we have equally spaced numbers inbetween each pair of power of two (positive and negative), and the spacing between the numbers doubles with each increase in the exponent, `E`. Think about this, it means that there is a constant spacing of *representable* numbers between each of these numbers `[(1,2),(2,4),(4,8), etc]`. This also applies to the negative powers of two, so: ``` 0.5 - 1 0.25 - 0.5 0.125 - 0.25 0.0625 - 0.125 etc. ``` And in each range, there are the same quantity of numbers. This means that if you take a number in the range `(0.25,0.5)` and add it to a number in the range `(0.5,1)`, then you have a 50% chance that the number cannot be exactly represented. If you sum two floating point numbers for which the exponents differ by `D`, then the chances of the sum being exactly representable are 2-D. If you then want to represent the range `0-1`, then you'll have to be very careful about which floats you use (i.e. force the last `N` bits of the fraction to be zero, where `N` is a function of `E`). If you go down this route, then you'll end up with far more floats at the top of the range than the bottom. The alternative is to decide how close to zero you want to be able to get. Lets say you want to get down to 0.0001. 0.0001 = (1+M) \* 2E log2(0.0001) = -13.28771... So we'll use -14 as our minimum exponent. And then to get up to 1, we just leave the exponent as -1. So now we have 13 ranges, each with twice as many values as the lower one which we can sum without having to worry about precision. This also means though, that the top range has 213 more values we can use. This obviously isn't okay. So, after picking a float, then *round* it to the nearest allowable value - in this case, by *round* I just mean set the last 13 bits to zero, and just put it all in a function, and apply it to your numbers immediately after you get them out of `rand`. Something like this: ``` from ctypes import * def roundf(x,bitsToRound): i = cast(pointer(c_float(x)), POINTER(c_int32)).contents.value bits = bin(i) bits = bits[:-bitsToRound] + "0"*bitsToRound i = int(bits,2) y = cast(pointer(c_int32(i)), POINTER(c_float)).contents.value return y ``` (images from wikipedia)
## If you mean to find two values that add up to 1.0 I understand that you want to pick two floating-point numbers between 0.0 and 1.0 such that they add to 1.0. Do this: * pick the largest L of the two. It has to be between 0.5 and 1.0. * define the smallest number S as 1.0 - L. Then in floating-point, S + L is exactly 1.0. --- If for some reason you obtain the smallest number S first in your algorithm, compute L = 1.0 - S and then S0 = 1.0 - L. Then L and S0 add up exactly to 1.0. Consider S0 the “rounded” version of S. ## If you mean several values X1, X2, …, XN Here is an alternative solution if you are adding N numbers, each between 0.0 and 1.0, and expect the operations X1 + X2 + … and 1.0 - X1 … to behave like they do in math. Each time you obtain a new number Xi, do: Xi ← 1.0 - (1.0 - Xi). Only use this new value of Xi from that point onwards. This assignment will slightly round Xi so that it behaves well in all sums whose intermediate results are between 0.0 and 1.0. **EDIT:** after doing the above for values X1, …, XN-1, compute XN as 1 - X1 - … - XN-1. This floating-point computation will be exact (despite involving floating-point), so that you will have X1 + … + XN = 1 exactly.
Rounding floats so that they sum to precisely 1
[ "", "python", "math", "python-3.x", "floating-point", "" ]
I have a file loaded in memory from a Django form. It is giving me the following error: ``` new-line character seen in unquoted field - do you need to open the file in universal-newline mode? ``` Another solution used [this](https://stackoverflow.com/questions/5745557/getting-new-line-character-seen-in-unquoted-field-when-parsing-csv-document-us). However, i already have the file in memory so i require to change it to opening in `"rU"` format. This is my relevant code in `views.py` ``` form = ResultsUploadForm(request.POST, request.FILES) if form.is_valid(): form.save() reader = csv.reader(request.FILES['file']) for row in reader: #etc... ``` Does anyone know how to go about fixing this? The error is thrown from this statement `for row in reader:`
I found the solution in [another post](https://stackoverflow.com/questions/16404339/csv-file-uploading-error-in-django-in-mac-new-line-character-seen-in-unquoted-f?rq=1) The issue was how i was saving the .csv file. When producing a .csv file in excel for mac save it as "Windows Comma Separated Values (.csv)" This will stop the addition of unwanted characters that throw of `import csv` in Django and python.
You can change the read mode to 'rU' instead of 'r' or 'rb'
new-line character seen in unquoted field
[ "", "python", "django", "" ]
I want to display hour when i call `date.now.hour` but I get this error ``` AttributeError: 'function' object has no attribute 'hour' ``` this is my code: ``` #!/usr/bin/python class Date: def now(self): self.hour = "hour" print "Now" def __call__(self, string): print string date = Date() date('hello') # print hello date.now.hour # print hour ``` My task is > Make a class that can do this: > > `date.now()` - output: `'now'` > > `date('hai')` - output: `'hai'` > > `date.now` output: `'now'` > > `date.now.hour` output: `'hour'`
You are quite close - one of your tasks are already done: > `date('hai')` - `output: 'hai'` What is still left to do is > `date.now()` - output: `'now'` > > `date.now` - output: `'now'` > > `date.now.hour` output: `'hour'` So your `date.now` has quite a lot of requirements which only can be accomplished with a separate class: ``` class Now(object): def __str__(self): return ... def __call__(self): return ... hour = property(lambda self: 'hour') ``` or something like this. This class you can use inside your `class Date`. --- Another option would be to have `now` be a property of your `class Date`, but this would work analogous. You'd need a `class Now` like above, but you would it use like ``` class Date(object): def __call__ # as before @property def now(self): return Now() ```
Just call it `date.now()` - you'll never be able to access the `hour` attribute of the function since it's an attribute of the object. Doing `date.hour` will allow you to see `hour`. ``` >>> date.hour 'hour' ``` What you should do though is set all of these properties in the `__init__` function of your class. ``` class Date(): def __init__(self, hour): self.hour = hour def now(self): print self.hour #if you will def __call__(self string): print string ```
Call attribute method python
[ "", "python", "python-2.7", "" ]
I have some Python code I need to add logging to. I've always preferred nice big C macro looking statements like "DEBUG()", "ERROR()", etc for logging. I feel it makes the code easier to read (no objects) when trace-points are visually differentiable from the actual code. I also would like to be able to set logging levels at a per-module level. How could I make a module called "log" that is capable of doing this (while making use of the Python std library logging module)? E.g.: File: main.py ``` # This imports LOG_MODULE_NAME, DEBUG, WARN, etc from log import * import my_module LOG_MODULE_NAME("main") log.set_level("main", log.LVL_DEBUG) log.set_level("my_module", log.LVL_WARN) if __name__ == "__main__": foo = my_module.myFunc(2) DEBUG("Exiting main.py") ``` File: my\_module.py ``` from log import * LOG_MODULE_NAME("my_module") def myFunc(x): DEBUG("Entering function") if x != 1: WARN("I thought it would be 1") DEBUG("Exiting function") return x+1 ``` I'd expect output to look something like: ``` [WARN:my_module - my_module.py:9] I thought it would be 1 [DEBUG:main - main.py:11] Exiting main.py ```
If you want to have the logger's name indicate the module in which it was used, you can use the [`logger.getLogger([name])`](http://docs.python.org/2/library/logging.html#logging.getLogger) module function, and pass `__name__` as its (optional) argument, as explained [here](http://docs.python.org/2/library/logging.html#logger-objects). If you want to use names like `DEBUG()`, do something like this in *each* of your files... ``` LOG_MODULE_NAME = logging.getLogger(__name__) def DEBUG(msg): global LOG_MODULE_NAME LOG_MODULE_NAME.debug(msg) ``` I am not clear on the way that global namespaces actually work in Python... [this answer](https://stackoverflow.com/a/15890156/691859) says > each module has its own "global" namespace. So I guess you will be just fine like that, since `LOG_MODULE_NAME` won't collide between modules. I believe that this approach will give you *one* logfile, where the lines will look like this: ``` DEBUG:my_module:Entering function WARN:my_module:I thought it would be 1 DEBUG:my_module:Exiting function DEBUG:root:Exiting main.py ``` Not instrospective enough? You want the [`inpsect`](http://docs.python.org/2/library/inspect.html#module-inspect) module, which will give you a lot of [information](http://docs.python.org/2/library/inspect.html#types-and-members) about the program while it's running. This will, for instance, get you the current line number. Your note about "setting log levels at a per-module level" makes me think that you want something like [`getEffectiveLevel()`](http://docs.python.org/2/library/logging.html#logging.Logger.getEffectiveLevel). You could try to smush that in like this: ``` LOG_MODULE_NAME = logging.getLogger(__name__) MODULE_LOG_LEVEL = log.LVL_WARN def DEBUG(msg): if MODULE_LOG_LEVEL = log.LVL_DEBUG: global LOG_MODULE_NAME LOG_MODULE_NAME.debug(msg) ``` I'm not experienced enough with the `logging` module to be able to tell you how you might be able to make each module's log change levels dynamically, though.
These answers seem to skip the very simple idea that functions are first-class objects which allows for: ``` def a_function(n): pass MY_HAPPY_NAME = a_function MY_HAPPY_NAME(15) # which is equivalent to a_function(15) ``` **Except** I recommend that you don't do this. [PEP8 coding conventions](http://www.python.org/dev/peps/pep-0008/) are widely used because life is too short to make me have to read identifiers in the COBOLy way that you like to write them. Some other answers also use the `global` statement which is almost always not needed in Python. If you are making module-level logger instances then ``` import logging log = logging.getLogger(__name__) def some_method(): ... log.debug(...) ``` is a perfectly workable, concise way of using the module-level variable `log`. You could even do ``` log = logging.getLogger(__name__) DEBUG = log.debug def some_method(): ... DEBUG(...) ``` but I'd reserve the right to call that ugly.
Per-file/module logger in Python
[ "", "python", "logging", "" ]
How do I get rid of the multiple convert functions in the following dynamic SQL? ``` IF @MediaTypeID > 0 or @MediaGroupID > 0 BEGIN SET @SQL = @SQL + 'INNER JOIN (SELECT lmc.ID FROM Lookup_MediaChannels (nolock) lmc INNER JOIN Lookup_SonarMediaTypes (nolock) lsmt ON lmc.SonarMediaTypeID = lsmt.ID WHERE (ISNULL('+ CONVERT(VARCHAR(10),@MediaTypeID) +',0) = 0 OR lsmt.ID = '+ CONVERT(VARCHAR(10),@MediaTypeID) +') AND (ISNULL('+ CONVERT(VARCHAR(10),@MediaGroupID)+',0) = 0 OR lsmt.SonarMediaGroupID = '+ CONVERT(VARCHAR(10),@MediaGroupID) +'))t ON t.ID = lmc.ID ' ``` I tried to convert them first and use a variable instead of the convert calls like below ``` IF @MediaTypeID > 0 or @MediaGroupID > 0 BEGIN SET @TypeID = CONVERT(VARCHAR(10),@MediaTypeID) SET @GroupID = CONVERT(VARCHAR(10),@MediaGroupID) SET @SQL = @SQL + 'INNER JOIN (SELECT lmc.ID FROM Lookup_MediaChannels (nolock) lmc INNER JOIN Lookup_SonarMediaTypes (nolock) lsmt ON lmc.SonarMediaTypeID = lsmt.ID WHERE (ISNULL('+ @TypeID +',0) = 0 OR lsmt.ID = '+ @TypeID +') AND (ISNULL('+ @GroupID+',0) = 0 OR lsmt.SonarMediaGroupID = '+ @GroupID +'))' END ``` but it gave me this error > Msg 245, Level 16, State 1, Line 13 > Conversion failed when converting the varchar value ',0) = 0 OR lsmt.ID = ' to data type int.
The error you are getting is because you are trying to convert the variables MediaTypeID and MediaGroupID from int to varchar. That operation does not fail, it just doesn't happen. Problem is that both are still integers, that you are trying to add in the dynamic code causing the error. So what i did was to declare 2 new variables, that should fix the problem. If you look into the code you didn't include, you should notice that MediaTypeID and MediaGroupID are both numeric most likely integers. ``` IF @MediaTypeID > 0 or @MediaGroupID > 0 BEGIN DECLARE @TypeID2 VARCHAR(10) DECLARE @GroupID2 VARCHAR(10) SET @TypeID2 = NULLIF(CONVERT(VARCHAR(10),@MediaTypeID ), 0) SET @GroupID2 = NULLIF(CONVERT(VARCHAR(10),@MediaGroupID), 0) SET @SQL = @SQL + 'INNER JOIN (SELECT lmc.ID FROM Lookup_MediaChannels (nolock) lmc INNER JOIN Lookup_SonarMediaTypes (nolock) lsmt ON lmc.SonarMediaTypeID = lsmt.ID WHERE '+ coalesce( @TypeID2 +' = lsmt.ID', '1=1') + coalesce( 'AND' + @GroupID2+' = lsmt.SonarMediaGroupID', '') + ')t ON t.ID = lmc.ID ' END ```
The error you are getting may have been caused by NULL @MediaTypeID or @MediaGroupID values because your code does not properly handle NULLS. However, having an OR condition like that in the WHERE clause is bad for performance because it prevents the query optimizer from using an index. I would suggest rewriting it to avoid the OR (which also cuts down on the number of CONVERTs: ``` IF @MediaTypeID > 0 or @MediaGroupID > 0 BEGIN SET @SQL = @SQL + 'INNER JOIN (SELECT lmc.ID FROM Lookup_MediaChannels (nolock) lmc INNER JOIN Lookup_SonarMediaTypes (nolock) lsmt ON lmc.SonarMediaTypeID = lsmt.ID WHERE 1=1 ' IF @MediaTypeID > 0 SET @SQL = @SQL + ' AND lsmt.ID = ' + CONVERT(VARCHAR(10),@MediaTypeID) IF @MediaGroupID > 0 SET @SQL = @SQL + ' AND lsmt.SonarMediaGroupID = ' + CONVERT(VARCHAR(10),@MediaGroupID) SET @SQL = @SQL + ') t ON t.ID = lmc.ID ' END ```
minimizing function calls inside dynamic sql?
[ "", "sql", "sql-server", "t-sql", "" ]
I have a piece of code which is working in Linux, and I am now trying to run it in windows, I import sys but when I use sys.exit(). I get an error, sys is not defined. Here is the begining part of my code ``` try: import numpy as np import pyfits as pf import scipy.ndimage as nd import pylab as pl import os import heapq import sys from scipy.optimize import leastsq except ImportError: print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)" sys.exit() ``` Why is sys not working??
Move `import sys` *outside* of the `try`-`except` block: ``` import sys try: # ... except ImportError: # ... ``` If any of the imports *before* the `import sys` line fails, the *rest* of the block is not executed, and `sys` is never imported. Instead, execution jumps to the exception handling block, where you then try to access a non-existing name. `sys` is a built-in module anyway, it is *always* present as it holds the data structures to track imports; if importing `sys` fails, you have bigger problems on your hand (as that would indicate that *all* module importing is broken).
You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example: ``` try: import datetime import foo import sys except ImportError: pass ``` Let's say `foo` doesn't exist. Then only `datetime` will be imported. What you can do is import the sys module at the beginning of the file, before the try/except statement: ``` import sys try: import numpy as np import pyfits as pf import scipy.ndimage as nd import pylab as pl import os import heapq from scipy.optimize import leastsq except ImportError: print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)" sys.exit() ```
python: sys is not defined
[ "", "python", "sys", "" ]
``` while int(input("choose a number")) != 5 : ``` Say I wanted to see what number was input. Is there an indirect way to get at that? EDIT Im probably not being very clear lol. . I know that in the debugger, you can step through and see what number gets input. Is there maybe a memory hack or something like it that lets you get at 'old' data after the fact?
Nope - you have to assign it... Your example could be written using the two-argument style `iter` though: ``` for number in iter(lambda: int(input('Choose a number: ')), 5): print number # prints it if it wasn't 5... ```
Do something like this. You don't have to assign, but just make up an additional function and use it every time you need to do this. Hope this helps. ``` def printAndReturn(x): print(x); return(x) while printAndReturn(int(input("choose a number"))) != 5 : # do your stuff ```
Is there any way to access the result something never assigned?
[ "", "python", "python-3.x", "" ]
I have two dictionaries in Python: ``` d1 = {'a': 10, 'b': 9, 'c': 8, 'd': 7} d2 = {'a': 1, 'b': 2, 'c': 3, 'e': 2} ``` I want to substract values between dictionaries d1-d2 and get the result: ``` d3 = {'a': 9, 'b': 7, 'c': 5, 'd': 7 } ``` Now I'm using two loops but this solution is not too fast ``` for x,i in enumerate(d2.keys()): for y,j in enumerate(d1.keys()): ```
I think a very Pythonic way would be using [dict comprehension](http://www.python.org/dev/peps/pep-0274/): ``` d3 = {key: d1[key] - d2.get(key, 0) for key in d1} ``` Note that this only works in Python 2.7+ or 3.
Use [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter), iif all resulting values are known to be strictly positive. The syntax is very easy: ``` >>> from collections import Counter >>> d1 = Counter({'a': 10, 'b': 9, 'c': 8, 'd': 7}) >>> d2 = Counter({'a': 1, 'b': 2, 'c': 3, 'e': 2}) >>> d3 = d1 - d2 >>> print d3 Counter({'a': 9, 'b': 7, 'd': 7, 'c': 5}) ``` Mind, if not all values are known to remain *strictly* positive: * elements with values that become zero will be omitted in the result * elements with values that become negative will be missing, or replaced with wrong values. E.g., `print(d2-d1)` can yield `Counter({'e': 2})`.
How to subtract values from dictionaries
[ "", "python", "dictionary", "" ]
I'm going through the Python 2.7 tutorial, and I was looking at the output of the following statement: ``` def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in arguments: print arg print "-" * 40 keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw] ``` So, if I call the program as such: ``` cheeseshop("Cheddar", "No.", "Seriously?", Shopkeeper="Michael Palin", Client="John Cleese") ``` It outputs: ``` Do you have any Cheddar? I'm sorry, we're all out of Cheddar No. Seriously? -------------------------------------- Client: John Cleese Shopkeeper: Michael Palin ``` This is correct. If I change that print statement to `print keywords`, I get the following representation: ``` {'Shopkeeper': 'Ryan Lambert', 'Client': 'John Cleese'} ``` I'm a bit confused on how printing `keywords[kw]` just comes back with a name, and `keywords` does not.
[In Python, you can pass optional keyword parameters by putting a `**` in front of the function parameter's list.](http://docs.python.org/2/faq/programming.html) So the `keywords` variable is actually a dictionary type. Thus, if you do: ``` print keywords ``` you get back (reformatted to make the mapping more obvious) ``` { 'Shopkeeper': 'Ryan Lambert', 'Client': 'John Cleese' } ``` which is a dictionary. And if you do: ``` print keywords[kw] ``` you get back the value of the dictionary associated with the key `kw`. So if `kw` was `'Shopkeeper'`, then `keywords[kw]` becomes `'Ryan Lambert'`, and if `kw` was `'Client'`, then `keywords[kw]` becomes `'John Cleese'`
keywords is stored as a *dictionary*. ( See [this](http://docs.python.org/2/tutorial/datastructures.html#dictionaries) for more) If you print the dictionary itself it is going to output the complete set of pairs it contains (key,value). On your program: * keys are: 'Shopkeeper' and 'Client' * values are respectively: 'Ryan Lambert' and 'John Cleese' One way to access the values is to "search" for it with its key: dict[key] So when you wrote: "keywords[kw]" you are actually passing a key and python is going to give you the corresponding value. You can think it as similar as accessing an array value: ``` a = ['a', 'b', 'c'] ``` if you: ``` print a #output: ['a', 'b', 'c'] print a[0] # outputs: 'a' ``` just unlike arrays the data is not stored "neatly" together in memory, but using hashing Hope it helped, Cheers
Python keyword output interpretation
[ "", "python", "dictionary", "keyword", "" ]
Split tests into even time slaves. I have a full list of how long each test takes. They are python behave test features. Slaves are created via Jenkins. --- I have tests split out on to x amount of slaves. These slaves run the tests and report back. Problem: Some of the slaves are getting bigger longer running tests than others. eg. one will take 40 mins and another will take 5 mins. I want to average this out. I currently have a list of the file and time it takes. ``` [ ['file_A', 501], ['file_B', 350], ['file_C', 220], ['file_D', 100] ] ``` extra... there are n number of files. At the moment these are split in to lists by number of files, I would like to split them by the total time taken. eg... 3 slaves running these 4 tests would look like... ``` [ [ ['file_A', 501], ], [ ['file_B', 350], ], [ ['file_C', 220], ['file_D', 100] ] ] ``` Something like that... Please help Thanks!
You could do something like: ``` def split_tasks(lst, n): # sorts the list from largest to smallest sortedlst = sorted(lst, key=lambda x: x[1], reverse=True) # dict storing the total time for each set of tasks totals = dict((x, 0) for x in range(n)) outlst = [[] for x in range(n)] for v in sortedlst: # since each v[1] is getting smaller, the place it belongs should # be the outlst with the minimum total time m = min(totals, key=totals.get) totals[m] += v[1] outlst[m].append(v) return outlst ``` Which produces the expected output: ``` [[['file_A', 501]], [['file_B', 350]], [['file_C', 220], ['file_D', 100]]] ```
Sort your tests into descending order of the time taken to run, send one to each slave from the top of the list and then give them another as they finish - using this strategy if a test hangs or takes longer than usual all the other tests will still get finished in the minimum time. If you can not distribute the tests on completion then allocate a list for each server and "deal" the tests out in same manner.
Split tests into even time slaves
[ "", "python", "testing", "linear-programming", "" ]
i am trying to learn python with codeacademy. the assignment was make 3 dictionaries (for each student) and then make a list of the 3 dictionaries. then, i am supposed to print out all the data in the list. i tried to call out the values the same way i used for a dictionary by itself (lloyd[values]), but then it says that values is not defined o\_O. I have also tried to 'print names' but then the error message is that i didn't print out one of the values. i'd appreciate your help very much. ``` lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] } students = [lloyd, alice, tyler] for names in students: print lloyd[values] ```
If you want to print all the information for each student, you have to loop over the students and the values stored in the dictionaries: ``` students = [lloyd, alice, tyler] for student in students: for value in student: print value, "is", student[value] ``` Note, however, that dictionaries are not ordered, so the order of the values might not be the way you want it. In this case, print them individually, using the name of the value as a string as key: ``` for student in students: print "Name is", student["name"] print "Homework is", student["homework"] # same for 'quizzes' and 'tests' ``` Finally, you could also use the `pprint` module for "pretty-printing" the student dictionaries: ``` import pprint for student in students: pprint.pprint(student) ```
I would suggest using namedtuple instead for readability and scalability: ``` from collections import namedtuple Student = namedtuple('Student', ['name', 'hw', 'quiz', 'test']) Alice = Student('Alice', herHWLst, herQuizLst, herTestLst) Ben = Student('Ben', hisHWLst, hisQuizLst, hisTestLst) students = [Alice, Ben] for student in students: print student.name, student.hw[0], student.quiz[1], student.test[2] #whatever value you want ``` If you really want to create tons of dictionaries, you can read it with your code above by: ``` for student in students: name = student['name'] homeworkLst = student['homework'] # get more values from dict if you want print name, homeworkLst ``` Accessing dictionary is super fast in Python, but creating them may not be as fast and efficent. The namedtuple is more practical in this case.
how do i call dictionary values from within a list of dictionaries ?
[ "", "python", "list", "dictionary", "" ]
I have data in the following form: ``` <a> <b> _:h1 <c>. _:h1 <e> "200"^^<http://www.w3.org/2001/XMLSchema#integer> <f> . _:h1 <date> "Mon, 30 Apr 2012 07:01:51 GMT" <p> . _:h1 <server> "Apache/2" <df> . _:h1 <last-modified> "Sun, 25 Mar 2012 14:15:37 GMT" <hf> . ``` I need to convert it into the following form using Python: ``` <a> <b> _:h1. <1> <c>. _:h1 <e> "200"^^<http://www.w3.org/2001/XMLSchema#integer> . <1> <f>. _:h1 <date> "Mon, 30 Apr 2012 07:01:51 GMT". <1> <p>. _:h1 <server> "Apache/2" . <1> <df>. _:h1 <last-modified> "Sun, 25 Mar 2012 14:15:37 GMT" . <1> <hf>. ``` I wrote code in Python which using the `str.split()` method. It splits the string based on space. However, it does not solve my purpose as by using it "Sun, 25 Mar 2012 14:15:37 GMT" also gets split. Is there some other way to achieve this using Python?
You can use the `rfind` or `rindex` methods to find the last occurrence of `<` in your lines. ``` data = """[your data]""" data_new = "" for line in data.splitlines(): i = line.rfind("<") data_new += line if i == -1 else line[:i] + ". \n<1> " + line[i:] + "\n" data_new = data_new.strip() ```
Is that N3/Turtle? If so, I think you want [RDFlib](https://github.com/RDFLib/rdflib). Also see: [Reading a Turtle/N3 RDF File with Python](https://stackoverflow.com/questions/3557561/reading-a-turtle-n3-rdf-file-with-python)
Split string to desired form using Python
[ "", "python", "" ]
I have a list like this: ``` website = ['http://freshtutorial.com/install-xamp-ubuntu/', 'http://linuxg.net/how-to-install-xampp-on-ubuntu-13-04-12-10-12-04/', 'http://ubuntuforums.org/showthread.php?t=2149654', 'http://andyhat.co.uk/2012/07/installing-xampp-32bit-ubuntu-11-10-12-04/', 'http://askubuntu.com/questions/303068/error-with-tar-command-cannot-install-xampp-1-8-1-on-ubuntu-13-04', 'http://askubuntu.com/questions/73541/how-to-install-xampp'] ``` I want to search if the following list contain the certain URL or not. URL would be in this format : `url = 'http://freshtutorial.com'` The website is the 1st element of a list. Thus, I want to print *1* **not 0**. I want everything in the loop so that if there's no website with that URL, it would go again and dynamically generate the list and again search for the website. I have done this upto now: ``` for i in website: if url in website: print "True" ``` I can't seem to print the position and wrap everything in loop. Also, is it better to use `regex` or `if this in that` syntax. Thanks
Here is the complete program: ``` def search(li,ur): for u in li: if u.startswith(ur): return li.index(u)+1 return 0 def main(): website = ['http://freshtutorial.com/install-xamp-ubuntu/', 'http://linuxg.net/how-to-install-xampp-on-ubuntu-13-04-12-10-12-04/', 'http://ubuntuforums.org/showthread.php?t=2149654', 'http://andyhat.co.uk/2012/07/installing-xampp-32bit-ubuntu-11-10-12-04/', 'http://askubuntu.com/questions/303068/error-with-tar-command-cannot-install-xampp-1-8-1-on-ubuntu-13-04', 'http://askubuntu.com/questions/73541/how-to-install-xampp'] url = 'http://freshtutorial.com' print search(website,url) if __name__ == '__main__': main() ```
``` for i, v in enumerate(website, 1): if url in v: print i ```
How to find the position of specific element in a list?
[ "", "python", "list", "python-2.7", "" ]
``` CREATE TABLE [dbo].[theRecords]( [id] [int] IDENTITY(1,1) NOT NULL, [name] [varchar](50) NULL, [thegroup] [varchar](50) NULL, [balance] [int] NULL, ) GO insert into theRecords values('blue',1,10) insert into theRecords values('green',1,20) insert into theRecords values('yellow',2,5) insert into theRecords values('red',2,4) insert into theRecords values('white',3,10) insert into theRecords values('black',4,10) ``` ![enter image description here](https://i.stack.imgur.com/MYkEg.png) Firstly, i want to get the sum of balances in each group,then for names that have only one group,the name should be retained,then names that belong to same group should have their name changed too the group name. ``` name | balance 1 30 2 9 white 10 black 10 ```
To determine if all the names are the same, I like to compare the minimum to the maximum: ``` select (case when min(name) = max(name) then max(name) else thegroup end) as name, sum(balance) as balance from theRecords r group by thegroup; ``` Calculating the `min()` and `max()` is generally more efficient than a `count(distinct)`.
Use group function to group the names with the sum of the balance for each name. Do this below: ``` select thegroup "name", sum(balance) "balance" from theRecords group by thegroup order by 1; ``` [Example](http://sqlfiddle.com/#!2/c986f/7/0)
complex grouping issue in query
[ "", "sql", "sql-server", "grouping", "" ]
I have some puLP code, which solves my knapsack problem. ``` prob = LpProblem("Knapsack problem", LpMaximize) x1 = LpVariable("x1", 0, 12, 'Integer') x2 = LpVariable("x2", 0, 12, 'Integer') x3 = LpVariable("x3", 0, 12, 'Integer') x4 = LpVariable("x4", 0, 12, 'Integer') x5 = LpVariable("x5", 0, 12, 'Integer') x6 = LpVariable("x6", 0, 12, 'Integer') x7 = LpVariable("x7", 0, 12, 'Integer') x8 = LpVariable("x8", 0, 12, 'Integer') x9 = LpVariable("x9", 0, 12, 'Integer') x10 = LpVariable("x10", 0, 12, 'Integer') x11 = LpVariable("x11", 0, 12, 'Integer') x12 = LpVariable("x12", 0, 12, 'Integer') x13 = LpVariable("x13", 0, 12, 'Integer') x14 = LpVariable("x14", 0, 12, 'Integer') x15 = LpVariable("x15", 0, 12, 'Integer') x16 = LpVariable("x16", 0, 12, 'Integer') x17 = LpVariable("x17", 0, 12, 'Integer') x18 = LpVariable("x18", 0, 12, 'Integer') x19 = LpVariable("x19", 0, 12, 'Integer') x20 = LpVariable("x20", 0, 12, 'Integer') x21 = LpVariable("x21", 0, 12, 'Integer') x22 = LpVariable("x22", 0, 12, 'Integer') x23 = LpVariable("x23", 0, 12, 'Integer') x24 = LpVariable("x24", 0, 12, 'Integer') x25 = LpVariable("x25", 0, 12, 'Integer') prob += 15 * x1 + 18 * x2 + 18 * x3 + 23 * x4 + 18 * x5 + 20 * x6 + 15 * x7 + 16 * x8 + 12 * x9 + 12 * x10 + 25 * x11 + 25 * x12 + 28 * x13 + 35 * x14 + 28 * x15 + 28 * x16 + 25 * x17 + 25 * x18 + 25 * x19 + 28 * x20 + 25 * x21 + 32 * x22 + 32 * x23 + 28 * x24 + 25 * x25, "obj" prob += 150 * x1 + 180 * x2 + 180 * x3 + 230 * x4 + 180 * x5 + 200 * x6 + 150 * x7 + 160 * x8 + 120 * x9 + 120 * x10 + 250 * x11 + 250 * x12 + 280 * x13 + 350 * x14 + 280 * x15 + 280 * x16 + 250 * x17 + 250 * x18 + 250 * x19 + 280 * x20 + 250 * x21 + 320 * x22 + 320 * x23 + 280 * x24 + 250 * x25 == 6600, "c1" prob.solve() print "Status:", LpStatus[prob.status] for v in prob.variables(): print v.name, "=", v.varValue print ("objective = %s" % value(prob.objective)) ``` But to this code I need append another restriction: For example, a restriction That the number of non-zero `prob.variables` must equal (say) 10. Could anybody help with that? UPDATE: For this code I have output: ``` Status: Optimal X1 = 1.0 x10 = 0.0 x11 = 0.0 x12 = 0.0 x13 = 0.0 x14 = 0.0 x15 = 0.0 x16 = 0.0 x17 = 0.0 x18 = 0.0 x19 = 0.0 x2 = 0.0 x20 = 0.0 x21 = 0.0 x22 = 0.0 x23 = 0.0 x24 = 0.0 x25 = 0.0 x3 = 0.0 x4 = 11.0 x5 = 0.0 x6 = 10.0 x7 = 0.0 x8 = 12.0 x9 = 0.0 objective = 660.0 ``` The number of `prob.variables` that have non-zero values equals only 4. But say I need 10, how would I ensure that?
If you want a certain number of non-zero values, you can do that by introducing new 0/1 variables. **Formulation** Introduce 25 new `Y` variables [y1..y25] which are all binary {0,1} If X[i] > 0, we want Y[i] to take on the value 1. You can do by adding the following constraints. ``` x[i] < y[i] x M (where M is some big number, say 10,000) for 1 in 1..25 ``` Now, to ensure that at least 10 Y values are non-zero, we want at least 10 of them to be 1. Sum over Y[1]...y[25] >= 10 will ensure that. **In PuLP** The puLP code is untested, but will give you the right idea to proceed. ``` x=[] y=[] for index in range(25): y[index] = LpVariable("y"+str(index), 0, 1) #binary variables prob += x[index] <= 10000 * y[index], "If x%s is non-zero, then y%s is forced to be 1",%index, %index prob += lpSum([y[i] for i in range(25)]) >= 10,"Ensuring at least 10 items are non-zero" ``` Hope that helps.
I second the provided answer, but also would comment on making better use of PuLP's (and Python's) list comprehensions for shorter code: ``` from pulp import * prob = LpProblem("Knapsack problem", LpMaximize) cost = [15,18,18,23,18,20,15,16,12,12,25,25,28,35,28,28,25,25,25,28,25,32,32,28,25] x = LpVariable.dicts('x',range(1,26),lowBound=0,upBound=12,cat=pulp.LpInteger) cap = [150,180,180,230,180,200,150,160,120,120,250,250,280,350,280,280,250,250,250,280,250,320,320,280,250] prob += pulp.lpSum([cost[ix]*x[ix] for ix in range(1,25)]), "obj" prob += pulp.lpSum([cap[ix]*x[ix] for ix in range(1,25)]) == 6600, "c1" prob.solve() print "Status:", LpStatus[prob.status] for v in prob.variables(): if v.varValue>0.0001: print v.name, "=", v.varValue print ("objective = %s" % value(prob.objective)) ``` I may have mistyped some coefficients in there, but I'm sure you get my point.
Knapsack in PuLP, adding Constraints on Number of Items selected
[ "", "python", "knapsack-problem", "pulp", "" ]
Suppose this for loop in `C/C++`: ``` int start_value = 10; int end_value = 20; for(int i=start_value;i<end_value;i++) cout << i; ``` And if `start_value` is greater than `end_value` the loop will not iterate. How to write the same thing in `Python'?
In python 3.x ``` start_value = 10; end_value = 20; for i in range(start_value, end_value): print(i) ``` In python 2.x ``` start_value = 10; end_value = 20; for i in xrange(start_value, end_value): print i ```
You can use the [`range()`](http://docs.python.org/2/library/functions.html#range) function: ``` start_value = 10 end_value = 20 for i in range(start_value, end_value): print i # Or print(i) in Python 3 ``` `range(10, 20)` returns: ``` [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] ``` Note that if you're using python 3, `range()` will return an iterator (the output will still be the same however). This can also be achieved in python 2 by using [`xrange()`](http://docs.python.org/2/library/functions.html#xrange). It is mainly used for performance advantages. In python, there is no need to do `i += 1` at the end of the loop because the for-loop automatically goes to the next item in the list after the loop.
How to write a special for loop case of C++ in Python?
[ "", "python", "for-loop", "" ]
My auto number has 2 parts 3 digits are serial number and last 8 digits are month and year of Invoice For example: `001072013` So if I want a next `InvoiceNo` I select from last entry of invoice number from database like this ``` select TOP 1 InvoiceNo from BuyInvoice ``` cut the first 3 digits, and make increment, and combine it to month and year of Invoice So it would be `002072013` The problem is the above statement doesn't return the last entry value and ascending and descending both don't work
I would try: ``` select TOP 1 InvoiceNo from BuyInvoice order by right(InvoiceNo,4) desc, right(InvoiceNo, 6) desc, InvoiceNo desc ```
*I assume that `BuyInvoice` table has an `InvoiceDate` column that has the same values like the `date` part of `InvoiceNo` column.* In this case I would use (the solution is not tested): ``` DECLARE @InvoiceDate DATE; SET @InvoiceDate='2013-07-20'; BEGIN TRANSACTION; DECLARE @LastInvoiceNo VARCHAR(9); SELECT TOP(1) @LastInvoiceNo=bi.InvoiceNo -- This table hint (UPDLOCK) take a U lock on this row[s] so any concurrent [similar] transactions will have to wait till this transaction is finished -- This will prevent duplicated new InvoiceNo FROM dbo.BuyInvoice bi WITH(UPDLOCK) WHERE bi.InvoiceDate=@InvoiceDate ORDER BY bi.InvoiceNo DESC; DECLARE @Seq SMALLINT; SET @Seq=ISNULL(CONVERT(SMALLINT,LEFT(@LastInvoiceNo,3)),0); SET @Seq=@Seq+1; DECLARE @NewInvoiceNo VARCHAR(9); SET @NewInvoiceNo=RIGHT('00'+CONVERT(VARCHAR(3),@Seq),3)+STUFF(STUFF(CONVERT(VARCHAR(10),@InvoiceDate,101),3,1,''),5,1,''); -- Convert style 101 = mm/dd/yyyy ... INSERT dbo.BuyInvoice(InvoiceNo,InvoiceDate,...) VALUES (@NewInvoiceNo,@InvoiceDate,...); ... COMMIT TRANSACTION; ``` Also, I would use `BEGIN TRY ... END CATCH` to intercept exceptions and to rollback this transaction if needed ([link](http://msdn.microsoft.com/en-us/library/ms175976.aspx) : example B). Also, I will create following indices: ``` -- This way, the InvoiceNo column will have uniques values CREATE UNIQUE INDEX IUN_BuyInvoice_InvoiceNo ON dbo.BuyInvoice(InvoiceNo); GO -- This index is used by SELECT TOP(1) ... query CREATE UNIQUE INDEX IN_BuyInvoice_InvoiceDate_InvoiceNo ON dbo.BuyInvoice(InvoiceDate,InvoiceNo); GO ```
sql statement to retrieve the last entry value from database
[ "", "sql", "sql-server", "" ]
I have this function: ``` def second(n): z =0 while z < n: z = z +1 for i in range(n): print(z) ``` which produces this output for `second(3)`: ``` 1 1 1 2 2 2 3 3 3 ``` How can I store these in a list for further use?
Print doesn't save the results - it just sends them (one at a time) to standard output (stdout) for display on the screen. To get an in order copy of the results I humbly suggest you turn this into a [generator function](http://wiki.python.org/moin/Generators) by using the `yield` keyword. For example: ``` >>> def second(n): ... z =0 ... while z < n: ... z = z +1 ... for i in range(n): ... yield z ... >>> print list(second(3)) [1, 1, 1, 2, 2, 2, 3, 3, 3] ``` In the above code `list()` expands the generator into a list of results that you can assign to a variable to save. If you want to save a list of all the results for `second(3)` you could alternatively do `results = list(second(3))` instead of printing it.
You could utilise `itertools` here to return an iterable for you, and either loop over that, or explicitly convert to a `list`, eg: ``` from itertools import chain, repeat def mysecond(n): return chain.from_iterable(repeat(i, n) for i in xrange(1, n)) print list(mysecond(3)) ```
How to store the result of a function in a list?
[ "", "python", "list", "" ]
I am parsing PDB files and I have a list of chain names along with XYZ coordinates in the format (chain,[coordinate]). I have many coordinates, but only 3 different chains. I would like to condense all of the coordinates from the same chain to be in one list so that i get chain = [coordinate], [coordinate],[coordinate] and so on. I looked at the biopython documentation, but I had a hard time understanding exactly how to get the coordinates I wanted, so I decided to extract the coordinates manually. This is the code I have so far: ``` pdb_file = open('1adq.pdb') import numpy as np chainids = [] chainpos= [] for line in pdb_file: if line.startswith("ATOM"): # get x, y, z coordinates for Cas chainid =str((line[20:22].strip())) atomid = str((line[16:20].strip())) pdbresn= int(line[23:26].strip()) x = float(line[30:38].strip()) y = float(line[38:46].strip()) z = float(line[46:54].strip()) if line[12:16].strip() == "CA": chainpos.append((chainid,[x, y, z])) chainids.append(chainid) allchainids = np.unique(chainids) print(chainpos) ``` and some output: ``` [('A', [1.719, -25.217, 8.694]), ('A', [2.934, -21.997, 7.084]), ('A', [5.35, -19.779, 8.986]) ``` My ideal output would be: ``` A = ([1.719, -25.217, 8.694]), ([2.934, -21.997, 7.084]),(5.35, -19.779,8.986])... ``` Thanks! ``` Here is a section of PDB file: ATOM 1 N PRO A 238 1.285 -26.367 7.882 0.00 25.30 N ATOM 2 CA PRO A 238 1.719 -25.217 8.694 0.00 25.30 C ATOM 3 C PRO A 238 2.599 -24.279 7.885 0.00 25.30 C ATOM 4 O PRO A 238 3.573 -24.716 7.275 0.00 25.30 O ATOM 5 CB PRO A 238 2.469 -25.791 9.881 0.00 25.30 C ``` A is the chain name there in column 4. I do not know what the chain name is a priori but since I am parsing line by line, I am sticking the chain name with the coordinates in the format I mentioned earlier. Now I would like to pull all of the coordinates with an "A" before them and stick them in one list called "A". I can't just hard code in an "A" because it is not always "A". I also have "L" and "H", but I think I can get them once I get over the hump of understanding..
just make a list of tuple ``` >>> chainpos.append((chainid,x, y, z)) >>> chainpos [('A', 1.719, -25.217, 8.694), ('A', 2.934, -21.997, 7.084)] >>> import itertools >>> for id, coor in itertools.groupby(chainpos,lambda x:x[0]): ... print(id, [c[1:] for c in coor]) ```
Do you want something like: ``` import numpy as np chain_dict = {} for line in open('input'): if line.startswith("ATOM"): line = line.split() # get x, y, z coordinates for Cas chainid = line[4] atomid = line[2] pdbresn= line[5] xyz = [line[6],line[7],line[8]] if chainid not in chain_dict: chain_dict[chainid]=[xyz] else: chain_dict[chainid].append(xyz) ``` which, for your example data, gives: ``` >>> chain_dict {'A': [['1.285', '-26.367', '7.882'], ['1.719', '-25.217', '8.694'], ['2.599', '-24.279', '7.885'], ['3.573', '-24.716', '7.275'], ['2.469', '-25.791', '9.881']] ``` and since it's a dictionary, obviously you can do: ``` >>> chain_dict['A'] [['1.285', '-26.367', '7.882'], ['1.719', '-25.217', '8.694'], ['2.599', '-24.279', '7.885'], ['3.573', '-24.716', '7.275'], ['2.469', '-25.791', '9.881']] ``` to get just the xyz coords of the chain you're interested in.
Separating a list of (X,Y)
[ "", "python", "list", "zip", "biopython", "" ]
I am learning Python, and struggling with conditions of a `for` loop. I must be missing something simple. I have a list with some int values, and I want to (1) print all even numbers and (2) only print values up to a certain index. I can print the even numbers fine, but cannot seem to print only to a certain index. ``` numbers = [951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345] ``` 1. Prints all numbers in list -- ok: ``` for i in numbers: print i ``` 2. Prints all even numbers in the list -- ok: ``` for i in numbers: if i % 2 == 0: print i ``` Let's say I want to only print even numbers up to and including the entry with the value 980 -- so that would be 402, 984, 360, 408, 980. I have tried, unsuccessfully, to implement a count and while loop and also a conditional where I print `numbers[n] < numbers.index(980)`.
There is a `break` statement which leaves current loop: ``` >>> for i in numbers: ... if i % 2 == 0: ... print i ... if i == 980: ... break ... 402 984 360 408 980 ```
Use the [`enumerate()` function](http://docs.python.org/2/library/functions.html#enumerate) to include a loop index: ``` for i, num in enumerate(numbers): if num % 2 == 0 and i < 10: print num ``` Alternatively, just slice your list to only consider the first `n` elements, albeit that that creates a new copy of the sublist: ``` for num in numbers[:10]: if num % 2 == 0: print num ``` If you need to test for specific values of `num`, you can also exit a `for` loop early with `break`: ``` for i, num in enumerate(numbers): if num % 2 == 0: print num if num == 980 or i >= 10: break # exits the loop early ```
Python (loops) with a list
[ "", "python", "list", "loops", "" ]
How to select the records for the 3 recent years, with JUST considering the year instead of the whole date `dd-mm-yy`. let's say this year is 2013, the query should display all records from 2013,2012 and 2011. if next year is 2014, the records shall be in 2014, 2013, 2012 and so on.... ``` table foo ID DATE ----- --------- a0001 20-MAY-10 a0002 20-MAY-10 a0003 11-MAY-11 a0004 11-MAY-11 a0005 12-MAY-11 a0006 12-JUN-12 a0007 12-JUN-12 a0008 12-JUN-12 a0009 12-JUN-13 a0010 12-JUN-13 ```
I think the clearest way is to use the `year()` function: ``` select * from t where year("date") >= 2011; ``` However, the use of a function in the `where` clause often prevents an index from being used. So, if you have a large amount of data and an index on the date column, then something that uses the current date is better. The following takes this approach: ``` select * from t where "date" >= trunc(add_months(sysdate, -3*12), 'yyyy') ```
``` SELECT ID, DATE FROM FOO WHERE DATE >= TRUNC(ADD_MONTHS(SYSDATE, -3*12), 'YYYY'); ``` Here we are getting last 36 months data by using **ADD\_MONTHS**. We are **adding 12\*3** i.e. last 3 years data froom **SYSDATE**
select record for recent n years
[ "", "sql", "oracle", "date", "select", "" ]
Given the JSON below, what would be the best way to create a hierarchical list of "name" for a given "id"? There could be any number of sections in the hierarchy. For example, providing id "156" would return "Add Storage Devices, Guided Configuration, Configuration" I've been looking into using `iteritems()`, but could do with some help. ``` { "result": true, "sections": [ { "depth": 0, "display_order": 1, "id": 154, "name": "Configuration", "parent_id": null, "suite_id": 5 }, { "depth": 1, "display_order": 2, "id": 155, "name": "Guided Configuration", "parent_id": 154, "suite_id": 5 }, { "depth": 2, "display_order": 3, "id": 156, "name": "Add Storage Devices", "parent_id": 155, "suite_id": 5 }, { "depth": 0, "display_order": 4, "id": 160, "name": "NEW", "parent_id": null, "suite_id": 5 }, { "depth": 1, "display_order": 5, "id": 161, "name": "NEWS", "parent_id": 160, "suite_id": 5 } ] } ```
Here's one approach: ``` def get_path(data, section_id): path = [] while section_id is not None: section = next(s for s in data["sections"] if s["id"] == section_id) path.append(section["name"]) section_id = section["parent_id"] return ", ".join(path) ``` ... which assumes that `data` is the result of `json.loads(json_text)` or similar, and `section_id` is an `int` (which is what you've got for ids in that example JSON). For your example usage: ``` >>> get_path(data, 156) u'Add Storage Devices, Guided Configuration, Configuration' ```
Probably the simplest way is to create a dictionary mapping the IDs to names. For example: ``` name_by_id = {} data = json.loads(the_json_string) for section in data['sections']: name_by_id[section['id']] = section['name'] ``` or using dict comprehensions: ``` name_by_id = {section['id']: section['name'] for section in data['sections']} ``` then you can get specific element: ``` >>> name_by_id[156] ... 'Add Storage Devices' ``` or get all IDs: ``` >>> name_by_id.keys() ... [160, 161, 154, 155, 156] ```
Creating a hierarchy path from JSON
[ "", "python", "json", "" ]
When I try to upload file via FileField of my model using Django administration I get following response from Django development server: ``` <h1>Bad Request (400)</h1> ``` The only output in console is: ``` [21/Jul/2013 17:55:23] "POST /admin/core/post/add/ HTTP/1.1" 400 26 ``` I have tried to find an error log, but after reading few answers here I think there is nothing like that because Django usually prints debug info directly to browser window when `Debug=True` (my case). How can I debug this problem further?
In my case it was a leading '/' character in models.py. Changed `/products/` to `products/` in: `product_image = models.ImageField(upload_to='products/')`
Please check your upload location. I've also had 400 and in my case it was a permission issue. > ERROR 2013-12-15 19:23:37,044 base 22938 140546689459968 Attempted access to '/uploads/nook.jpg' denied. Configuring logging as shown here helped me: <https://docs.djangoproject.com/en/1.6/topics/logging/#configuring-logging>
File upload - Bad request (400)
[ "", "python", "django", "" ]
Have a call to an SQL db via python that returns output in paired dictionaries within a list: ``` [{'Something1A':Num1A}, {'Something1B':Num1B}, {'Something2A':Num2A} ...] ``` I want to iterate through this list but pull two dictionaries at the same time. I know that `for obj1, obj2 in <list>` isn't the right way to do this, but what is?
You can do this using zip with an iterator over the list: ``` >>> dicts = [{'1A': 1}, {'1B': 2}, {'2A': 3}, {'2B': 4}] >>> for obj1, obj2 in zip(*[iter(dicts)]*2): print obj1, obj2 {'1A': 1} {'1B': 2} {'2A': 3} {'2B': 4} ```
Use [`zip()`](http://docs.python.org/2/library/functions.html#zip) here. ``` >>> testList = [{'2': 2}, {'3':3}, {'4':4}, {'5':5}] >>> for i, j in zip(testList[::2], testList[1::2]): print i, j {'2': 2} {'3': 3} {'4': 4} {'5': 5} ``` Alternative (without using `zip()`): ``` for elem in range(0, len(testList), 2): firstDict, secondDict = testList[i], testList[i+1] ```
python: iterate through two objects in a list at once
[ "", "python", "list", "dictionary", "iteration", "" ]
I've got a `DataFrame` which contains stock values. It looks like this: ``` >>>Data Open High Low Close Volume Adj Close Date 2013-07-08 76.91 77.81 76.85 77.04 5106200 77.04 ``` When I try to make a conditional new column with the following if statement: ``` Data['Test'] =Data['Close'] if Data['Close'] > Data['Open'] else Data['Open'] ``` I get the following error: ``` Traceback (most recent call last): File "<pyshell#116>", line 1, in <module> Data[1]['Test'] =Data[1]['Close'] if Data[1]['Close'] > Data[1]['Open'] else Data[1]['Open'] ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() ``` I then used `a.all()` : ``` Data[1]['Test'] =Data[1]['Close'] if all(Data[1]['Close'] > Data[1]['Open']) else Data[1]['Open'] ``` The result was that the entire `['Open']` Column was selected. I didn't get the condition that I wanted, which is to select every time the biggest value between the `['Open']` and `['Close']` columns. Any help is appreciated. Thanks.
From a DataFrame like: ``` >>> df Date Open High Low Close Volume Adj Close 0 2013-07-08 76.91 77.81 76.85 77.04 5106200 77.04 1 2013-07-00 77.04 79.81 71.81 72.87 1920834 77.04 2 2013-07-10 72.87 99.81 64.23 93.23 2934843 77.04 ``` The simplest thing I can think of would be: ``` >>> df["Test"] = df[["Open", "Close"]].max(axis=1) >>> df Date Open High Low Close Volume Adj Close Test 0 2013-07-08 76.91 77.81 76.85 77.04 5106200 77.04 77.04 1 2013-07-00 77.04 79.81 71.81 72.87 1920834 77.04 77.04 2 2013-07-10 72.87 99.81 64.23 93.23 2934843 77.04 93.23 ``` `df.ix[:,["Open", "Close"]].max(axis=1)` might be a little faster, but I don't think it's as nice to look at. Alternatively, you could use `.apply` on the rows: ``` >>> df["Test"] = df.apply(lambda row: max(row["Open"], row["Close"]), axis=1) >>> df Date Open High Low Close Volume Adj Close Test 0 2013-07-08 76.91 77.81 76.85 77.04 5106200 77.04 77.04 1 2013-07-00 77.04 79.81 71.81 72.87 1920834 77.04 77.04 2 2013-07-10 72.87 99.81 64.23 93.23 2934843 77.04 93.23 ``` Or fall back to numpy: ``` >>> df["Test"] = np.maximum(df["Open"], df["Close"]) >>> df Date Open High Low Close Volume Adj Close Test 0 2013-07-08 76.91 77.81 76.85 77.04 5106200 77.04 77.04 1 2013-07-00 77.04 79.81 71.81 72.87 1920834 77.04 77.04 2 2013-07-10 72.87 99.81 64.23 93.23 2934843 77.04 93.23 ``` The basic problem is that `if/else` doesn't play nicely with arrays, because `if (something)` always coerces the `something` into a single `bool`. It's not equivalent to "for every element in the array something, if the condition holds" or anything like that.
``` In [7]: df = DataFrame(randn(10,2),columns=list('AB')) In [8]: df Out[8]: A B 0 -0.954317 -0.485977 1 0.364845 -0.193453 2 0.020029 -1.839100 3 0.778569 0.706864 4 0.033878 0.437513 5 0.362016 0.171303 6 2.880953 0.856434 7 -0.109541 0.624493 8 1.015952 0.395829 9 -0.337494 1.843267 ``` This is a where conditional, saying give me the value for A if A > B, else give me B ``` # this syntax is EQUIVALENT to # df.loc[df['A']>df['B'],'A'] = df['B'] In [9]: df['A'].where(df['A']>df['B'],df['B']) Out[9]: 0 -0.485977 1 0.364845 2 0.020029 3 0.778569 4 0.437513 5 0.362016 6 2.880953 7 0.624493 8 1.015952 9 1.843267 dtype: float64 ``` In this case `max` is equivalent ``` In [10]: df.max(1) Out[10]: 0 -0.485977 1 0.364845 2 0.020029 3 0.778569 4 0.437513 5 0.362016 6 2.880953 7 0.624493 8 1.015952 9 1.843267 dtype: float64 ```
New column based on conditional selection from the values of 2 other columns in a Pandas DataFrame
[ "", "python", "pandas", "python-3.3", "" ]
I'm playing around with the Angel List (AL) API and want to pull all jobs in San San Francisco. Since I couldn't find an active Python wrapper for the api (if I make any headway, I think I'd like to make my own), I'm using the requests library. The AL API's results are paginated, and I can't figure out how to move beyond the first page of the results. Here is my code: ``` import requests r_sanfran = requests.get("https://api.angel.co/1/tags/1664/jobs").json() r_sanfran.keys() # returns [u'per_page', u'last_page', u'total', u'jobs', u'page'] r_sanfran['last_page'] #returns 16 r_sanfran['page'] # returns 1 ``` I tried adding arguments to `requests.get`, but that didn't work. I also tried something really dumb - changing the value of the 'page' key like that was magically going to paginate for me. eg. `r_sanfran['page'] = 2` I'm guessing it's something relatively simple, but I can't seem to figure it out so any help would be awesome. Thanks as always. [Angel List API documentation](https://angel.co/api) if it's helpful.
Read `last_page` and make a get request for each page in the range: ``` import requests r_sanfran = requests.get("https://api.angel.co/1/tags/1664/jobs").json() num_pages = r_sanfran['last_page'] for page in range(2, num_pages + 1): r_sanfran = requests.get("https://api.angel.co/1/tags/1664/jobs", params={'page': page}).json() print r_sanfran['page'] # TODO: extract the data ```
Improving on @alecxe's answer: if you use a Python Generator and a requests HTTP session you can improve the performance and resource usage if you are querying lots of pages or very large pages. ``` import requests session = requests.Session() def get_jobs(): url = "https://api.angel.co/1/tags/1664/jobs" first_page = session.get(url).json() yield first_page num_pages = first_page['last_page'] for page in range(2, num_pages + 1): next_page = session.get(url, params={'page': page}).json() yield next_page for page in get_jobs(): # TODO: process the page ```
Python requests arguments/dealing with api pagination
[ "", "python", "api", "http", "pagination", "python-requests", "" ]
I've got a python formula that randomly places operands in between numbers. The list could, for example, look like this: ``` ['9-8+7', '7-8-6'] ``` What I want to do is get the value of each string, so that looping through the strings, an array would see 9-8+7 and would append 8 and 7-8-6 would append -7. I can't convert a string with operands to int, so is this possible at all? Or should I change the algorithm so that instead of creating a string with each random output it calculates the value of it immediately? Thank you in advance.
You can do `eval` on the list items, but that's a potential security hole and should only be used if you fully trust the source. ``` >>> map(eval, ['9-8+7', '7-8-6']) [8, -7] ``` If you control the code producing the string, computing the values directly sounds like a better approach (safer and probably faster).
As Fredrik pointed out, you can do eval in Python. I thought I'd add a more general approach that would work in any language, and might shed some light on simple parsers for those that haven't seen them in action. You're describing a language whose formal definition looks something like this: ``` expr := sum sum := prod [("+" | "-") prod]... prod := digit [("*" | "/") digit]... digit := '0'..'9' ``` This grammar (which I'm not bothering to make correct EBNF) accepts these strings: "3", "4\*5/2", and "8\*3+9", and so on. This gives us a clue how to parse it, and evaluation is no more work than accumulating results as we go. The following is working Python 2 code. Notice how closely the code follows the grammar. ``` class ParseFail(Exception): pass def eval_expr(str): value, pos = eval_sum(str, 0) return value def eval_sum(str, pos): value, pos = eval_product(str, pos) accum = value while pos != len(str): op = str[pos] if not str[pos] in ['+', '-']: raise ParseFail("Unexpected symbol at position " "{pos} of {str}".format(str=str, pos=pos)) value, pos = eval_product(str, pos + 1) if op == '+': accum += value else: accum -= value return accum, pos def eval_product(str, pos): value, pos = eval_digit(str, pos) accum = value while pos != len(str): op = str[pos] if not str[pos] in ['*', '/']: return accum, pos value, pos = eval_digit(str, pos + 1) if op == '*': accum *= value else: accum /= value return accum, pos def eval_digit(str, pos): if not str[pos].isdigit(): raise ParseFail("Unexpected symbol at position " "{pos} of {str}".format(str=str, pos=pos)) return int(str[pos]), pos + 1 try: print "3 ->", eval_expr("3") print "3*4 ->", eval_expr("3*4") print "2+3*4-5 ->", eval_expr("2+3*4-5") # Should raise ParseFail print "2+3*4^2-5 ->", eval_expr("2+3*4^2-5") except ParseFail as err: print print err.args[0] ``` Here's a sample run: ``` $ python simple_expr.py 3 -> 3 3*4 -> 12 2+3*4-5 -> 9 2+3*4^2-5 -> Unexpected symbol at position 5 of 2+3*4^2-5 ``` It would be pretty easy to extend this to a full string calculator with more operators, such as the exponent operator '^' and multi-digit integers. Parentheses, floats and functions might be a bit of work, but not that hard either. Every programmer should try it once in their lives, in my opinion.
Calculate from list of strings - Python
[ "", "python", "string", "int", "" ]
I'm pretty useless at SQL it seems and I'm trying to figure out what is the correct query to use. I have a table Items and a table Reservations. An item can have many reservations and reservations are made between two dates. I'm trying to create a search query which will return all the Items which don't have reservations between two user inputted dates. the SQL I have at the minute looks like: ``` SELECT `Item`.`id`, `Item`.`user_id`, `Item`.`name`, `Item`.`description`, `User`.`id`, `User`.`username`, `User`.`password`, `User`.`email` FROM `database`.`items` AS `Item` LEFT JOIN `database`.`reservations` AS `ReservationJoin` ON (`ReservationJoin`.`item_id` = `Item`.`id` AND `ReservationJoin`.`start` >= '2013-07-17' and `ReservationJoin`.`finnish` <= '2013-07-20') LEFT JOIN `database`.`users` AS `User` ON (`Item`.`user_id` = `User`.`id`) WHERE ((`Item`.`name` LIKE '%projector%') OR (`Item`.`description` LIKE '%projector%') AND `ReservationJoin`.`id` IS NULL LIMIT 10 ``` I'm doing this in cakephp 2.3 so the code looks like: ``` $this->paginate = array( "conditions" => array( "or" => array( "Item.name LIKE" => '%'.$projector.'%', "Item.description LIKE" => '%'.$projector.'%', ), "ReservationJoin.id" => null, ), "joins" => array( array( "table" => "reservations", "alias" => "ReservationJoin", "type" => "LEFT", "conditions" => array( "ReservationJoin.item_id = Item.id", "ReservationJoin.checkin >= '{$start}' and ReservationJoin.checkout <= '{$finnish}'", ) ) ), "limit"=>10 ); $data = $this->paginate('Item'); ``` This isn't working and I think it's to do with the join not excluding the reservations properly. But I've not been able to figure out what the correct mysql is. Can a kind soul tell me what I should be using? thanks
I think it may be easier for you in CakePHP to put all of the conditions in a WHERE clause. (This could also be done with some OUTER JOINs but it may be difficult to transcribe into CakePHP) ``` SELECT id, user_id, name, description FROM items WHERE ((name LIKE '%projector%') OR (description LIKE '%projector%')) AND NOT EXISTS( SELECT * FROM reservations WHERE items.id = reservations.item_id AND ( '2013-07-17' BETWEEN start and finnish OR '2013-07-20' BETWEEN start and finnish OR start BETWEEN '2013-07-17' AND '2013-07-20')); ``` Or, using the same logic the WHERE clause can be cleaned up to be ``` SELECT id, user_id, name, description FROM items WHERE ((name LIKE '%projector%') OR (description LIKE '%projector%')) AND NOT EXISTS( SELECT * FROM reservations WHERE items.id = reservations.item_id AND NOT( '2013-07-17' > finnish OR '2013-07-20' < start )); ```
If something has a reservation between two dates, then one of the following is true: 1. It has a start date between the dates 2. It has an end date between the dates 3. It has a start date before the earlier date and an end date after the second one The following query uses this logic in a `having` clause. The approach is to aggregate at the item level and ensure that the three above conditions are true: ``` SELECT i.`id`, i.`user_id`, i.`name`, i.`description` FROM `database`.`items`i LEFT JOIN `database`.`reservations` r ON r.`item_id` = i.`id` WHERE ((i.`name` LIKE '%projector%') OR (i.`description` LIKE '%projector%') group by i.id having max(start between '2013-07-17' and '2013-07-20') = 0 and max(finish between '2013-07-17' and '2013-07-20') = 0 and max(start < '2013-07-17' and finished > '2013-07-20') = 0 LIMIT 10; ``` Note that none matches are returned, because the conditions are treated as false when `start` and `ned` are NULL.
mysql query - how to find items not within certain dates
[ "", "mysql", "sql", "cakephp", "" ]
I have the following table I want to update the status from 0 to 1 and 1 to 0 in a single query ``` ID Name Status ------------------------------------------ 1 Ben 0 2 John 1 3 Mark 0 4 Gates 0 5 Ricky 1 ```
If column status can be `null` or status can have more than two values, this solution should work for you. ``` update tab set status = case when status=0 then 1 when status=1 then 0 end ```
Plenty of ways to do this, as the number of answers already show. Mine would just be: ``` UPDATE [Table] set status = 1-status ``` If there are non-0 and non-1 rows in the table that shouldn't be touched, I'd also add: ``` WHERE status in (0,1) ```
Update values in column in a single query
[ "", "sql", "sql-server-2008", "" ]
While following a tutorial for python, I got to know that we can use *print* for a variable name, and it works fine. But after assigning the print variable, how do we get back the original print function? ``` >>> print("Hello World!!") Hello World!!! >>> print = 5 >>> print("Hi") ``` Now, the last call gives the error **TypeError: 'int' object is not callable**, since now print has the integer value 5. But, how do we get back the original functionality of print now? Should we use the class name for the print function or something? As in, `SomeClass.print("Hi")`? Thanks in advance.
``` >>> print = 5 >>> print = __builtins__.print >>> print("hello") hello ```
You can actually delete the variable so the built-in function will work again: ``` >>> print = 5 >>> print('cabbage') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable >>> del print >>> print('cabbage') cabbage ```
Using print as a variable name in python
[ "", "python", "" ]
This should be simple but I can't figure this one out. I need to get a row of data that where a field in that row is the max value of that column and a particular status has been set on that row filtered down by a value. This is an example of the table: ``` ID Date Entered Item Status 1 1/1/2012 Joe Ready 2 1/2/2012 Joe Ready 3 1/1/2012 Sam Ready 4 1/2/2012 Sam Not Ready 5 1/2/2012 Sam Ready 6 1/1/2013 Jimmy Not Ready ``` The result set that I want to get back is: ``` ID Date Entered Item Status 2 1/2/2012 Joe Ready 5 1/2/2012 Sam Ready ``` This is one of my many failed attempts thus far: ``` Select id, max(Date_Entered), Item from table1 where status = 'Ready' Group by Item, id ``` This returns too many items with duplicates ``` Select max(Date_Entered), RELEASE_GROUP_C from table1 where status = 'Ready' Group by item ``` This doesn't return the ID.
You can use the `ROW_NUMBER()` function for this: ``` SELECT ID, [Date Entered], Item, Status FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY Item ORDER BY [Date Entered] DESC)'RowRank' FROM Table1 WHERE Status = 'Ready' )sub WHERE RowRank = 1 ``` Demo: [SQL Fiddle](http://sqlfiddle.com/#!3/d8a8b/1/0) The `ROW_NUMBER()` function assigns a number to each row starting at 1 for each grouping defined in the `PARTITION BY` section and the order based on the `ORDER BY` section, in this case, for each `Item` it will start numbering at 1 for the newest/latest date.
Like this? ``` SELECT ID, Date_Entered, Item, Status FROM t1 WHERE Status = 'Ready' AND t1.Date_Entered = (SELECT MAX(Date_Entered) FROM t1) ```
SQL statement to to find where items are of a type, contain a status, and are the most recent addition
[ "", "sql", "sql-server", "" ]
I've come cross this question. Code: ``` >>> values = [0, 1, 2] >>> values[1] = values >>> values [0, [...], 2] ``` The result I expect is: ``` [0, [0, 1, 2], 2] ``` Is this an infinite assignment for python list? What is behind the scene? Thanks.
You have a recursive list there. `values[1]` is a reference to `values`. If you want to store the value of `values` you need to copy it, the easiest way to do so is ``` values[1] = values[:] ```
You put the same list as the second element inside itself. So the second element of the internal list is itself again. You need to copy initial list to avoid recursion: ``` >>> values[1] = values[:] ```
infinite assignment in python list?
[ "", "python", "list", "infinite", "" ]
I have an existing Stored procedure that generate employee ID. The employee ID have a format of EPXXXX, EP then 4 numeric values. I want my stored procedure to be shorten. ![enter image description here](https://i.stack.imgur.com/fV9Ya.png) given the table (tblEmployee) above. Below is the stored procedure for inserting the new employee with the new employee number. The process is I have to get the last employee id, get the last 4 digits (which is the number), convert it to integer, add 1 to increment, check if the number is less than 10, 100 or 1000 or equal/greater than 1000, add the prefix before inserting the new records to the table. ``` create procedure NewEmployee @EmployeeName VARCHAR(50) AS BEGIN SET NOCOUNT ON DECLARE @lastEmpID as VARCHAR(6) SET @lastEmpID = ( SELECT TOP 1 Employee_ID FROM tblEmployee ORDER BY Employee_ID DESC ) DECLARE @empID as VARCHAR(4) SET @empID = ( SELECT RIGHT(@lastEmpID, 4) ) DECLARE @numEmpID as INT @numEmpID = ( SELECT CONVERT(INT, @empID) + 1 ) DECLARE @NewEmployeeID as VARCHAR(6) IF @numEmp < 10 SET @NewEmployee = SELECT 'EP000' + CONVERT(@EmpID) IF @numEmp < 100 SET @NewEmployee = SELECT 'EP00' + CONVERT(@EmpID) IF @numEmp < 1000 SET @NewEmployee = SELECT 'EP0' + CONVERT(@EmpID) IF @numEmp >= 1000 SET @NewEmployee = SELECT 'EP' + CONVERT(@EmpID) INSERT INTO tblEmployee(Employee_ID, Name) VALUES (@NewEmployeeID, @EmployeeName) END ```
Try this one - ``` CREATE PROCEDURE dbo.NewEmployee @EmployeeName VARCHAR(50) AS BEGIN SET NOCOUNT ON; INSERT INTO dbo.tblEmployee(Employee_ID, Name) SELECT 'EP' + RIGHT('0000' + CAST(Employee_ID + 1 AS VARCHAR(4)), 4) , @EmployeeName FROM ( SELECT TOP 1 Employee_ID = CAST(RIGHT(Employee_ID, 4) AS INT) FROM dbo.tblEmployee ORDER BY Employee_ID DESC ) t END ```
I'm not suggesting over what you have currently but, i'd do this way. This is the way I've implemented in my application. Which im gonna give you. Hope you Like this. This is fully Dynamic and Works for all the Transaction you could have. I've a table Which hold the Document Number as : ``` CREATE TABLE INV_DOC_FORMAT( DOC_CODE VARCHAR(10), DOC_NAME VARCHAR(100), PREFIX VARCHAR(10), SUFFIX VARCHAR(10), [LENGTH] INT, [CURRENT] INT ) ``` Which would hold the Data Like : ``` INSERT INTO INV_DOC_FORMAT(DOC_CODE,DOC_NAME,PREFIX,SUFFIX,[LENGTH],[CURRENT]) VALUES('01','INV_UNIT','U','',5,0) INSERT INTO INV_DOC_FORMAT(DOC_CODE,DOC_NAME,PREFIX,SUFFIX,[LENGTH],[CURRENT]) VALUES('02','INV_UNIT_GROUP','UG','',5,0) ``` And, i'd have a fUNCTION OR Procedure but, i've an function here Which would generate the Document Number. ``` CREATE FUNCTION GET_DOC_FORMAT(@DOC_CODE VARCHAR(100))RETURNS VARCHAR(100) AS BEGIN DECLARE @PRE VARCHAR(10) DECLARE @SUF VARCHAR(10) DECLARE @LENTH INT DECLARE @CURRENT INT DECLARE @FORMAT VARCHAR(100) DECLARE @REPEAT VARCHAR(10) IF NOT EXISTS(SELECT DOC_CODE FROM INV_DOC_FORMAT WHERE DOC_CODE=@DOC_CODE) RETURN '' SELECT @PRE= PREFIX FROM INV_DOC_FORMAT WHERE DOC_CODE=@DOC_CODE SELECT @SUF= SUFFIX FROM INV_DOC_FORMAT WHERE DOC_CODE=@DOC_CODE SELECT @LENTH= [LENGTH] FROM INV_DOC_FORMAT WHERE DOC_CODE=@DOC_CODE SELECT @CURRENT= [CURRENT] FROM INV_DOC_FORMAT WHERE DOC_CODE=@DOC_CODE SET @REPEAT=REPLICATE('0',(@LENTH-LEN(CONVERT(VARCHAR, @CURRENT)))) SET @FORMAT=@PRE + @REPEAT +CONVERT(VARCHAR, @CURRENT+1) + @SUF RETURN @FORMAT END ``` You can use the Function like : ``` INSERT INTO INV_UNIT(UNIT_CODE,UNIT_NAME,UNIT_ALIAS,APPROVED,APPROVED_USER_ID,APPROVED_DATE) VALUES(DBO.GET_DOC_FORMAT('01'),@Unit_Name,@Unit_Alias,@APPROVED,@APPROVED_USER_ID,@APPROVED_DATE) --After Transaction Successfully complete, You can UPDATE INV_DOC_FORMAT SET [CURRENT]=[CURRENT]+1 WHERE DOC_CODE='01' ``` Or, you can create an Single Procedure which would handle all the things alone too. Hope you got the way... Hence, Looking at your Way, you are making an Mistake. You are getting SET @lastEmpID = ( SELECT TOP 1 Employee\_ID FROM tblEmployee ORDER BY Employee\_ID DESC ) Last employee id, and then you are manipulating the rest of the ID. This would create or reuse the ID that was generated earlier however deleted now. Suppose EMP0010 was there. After some day that EMP has been Deleted. So, When you again create an Employeee next time, You gonna have Same Emp ID you had before for anohter Employe but no more exits however. I dont think thats a good idea. And, Instead of this : ``` DECLARE @NewEmployeeID as VARCHAR(6) IF @numEmp < 10 SET @NewEmployee = SELECT 'EP000' + CONVERT(@EmpID) IF @numEmp < 100 SET @NewEmployee = SELECT 'EP00' + CONVERT(@EmpID) IF @numEmp < 1000 SET @NewEmployee = SELECT 'EP0' + CONVERT(@EmpID) IF @numEmp >= 1000 SET @NewEmployee = SELECT 'EP' + CONVERT(@EmpID) ``` Which you used to repeat an Zero. You would use **Replicate Function()** of SQL. Like above on the Example of Mine. ``` SET @REPEAT=REPLICATE('0',(@LENTH-LEN(CONVERT(VARCHAR, @CURRENT)))) ```
Auto increment Alphanumeric ID in MSSQL
[ "", "sql", "sql-server", "" ]
I was implementing the dynamic programming algorithm and I got this error. This is my code: ``` def shoot(aliens): s=[0]*10 s[0]=0 s[1]=0 for j in xrange(2,len(aliens)): for i in xrange(0,j): s[j]=max(s[i] + min(aliens[j],fib(j-i))) <---Error here print s[len(aliens)-1] return s[len(aliens)-1] def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n-1) + fib(n-2) aliens=[1,10,10,1] print shoot(aliens) ``` it says that: ``` Traceback (most recent call last): File "module1.py", line 30, in <module> print shoot(aliens) File "module1.py", line 19, in shoot s[j]=max(s[i] + min(aliens[j],fib(j-i))) TypeError: 'int' object is not iterable ``` Please help me UPDATE: oh, I get it. I mean ``` s[j]=max(s[i] + min(aliens[j],fib(j-i))) ``` But im wrong. so, I edited it like that, but I do not know how to use max() to take out the largest in an array. ``` b=0 for j in xrange(2,len(aliens)): for i in xrange(0,j): a[b]=(s[i] + min(aliens[j],fib(j-i))) b+=1 s[j]=Largest(a[b]); <--How can I do that with Max() function ```
`max` and `min` functions require several arguments or a range of elements. Your call to `min()` has two arguments (ok), but your call to `max()` has only one. Not sure what you want to maximize here...
You are doing something like following: ``` >>> max(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable ``` Did you want to do this? ``` s[j] = max(s[i], min(aliens[j],fib(j-i))) ``` or ``` s[j] = max(s[j], s[i] + min(aliens[j],fib(j-i))) ```
TypeError: 'int' object is not iterable?
[ "", "python", "" ]
I have a table like so: ``` Item --------- id parentId name inventoryNumber ``` I need to update the inventoryNumber if and only if the row... 1. parentId = 12345 2. name string matches exactly a given string "The quick brown fox" 3. the row is the only row that matches the first two criteria. I believe I know how to do this if I was just doing a select... ``` SELECT * FROM Item WHERE parentId=12345 AND name LIKE 'The quick brown fox' HAVING count(*)=1 ``` but I need to update the row... `UPDATE Item SET inventoryNumber = 456 WHERE` *this is the only row where parentId=12345 and the only row where name='The quick brown fox'* I have about 5000 of these rows to update so it would greatly reduce my workload if I can get a way to update in a single statement. Can this be done? **UPDATE:** I already tried putting this in a subquery like: ``` UPDATE Item SET inventoryNumber = 456 WHERE id IN ( SELECT id FROM Item WHERE parentId = 12345 AND name LIKE 'The quick brown fox' HAVING count(*)=1 ); ``` But I get an error from MySql when I do that "You can't specify target table 'item' for update in FROM clause:
How about using a `subquery`: **EDIT** ``` CREATE TABLE Item_tmp LIKE Item; INSERT INTO Item_tmp SELECT * FROM Item; UPDATE Item SET inventoryNumber = 456 WHERE id IN ( SELECT id FROM Item_tmp WHERE parentId = 12345 AND name LIKE 'The quick brown fox' HAVING count(*)=1 ); ```
Here is a [working demo on SQL Fiddle](http://sqlfiddle.com/#!2/f2b96/1). It uses this SQL query: ``` UPDATE Item SET Item.inventoryNumber = 200 WHERE Item.id IN ( SELECT A.id FROM ( SELECT * FROM Item i GROUP BY i.parentId, i.name HAVING COUNT(*)=1 ) AS A WHERE A.parentId = 12345 AND A.name = 'The quick brown fox' ) ``` Breakdown of the query: * Innermost query: Use `GROUP BY` to select unique rows (based on your criteria #3) * Next: Filter out rows based on your criteria #1 and #2 * Use the results in the `WHERE` clause of `UPDATE`.
Mysql update a row if its the only matching result
[ "", "mysql", "sql", "" ]
I am trying to print all the letters in all the words in a list, without duplicates. I tried: ``` >>> wordlist = ['cat','dog','rabbit'] >>> letterlist = [] >>> [[letterlist.append(x) for x in y] for y in wordlist] [[None, None, None], [None, None, None], [None, None, None, None, None, None]] >>> letterlist ['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't'] ``` The desired result is `['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']` instead. How do I modify the list comprehension to remove duplicates?
If you want to edit you own code: ``` [[letterlist.append(x) for x in y if x not in letterlist] for y in wordlist] ``` or ``` list(set([[letterlist.append(x) for x in y if x not in letterlist] for y in wordlist])) ``` else: ``` list(set(''.join(wordlist))) ```
Do you care about maintaining order? ``` >>> wordlist = ['cat','dog','rabbit'] >>> set(''.join(wordlist)) {'o', 'i', 'g', 'd', 'c', 'b', 'a', 't', 'r'} ```
Python list comprehension: list sub-items without duplicates
[ "", "python", "" ]
This may not be possible, but if it is, it'd be convenient for some code I'm writing: ``` ListOne = ['jumps', 'over', 'the'] ListTwo = ['The', 'quick', 'brown', 'fox', ListOne, 'lazy', 'dog!'] ``` If I do this, I'll end up with ListOne being a single item being a list inside of ListTwo. But instead, I want to expand ListOne into ListTwo, but I don't want to have to do something like: ``` ListOne = ['jumps', 'over', 'the'] ListTwo = ['The', 'quick', 'brown', 'fox'] ListTwo.extend(ListOne) ListTwo.extend(['lazy', 'dog!'] ``` This will work but it's not as readable as the above code. Is this possible?
You can just use the `+` operator to concatenate lists: ``` ListOne = ['jumps', 'over', 'the'] ListTwo = ['The', 'quick', 'brown', 'fox'] + ListOne + ['lazy', 'dog!'] ``` `ListTwo` will be: ``` ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!'] ```
Another alternative is to use slicing assignment: ``` >>> ListOne = ['jumps', 'over', 'the'] >>> ListTwo = ['The', 'quick', 'brown', 'fox', 'lazy', 'dog!'] >>> ListTwo[4:4] = ListOne >>> ListTwo ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!'] ```
Python 2: insert existing list inside of new explicit list definition
[ "", "python", "list", "" ]
I am trying to get the number of bookings and their total value by date for every day within a given date range. ## My table looks like: ``` BookingId (int) BookingFare (decimal) BookingDateTime (datetime) ``` I can convert BookingDateTime to a date only by using: ``` SELECT CONVERT(varchar(8), BookingDateTime, 112) as BookingDateOnly FROM [TaxiBookingOnline].[dbo].[Bookings] ``` What I'm after is something like this: ``` Date Bookings Value 2013-07-10 10 256.24 2013-07-11 12 321.44 2013-07-12 14 311.53 ``` I get the feeling I should be aliasing the table, joining it to itself and then using 'GROUP BY' but I am failing to get this to work. Any help would be much appreciated. Thanks.
How about ``` select cast(BookingDateTime as date) [Date], count(*) [Bookings], sum(BookingFare) [Value] from t group by cast(BookingDateTime as date) ```
``` SELECT CONVERT(VARCHAR(8), BookingsDateTime, 112) AS [Date], COUNT(*) AS [Bookings], SUM(BookingsFare AS [Value] FROM MyTable GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, BookingDateTime)) ``` Group by `SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, dateColumn))` which will effectively get the date portion of the `datetime`, then you can use `count` or `sum` as necessary on the grouped values. EDIT: If you're using SQL Server >= 2008, you can cast to [`date`](http://msdn.microsoft.com/en-us/library/bb630352.aspx) (like @AlexK has done) otherwise you have to hack around it using `DATEADD`.
SQL statement to get a total for a given date range
[ "", "sql", "sql-server", "t-sql", "" ]
Im new in bash scripting. I want to save sql-query outputs in variable, but actually I must connect for every query to mysql with: ``` mysql -u $MYUSER -p$MYPASS -D database ``` and want to save every output in seperatly variable sample query is: `SELECT domain FROM domains WHERE user='$USER'` to ``` $variable1 = FIRST_OUTPUT $variable2 = 2ND_OUTPUT ``` thank you
Taken from [bash script - select from database into variable](https://stackoverflow.com/questions/1636977/bash-script-select-from-database-into-variable), you can read the query result into a variable. ### Example ``` mysql> SELECT * FROM domains; +-------+---------+ | user | domain | +-------+---------+ | user1 | domain1 | | user2 | domain2 | | user3 | domain3 | +-------+---------+ ``` ### Usage ``` $ myvar=$(mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains") $ echo $myvar domain1 domain2 domain3 ``` `echo` is the bash command for output. You can then [split `$myvar` into separate variables](https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash): ``` $ read var1 var2 var3 <<< $myvar $ echo $var1 domain1 $ echo $var2 domain2 ``` You can combine these two commands into a single one: ``` read var1 var2 var3 <<< $(mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains") ``` It is possible to store the results into arrays (useful if you don't know how many records there): ``` $ read -ra vars <<< $(mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains") $ for i in "${vars[@]}"; do $ echo $i $ done domain1 domain2 domain3 ```
Another way of doing is: ``` dbquery=`mysql -D$MYDB -u$MYUSER -p$MYPASS -se "SELECT domain FROM domains"` dbquery_array=( $( for i in $dbquery ; do echo $i ; done ) ) ``` The first line stores all the output from the query in a varriable `dbquery` in a array-like-way. The second line converts the `dbquery` into an array `dbquery_array` with a simple `for` loop.
bash - SQL Query Outputs to variable
[ "", "mysql", "sql", "bash", "shell", "variables", "" ]
Hi what I am trying to achieve is a query which has a dynamic column name in the where clause depending on whether a column is null or not. So as an example, if a row has an Appointment Date which is not null, the where clause will be: ``` WHERE `Building ID` = '1' and `Appointment Date`='2013-10-10' ; ``` And if the Appointment Date is null, the where clause will be: ``` WHERE `Building ID` = '1' and `Backup Date`='2013-10-10' ; ``` Right now my subquery in the where clause is returning too many rows so the query fails, how should I get around this issue? My query is below: ``` SELECT `Job ID` FROM jobs WHERE `Building ID` = '1' and (select case when `Appointment Date` IS NOT NULL THEN `Appointment Date` else `Backup Date` end FROM jobs WHERE `Building ID` = '1') = '2013-10-10' ```
``` SELECT `Job ID` FROM jobs WHERE `Building ID` = '1' and case when `Appointment Date` IS NOT NULL then `Appointment Date` = '2013-10-10' else `Backup Date` = '2013-10-10' end ```
Use the `COALESCE()` function. It returns the first of its parameters which is not null. ``` WHERE `Customer ID` = '1' and COALESCE(`Appointment Date`, `Backup Date`) ='2013-10-10' ; ```
Case subquery returning too many rows within where clause
[ "", "mysql", "sql", "" ]
So lets say I have a class: ``` class SuperClass(): def __init__(self, number): self._inputnumber = number self._initallist = [] ``` And then I want to build subclasses of this class which have methods that can add items to the initialized list, read items from it, or remove items from it. For example. ``` class SubClass(SuperClass): def __init__(self, number, current_line, new_line): self._number = number self._thisline = current_line self._gohere = new_line def execute(self): (SuperClass._initallist).append(self._thisline + 1) ``` This is a bit of a rough example of what I am trying to do. I want to be able to have my initial list available for a couple of classes so that they can both act upon it as shown above. What ends up happening in my case, though, is that I get an AttributeError saying that my SuperClass doesn't have the named attribute. ``` AttributeError: type object 'SuperClass' has no attribute '_initiallist' ``` Any tips on how to do this? Is it even possible or do I have to do something else to achieve this result?
"I want to build subclasses of this class which have methods that can add items to the initialized list,..." Are you saying you want the subclasses to inherit the *instance attribute* `_initiallist` and provide methods to act upon it? If this is the case then *instances* of the subclasses will each have an `_initiallist` attribute *but* each `_initiallist` for each instance of the class will be a different list. In that case the solution is as **zhangyangyu** described. --- "I want to be able to have my initial list available for a couple of classes so that they can both act upon it as shown above." Based on the title, I could interpret this as: I want the `_initiallist` attribute of some *instance* of the superclass to be available for *instances* of a couple of subclasses so they can all act upon the same exact list. You could do that if `_initiallist` is a class attribute, or you could pass an instance of the superclass as an `__init__` argument when instantiating the subclass, as far as I know currently. Also, this would mean that the two classes in your example do not posses an **is a** relationship, but rather, your superclass is really a sharedobject (AFAIK). If you make it a class attribute then you lose some flexibility because then different instances of the superclass will all have an attribute `_initiallist` that points to the same exact list. Where as if you keep it as an instance attribute and pass an instance of the superclass to the subclass as an argument (as a shared object), then you can still achieve what you want to do and still have the flexibility to create multiple instances of your shared object. ``` class SharedObject(object): def __init__(self, number): self._inputnumber = number self._initiallist = [] class Client(object): def __init__(self, obj, current_line, new_line): self._sharedobj = obj self._thisline = current_line self._gohere = new_line def execute(self): self._sharedobj._initiallist.append(self._thisline + 1) ```
`_initallist` is an instance attribute, you can not access it by `Super._initallist`. I think what you want to do is below. You need to init `SuperClass` in the `SubClass`. And I think if this is a right **is-one** relation, there need to be a `number` in `SubClass`. ``` class SuperClass(): def __init__(self, number): self._inputnumber = number self._initallist = [] class SubClass(SuperClass): def __init__(self, number, current_line, new_line): SuperClass.__init__(self, number) self._thisline = current_line self._gohere = new_line def execute(self): self._initallist.append(self._thisline + 1) ```
Is it possible to update an object initialized in a superclass from a subclass?
[ "", "python", "inheritance", "subclass", "superclass", "" ]
I was hoping to make a list of all subclasses of a given class by having each subclass register itself in a list that a parent class holds, ie something like this: ``` class Monster(object): monsters = list() class Lochness(Monster): Monster.monsters.append(Lochness) class Yeti(Monster): Monster.monsters.append(Yeti) ``` This obviously doesn't work because the classes haven't been created yet when I want to add them to the list. And, it'd be much nicer if it were done automatically (like \_\_subclass\_\_) I'm aware that \_\_subclass\_\_ has this functionality, but I was wondering (for my own edification) how you'd implement it yourself. It seems like you'd want to create some sort of subclass of the metaclass which is creating everything to register it with Monster? Or is that completely off base
Classes *already* register what subclasses are defined; call the [`class.__subclasses__()` method](http://docs.python.org/2/library/stdtypes.html#class.__subclasses__) to get a list: ``` >>> class Monster(object): ... pass ... >>> class Lochness(Monster): ... pass ... >>> class Yeti(Monster): ... pass ... >>> Monster.__subclasses__() [<class '__main__.Lochness'>, <class '__main__.Yeti'>] ``` `.__subclasses__()` returns a list of *currently still alive* subclasses. If you ever would clear all references to `Yeti` (`del Yeti` in the module, delete all instances, subclasses, imports, etc.) then it'd no longer be listed when you call `.__subclasses__()`. Note that in essence, `.__subclasses__()` is a [CPython implementation detail](http://mail.python.org/pipermail/python-list/2003-August/210297.html), but the method is present in all Python versions that support new-style classes (2.2 and up, all the way to 3.x). Otherwise, the canonical way to hook into class creation is to define a [metaclass](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python): ``` class MonstersMeta(type): def __new__(metaclass, name, bases, namespace): cls = super(MonstersMeta, metaclass).__new__(metaclass, name, bases, namespace) if issubclass(cls, Monster) and not cls is Monster: Monster.monsters.append(cls) return cls class Monster(object): __metaclass__ = MonstersMeta monsters = [] class Lochness(Monster): pass class Yeti(Monster): pass ``` Demo: ``` >>> class Monster(object): ... __metaclass__ = MonstersMeta ... monsters = [] ... >>> class Lochness(Monster): ... pass ... >>> class Yeti(Monster): ... pass ... >>> Monster.monsters [<class '__main__.Lochness'>, <class '__main__.Yeti'>] ``` or you can use a [class decorator](https://stackoverflow.com/questions/681953/python-class-decorator): ``` def registered_monster(cls): Monster.monsters.append(cls) return cls class Monster(object): monsters = [] @registered_monster class Lochness(Monster): pass @registered_monster class Yeti(Monster): pass ``` Demo: ``` >>> class Monster(object): ... monsters = [] ... >>> @registered_monster ... class Lochness(Monster): ... pass ... >>> @registered_monster ... class Yeti(Monster): ... pass ... >>> Monster.monsters [<class '__main__.Lochness'>, <class '__main__.Yeti'>] ``` The difference being where you put the responsibility of registering monsters; with the base `MonstersMeta` type, or with explicit decorators. Either way, the metaclass or the class decorator registers a permanent reference. You can use the [`weakref` module](http://docs.python.org/2/library/weakref.html) if you really, really want to emulate the `.__subclasses__()` behaviour.
Except from the obvious solution for this case to use `type.__subclasses__()`, you could use a decorator for similar problems: ``` class Monster(object): monsters = list() def isMonster(cls): Monster.monsters.append(cls) return cls @isMonster class Lochness(Monster): pass @isMonster class Yeti(Monster): pass print(Monster.monsters) # [<class '__main__.Lochness'>, <class '__main__.Yeti'>] ```
Executing code after construction of class object
[ "", "python", "" ]
I'm writing a function that takes in a list of integers and returns a list of relative positioned elements. That is to say, if my input into said function is *[1, 5, 4]* the output would be *[0, 2, 1]*, since 1 is the lowest element, 5 is the highest and 4 in the middle, all elements are unique values, or a *set()* But code speaks, the function i have so far is ``` def relative_order(a): rel=[] for i in a: loc = 0 for v in a: if i > v: loc += 1 rel.append(loc) return rel ``` It does work, but since i'm sending big lists into this function, and i have to compare each element to all elements in each iteration it's taking ~5sec with a list of 10.000 elements. My question is how can i improve the speed on said function and maybe be a bit more Pythonic, i tried comprehension lists, but my Python skills are lacking and i only came up with an imperative way of implementing this problem.
This can be written as a list comprehension like this: ``` lst = [1, 5, 4] s = sorted(lst) [s.index(x) for x in lst] => [0, 2, 1] ``` And here's another test, using @frb's example: ``` lst = [10, 2, 3, 9] s = sorted(lst) [s.index(x) for x in lst] => [3, 0, 1, 2] ```
Here's another go that should be more efficient that keeping `.index`'ing into the list as it's stated that no duplicate values will occur, so we can do the lookup O(1) instead of linear... (and actually meets the requirements): ``` >>> a = [10, 2, 3, 9] >>> indexed = {v: i for i, v in enumerate(sorted(a))} >>> map(indexed.get, a) [3, 0, 1, 2] ```
Relative order of elements in list
[ "", "python", "list", "sorting", "" ]
Hi: This is a follow up to this question: [How to copy all python instances to a new class?](https://stackoverflow.com/questions/17744721/how-to-copy-all-python-instances-to-a-new-class/17744957?noredirect=1#17744957) The problem is that `deepcopy()` is not copying the objects correctly, this can be seen through this working code: ``` from kivy.app import App from kivy.uix.floatlayout import FloatLayout class MyApp(App): def build(self): global Myroot self.root = FloatLayout() Myroot = self.root Starthere(None) return class VarStorage: pass VS=VarStorage() from kivy.uix.button import Button import copy def Starthere(instance): VS.MyButton=Button() print str(VS.MyButton) VSCopy=copy.deepcopy(VS) print str(VSCopy.MyButton) MyApp().run() ``` From my understanding of copy, it should print twice the same button, but the result is: ``` <kivy.uix.button.Button object at 0x046C2CE0> <kivy.uix.button.Button object at 0x04745500> ``` How to make `deepcopy()` copy the same object instead of a new (non existing) one? Thank you! ---------------------- EDIT ----------------------------- After trying `copy()` instead of `deepcopy()`, its not what Im intending to do: What I get with `deepcopy()`: * Copied class of VS, with copied items for those which are not objects (for instance, if VS.text="text", VSCopy.text will have the same contents without being linked whatsoever). * But, for objects, what I need is a *copy of the reference to such object*, which I dont get, since I get a new reference pointint a new object. What I get with `copy()`: * Copied class VSCopy with refferences pointing to original class VS. I dont want this since I want to change VS's contents (thats why Im trying to copy it) and still have the original ones available in VSCopy. Is there such a function in copy module?
> Is there such a function in copy module? No, I'm afraid there is not. It sounds like you want some sort of hybrid deep/shallow behavior, and that's not what exists in the `copy` module. You either get a shallow copy, or a deep one. Sorry for the bad news. :) You may just want to write your own copier, or see if you can accomplish your task without copying *per se*. (I see you edited your question, so I've answered again to see if I can help. (Please see my first answer for a response to your original Q.))
You need to use `shallowcopy` instead of `deepcopy`. From [copy module](http://docs.python.org/2/library/copy.html) docs: > * A shallow copy constructs a new compound object and then (to the > extent possible) inserts references into it to the objects found in > the original. > * A deep copy constructs a new compound object and then, > recursively, inserts copies into it of the objects found in the > original. You can use [`copy.copy()`](http://docs.python.org/2/library/copy.html#copy.copy) to create a *shallow copy*: ``` VSCopy = copy.copy(VS) ```
Python deepcopy changes the reference to an object
[ "", "python", "button", "kivy", "deep-copy", "" ]
I need to print the position of the last time I encounter a specific character, in a given string. How may I do that? ie. For this string "alahambra", I need to find the last time the letter "a" appears, so the result should be: 8. I´ve tried this code, but it doesn´t always work: ``` def find_last(search, target): first=search.find(search) last=len(search) result=search.find(target,last-1) return result ``` **Examples:** > print find\_last('aaaaa', 'aa') should print 3, and **it prints -1 instead, that´s wrong!** > print find\_last('aaaa', 'b') should print -1, and it prints -1, that´s correct. > print find\_last("111111111", "1") should print 8, and it prints 8, that´s correct. > print find\_last("222222222", "") should print 9, and **it prints 8 instead, that´s wrong!** > print find\_last("", "3") should print -1, and it prints -1, that´s correct. > print find\_last("", "") should print 0, and it prints 0, that´s correct. What´s wrong in my code and how should I change it? Thanks!
``` >>> "alahambra".rindex('a') 8 >>> ``` This will raise an error if the substring is not found. Use `rfind` will return -1 in this case. ``` >>> "alahambra".rfind('a') 8 >>> >>> ''.rfind('b') -1 >>> ```
you could use `rindex` or `rfind` - <http://docs.python.org/2/library/string.html> ``` "alahambra".rfind('a') ``` the difference between them is that `rindex` will raise error when the substring is not found and `rfind` will return -1
Python: How to print last X character found in a string? What´s wrong with my code that doesn´t always work?
[ "", "python", "string", "indexing", "" ]
``` def gradient(X_norm,y,theta,alpha,m,n,num_it): temp=np.array(np.zeros_like(theta,float)) for i in range(0,num_it): h=np.dot(X_norm,theta) #temp[j]=theta[j]-(alpha/m)*( np.sum( (h-y)*X_norm[:,j][np.newaxis,:] ) ) temp[0]=theta[0]-(alpha/m)*(np.sum(h-y)) temp[1]=theta[1]-(alpha/m)*(np.sum((h-y)*X_norm[:,1])) theta=temp return theta X_norm,mean,std=featureScale(X) #length of X (number of rows) m=len(X) X_norm=np.array([np.ones(m),X_norm]) n,m=np.shape(X_norm) num_it=1500 alpha=0.01 theta=np.zeros(n,float)[:,np.newaxis] X_norm=X_norm.transpose() theta=gradient(X_norm,y,theta,alpha,m,n,num_it) print theta ``` My theta from the above code is `100.2 100.2`, but it should be `100.2 61.09` in matlab which is correct.
I think your code is a bit too complicated and it needs more structure, because otherwise you'll be lost in all equations and operations. In the end this regression boils down to four operations: 1. Calculate the hypothesis h = X \* theta 2. Calculate the loss = h - y and maybe the squared cost (loss^2)/2m 3. Calculate the gradient = X' \* loss / m 4. Update the parameters theta = theta - alpha \* gradient In your case, I guess you have confused `m` with `n`. Here `m` denotes the number of examples in your training set, not the number of features. Let's have a look at my variation of your code: ``` import numpy as np import random # m denotes the number of examples here, not the number of features def gradientDescent(x, y, theta, alpha, m, numIterations): xTrans = x.transpose() for i in range(0, numIterations): hypothesis = np.dot(x, theta) loss = hypothesis - y # avg cost per example (the 2 in 2*m doesn't really matter here. # But to be consistent with the gradient, I include it) cost = np.sum(loss ** 2) / (2 * m) print("Iteration %d | Cost: %f" % (i, cost)) # avg gradient per example gradient = np.dot(xTrans, loss) / m # update theta = theta - alpha * gradient return theta def genData(numPoints, bias, variance): x = np.zeros(shape=(numPoints, 2)) y = np.zeros(shape=numPoints) # basically a straight line for i in range(0, numPoints): # bias feature x[i][0] = 1 x[i][1] = i # our target variable y[i] = (i + bias) + random.uniform(0, 1) * variance return x, y # gen 100 points with a bias of 25 and 10 variance as a bit of noise x, y = genData(100, 25, 10) m, n = np.shape(x) numIterations= 100000 alpha = 0.0005 theta = np.ones(n) theta = gradientDescent(x, y, theta, alpha, m, numIterations) print(theta) ``` At first I create a small random dataset which should look like this: ![Linear Regression](https://i.stack.imgur.com/xCyZn.png) As you can see I also added the generated regression line and formula that was calculated by excel. You need to take care about the intuition of the regression using gradient descent. As you do a complete batch pass over your data X, you need to reduce the m-losses of every example to a single weight update. In this case, this is the average of the sum over the gradients, thus the division by `m`. The next thing you need to take care about is to track the convergence and adjust the learning rate. For that matter you should always track your cost every iteration, maybe even plot it. If you run my example, the theta returned will look like this: ``` Iteration 99997 | Cost: 47883.706462 Iteration 99998 | Cost: 47883.706462 Iteration 99999 | Cost: 47883.706462 [ 29.25567368 1.01108458] ``` Which is actually quite close to the equation that was calculated by excel (y = x + 30). Note that as we passed the bias into the first column, the first theta value denotes the bias weight.
Below you can find my implementation of gradient descent for linear regression problem. At first, you calculate gradient like `X.T * (X * w - y) / N` and update your current theta with this gradient simultaneously. * X: feature matrix * y: target values * w: weights/values * N: size of training set Here is the python code: ``` import pandas as pd import numpy as np from matplotlib import pyplot as plt import random def generateSample(N, variance=100): X = np.matrix(range(N)).T + 1 Y = np.matrix([random.random() * variance + i * 10 + 900 for i in range(len(X))]).T return X, Y def fitModel_gradient(x, y): N = len(x) w = np.zeros((x.shape[1], 1)) eta = 0.0001 maxIteration = 100000 for i in range(maxIteration): error = x * w - y gradient = x.T * error / N w = w - eta * gradient return w def plotModel(x, y, w): plt.plot(x[:,1], y, "x") plt.plot(x[:,1], x * w, "r-") plt.show() def test(N, variance, modelFunction): X, Y = generateSample(N, variance) X = np.hstack([np.matrix(np.ones(len(X))).T, X]) w = modelFunction(X, Y) plotModel(X, Y, w) test(50, 600, fitModel_gradient) test(50, 1000, fitModel_gradient) test(100, 200, fitModel_gradient) ``` [![test1](https://i.stack.imgur.com/rJhFs.png)](https://i.stack.imgur.com/rJhFs.png) [![test2](https://i.stack.imgur.com/iXWTq.png)](https://i.stack.imgur.com/iXWTq.png) [![test2](https://i.stack.imgur.com/aRP0S.png)](https://i.stack.imgur.com/aRP0S.png)
gradient descent using python and numpy
[ "", "python", "numpy", "machine-learning", "linear-regression", "gradient-descent", "" ]
I apologize for the simplicity of this question, I have searched multiple times but it may be so simple it hasn't been asked before. I wrote a Fibonacci function that prints every Fibonacci number under 3000. ``` def fibonacci(): a, b = 0, 1 while b < 3000: a, b = b, a + b print a return a ``` How can I make it so it returns the first n Fibonacci numbers? Also, how can I make it just print the nth value? For example print [6], which would return 8. I tried to make it a string: ``` a = str(fibonacci()) print a[6] ``` but that didn't work, and I'm not sure why. Thanks for helping.
There are several ways to do this; here's a semi-clever one: First, change `print` to `yield`, so the function returns the numbers instead of printing them: ``` def ifibonacci(): a, b = 0, 1 while b < 3000: a, b = b, a + b yield a ``` Then use `itertools.islice` to slice out the numbers you want: ``` import itertools print list(itertools.islice(ifibonacci(), 10)) # prints [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] print list(itertools.islice(ifibonacci(), 6, 6+1)) # prints [13] which isn't quite right; see below ``` Note that your function doesn't output [the initial 0](http://oeis.org/A000045), so the indexes are off by one. To fix that, move the `yield` up one line: ``` def ifibonacci(): a, b = 0, 1 while b < 3000: yield a a, b = b, a + b print list(itertools.islice(ifibonacci(), 6, 6+1)) # prints [8] ``` (also, this still won't print numbers larger than 3000. fixing that is left as an exercise)
First, your function needs to know what `n` to use. That's simple enough - just tell it `n` as an argument: ``` def fibonacci(n): ``` If you want to return the first `n` fibonacci numbers, you'll need to keep a [list](http://docs.python.org/2/tutorial/introduction.html#lists) of them: ``` numbers = [0, 1] # Start off with the first 2 numbers ``` Then, compute the fibonacci numbers pretty much the way you did before, except stopping at the `n`th one, and adding together the last two list elements instead of `a` and `b`: ``` # xrange(2, n) is a sequence going from 2 to n-1 for i in xrange(2, n): # Add together the last two fibonacci numbers and append the result # to the list numbers.append(numbers[-2] + numbers[-1]) ``` Finally, return the list: ``` return numbers ``` The end result: ``` def fibonacci(n): numbers = [0, 1] for i in xrange(2, n): numbers.append(numbers[-2] + numbers[-1]) return numbers ``` This will return a list of the first `n` fibonnaci numbers (for `n >= 2`). You'll need to special-case `n == 0` or `n == 1` if you want to handle those values.
How to get nth result from simple function in python?
[ "", "python", "fibonacci", "" ]
From a purely performance standpoint, is it generally the best practice to assign the result of a repetitive arithmetic operation to a variable and use that variable throughout the code? Or does Python have some internal way of caching the result and using it whenever it encounters the repeated statement. For example is this more efficient: ``` a = 50 b = a*12-1 c = a*b print c #some code print c*100 + 10 #some code print c/100 + 20 #etc ``` Than this: ``` print 50*(50*12-1) #some code print 50*(50*12-1) * 100 + 10 #some code print 50*(50*12-1) / 100 + 20 #etc ```
Seem likes a pretty negligible speed up to me: ``` > python -m timeit 'a = 50; b = a*12-1; c = a*b; c; c*100+10; c/100+20;' 1000000 loops, best of 3: 0.27 usec per loop > python -m timeit '50*(50*12-1); 50*(50*12-1) * 100 + 10; 50*(50*12-1) / 100 + 20' 1000000 loops, best of 3: 0.218 usec per loop ``` Assignment is marginally slower than continually recalculating, but as korylprince states in the comments, assignment will lead to easier to read code. edit: I think this is what gnibbler meant in the comments, but it is slower still: ``` > python -m timeit 'def x(): a = 50; b = a*12-1; c = a*b; c; c*100+10; c/100+20;' 'x()' 1000000 loops, best of 3: 0.428 usec per loop ``` edit2: This is actually what gnibbler meant in the comments, and the difference is still negligle. The comments about using more readable one still hold: ``` > python -m timeit -s 'def x(): a = 50; b = a*12-1; c = a*b; c; c*100+10; c/100+20;' 'x()' 1000000 loops, best of 3: 0.367 usec per loop > python -m timeit -s 'def x(): 50*(50*12-1); 50*(50*12-1) * 100 + 10; 50*(50*12-1) / 100 + 20' 'x()' 1000000 loops, best of 3: 0.278 usec per loop ```
I don't know of any Python implementation that caches the intermediate results. Binding a local variable is pretty cheap, so after a couple of calculations, it will come out faster. In the special cases where only constants are used, the peephole optimiser can reduce those to constants eg. ``` $ python3.3 Python 3.3.0 (default, Sep 29 2012, 17:17:45)  [GCC 4.7.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def x(): ... 50*(50*12-1) ... 50*(50*12-1) * 100 + 10 ... 50*(50*12-1) / 100 + 20 ... >>> dis.dis(x) 2 0 LOAD_CONST 9 (29950) 3 POP_TOP 3 4 LOAD_CONST 14 (2995010) 7 POP_TOP 4 8 LOAD_CONST 19 (319.5) 11 POP_TOP 12 LOAD_CONST 0 (None) 15 RETURN_VALUE ``` If in doubt, prefer the readable version. Micro optimise if you really need those extra microseconds
repetitive arithmetic in Python
[ "", "python", "" ]
I have two files with tens of thousands of lines each, output1.txt and output2.txt. I want to iterate through both files and return the line (and content) of the lines that differ between the two. They're mostly the same which is why I can't find the differences (filecmp.cmp returns false).
You can do something like this: ``` import difflib, sys tl=100000 # large number of lines # create two test files (Unix directories...) with open('/tmp/f1.txt','w') as f: for x in range(tl): f.write('line {}\n'.format(x)) with open('/tmp/f2.txt','w') as f: for x in range(tl+10): # add 10 lines if x in (500,505,1000,tl-2): continue # skip these lines f.write('line {}\n'.format(x)) with open('/tmp/f1.txt','r') as f1, open('/tmp/f2.txt','r') as f2: diff = difflib.ndiff(f1.readlines(),f2.readlines()) for line in diff: if line.startswith('-'): sys.stdout.write(line) elif line.startswith('+'): sys.stdout.write('\t\t'+line) ``` Prints (in 400 ms): ``` - line 500 - line 505 - line 1000 - line 99998 + line 100000 + line 100001 + line 100002 + line 100003 + line 100004 + line 100005 + line 100006 + line 100007 + line 100008 + line 100009 ``` If you want the line number, use enumerate: ``` with open('/tmp/f1.txt','r') as f1, open('/tmp/f2.txt','r') as f2: diff = difflib.ndiff(f1.readlines(),f2.readlines()) for i,line in enumerate(diff): if line.startswith(' '): continue sys.stdout.write('My count: {}, text: {}'.format(i,line)) ```
## 7.4. [difflib](http://docs.python.org/2/library/difflib.html) — Helpers for computing deltas New in version 2.1. This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce difference information in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.
Returning lines that differ between two files (Python)
[ "", "python", "file", "lines", "" ]
I'm working on a project in Python using the "thread" module. How can I make a global variable (in my case I need it to be True or False) that all the threads in my project (about 4-6) can access?
We can define the variable outside the thread classes and declare it global inside the methods of the classes. Please see below trivial example which prints AB alternatively. Two variables `flag` and `val` are shared between two threads `Thread_A` and `Thread_B`. `Thread_A` prints `val=20` and then sets `val` to 30. `Thread_B` prints `val=30`, since `val` is modified in `Thread_A`. `Thread_B` then sets `val` to 20 which is again used in `Thread_A`. This demonstrates that variable `val` is shared between two threads. Similarly variable `flag` is also shared between two threads. ``` import threading import time c = threading.Condition() flag = 0 #shared between Thread_A and Thread_B val = 20 class Thread_A(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): global flag global val #made global here while True: c.acquire() if flag == 0: print "A: val=" + str(val) time.sleep(0.1) flag = 1 val = 30 c.notify_all() else: c.wait() c.release() class Thread_B(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): global flag global val #made global here while True: c.acquire() if flag == 1: print "B: val=" + str(val) time.sleep(0.5) flag = 0 val = 20 c.notify_all() else: c.wait() c.release() a = Thread_A("myThread_name_A") b = Thread_B("myThread_name_B") b.start() a.start() a.join() b.join() ``` Output looks like ``` A: val=20 B: val=30 A: val=20 B: val=30 A: val=20 B: val=30 A: val=20 B: val=30 ``` Each thread prints the value which was modified in another thread.
With no clue as to what you are really trying to do, either go with nio's approach and use locks, or consider condition variables: From the [docs](http://docs.python.org/2/library/threading.html#condition-objects) ``` # Consume one item cv.acquire() while not an_item_is_available(): cv.wait() get_an_available_item() cv.release() # Produce one item cv.acquire() make_an_item_available() cv.notify() cv.release() ``` You can use this to let one thread tell another a condition has been met, without having to think about the locks explicitly. This example uses `cv` to signify that an item is available.
Python creating a shared variable between threads
[ "", "python", "multithreading", "" ]
I have some data in HDFS,i need to access that data using python,can anyone tell me how data is accessed from hive using python?
*You can use hive library for access hive from python,for that you want to import hive Class from hive import ThriftHive* Below the Example ``` import sys from hive import ThriftHive from hive.ttypes import HiveServerException from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol try: transport = TSocket.TSocket('localhost', 10000) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = ThriftHive.Client(protocol) transport.open() client.execute("CREATE TABLE r(a STRING, b INT, c DOUBLE)") client.execute("LOAD TABLE LOCAL INPATH '/path' INTO TABLE r") client.execute("SELECT * FROM r") while (1): row = client.fetchOne() if (row == None): break print row client.execute("SELECT * FROM r") print client.fetchAll() transport.close() except Thrift.TException, tx: print '%s' % (tx.message) ```
To install you'll need these libraries: ``` pip install sasl pip install thrift pip install thrift-sasl pip install PyHive ``` If you're on Linux, you may need to install SASL separately before running the above. Install the package `libsasl2-dev` using `apt-get` or `yum` or whatever package manager. For Windows there are some options [on GNU.org](http://www.gnu.org/software/gsasl/manual/html_node/Installing-under-Windows.html "GNU Installing SASL on Windows"). On a Mac SASL should be available if you've installed xcode developer tools (`xcode-select --install`) After installation, you can execute a hive query like this: ``` from pyhive import hive conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU") ``` Now that you have the hive connection, you have options how to use it. You can just straight-up query: ``` cursor = conn.cursor() cursor.execute("SELECT cool_stuff FROM hive_table") for result in cursor.fetchall(): use_result(result) ``` ...or to use the connection to make a Pandas dataframe: ``` import pandas as pd df = pd.read_sql("SELECT cool_stuff FROM hive_table", conn) ```
Access Hive Data Using Python
[ "", "python", "hive", "" ]
In my Python project I have a pool of objects, each tagged with a set of words. I want to generate all sets including subsets of tags, mapped to the linked objects. Those subsets should not be smaller than a complete tag set of any project. For instance, let's say there are these objects with their tags: ``` apple: fruit, green, nature sometree: tree, green, wood, nature banana: fruit, nature someplant: green, wood, nature otherplant: green, wood, nature ``` The result should be: ``` (fruit, nature): banana, apple (fruit, green, nature): apple (green, wood, nature): sometree, someplant, otherplant (green, wood, nature, tree): sometree ``` I don't want the result to include tag sets that don't exists as a complete tag set for at least one objects. To achieve this, I came up with a `O(n²)` algorithm, but wonder if there are more clever approaches like e.g. some tree-based index or a prefix-trie? I won't have too much objects, maybe 2000. However, it should be fast. My current solution iterates all objects to create a dictionary mapping all tag sets to objects. In a second iteration I test each tag set if it is a subset of any other tag sets and if so, remember the objects of the supersets. **Update**: In `O(n²)` abovel, `n` referrs to the number of objects. I will have many objects where each has about five tags. **Solution**: Thanks for all the replies. I ended up using the method of azorius, because it is both fast and robust. This is a complete example to list all groups: ``` tagged = { 'apple': ['fruit', 'green', 'nature'], 'sometree': ['tree', 'green', 'wood', 'nature'], 'banana': ['fruit', 'nature'], 'someplant': ['green', 'wood', 'nature'], 'otherplant': ['green', 'wood', 'nature'] } tag_sets = set() tags_to_objects = {} for obj, tags in tagged.items(): for tag in tags: try: tags_to_objects[tag].add(obj) except KeyError: tags_to_objects[tag] = set([obj]) # Record all tag sets tag_set = frozenset(tags) tag_sets.add(tag_set) groups = {} for tag_set in tag_sets: objects = None for tag in tag_set: if objects: objects = objects.intersection(tags_to_objects[tag]) else: objects = tags_to_objects[tag] groups[tag_set] = objects for k,v in groups.items(): print '(%s): %s' % (', '.join(k), ', '.join(v)) ``` Since there where several solutions, I did some timing tests on 1035 objects with about five tags each: * code of azorius: 127ms * code of Bruce: 115ms * code of pillmuncher: 137ms The code of pillmuncher is in my opinion the most elegant.
why not use sets?, according to <http://wiki.python.org/moin/TimeComplexity> sets have the following average time complexity O(min(len(s), len(t)), aka O(n)! ``` fruit = set(("apple", "banana")) green = set(("apple", "sometree", "someplant", "otherplant")) nature = set(("apple", "banana", "sometree", "someplant", "otherplant")) tree = set (("sometree",)) wood = set (("sometree", "someplant", "otherplant")) In [90]: fruit.intersection(nature) Out[90]: set(['apple', 'banana']) In [91]: fruit.intersection(nature).intersection(green) Out[91]: set(['apple']) In [92]: green.intersection(wood).intersection(nature) Out[92]: set(['sometree', 'someplant', 'otherplant']) In [93]: green.intersection(wood).intersection(nature).intersection(tree) Out[93]: set(['sometree']) ``` looking back at this code, a much more elegant answer would be to use reduce: ``` In [90]: reduce(set.intersection, [fruit, nature]) Out[90]: set(['apple', 'banana']) In [91]: reduce(set.intersection, [fruit, nature, green]) Out[91]: set(['apple']) In [92]: reduce(set.intersection, [green, wood, nature]) Out[92]: set(['sometree', 'someplant', 'otherplant']) In [93]: reduce(set.intersection, [green, wood, nature, tree]) Out[93]: set(['sometree']) ```
May be you can use bipartite graph. Let O and T forms a bipartite graph. O are the objects and T are the tags. An object and a tag has edge means, that object has that tag. You have to maintain adjacency lists for T and adjacency matrix for O. and hash table for the tags vertices and their degrees. Now input is some tags. Check their degrees and find out which has smallest degree. Now get the neighbours of it from adjacency lists and iterate over it. Check if each of them has an edge has between to other tags. use adjacency matrix for it. If it has edges to each of the other tags, store it. Else if has not any edge to any of the other tags, discard it. If t is the number of tags, and o is the number of objects. Building up adjacency list, matrix and degree-array will take O(t\*o) time and O(t\*o) space. After that, at each query of t' tags, it will take O(t'\*o) time. Hope this helps.
Python: data structure to index sets to find supersets?
[ "", "python", "algorithm", "data-structures", "indexing", "set", "" ]
When I try to execute my TSQL code, I get the exception: ``` Msg 2714, Level 16, State 6, Line 2 There is already an object named 'Role' in the database. Msg 2714, Level 16, State 6, Line 2 There is already an object named 'User' in the database. ``` But I don't have any database. I need advice. Code is shown below: ``` USE master GO CREATE DATABASE PortalDB GO CREATE TABLE [Role] ( [ID] INT IDENTITY(1,1) PRIMARY KEY CLUSTERED, [Name] NVARCHAR(50) NOT NULL, ) GO CREATE TABLE [User] ( [ID] INT IDENTITY(1,1) PRIMARY KEY CLUSTERED, [Name] NVARCHAR(50) NOT NULL, [UserName] NVARCHAR(50) NOT NULL, [Password] NVARCHAR (100) NOT NULL, [Email] NVARCHAR (100) NOT NULL, [RoleID] INT NOT NULL FOREIGN KEY REFERENCES [Role](ID) ) ```
It's not saying there's a table, it's saying there's an object, you've picked two reserved words as table names, which isn't ideal, but moreso they are names of existing objects. You should choose other names. Technically you could create a user table like this: ``` CREATE TABLE dbo.[user] ``` But you should just not use reserved words as table names. Also, make sure you're using the correct database when you create a table. After the create database you can use: ``` USE PortalDB GO ``` Or you could specify in the `CREATE TABLE` like: ``` CREATE TABLE PortalDB.dbo.[tablename] ```
Why are you creating the objects in Master? It is a system DB.
There is already an object named 'Roles' in the database
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
How would I remove the leading zeros from a number which is in the form of varchar. I have tried the following: Option 1: ``` insert into example_table (columnName) (SELECT SUBSTR(columnName2, InStr('%[^0 ]%', columnName2 + ' '), 10) from columnName2); ``` With this, the error I get is ``` SQL Error: ORA-01722: invalid number ORA-02063: preceding line from xxxx 01722. 00000 - "invalid number" ``` Option 2: ``` insert into example_table (columnName) (SELECT SUBSTR(columnName2, InStr('%[^0 ]%', columnName2 + ' '), LEN(columnName2)) from columnName2); ``` This time I get ``` Error at Command Line:23 Column:87 Error report: SQL Error: ORA-00904: "LEN": invalid identifier ``` Option 3: ``` SUBSTRING (columnName2, PATINDEX('%[^0 ]%', columnName2 + ' '), 10)); ``` Similar to above, I get ``` Error at Command Line:23 Column:41 Error report: SQL Error: ORA-00904: "PATINDEX": invalid identifier 00904. 00000 - "%s: invalid identifier" ``` **EDIT** I think that the trim route might be my best option, however... I am uncertain how to use it in the case I have. ``` INSERT INTO temp_table (columnNeedTrim, column2, column3, column4, column5) SELECT * FROM (SELECT( SELECT TRIM(leading '0' from columnNeedTrim) FROM table), table.column2, table2.column3, table.column4 table.column5 FROM table INNER JOIN table2 ON table1.columnNeedTrim=table2.columnNeedTrim) WHERE NOT EXISTS (SELECT * FROM temp_table); ``` I now get an error because my trim function returns multiple row result. ``` Error report: SQL Error: ORA-01427: single-row subquery returns more than one row 01427. 00000 - "single-row subquery returns more than one row" ``` I am not sure how to work a trim (or a cast) into the statement above. Any help on that? Thanks for any help!
Oracle has built-in `TRIM` functions for strings. Assuming you have a string like `'00012345'` and you want to keep it as a string, not convert it to an actual `NUMBER`, you can use the [`LTRIM` function](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions096.htm) with the optional second `set`parameter specifying that you're triming zeros: ``` select ltrim('000012345', '0') from dual; LTRIM ----- 12345 ``` If you might also have leading spaces you can trim both in one go: ``` select ltrim(' 00012345', '0 ') from dual; LTRIM ----- 12345 ``` You could also convert to a number and back, but that seems like a lot of work unless you have other formatting that you want to strip out: ``` select to_char(to_number('000012345')) from dual; ``` --- Incidentally, the immediate reason you get the ORA-01722 from your first attempt is that you're using the numeric `+` operator instead of Oracle's string concentenation operator `||`. It's doing an implicit conversion of your string to a number, which it seems you're trying to avoid, and the implicit conversion of the single space - whatever that is for - is causing the error. (Possibly some of your values are not, in fact, numbers at all - another example of why numbers should be stored in `NUMBER` fields; and if that is the case then converting (or casting) to a number and back would still get the ORA-01722). You'd get the same thing in the second attempt if you were using `LENGTH` instead of `LEN`. Neither would work anyway as `INSTR` doesn't recognise regular expressions. You could use `REGEXP_INSTR` instead, but you'd be better off with @schurik's `REGEXP_REPLACE` version if you wanted to go down that route. --- I'm not sure I understand your question edit. It looks like your insert can be simplified to: ``` INSERT INTO temp_table (columnNeedTrim, column2, column3, column4, column5) SELECT LTRIM(table1.columnNeedTrim, '0 '), table1.column2, table1.column3, table1.column4, table1.column5 FROM table1 INNER JOIN table2 ON table2.columnNeedTrim = table1.columnNeedTrim WHERE NOT EXISTS ( SELECT * FROM temp_table WHERE columnNeedTrim = LTRIM(t42.columnNeedTrim, '0 ')); ``` (I don't understand why you're doing a subquery in your version, or why you're getting the trimmed value from *another* subquery.) You could also use `MERGE`: ``` MERGE INTO temp_table tt USING ( SELECT LTRIM(t42.columnNeedTrim, '0 ') AS columnNeedTrim, t42.column2, t42.column3, t42.column4, t42.column5 FROM t42 INNER JOIN t43 ON t43.columnNeedTrim=t42.columnNeedTrim ) sr ON (sr.columnNeedTrim = tt.columnNeedTrim) WHEN NOT MATCHED THEN INSERT (tt.columnNeedTrim, tt.column2, tt.column3, tt.column4, tt.column5) VALUES (sr.columnNeedTrim, sr.column2, sr.column3, sr.column4, sr.column5); ```
``` SELECT '00012345' AS zeroWith, TRIM(LEADING 0 FROM '00012345') AS zeroWithOut FROM dual; ``` > Result : zeroWith > 00012345 & zeroWithOut > 12345
Removing leading zeros from varchar sql developer
[ "", "sql", "oracle", "" ]
I have two tables ``` CREATE TABLE Categories ( Category INTEGER, Id INTEGER, FOREIGN KEY (Category) REFERENCES CategoriesInfo(Category) ) CREATE TABLE 'CategoriesInfo' ( 'Category' INTEGER PRIMARY KEY NOT NULL, 'Name' TEXT ) ``` with index ``` CREATE UNIQUE INDEX idxCategory ON Categories (Category, Id) ``` If I run ``` EXPLAIN QUERY PLAN SELECT CategoriesInfo.Category, Name FROM Categories, CategoriesInfo Where Categories.Category=CategoriesInfo.Category AND Id=:id ORDER BY Name ``` it says ``` Array ( [0] => Array ( [selectid] => 0 [order] => 0 [from] => 1 [detail] => SCAN TABLE CategoriesInfo (~1475 rows) ) [1] => Array ( [selectid] => 0 [order] => 1 [from] => 0 [detail] => SEARCH TABLE Categories USING COVERING INDEX idxCategory (Category=? AND Id=?) (~1 rows) ) [2] => Array ( [selectid] => 0 [order] => 0 [from] => 0 [detail] => USE TEMP B-TREE FOR ORDER BY ) ) ``` But if I use joins ``` EXPLAIN QUERY PLAN SELECT CategoriesInfo.Category, CategoriesInfo.Name FROM Categories LEFT JOIN CategoriesInfo ON (Categories.Category=CategoriesInfo.Category) WHERE Categories.Id=:id ORDER BY Name ``` I get ``` Array ( [0] => Array ( [selectid] => 0 [order] => 0 [from] => 0 [detail] => SEARCH TABLE Categories USING AUTOMATIC COVERING INDEX (Id=?) (~6 rows) ) [1] => Array ( [selectid] => 0 [order] => 1 [from] => 1 [detail] => SEARCH TABLE CategoriesInfo USING INTEGER PRIMARY KEY (rowid=?) (~1 rows) ) [2] => Array ( [selectid] => 0 [order] => 0 [from] => 0 [detail] => USE TEMP B-TREE FOR ORDER BY ) ) ``` Then, using joins should be faster. But when I run both codes with phpliteadmin, * The 1st takes 0 seconds * The 2nd takes 0.3281 seconds Why??
I would point out the two queries aren't equivalent. Your first query effectively performs an INNER JOIN, while your second one is a LEFT JOIN. I would wager this is the cause of the speed difference. Your LEFT JOIN is going to require that all records from Categories are included in the output, something your first query does not require. Try changing the LEFT JOIN to INNER JOIN and then compare the speed.
A common misconception with explain plans is that they are giving a realistic expectation of the performance of a query. What they do, however, is provide you with a **good estimate** of what the database thinks it will take to run the query. This is based on many factors such as table indices, statistics on the tables involved in the query, degree of parallelism, and overall resources allocated for the system.
Why a SQL query is slower than another if according to EXPLAIN QUERY PLAN it should be the opposite?
[ "", "sql", "performance", "sqlite", "sql-execution-plan", "" ]
I need to check if all the letters that form a given word are contained inside a given string. I´ve tried something but isn´t working: ``` def check(texto, control): for letra in control: if texto.find(letra) == control.find(letra): return control + " is not here" else: return control + " is here!" ``` > print check('jshdgfyrgj', 'Correo') Should return "Correo is not here" > print check('cfgotyrrtepo', 'Correo') Should return "Correo is here!" It currently returns correo is here in all cases. Whats wrong with my code? Thanks!
A couple issues - one, you expect the function to ignore case differences, but don't tell it to do so. - 'c' is not 'C'. For checking to see whether a letter is in a string it's often better to use `letter in text_string` rather than the `str.find()` method. Be sure you understand what find returns - check out the [docs](http://docs.python.org/3/library/stdtypes.html#str.find). In the example below I use `letter in set(text_string)` - this only checks the letters of `text_string` once if there are duplicates. For small strings this won't make much of a difference in performance. You can use the `all` function to do a bunch of boolean checks. ``` def check(text, control): # Set both strings to lower case, since we're ignoring case text = text.lower() control = control.lower() # Check that each character in control is in text return all((c in text for c in set(control))) >>> check('jshdgfyrgj', 'Correo') 2: False >>> check('cfgotyrrtepo', 'Correo') 3: True ```
Why not something like: ``` def check(texto, control): texto = [letter for letter in texto] while texto: for letra in control: if letra in texto: texto.remove(letra) else: return False return True ``` this ensures repeated letters are repeated in texto also. e.g. ``` >>> check('abc','bac') True >>> check('abc','bacc') False ```
checking each letter to see if it contains all letters needed, this code isn´t working
[ "", "python", "string", "for-loop", "" ]
I have a list of dict for example, ``` [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name': u'Sports'}] ``` Now, I have to retrieve the following list from this dict without using list comprehension ``` [u'Library', u'Arts', u'Sports'] ``` Is there any way to achieve this in python? I saw many similar questions, but all answers were using list comprehension. Any suggestion is appreciated. Thanks in advance.
You could use `itemgetter`: ``` from operator import itemgetter categories = map(itemgetter('name'), things) ``` But a list comprehension is good too. What's wrong with list comprehensions?
You could use [`map()`](http://docs.python.org/2/library/functions.html#map) here. `map()` applies the lambda to every item of `testList` and returns it as a list. ``` >>> testList = [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name': u'Sports'}] >>> map(lambda x: x['name'], testList) [u'Library', u'Arts', u'Sports'] ```
Getting a list of values from a list of dict in python: Without using list comprehension
[ "", "python", "" ]
I'm trying to create what I think is a 'projection' from a larger dictionary space onto a smaller dimension space. So, if I have: ``` mine = [ {"name": "Al", "age": 10}, {"name": "Bert", "age": 15}, {"name": "Charles", "age": 17} ] ``` I'm trying to find a functional expression to return only: ``` [ {"name": "Al"}, {"name": "Bert"}, {"name": "Charles"} ] ``` I've tried... ``` >>> filter(lambda x: x['name'],mine) [{'age': 10, 'name': 'Al'}, {'age': 15, 'name': 'Bert'}, {'age': 17, 'name': 'Charles'}] >>> map(lambda x : x['name'],mine) ['Al', 'Bert', 'Charles'] ``` But seem to still be missing the right function. I know how to do it with a list comprehension, but would like to do learn how to do this functionally.
Sounds like a job for list comprehensions, whether you like them or not. ``` >>> [{"name": d["name"]} for d in mine] [{'name': 'Al'}, {'name': 'Bert'}, {'name': 'Charles'}] ``` The solution without a list comprehension would require an additional function definition: ``` def project(key, d): return {k: d[k]} map(partial(project, "name"), mine) ``` Or a `lambda` (yuck): ``` map(lambda d: {"name": d["name"]}, mine) ```
***CODE:*** ``` print([{'name': d['name']} for d in mine]) ``` ***OUTPUT:*** ``` [{'name': 'Al'}, {'name': 'Bert'}, {'name': 'Charles'}] ```
Python list of dictionaries projection, filter, or subset?
[ "", "python", "functional-programming", "functools", "" ]
I need a linux bash script that can replace the spaces in name="this is a test". example: ``` <input name="this is a test" id="testing 1 2 3" /> ``` would change to this: ``` <input name="thisisatest" id="testing 1 2 3" /> ``` EDIT: The script must be able to match anything between the double quotes. It could be this: ``` <input name="THIS STRING WILL VARY" id="testing 1 2 3" /> ``` Any ideas?
Using Python - to take an HTML file, and remove spaces from `input` tags that have a `name` attribute equal to `this is a test`, you can use: ``` from bs4 import BeautifulSoup with open('input') as fin, open('output', 'w') as fout: soup = BeautifulSoup(fin.read()) for tag in soup.find_all('input', {'name': 'this is a test'}): tag['name'] = tag['name'].replace(' ', '') fout.write(str(soup)) ``` In response to: > I forgot to say that the string "this is a test" can be anything You can just filter out all `input` tags that have a `name` attribute and apply whatever logic you want - the below will remove spaces from any name attribute: ``` for tag in soup.find_all('input', {'name': True}): tag['name'] = tag['name'].replace(' ', '') ```
Here's an awk one-liner ``` awk ' BEGIN {FS=OFS="\""} {for (f=2; f<=NF; f++) if ($(f-1) ~ /name=$/) gsub(/ /, "", $f)} 1 ' file ``` It uses double quotes as the field separator. A quoted string will therefore be an odd-numbered field.
bash script to replace spaces in html
[ "", "python", "html", "linux", "bash", "sed", "" ]
OK I was looking into number formatting and I found that you could use **%d** or **%i** to format an integer. For example: ``` number = 8 print "your number is %i." % number ``` or ``` number = 8 print "your number is %d." % number ``` But what is the difference? I mean i found something but it was total jibberish. Anyone speak Mild-Code or English here?
Python copied the C formatting instructions. For *output*, `%i` and `%d` are the exact same thing, both in Python and in C. The difference lies in what these do when you use them to parse *input*, in C by using the `scanf()` function. See [Difference between format specifiers %i and %d in printf](https://stackoverflow.com/questions/1893490/difference-between-format-specifiers-i-and-d-in-printf). Python doesn't have a `scanf` equivalent, but the Python string formatting operations retained the two options to remain compatible with C. The new `str.format()` and `format()` [format specification mini-language](http://docs.python.org/2/library/string.html#formatspec) dropped support for `i` and stuck with `d` only.
No difference. And here's [the proof.](http://docs.python.org/2/library/stdtypes.html#string-formatting) The reason why there are two is that, %i is just an alternative to %d ,if you want to look at it at a high level (from python point of view). Here's what python.org has to say about %i: `Signed integer decimal.` And %d: `Signed integer decimal.` %d stands for decimal and %i for integer. but both are same, you can use both.
What is the difference between %i and %d in Python?
[ "", "python", "python-2.7", "integer", "string-formatting", "number-formatting", "" ]
I am looking for a way to return the rows of a table between a range, for instance how would I get rows 100 to 200 in a table that has 10,000 rows? This is not based off of any of the data within the row, and the primary key although incremental, cannot be used as an index. I am working with a rather large table that has to be shown to the user in an application. Right now I am getting all of the records and using a Java Array to get the rows x to y to send back to the user via Ajax (web application). This method takes quite a bit more time than I would like (though less than sending all of the records to the user at once) so I would just like to query the records I need. Any help is appreciated, thank you!
select \* from table limit 100,100 <http://dev.mysql.com/doc/refman/5.5/en/select.html> and search for "limit"
You can use LIMIT, but you must order the rows too. ``` select * from table order by id -- very important limit 100,100 ``` If you don't order the rows, theoretically you could always get the *same* 100 rows when changing the starting row. This is because unordered queries can return the rows in *any* order, and it will vary depending on other queries running at the same time and what rows are cached in memory, etc.
SQL results by row count range
[ "", "sql", "count", "range", "between", "" ]
I have this function that calls itself: ``` def get_input(): my_var = input('Enter "a" or "b": ') if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') get_input() else: return my_var print('got input:', get_input()) ``` Now, if I input just "a" or "b", everything works fine: ``` Type "a" or "b": a got input: a ``` But, if I type something else and then "a" or "b", I get this: ``` Type "a" or "b": purple You didn't type "a" or "b". Try again. Type "a" or "b": a got input: None ``` I don't know why `get_input()` is returning `None` since it should only return `my_var`. Where is this `None` coming from and how do I fix my function?
It is returning `None` because when you recursively call it: ``` if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') get_input() ``` ..you don't return the value. So while the recursion does happen, the return value gets discarded, and then you fall off the end of the function. Falling off the end of the function means that python implicitly returns `None`, just like this: ``` >>> def f(x): ... pass >>> print(f(20)) None ``` So, instead of just *calling* `get_input()` in your `if` statement, you need to `return` what the recursive call returns: ``` if my_var != "a" and my_var != "b": print('You didn\'t type "a" or "b". Try again.') return get_input() ```
To return a value other than None, you need to use a return statement. In your case, the if block only executes a return when executing one branch. Either move the return outside of the if/else block, or have returns in both options.
Why does my recursive function return None?
[ "", "python", "function", "recursion", "return", "" ]
How do you find the top correlations in a correlation matrix with Pandas? There are many answers on how to do this with R ([Show correlations as an ordered list, not as a large matrix](https://stackoverflow.com/questions/7074246/show-correlations-as-an-ordered-list-not-as-a-large-matrix) or [Efficient way to get highly correlated pairs from large data set in Python or R](https://stackoverflow.com/questions/11268822/efficient-way-to-get-highly-correlated-pairs-from-large-data-set-in-python-or-r)), but I am wondering how to do it with pandas? In my case the matrix is 4460x4460, so can't do it visually.
You can use `DataFrame.values` to get an numpy array of the data and then use NumPy functions such as `argsort()` to get the most correlated pairs. But if you want to do this in pandas, you can `unstack` and sort the DataFrame: ``` import pandas as pd import numpy as np shape = (50, 4460) data = np.random.normal(size=shape) data[:, 1000] += data[:, 2000] df = pd.DataFrame(data) c = df.corr().abs() s = c.unstack() so = s.sort_values(kind="quicksort") print so[-4470:-4460] ``` Here is the output: ``` 2192 1522 0.636198 1522 2192 0.636198 3677 2027 0.641817 2027 3677 0.641817 242 130 0.646760 130 242 0.646760 1171 2733 0.670048 2733 1171 0.670048 1000 2000 0.742340 2000 1000 0.742340 dtype: float64 ```
@HYRY's answer is perfect. Just building on that answer by adding a bit more logic to avoid duplicate and self correlations and proper sorting: ``` import pandas as pd d = {'x1': [1, 4, 4, 5, 6], 'x2': [0, 0, 8, 2, 4], 'x3': [2, 8, 8, 10, 12], 'x4': [-1, -4, -4, -4, -5]} df = pd.DataFrame(data = d) print("Data Frame") print(df) print() print("Correlation Matrix") print(df.corr()) print() def get_redundant_pairs(df): '''Get diagonal and lower triangular pairs of correlation matrix''' pairs_to_drop = set() cols = df.columns for i in range(0, df.shape[1]): for j in range(0, i+1): pairs_to_drop.add((cols[i], cols[j])) return pairs_to_drop def get_top_abs_correlations(df, n=5): au_corr = df.corr().abs().unstack() labels_to_drop = get_redundant_pairs(df) au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False) return au_corr[0:n] print("Top Absolute Correlations") print(get_top_abs_correlations(df, 3)) ``` That gives the following output: ``` Data Frame x1 x2 x3 x4 0 1 0 2 -1 1 4 0 8 -4 2 4 8 8 -4 3 5 2 10 -4 4 6 4 12 -5 Correlation Matrix x1 x2 x3 x4 x1 1.000000 0.399298 1.000000 -0.969248 x2 0.399298 1.000000 0.399298 -0.472866 x3 1.000000 0.399298 1.000000 -0.969248 x4 -0.969248 -0.472866 -0.969248 1.000000 Top Absolute Correlations x1 x3 1.000000 x3 x4 0.969248 x1 x4 0.969248 dtype: float64 ```
List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?
[ "", "python", "pandas", "correlation", "" ]
How do I multiply every element of one list with every element of another list in Python and then sum the result of the multiplying results variations? ``` list_1 = [0, 1, 2, 3, 4, 5] list_2 = [11, 23, m] ``` Where m element in the list\_2 can be any number while the length of the elements in the list is entered with the input. So basically that list contains minimum of 2 elements and can go to up to 12 based on the user requirements. What I am looking for is a function/algorithm which will allow the following list of the results.: 0\*11 + 0\*23 +..+ 0\*m 1\*11 + 0\*23 +..+ 0\*m 2\*11 + 0\*23 +..+ 0\*m .. 3\*11 + 2\*23 + .. + 5\*m .. 5\*11 + 5\*23 +..+ 5\*m
[`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product) can help you generate all ways to select elements of `list1` to multiply by elements of `list2`. ``` sums = [] for list1_choices in itertools.product(list1, repeat=len(list2)): sums.append(sum(x*y for x, y in zip(list1_choices, list2)) ``` Or, as a list comprehension: ``` [sum(x*y for x, y in zip(list1_choices, list2)) for list1_choices in itertools.product(list1, repeat=len(list2))] ```
``` [sum(x * y for x in list_2) for y in list_1] ```
multiply list elements in python
[ "", "python", "list", "" ]
i have a dictionary, in which each key has a list as its value and those lists are of different sizes. I populated keys and values using add and set(to avoid duplicates). If i output my dictionary, the output is: ``` blizzard set(['00:13:e8:17:9f:25', '00:21:6a:33:81:50', '58:bc:27:13:37:c9', '00:19:d2:33:ad:9d']) alpha_jian set(['00:13:e8:17:9f:25']) ``` Here, blizzard and alpha\_jian are two keys in my dictionary. Now, i have another text file which has two columns like ``` 00:21:6a:33:81:50 45 00:13:e8:17:9f:25 59 ``` As you can see, the first column items are one of the entries in each list of my dictionary. For example, 00:21:6a:33:81:50 belongs to the key 'blizzard' and 00:13:e8:17:9f:25 belongs to the key 'alpha\_jian'. The problem i want is, go through first column items in my text file, and if that column entry is found in dictionary, find its corresponding key, find the length of that corresponding list in the dictionary, and add them in new dictionary, say newDict. For example 00:21:6a:33:81:50 belongs to blizzard. Hence, newDict entry will be: ``` newDict[blizzard] = 4 // since the blizzard key corresponds to a list of length 4. ``` This is the code i expected to do this task: ``` newDict = dict() # myDict is present with entries like specified above with open("input.txt") as f: for line in f: fields = line.split("\t") for key, value in myDict.items(): if fields[0] == #Some Expression: newdict[key] = len(value) print newDict ``` Here, my question is what should be #Some Expression in my code above. If values are not lists, this is very easy. But how to search in lists? Thanks in advance.
You are looking for `in` ``` if fields[0] in value: ``` But this isn't a very efficient method, as it involves scanning the dict values over and over You can make a temporary datastructure to help ``` helper_dict = {k: v for v, x in myDict.items() for k in x} ``` So your code becomes ``` helper_dict = {k: v for v, x in myDict.items() for k in x} with open("input.txt") as f: for line in f: fields = line.split("\t") key = fields[0] if key in helper_dict: newdict[helper_dict[key]] = len(myDict[helper_dict[key]]) ```
Doesn't ``` if fields[0] in value: ``` solve your problem ? Or I don't understand your question ?
searching a value in a list and outputting its key
[ "", "python", "" ]
I'm writing an application in Python with the Tkinter GUI framework. It listens for keyboard and mouse events, so it must have focus. When it is launched from a terminal in Ubuntu, the following code works: ``` from Tkinter import * root = Tk() root.focus_force() def key(event): print "pressed", event.char def callback(event): print "clicked at", event.x, event.y frame = Frame(root, width=100, height=100) frame.bind("<Key>", key) frame.bind("<Button-1>", callback) frame.pack() frame.focus_force() root.mainloop() ``` However, when launched from a terminal in Mac OS X 10.8.4 (stock Python 2.7.2), focus is retained by the terminal emulator until the user clicks on the window. Does anyone know of a workaround for this?
I tried this and it worked well for me: ``` from os import system from platform import system as platform # set up your Tk Frame and whatnot here... if platform() == 'Darwin': # How Mac OS X is identified by Python system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''') ``` Of course, that'll bring your entire application to the front, not just a specific window, but after you do that, you can then use `focus_force()` on a specific frame or window and that'll get moved to become the frontmost of all your application windows. For those interested, I didn't write the `system()` call myself. I found it in [this thread on SourceForge](http://sourceforge.net/p/tcl/mailman/message/23718545/). The fact that I put the `system()` call within an if block that verifies this is running on OS X makes the solution cross platform - my understanding is that `focus_force()` works on all other platforms exactly as you want, and just performing it after the `system()` invocation wouldn't cause any problems in OS X, either.
came here wondering the same question, but I found this wise sounding answer from Kevin Walzer which suggests to use `py2app`: > Yes, this is standard behavior for OS X. Running an app in Terminal > keeps focus in the Terminal unless you switch by clicking windows. The > Command-Tab behavior is determined by the windowing system, not by a > newly spawned process. > > The way around this is to wrap your application up in a standard Mac app > bundle using py2app. The average Mac user isn't going to launch a > Python-based game from the command line. > > Kevin (from <https://groups.google.com/forum/#!topic/comp.lang.python/ZPO8ZN5dx3M>)
Tkinter window focus on Mac OS X
[ "", "python", "macos", "tkinter", "" ]
I'm trying to get ahold of the python class thing and I've written this little script which takes user input: ``` import sys class Uttenhaler_setup: Fbol=5.01333e-10 c=2.99792458e+8 L=1000 star_list=[] dusty_models=np.array([]) #array of all the dusty models incoming_stars='' #List of incoming stars def __init__(self): """Initiates the below modules.""" self.star_catalog() self.InputKey() def star_catalog(self): """Imports the star catalog""" try: star_catalog=raw_input('Input pathname of stellar catalog: ') with open(star_catalog) as incoming_stars: for line in incoming_stars.readlines(): x=[item for item in line.split()] self.star_list.append(x) #Appends the individual star-IDs to the empty array star_list. print 'Stars imported successfully.' except IOError: print 'Star import unsuccessful. Check that the star catalog file-path is correct. Program exiting now.' sys.exit() if __name__=='__main__': Uttenhaler_setup() ``` I can't seem to find the right syntax to print the results of self.star\_list outside of my method. Just looking for someone to point out my errors. Thanks.
Your problem is that you have set up `star_list` as a class variable, not an instance variable. If you declare `star_list` as `self.star_list` within your `__init__` method you will be able to access `star_list` as follows: ``` tst = Uttenhaler_setup() print(tst.star_list) ``` As you have things at the moment, you would need to access `star_list` with: ``` print(Uttenhaler_setup.star_list) ``` The difference is that a class variable is available to all instances of the class as a shared variable. If you change the value of a class variable, all instances of the class will see the change. However, an instance variable is local to a single instance or instantiation of a class. When you change an instance variable, the change is local to the particular instance of a class. Normally you will want to make almost all your variables to be instance variables. Use class variables for things like constants that should be the same for all instances of your class.
Do something like `my_stars = Uttenhaler_setup()` and then `print my_stars.star_list`.
How to print the result of a method outside of the method
[ "", "python", "class", "methods", "" ]
I tried to generate different random order in N loop, but python seems to generate same sequence. Is the code below correctly written as I am expecting? ``` import random import time def funcA(): nodeCount = 10 order = range(0, nodeCount) random.seed(0x87654321) random.shuffle(order) print("Shuffle order - ") print(order) if __name__ == '__main__': cnt = 0 while cnt < 3: # random.seed(0x87654321) funcA() time.sleep(5) cnt += 1 ```
The issue here is in this statement: ``` random.seed(0x87654321) ``` What this does is provide a "seed" value for the random number generator to use as random data. Since the seed is hardcoded *right before each call to the shuffle function*, the random number generator will behave the same every time. To fix the issue (and get different results each time you run it), simply remove this statement. If you want to initialize it with the seed, initialize once by doing it outside of the `while` loop: ``` if __name__ == '__main__': cnt = 0 random.seed(0x87654321) while cnt < 3: funcA() time.sleep(5) cnt += 1 ```
You're seeding the random number generator with a constant. Any sequence of identical calls to the random number generator with the same seed will produce the same output. If that's not what you want, don't call `seed`.
python randomly generated orders are the same
[ "", "python", "python-2.7", "" ]
I'm working on a Python script which opens a DBF file, and then from that creates a text output of the contents (either .txt or .csv). I've now managed to get it writing the output file, but I need to replace the space character in one of the database fields (It's a UK Car registration number, e.g. I need "AB09 CDE" to output as "AB09CDE") but I've been unable to work out how to do this as it seems to be nested lists. The field is rec[7] in the code below. ``` if __name__ == '__main__': import sys, csv from cStringIO import StringIO from operator import itemgetter # Read a database filename = 'DATABASE.DBF' if len(sys.argv) == 2: filename = sys.argv[1] f = open(filename, 'rb') db = list(dbfreader(f)) f.close() fieldnames, fieldspecs, records = db[0], db[1], db[2:] # Remove some fields that we don't want to use... del fieldnames[0:] del fieldspecs[0:] #Put the relevant data into the temporary table records = [rec[7:8] + rec[9:12] + rec[3:4] for rec in records] # Create outputfile output_file = 'OUTPUT.txt' f = open (output_file, 'wb') csv.writer(f).writerows(records) ``` This also adds a lot of spaces to the end of each outputted value. How would I get rid of these? I'm fairly new to Python so any guidance would be gratefully received!
The problem is that you are using slicing: ``` >>> L = [1,2,3,4,5,6,7,8,9,10] >>> L[7] 8 >>> L[7:8] #NOTE: it's a *list* of a single element! [8] ``` To replace spaces in `rec[7]` do: ``` records = [[rec[7].replace(' ', '')] + rec[9:12] + rec[3:4] for rec in records] ```
``` records = [rec[7].replace(' ', '') + rec[9:12] + rec[3:4] for rec in records] ``` ?
Python - Replacing characters in a list
[ "", "python", "list", "" ]
So I did lots of googling but still can't solve this problem. I tried this: ``` import csv mydict={4442:[4441,4442], 4441:[4441,4442]} with open('testcsv.csv','wb') as f: writer = csv.writer(f, delimiter=' ') for key, value in mydict.items(): writer.writerow([key, value]) ``` But this is completely not what I expected. Because it generates a csv file like: ``` 4441 "[4441, 4442]" 4442 "[4441, 4442]" ``` I'll never get the dictionary value read as list but a string. My read process is like: ``` result={} try: reader = csv.reader(open('testcsv.csv', 'rb')) result = dict(x for x in reader) #note: Everything turned to be string after reading from csv print "testcsv.csv found, load it from file." except: print "testcsv.csv not found. loop all over." ``` And then my result changed to : ``` print result print result[str(4442)] print result[str(4441)] {'4441': '[4441, 4442]', '4442': '[4441, 4442]'} [4441, 4442] [4441, 4442] ``` So my question is how to write / read as it is for a dictionary with integer list as its value ? **Update Solution, accepted answer below will also work:** ``` for row in reader: if row[1][1:-1] != '': result[int(row[0])] = map(int, row[1][1:-1].split(',')) else: result[int(row[0])] = [] ```
Space is not a good delimiter here, because the string representation of the list contains a space. For my answer I'm using '|' as the delimiter. To load the csv file so it creates a dict that is the same as the one you wrote, you can use something like this: ``` try: reader = csv.reader(open('bar.in', 'rb'), delimiter='|') result = dict((int(x[0]), eval(x[1])) for x in reader) print "testcsv.csv found, load it from file." except: print "testcsv.csv not found. loop all over." ``` So now result is: ``` {4441: [4441, 4442], 4442: [4441, 4442]} ``` Where all the numbers are ints. Remember though, this uses eval, and eval can be dangerous.
This works (and doesn't use`eval()`). Note that the way the rows of the csv file are written is slightly different from your version. ``` import csv mydict={4442:[4441,4442], 4441:[4441,4442]} with open('testcsv.csv', 'wb') as f: writer = csv.writer(f, delimiter=' ') for key, value in mydict.items(): writer.writerow([key] + value) # note difference from your version try: reader = csv.reader(open('testcsv.csv', 'rb'), delimiter=' ') result = dict((row[0], row[1:]) for row in (map(int, row) for row in reader)) print "testcsv.csv found, load it from file." print result except Exception as e: print "testcsv.csv not found. loop all over." print e ``` Output: ``` testcsv.csv found, load it from file. {4441: [4441, 4442], 4442: [4441, 4442]} ``` Note: The one-liner to create`result`is equivalent to: ``` result = {} for row in (map(int, row) for row in reader): result[row[0]] = row[1:] ```
Read/Write a dictionary with values as integer lists in a csv file in python 2.6.x
[ "", "python", "csv", "dictionary", "" ]
I haver to define a procedure, that takes as input a positive whole number, and prints out a multiplication table showing all the whole number multiplications up to and including the input number. for example, I need this output: > **print\_multiplication\_table(2)** > > 1 \* 1 = 1 > > 1 \* 2 = 2 > > 2 \* 1 = 2 > > 2 \* 2 = 4 So I´ve tried this: ``` def print_multiplication_table(n): count=0 multiplicador=n while count<multiplicador: count+=1 print n,"x", count, "=", n*count def print_multiplication_table(n): num=1 print str(num) + ' * ' + str(num) + ' = ' + str(num*num) while num<n: siguiente=num+1 conteo=num-1 while conteo<n: print str(num) + ' * ' + str(siguiente) + ' = ' + str(num*siguiente) print str(num) + ' * ' + str(siguiente) + ' = ' + str(num*siguiente) ``` But that generates a loop that runs forever, and I don´t know how to make it stop. Then I´ve tried a different, more elegant approach, like this one: ``` def print_multiplication_table(n): count=0 multiplicador=n while count<multiplicador: count+=1 print n,"x", count, "=", n*count ``` But it doesn´t take into account the multiplication of the numbers before the one that I´m multiplying (the output is 2x1=2, 2x2=4, but doesn´t multipli 1x1, nor 1x2). What changes do I need to make? Any hint? Thanks!
You need a nested `for` loop here. ``` >>> def print_multiplication_table(n): for i in xrange(1, n+1): for j in xrange(1, n+1): print "{}x{}={}".format(i, j, i*j) >>> print_multiplication_table(2) 1x1=1 1x2=2 2x1=2 2x2=4 ``` Your `while` loop doesn't work because you go from 1 to the number and only multiply the number with `count`, hence, generating a sequence like `10x1, 10x2, 10x3...`.
The simplest would be: ``` from itertools import product def pmt(n): for fst, snd in product(xrange(1, n + 1), repeat=2): print '{} * {} = {}'.format(fst, snd, fst * snd) pmt(2) 1 * 1 = 1 1 * 2 = 2 2 * 1 = 2 2 * 2 = 4 ```
Multiplying numbers in python from number 1, but only to a specific number given by the user
[ "", "python", "while-loop", "" ]
I would like to get an element from a `frozenset` (without modifying it, of course, as `frozenset`s are immutable). The best solution I have found so far is: ``` s = frozenset(['a']) iter(s).next() ``` which returns, as expected: ``` 'a' ``` In other words, is there any way of 'popping' an element from a `frozenset` without actually popping it?
*(Summarizing the answers given in the comments)* Your method is as good as any, with the caveat that, from Python 2.6, you should be using `next(iter(s))` rather than `iter(s).next()`. If you want a *random* element rather than an *arbitrary* one, use the following: ``` import random random.sample(s, 1)[0] ``` Here are a couple of examples demonstrating the difference between those two: ``` >>> s = frozenset("kapow") >>> [next(iter(s)) for _ in range(10)] ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a'] ``` ``` >>> import random >>> [random.sample(s, 1)[0] for _ in range(10)] ['w', 'a', 'o', 'o', 'w', 'o', 'k', 'k', 'p', 'k'] ```
If you know that there is but one element in the frozenset, you can use iterable unpacking: ``` s = frozenset(['a']) x, = s ``` This is somewhat a special case of the original question, but it comes in handy some times. If you have a lot of these to do it might be faster than next(iter..: ``` >>> timeit.timeit('a,b = foo', setup='foo = frozenset(range(2))', number=100000000) 5.054765939712524 >>> timeit.timeit('a = next(iter(foo))', setup='foo = frozenset(range(2))', number=100000000) 11.258678197860718 ```
How to get an arbitrary element from a frozenset?
[ "", "python", "iterator", "set", "immutability", "" ]
I have a table (in Postgres 9.1) that looks something like this: ``` CREATE TABLE actions ( user_id: INTEGER, date: DATE, action: VARCHAR(255), count: INTEGER ) ``` For example: ``` user_id | date | action | count ---------------+------------+--------------+------- 1 | 2013-01-01 | Email | 1 1 | 2013-01-02 | Call | 3 1 | 2013-01-03 | Email | 3 1 | 2013-01-04 | Call | 2 1 | 2013-01-04 | Voicemail | 2 1 | 2013-01-04 | Email | 2 2 | 2013-01-04 | Email | 2 ``` I would like to be able to view a user's total actions over time for a specific set of actions; for example, Calls + Emails: ``` user_id | date | count -----------+-------------+--------- 1 | 2013-01-01 | 1 1 | 2013-01-02 | 4 1 | 2013-01-03 | 7 1 | 2013-01-04 | 11 2 | 2013-01-04 | 2 ``` The monstrosity that I've created so far looks like this: ``` SELECT date, user_id, SUM(count) OVER (PARTITION BY user_id ORDER BY date) AS count FROM actions WHERE action IN ('Call', 'Email') GROUP BY user_id, date, count; ``` Which works for single actions, but seems to break for multiple actions when they happen on the same day, for example instead of the expected `11` on `2013-01-04`, we get `9`: ``` date | user_id | count ------------+--------------+------- 2013-01-01 | 1 | 1 2013-01-02 | 1 | 4 2013-01-03 | 1 | 7 2013-01-04 | 1 | 9 <-- should be 11? 2013-01-04 | 2 | 2 ``` Is it possible to tweak my query to resolve this issue? I tried removing the grouping on `count`, but Postgres doesn't seem to like that: > ``` > column "actions.count" must appear in the GROUP BY clause > or be used in an aggregate function > LINE 2: date, user_id, SUM(count) OVER (PARTITION BY user... > ^ > ```
This query produces the result you are looking for: ``` SELECT DISTINCT date, user_id, SUM(count) OVER (PARTITION BY user_id ORDER BY date) AS count FROM actions WHERE action IN ('Call', 'Email'); ``` The default window is already what you want, [according to the official docs](http://www.postgresql.org/docs/9.1/static/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS) and the "DISTINCT" eliminates duplicate rows when both Emails and Calls happen on the same day. See [SQL Fiddle](http://www.sqlfiddle.com/#!12/443a7/5).
The table has a column named "count", and the expresion in the SELECT clause is aliased as "count", it is ambiguous. Read documentation: <http://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-GROUPBY> > In case of ambiguity, a GROUP BY name will be interpreted as an > input-column name rather than an output column name. That means, that your query does not group by "count" evaluated in the SELECT clause, but rather it groups by "count" values taken from the table. This query gives expected results, see [SQL Fiddle](http://www.sqlfiddle.com/#!12/443a7/4) ``` SELECT date, user_id, count from ( Select date, user_id, SUM(count) OVER (PARTITION BY user_id ORDER BY date) AS count FROM actions WHERE action IN ('Call', 'Email') ) alias GROUP BY user_id, date, count; ```
Trending sum over time
[ "", "sql", "postgresql", "aggregate-functions", "window-functions", "" ]
``` CusID Order 3001 Hotdog 3001 Sausage 3002 Sausage 3003 Burger 3003 Hotdog 3002 Hotdog 3001 Burger ``` How I will use this count function? ``` SELECT COUNT(CusID) AS NumOfOrders FROM Orders ``` Desired output ``` CusID NumOfOrders 3001 3 3002 2 3003 2 ```
You need it with a `group by`: ``` SELECT CusId, COUNT(CusID) AS NumOfOrders FROM Orders group by CusId order by CusId; ```
The `group by` will give you that desired result along with `Count` function. ``` select CustID, count(CustID) from Orders group by CustID ``` Refer below fiddle link for sample [SQL Fiddle](http://sqlfiddle.com/#!3/3827b/2)
SQL Count Function By Column
[ "", "sql", "sql-server", "t-sql", "" ]
I had to implement the QuickSort algorithm for a homework in a language of my choice and I chose Python. During the lectures, we've been told that QuickSort is memory efficient because it works in-place; i.e., it has no additional copies of parts of the input array for recursions. With this in mind, I tried to implement the QuickSort algorithm in Python, but shortly afterwards realized that in order to write an elegant piece of code I would have to pass parts of the array to the function itself while recursing. Since Python creates new lists each time I do this, I have tried using Python3 (because it supports the nonlocal keyword). The following is my commented code. ``` def quicksort2(array): # Create a local copy of array. arr = array def sort(start, end): # Base case condition if not start < end: return # Make it known to the inner function that we will work on arr # from the outer definition nonlocal arr i = start + 1 j = start + 1 # Choosing the pivot as the first element of the working part # part of arr pivot = arr[start] # Start partitioning while j <= end: if arr[j] < pivot: temp = arr[i] arr[i] = arr[j] arr[j] = temp i += 1 j += 1 temp = arr[start] arr[start] = arr[i - 1] arr[i - 1] = temp # End partitioning # Finally recurse on both partitions sort(start + 0, i - 2) sort(i, end) sort(0, len(array) - 1) ``` Now, I'm not sure whether I did the job well or am I missing something. I have written a more Pythonic version of QuickSort but that surely doesn't work in-place because it keeps returning parts of the input array and concatenates them. My question is, is this the way of doing it in Python? I have searched both Google and SO but haven't found a true in-place implementation of QuickSort, so I thought it'd be best to ask.
Sure not the best way, plus this famous algorithm will have dozens of perfect implementations.. this is mine, quite easy to understand ``` def sub_partition(array, start, end, idx_pivot): 'returns the position where the pivot winds up' if not (start <= idx_pivot <= end): raise ValueError('idx pivot must be between start and end') array[start], array[idx_pivot] = array[idx_pivot], array[start] pivot = array[start] i = start + 1 j = start + 1 while j <= end: if array[j] <= pivot: array[j], array[i] = array[i], array[j] i += 1 j += 1 array[start], array[i - 1] = array[i - 1], array[start] return i - 1 def quicksort(array, start=0, end=None): if end is None: end = len(array) - 1 if end - start < 1: return idx_pivot = random.randint(start, end) i = sub_partition(array, start, end, idx_pivot) #print array, i, idx_pivot quicksort(array, start, i - 1) quicksort(array, i + 1, end) ``` Ok first a seperate function for the partition subroutine. It takes the array, the start and end point of interest, and the index of pivot. This functions should be clear Quicksort then call the partition subroutine for the first time on the whole array; then call recursevely itself to sort everything up to the pivot and everything after. ask if you dont understand something
I have started learning python lately and the following is my attempt at implementing quicksort using python. Hope it is helpful. Feedback is welcomed :) ``` #!/usr/bin/python Array = [ 3,7,2,8,1,6,8,9,6,9] def partition(a, left, right): pivot = left + (right - left)/2 a[left],a[pivot] = a[pivot], a[left] # swap pivot = left left += 1 while right >= left : while left <= right and a[left] <= a[pivot] : left += 1 while left <= right and a[right] > a[pivot] : right -= 1 if left <= right: a[left] , a[right] = a[right], a[left] # swap left += 1 right -= 1 else: break a[pivot], a[right] = a[right] , a[pivot] return right def quicksort(array , left,right): if left >= right: return if right - left == 1: if array[right] < array[left]: array[right], array[left] = array[left] , array[right] return pivot = partition(array, left, right) quicksort(array, left, pivot -1) quicksort(array, pivot+1,right) def main(): quicksort(Array, 0 , len(Array) -1) print Array main() ```
In-place QuickSort in Python
[ "", "python", "algorithm", "" ]
I'm using MVC4 with Visual Basic to make a web system. But when I have to save my data in my tables and relationships, I need to save in a lot of tables. So, I do this: ``` conn.Open() Dim guardador_datos2 As New SqlCommand("INSERT INTO Creadores (ID_Creador,Usuario) VALUES (" + ultimo_id_creador.ToString() + ", '" + creada_por + "')", conn) guardador_datos2.ExecuteNonQuery() conn.Close() conn.Open() Dim guardador_datos3 As New SqlCommand("INSERT INTO ReunionCreada_X_Usuario (ID_Reunion,ID_Creador) VALUES (" + ultimo_id.ToString() + "," + ultimo_id_creador.ToString() + ")", conn) guardador_datos3.ExecuteNonQuery() conn.Close() conn.Open() Dim guardador_datos4 As New SqlCommand("INSERT INTO Reuniones_X_DepartamentoEmpresa (ID_Departamento_X_Empresa,ID_Reunion) VALUES (" + departamento.ToString() + "," + ultimo_id.ToString() + ")", conn) guardador_datos4.ExecuteNonQuery() conn.Close() ``` I'm opening and closing the `SqlConnection` `conn` a lot of times (I only put three for example in here, but really there are like 9 `conn.Open` and `Close`). **Isn't there a better way to do this?** Like only open `conn` 1 time and execute everything? Actually if I do that, it sends me an error telling me that the connection is actually open
You don't need to open the connection multiple times, just once for the open and once for the close. We often do something like this: ``` conn.Open() Dim guardador_datos2 As New SqlCommand("INSERT INTO Creadores (ID_Creador,Usuario) VALUES (" + ultimo_id_creador.ToString() + ", '" + creada_por + "')", conn) guardador_datos2.ExecuteNonQuery() Dim guardador_datos3 As New SqlCommand("INSERT INTO ReunionCreada_X_Usuario (ID_Reunion,ID_Creador) VALUES (" + ultimo_id.ToString() + "," + ultimo_id_creador.ToString() + ")", conn) guardador_datos3.ExecuteNonQuery() Dim guardador_datos4 As New SqlCommand("INSERT INTO Reuniones_X_DepartamentoEmpresa (ID_Departamento_X_Empresa,ID_Reunion) VALUES (" + departamento.ToString() + "," + ultimo_id.ToString() + ")", conn) guardador_datos4.ExecuteNonQuery() conn.Close() ``` You might also want to wrap it in a Try/Catch/Finally block and use transactions, so that if one of your inserts fails, all of them roll back.
I would put it all in a try..catch, open your connection, do all the stuff required then close the connection. The finally part of the try..catch ensures that the connection is closed even if there is an error thrown: ``` conn.Open() try Dim guardador_datos2 As New SqlCommand("INSERT INTO Creadores (ID_Creador,Usuario) VALUES (" + ultimo_id_creador.ToString() + ", '" + creada_por + "')", conn) guardador_datos2.ExecuteNonQuery() Dim guardador_datos3 As New SqlCommand("INSERT INTO ReunionCreada_X_Usuario (ID_Reunion,ID_Creador) VALUES (" + ultimo_id.ToString() + "," + ultimo_id_creador.ToString() + ")", conn) guardador_datos3.ExecuteNonQuery() Dim guardador_datos4 As New SqlCommand("INSERT INTO Reuniones_X_DepartamentoEmpresa (ID_Departamento_X_Empresa,ID_Reunion) VALUES (" + departamento.ToString() + "," + ultimo_id.ToString() + ")", conn) guardador_datos4.ExecuteNonQuery() catch ex as exception throw(ex) finally conn.Close() end try ```
Better way to execute a lot of SQL commands in Visual Basic?
[ "", "sql", "vb.net", "asp.net-mvc-4", "" ]
is there a way to turn numbers, ether in a string, or an int, into words without loosing leading zero's? I'm trying to convert dates and times and phone numbers into words, but the second I convert the string value into an int I lose my leading zeros. here is my code right now for doing the number to words, and it works great as long as there are no leading zeros. here's an example of my problem... let's say I'm turning a date 08-02-2004 I wan't this to output as zero eight zero two... etc but for me to do that in it's current state I would have to do some round about methods... unless I'm missing something. ``` units = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine "] teens = ["", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] tens = ["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] thousands = ["","thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion "] def numToWords(self, num): words = [] if num == 0: words.append("zero") else: numStr = "%d" % num numStrLen = len(numStr) groups = (numStrLen + 2) / 3 numStr = numStr.zfill(groups * 3) for i in range(0, groups*3, 3): h = int(numStr[i]) t = int(numStr[i+1]) u = int(numStr[i+2]) g = groups - (i / 3 + 1) if h >= 1: words.append(units[h]) words.append("hundred") if t > 1: words.append(tens[t]) if u >= 1: words.append(units[u]) elif t == 1: if u >= 1: words.append(teens[u]) else: words.append(tens[t]) else: if u >= 1: words.append(units[u]) if g >= 1 and (h + t + u) > 0: words.append(thousands[g]) return ' '.join([w for w in words]) ``` any help or suggestions on this would be greatly appreciated.
Make sure you're supplying a string in the first place and only evaluate as an int when you have to. E.g.: ``` def numToWords(self, numStr): words = [] if int(numStr) == 0: words.append("zero") else: # no longer needed, it's already a string # numStr = "%d" % num numStrLen = len(numStr) groups = (numStrLen + 2) / ... ```
When you format your int into a string using %d, it drops any leading zeros. To keep them, you need to specify a minimum number of digits, like this: ``` numStr = "%03d" % num ``` This will append leading zeros to any number that has less than 3 digits (making the minimum number of digits 3, in this case). But before you go slapping on leading zeros willy-nilly, you first need to decide how many total digits you want to see.
how to convert numbers into words while keeping leading zeros?
[ "", "python", "numbers", "words", "" ]
I've seen similar questions to this one but none of them really address the trackback. If I have a class like so ``` class Stop_if_no_then(): def __init__(self, value one, operator, value_two, then, line_or_label, line_number): self._firstvalue = value_one self._secondvalue = value_two self._operator = operator self._gohere = line_or_label self._then = then self._line_number = line_number def execute(self, OtherClass): "code comparing the first two values and making changes etc" ``` What I want my execute method to be able to do is if self.\_then is not equal to the string "THEN" (in allcaps) then I want it to raise a custom error message and terminate the whole program while also not showing a traceback. If the error is encountered the only thing that should print out would look something like (I'm using 3 as an example, formatting is not a problem) this. ``` `Syntax Error (Line 3): No -THEN- present in the statement.` ``` I'm not very picky about it actually being an exception class object, so there's no issue in that aspect. Since I will be using this in a while loop, simple if, elif just repeats the message over and over (because obviously I am not closing the loop). I have seen sys.exit() but that also prints out a giant block of red text, unless I am not using it correctly. I don't want to catch the exception in my loop because there are other classes in the same module in which I need to implement something like this.
You can use a `try:` and then `except Exception as inst:` What that will do is give you your error message in a variable named inst and you can print out the arguments on the error with `inst.args`. Try printing it out and seeing what happens, and is any item in `inst.args` is the one you are looking for. EDIT Here is an example I tried with pythons IDLE: ``` >>> try: open("epik.sjj") except Exception as inst: d = inst >>> d FileNotFoundError(2, 'No such file or directory') >>> d.args (2, 'No such file or directory') >>> d.args[1] 'No such file or directory' >>> ``` EDIT 2: as for closing the program you can always `raise` and error or you can use `sys.exit()`
You can turn off the traceback by limiting its depth. ## Python 2.x ``` import sys sys.tracebacklimit = 0 ``` ## Python 3.x In Python 3.5.2 and 3.6.1, setting [`tracebacklimit`](https://docs.python.org/3/library/sys.html#sys.tracebacklimit) to `0` does not seem to have the intended effect. This is a known [bug](https://bugs.python.org/issue12276). Note that `-1` doesn't work either. Setting it to `None` does however seem to work, at least for now. In Python 3.6.2 and above you should set `tracebacklimit` to `0` or `-1`, as setting it to `None` does not disable the traceback output. ### Python 3.6.1 and below results: ``` >>> import sys >>> sys.tracebacklimit = 0 >>> raise Exception Traceback (most recent call last): File "<stdin>", line 1, in <module> Exception >>> sys.tracebacklimit = -1 >>> raise Exception Traceback (most recent call last): File "<stdin>", line 1, in <module> Exception >>> sys.tracebacklimit = None >>> raise Exception Exception ``` ### Python 3.6.2 and above results: ``` >>> import sys >>> sys.tracebacklimit = 0 >>> raise Exception Exception >>> sys.tracebacklimit = -1 >>> raise Exception Exception >>> sys.tracebacklimit = None >>> raise Exception Traceback (most recent call last): File "<stdin>", line 1, in <module> Exception ``` Nevertheless, for better or worse, if multiple exceptions are raised, they can all still be printed. For example: ``` socket.gaierror: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: urllib.error.URLError: <urlopen error [Errno -2] Name or service not known> ```
Print an error message without printing a traceback and close the program when a condition is not met
[ "", "python", "exception", "error-handling", "customization", "traceback", "" ]
When I use a method of `Class-A` to return an instance of `Class-B`, PyDev will not offer me auto-completion for the instance of `Class-B`. Is there a way to make this work so I don't potentially mistype a method name or forget an argument? Otherwise, PyDev loses much of its value!
I wonder if you're using some combination of classes / containers that hinders pydev's ability to predict your return value's type. This super-simplistic example works on my system and I get full code completion on `inst`: ``` class A(object): def __init__(self, params = None): self.myBs = [B() for _ in range(10)] def getB(self): return self.myBs[5] class B(object): def foo(self): pass inst = A().getB() # Auto-complete broken. PyDev thinks inst is a list. assert isinstance(inst, B) # Auto-complete working again. ``` After additional detail, the `assert` statement is necessary to trigger PyDev's autocomplete functionality.
Asserting isInstance breaks the "Better to ask forgiveness than permission" paradigm in python. Pydev understands specific decorators in docstrings for type hinting. Here's a set of examples: <http://pydev.sourceforge.net/manual_adv_type_hints.html> ``` class Foo(object): def method(self): pass def otherMethod(self): pass def returnFoo(): return Foo() """@type fooInstance: Foo""" fooInstance = returnFoo() ``` I haven't had much luck with the return type (using the epydoc syntax) but haven't tried much, but whatever the object is assigned to can be declared by the type you are expecting as in the example above.
In PyDev, how can I get autocompletion for an instance returned by a method?
[ "", "python", "pydev", "" ]
I have written a script in python, which works on a single file. I couldn't find an answer to make it run on multiple files and to give output for each file separately. ``` out = open('/home/directory/a.out','w') infile = open('/home/directory/a.sam','r') for line in infile: if not line.startswith('@'): samlist = line.strip().split() if 'I' or 'D' in samlist[5]: match = re.findall(r'(\d+)I', samlist[5]) # remember to chang I and D here aswell intlist = [int(x) for x in match] ## if len(intlist) < 10: for indel in intlist: if indel >= 10: ## print indel ###intlist contains lengths of insertions in for each read #print intlist read_aln_start = int(samlist[3]) indel_positions = [] for num1, i_or_d, num2, m in re.findall('(\d+)([ID])(\d+)?([A-Za-z])?', samlist[5]): if num1: read_aln_start += int(num1) if num2: read_aln_start += int(num2) indel_positions.append(read_aln_start) #print indel_positions out.write(str(read_aln_start)+'\t'+str(i_or_d) + '\t'+str(samlist[2])+ '\t' + str(indel) +'\n') out.close() ``` I would like my script to take multiple files with names like a.sam, b.sam, c.sam and for each file give me the output : aout.sam, bout.sam, cout.sam Can you please pass me either a solution or a hint. Regards, Irek
I'd recommend wrapping that script in a function, using the `def` keyword, and passing the names of the input and output files as parameters to that function. ``` def do_stuff_with_files(infile, outfile): out = open(infile,'w') infile = open(outfile,'r') # the rest of your script ``` Now you can call this function for any combination of input and output file names. ``` do_stuff_with_files('/home/directory/a.sam', '/home/directory/a.out') ``` If you want to do this for *all files* in a certain directory, use the `glob` library. To generate the output filenames, just replace the last three characters ("sam") with "out". ``` import glob indir, outdir = '/home/directory/', '/home/directory/out/' files = glob.glob1(indir, '*.sam') infiles = [indir + f for f in files] outfiles = [outdir + f[:-3] + "out" for f in files] for infile, outfile in zip(infiles, outfiles): do_stuff_with_files(infile, outfile) ```
Loop over filenames. ``` input_filenames = ['a.sam', 'b.sam', 'c.sam'] output_filenames = ['aout.sam', 'bout.sam', 'cout.sam'] for infn, outfn in zip(input_filenames, output_filenames): out = open('/home/directory/{}'.format(outfn), 'w') infile = open('/home/directory/{}'.format(infn), 'r') ... ``` **UPDATE** Following code generate output\_filenames from given input\_filenames. ``` import os def get_output_filename(fn): filename, ext = os.path.splitext(fn) return filename + 'out' + ext input_filenames = ['a.sam', 'b.sam', 'c.sam'] # or glob.glob('*.sam') output_filenames = map(get_output_filename, input_filenames) ```
python multiple inputs and multiple outputs
[ "", "python", "" ]
I have a virtual machine which reads instructions from tuples nested within a list like so: ``` [(0,4738),(0,36), (0,6376),(0,0)] ``` When storing this kind of machine code program, a text file is easiest, and has to be written as a string. Which is obviously quite hard to convert back. Is there any module which can read a string into a list/store the list in a readable way? requirements: * Must be human readable in stored form (hence "pickle" is not suitable) * Must be relatively easy to implement
[JSON!](http://docs.python.org/2/library/json.html) ``` import json with open(data_file, 'wb') as dump: dump.write(json.dumps(arbitrary_data)) ``` and similarly: ``` source = open(data_file, 'rb').read() data = json.loads(source) ```
Use the [`json` module](http://docs.python.org/2/library/json.html): ``` string = json.dumps(lst) lst = json.loads(string) ``` Demo: ``` >>> import json >>> lst = [(0,4738),(0,36), ... (0,6376),(0,0)] >>> string = json.dumps(lst) >>> string '[[0, 4738], [0, 36], [0, 6376], [0, 0]]' >>> lst = json.loads(string) >>> lst [[0, 4738], [0, 36], [0, 6376], [0, 0]] ``` An alternative could be to use [`repr()`](http://docs.python.org/2/library/functions.html#repr) and [`ast.literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval); for just lists, tuples and integers that also allows you to round-trip: ``` >>> from ast import literal_eval >>> string = repr(lst) >>> string '[[0, 4738], [0, 36], [0, 6376], [0, 0]]' >>> lst = literal_eval(string) >>> lst [[0, 4738], [0, 36], [0, 6376], [0, 0]] ``` JSON has the added advantage that it is a standard format, with support from tools outside of Python support serialising, parsing and validation. The `json` library is also a lot faster than the `ast.literal_eval()` function.
Convert a list to a string and back
[ "", "python", "python-2.7", "" ]
How can I rename the following files: ``` abc_2000.jpg abc_2001.jpg abc_2004.jpg abc_2007.jpg ``` into the following ones: ``` year_2000.jpg year_2001.jpg year_2004.jpg year_2007.jpg ``` The related code is: ``` import os import glob files = glob.glob('abc*.jpg') for file in files: os.rename(file, '{}.txt'.format(???)) ```
``` import os import glob files = glob.glob('year*.jpg') for file in files: os.rename(file, 'year_{}'.format(file.split('_')[1])) ``` The one line can be broken to: ``` for file in files: parts = file.split('_') #[abc, 2000.jpg] new_name = 'year_{}'.format(parts[1]) #year_2000.jpg os.rename(file, new_name) ```
Because I have done something similar today: ``` #!/usr/bin/env python import os import sys import re if __name__ == "__main__": _, indir = sys.argv infiles = [f for f in os.listdir(indir) if os.path.isfile(os.path.join(indir, f))] for infile in infiles: outfile = re.sub(r'abc', r'year' , infile) os.rename(os.path.join(indir, infile), os.path.join(indir, outfile)) ```
Rename multiple files in Python
[ "", "python", "file-rename", "" ]
In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using: ``` plt.savefig(filename1 + '.pdf') ``` or ``` plt.savefig(filename1 + '.jpg') ``` Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can anybody please help with this?
Use [`PdfPages`](http://matplotlib.org/api/backend_pdf_api.html#matplotlib.backends.backend_pdf.PdfPages) to solve your problem. Pass your `figure` object to the `savefig` method. For example, if you have a whole pile of `figure` objects open and you want to save them into a multi-page PDF, you might do: ``` import matplotlib.backends.backend_pdf pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf") for fig in xrange(1, figure().number): ## will open an empty extra figure :( pdf.savefig( fig ) pdf.close() ```
Do you mean save multiple figures *into* one file, or save multiple figures using *one script*? Here's how you can save two different figures using one *script*. ``` >>> from matplotlib import pyplot as plt >>> fig1 = plt.figure() >>> plt.plot(range(10)) [<matplotlib.lines.Line2D object at 0x10261bd90>] >>> fig2 = plt.figure() >>> plt.plot(range(10,20)) [<matplotlib.lines.Line2D object at 0x10263b890>] >>> fig1.savefig('fig1.png') >>> fig2.savefig('fig2.png') ``` ...which produces these two plots into their own ".png" files: ![enter image description here](https://i.stack.imgur.com/4i8T0.png) ![enter image description here](https://i.stack.imgur.com/qE4vB.png) To save them to the same *file*, use **subplots**: ``` >>> from matplotlib import pyplot as plt >>> fig = plt.figure() >>> axis1 = fig.add_subplot(211) >>> axis1.plot(range(10)) >>> axis2 = fig.add_subplot(212) >>> axis2.plot(range(10,20)) >>> fig.savefig('multipleplots.png') ``` The above script produces this single ".png" file: ![enter image description here](https://i.stack.imgur.com/8WnBH.png)
Python saving multiple figures into one PDF file
[ "", "python", "matplotlib", "" ]
I used to read files like this: ``` f = [i.strip("\n") for i in open("filename.txt")] ``` which works just fine. I prefer this way because it is cleaner and shorter than traditional file reading code samples available on the web (e.g. f = open(...) , for line in f.readlines() , f.close()). However, I wonder if there can be any drawback for reading files like this, e.g. since I don't close the file, does Python interpreter handles this itself? Is there anything I should be careful of using this approach?
This is the recommended way: ``` with open("filename.txt") as f: lines = [line.strip("\n") for line in f] ``` The other way may not close the input file for a long time. This may not matter for your application. The `with` statement takes care of closing the file for you. In CPython, just letting the file handle object be garbage-collected should close the file for you, but in other flavors of Python (Jython, IronPython, PyPy) you definitely can't count on this. Also, the `with` statement makes your intentions very clear, and conforms with common practice.
From the [docs](http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects): > When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. You should always close a file after working with it. Python **will not** automatically do it for you. If you want a cleaner and shorter way, use a [`with`](http://docs.python.org/2/reference/compound_stmts.html#with) statement: ``` with open("filename.txt") as myfile: lines = [i.strip("\n") for i in myfile] ``` This has two advantages: * It automatically closes the file after the `with` block * If an exception is raised, the file is closed regardless.
What happens if I read a file without closing it afterwards?
[ "", "python", "file-io", "" ]
My question is more of an understanding question than a strict programming question. I know that python variables are actually pointers, which means they don't actually store a value, but rather point to the place in memory where that value is stored. What i can't figure out is how the following 2 cases differ: ``` >>> a = 3 >>> b = a >>> a 3 >>> b 3 >>>b = 4 >>> b 4 >>> a 3 ``` The new value assigned to 'b' does not change the value pointed to by 'a'. As oppose to: ``` >>> a = [1,2,3] >>> b = a >>> a [1,2,3] >>> b [1,2,3] >>> b.append(4) >>> b [1,2,3,4] >>> a [1,2,3,4] ``` The new value assigned to b changed the value pointed to by a
Calling `b.append` doesn't assign `b` to a new list. It still points to the same position in memory. ``` >>> b = [1,2,3] >>> id(b) 36586568L >>> b.append(4) >>> id(b) 36586568L ``` Since it is the underlying data that changes, any other identifiers also pointing to that data will be affected.
This has been covered many times before. Short answer is that they aren't strictly pointers. They are more like labels. In your top case, b is re-labeled to 4 and thus changes. In your bottom case (with the array) b is not re-labeled, but only it's contents appended to. That's why arrays seem to act differently.
changing the value of var1
[ "", "python", "pointers", "variable-assignment", "" ]
I'm really sorry if this is a lame question, but I think this may potentially help others making the same transition from C to Python. I have a program that I started writing in C, but I think it's best if I did it in Python because it just makes my life a lot easier. My program retrieves intraday stock data from Yahoo! Finance and stores it inside of a struct. Since I'm so used to programming in C I generally try to do things the hard way. What I want to know is what's the most "Pythonesque" way of storing the data into an organized fashion. I was thinking an array of tuples? Here's a bit of my C program. ``` // Parses intraday stock quote data from a Yahoo! Finance .csv file. void parse_intraday_data(struct intraday_data *d, char *path) { char cur_line[100]; char *csv_value; int i; FILE *data_file = fopen(path, "r"); if (data_file == NULL) { perror("Error opening file."); return; } // Ignore the first 15 lines. for (i = 0; i < 15; i++) fgets(cur_line, 100, data_file); i = 0; while (fgets(cur_line, 100, data_file) != NULL) { csv_value = strtok(cur_line, ","); csv_value = strtok(NULL, ","); d->close[i] = atof(csv_value); csv_value = strtok(NULL, ","); d->high[i] = atof(csv_value); csv_value = strtok(NULL, ","); d->low[i] = atof(csv_value); csv_value = strtok(NULL, ","); d->open[i] = atof(csv_value); csv_value = strtok(NULL, "\n"); d->volume[i] = atoi(csv_value); i++; } d->close[i] = 0; d->high[i] = 0; d->low[i] = 0; d->open[i] = 0; d->volume[i] = 0; d->count = i - 1; i = 0; fclose(data_file); } ``` So far my Python program retrieves the data like this. ``` response = urllib2.urlopen('https://www.google.com/finance/getprices?i=' + interval + '&p=' + period + 'd&f=d,o,h,l,c,v&df=cpct&q=' + ticker) ``` Question is, what's the best or most elegant way of storing this data in Python?
Keep it simple. Read the line, split it by commas, and store the values inside a (`named`)`tuple`. That’s pretty close to using a `struct` in C. If your program gets more elaborate it might (!) make sense to replace the tuple by a class, but not immediately. Here’s an outline: ``` from collections import namedtuple IntradayData = namedtuple('IntradayData', ['close', 'high', 'low', 'open', 'volume', 'count']) response = urllib2.urlopen('https://www.google.com/finance/getprices?q=AAPL') result=response.read().split('\n') result = result[15 :] # Your code does this, too. Not sure why. all_data = [] for i, data in enumerate(x): if data == '': continue c, h, l, o, v, _ = map(float, data.split(',')) all_data.append(IntradayData(c, h, l, o, v, i)) ```
I believe it depends on how much data manipulation you will want to do after retrieving data. If, for example, you plan to just print them on the screen then an array of tuple would do. However, if you need to be able to sort, search, and other kind of data manipulation I believe a custom class could help: you would then work with a list (or even a home-brew container) of custom objects, allowing you for easily adding custom methods, based on your need. Note that this is just my opinion, and I'm not an advanced Python developer.
From C to Python
[ "", "python", "c", "" ]
I am having table as below.. ``` r_Id Marks 1 25 1 25 1 25 2 30 2 30 ``` now i want a query in which sum of marks for each r\_id should be calculated and result should be ``` r_Id MARKS Sum 1 25 75 1 25 75 1 25 75 2 30 60 2 30 60 ``` I need to do this in oracle without using PL/SQL. Please Help. I have tried using CUBE, ROLLUP, GROUPING SETS in GROUP BY, but nothing is working.
You want to use the analytic functions for this. These are the functions that use an `over` clause: ``` select r_id, Marks, sum(Marks) over (partition by r_id) from t; ```
You could do something like this: ``` select table1.*, sums.mark_sum from table1 inner join ( select r_id, sum(marks) mark_sum from table1 group by r_id ) sums on sums.r_id = table1.r_id ``` On SQLFiddle: <http://sqlfiddle.com/#!4/5a935/2>
Sum for same ID in every row SQL
[ "", "sql", "oracle", "group-by", "sum", "" ]
Let's say I have a text file contains a bunch of ip ranges like this: ``` x.x.x.x-y.y.y.y x.x.x.x-y.y.y.y x.x.x.x-y.y.y.y x.x.x.x-y.y.y.y x.x.x.x-y.y.y.y ``` x.x.x.x is start value and y.y.y.y is end value of range. How can I convert these ip ranges to all possible IPs in a new text file in python? PS: This question is not same as any of my previous questions. I asked "how to generate all possible ips from cidr notations" in my previous question. But in here I ask "how to generate from ip range list". These are different things.
This function returns all ip addresses like from start to end: ``` def ips(start, end): import socket, struct start = struct.unpack('>I', socket.inet_aton(start))[0] end = struct.unpack('>I', socket.inet_aton(end))[0] return [socket.inet_ntoa(struct.pack('>I', i)) for i in range(start, end)] ``` These are the building blocks to build it on your own: ``` >>> import socket, struct >>> ip = '0.0.0.5' >>> i = struct.unpack('>I', socket.inet_aton(ip))[0] >>> i 5 >>> i += 1 >>> socket.inet_ntoa(struct.pack('>I', i)) '0.0.0.6' ``` Example: ``` ips('1.2.3.4', '1.2.4.5') ['1.2.3.4', '1.2.3.5', '1.2.3.6', '1.2.3.7', ..., '1.2.3.253', '1.2.3.254', '1.2.3.255', '1.2.4.0', '1.2.4.1', '1.2.4.2', '1.2.4.3', '1.2.4.4'] ``` *Read from file* In your case you can read from a file like this: ``` with open('file') as f: for line in f: start, end = line.strip().split('-') # .... ```
Python 3 only, for IPv4, same idea with @User but use new Python3 standard library: `ipaddress` IPv4 is represented by 4 bytes. So next IP is actually next number, a range of IPs can be represented as a range of integer numbers. 0.0.0.1 is 1 0.0.0.2 is 2 ... 0.0.0.255 is 255 0.0.1.0 is 256 0.0.1.1 is 257 By code (ignore the In []: and Out []:) ``` In [68]: from ipaddress import ip_address In [69]: ip_address('0.0.0.1') Out[69]: IPv4Address('0.0.0.1') In [70]: ip_address('0.0.0.1').packed Out[70]: b'\x00\x00\x00\x01' In [71]: int(ip_address('0.0.0.1').packed.hex(), 16) Out[71]: 1 In [72]: int(ip_address('0.0.1.0').packed.hex(), 16) Out[72]: 256 In [73]: int(ip_address('0.0.1.1').packed.hex(), 16) Out[73]: 257 ``` `ip.packed.hex()` returns the hexadecimal form of 4 bytes, as it is in hexadecimal, it is shorter (e.g: 0xff hex == 255 decimal == 0b11111111 binary), and thus, often used for representing bytes. `int(hex, 16)` returns integer value corresponding to the hex value as it is more human friendly, and can be used as input for `ip_address`. ``` from ipaddress import ip_address def ips(start, end): '''Return IPs in IPv4 range, inclusive.''' start_int = int(ip_address(start).packed.hex(), 16) end_int = int(ip_address(end).packed.hex(), 16) return [ip_address(ip).exploded for ip in range(start_int, end_int)] ips('192.168.1.240', '192.168.2.5') ``` Returns: ``` ['192.168.1.240', '192.168.1.241', '192.168.1.242', '192.168.1.243', '192.168.1.244', '192.168.1.245', '192.168.1.246', '192.168.1.247', '192.168.1.248', '192.168.1.249', '192.168.1.250', '192.168.1.251', '192.168.1.252', '192.168.1.253', '192.168.1.254', '192.168.1.255', '192.168.2.0', '192.168.2.1', '192.168.2.2', '192.168.2.3', '192.168.2.4'] ```
How can I generate all possible IPs from a list of ip ranges in Python?
[ "", "python", "ip", "converters", "generator", "cidr", "" ]
I was wondering while testing my website that is there any way that the user can fetch data from my database by making some further modification in the following query ``` SELECT * FROM users WHERE login='admin' AND password='1' OR '1'='1'; ``` provided that he knew `admin` username and used `'1'='1'` for password to hack into it. What else can he add to echo the password on screen or find table details? I want to do this to understand the limits the unprotected `SQL` can harm us for my presentation on SQL injection
Assuming that : ``` ' OR '1'='1'; ``` is a hack then possibilites might be endless if input is not sanitized eg: ``` ' OR '1'='1'; drop table users; ``` ect.
form injection into username and password boxes should be as follows.. z' OR 'x'= 'x..... but attackers can use an url injection technique to fetch info from your website
SQL Injection Exploiting Login form
[ "", "sql", "sql-injection", "" ]
I am dynamically creating a QTableView from a Pandas dataframe. I have example code [here.](https://gist.github.com/MarshallChris/6029919) I can create the table, with the checkboxes but I cannot get the checkboxes to reflect the model data, or even to change at all to being unchecked. I am following example code from this previous [question](https://stackoverflow.com/questions/3363190/qt-qtableview-how-to-have-a-checkbox-only-column) and taking @raorao answer as a guide. This will display the boxes in the table, but non of the functionality is working. Can anyone suggest any changes, or what is wrong with this code. Why is it not reflecting the model, and why can it not change? Do check out my full example code [here.](https://gist.github.com/MarshallChris/6029919) **Edit one** : Update after comment from Frodon : corrected string cast to bool with a comparison xxx == 'True' ``` class CheckBoxDelegate(QtGui.QStyledItemDelegate): """ A delegate that places a fully functioning QCheckBox in every cell of the column to which it's applied """ def __init__(self, parent): QtGui.QItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): ''' Important, otherwise an editor is created if the user clicks in this cell. ** Need to hook up a signal to the model ''' return None def paint(self, painter, option, index): ''' Paint a checkbox without the label. ''' checked = index.model().data(index, QtCore.Qt.DisplayRole) == 'True' check_box_style_option = QtGui.QStyleOptionButton() if (index.flags() & QtCore.Qt.ItemIsEditable) > 0: check_box_style_option.state |= QtGui.QStyle.State_Enabled else: check_box_style_option.state |= QtGui.QStyle.State_ReadOnly if checked: check_box_style_option.state |= QtGui.QStyle.State_On else: check_box_style_option.state |= QtGui.QStyle.State_Off check_box_style_option.rect = self.getCheckBoxRect(option) # this will not run - hasFlag does not exist #if not index.model().hasFlag(index, QtCore.Qt.ItemIsEditable): #check_box_style_option.state |= QtGui.QStyle.State_ReadOnly check_box_style_option.state |= QtGui.QStyle.State_Enabled QtGui.QApplication.style().drawControl(QtGui.QStyle.CE_CheckBox, check_box_style_option, painter) def editorEvent(self, event, model, option, index): ''' Change the data in the model and the state of the checkbox if the user presses the left mousebutton or presses Key_Space or Key_Select and this cell is editable. Otherwise do nothing. ''' print 'Check Box editor Event detected : ' if not (index.flags() & QtCore.Qt.ItemIsEditable) > 0: return False print 'Check Box edior Event detected : passed first check' # Do not change the checkbox-state if event.type() == QtCore.QEvent.MouseButtonRelease or event.type() == QtCore.QEvent.MouseButtonDblClick: if event.button() != QtCore.Qt.LeftButton or not self.getCheckBoxRect(option).contains(event.pos()): return False if event.type() == QtCore.QEvent.MouseButtonDblClick: return True elif event.type() == QtCore.QEvent.KeyPress: if event.key() != QtCore.Qt.Key_Space and event.key() != QtCore.Qt.Key_Select: return False else: return False # Change the checkbox-state self.setModelData(None, model, index) return True ```
I've found a solution for you. The trick was: 1. to write the `setData` method of the model 2. to always return a QVariant in the `data` method Here it is. (I had to create a class called `Dataframe`, to make the example work without pandas. Please replace all the `if has_pandas` statements by yours): ``` from PyQt4 import QtCore, QtGui has_pandas = False try: import pandas as pd has_pandas = True except: pass class TableModel(QtCore.QAbstractTableModel): def __init__(self, parent=None, *args): super(TableModel, self).__init__() self.datatable = None self.headerdata = None def update(self, dataIn): print 'Updating Model' self.datatable = dataIn print 'Datatable : {0}'.format(self.datatable) if has_pandas: headers = dataIn.columns.values else: headers = dataIn.columns header_items = [ str(field) for field in headers ] self.headerdata = header_items print 'Headers' print self.headerdata def rowCount(self, parent=QtCore.QModelIndex()): return len(self.datatable.index) def columnCount(self, parent=QtCore.QModelIndex()): if has_pandas: return len(self.datatable.columns.values) else: return len(self.datatable.columns) def data(self, index, role=QtCore.Qt.DisplayRole): if role == QtCore.Qt.DisplayRole: i = index.row() j = index.column() return QtCore.QVariant('{0}'.format(self.datatable.iget_value(i, j))) else: return QtCore.QVariant() def setData(self, index, value, role=QtCore.Qt.DisplayRole): if index.column() == 4: self.datatable.iset_value(index.row(), 4, value) return value return value def headerData(self, col, orientation, role): if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole: return '{0}'.format(self.headerdata[col]) def flags(self, index): if index.column() == 4: return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled else: return QtCore.Qt.ItemIsEnabled class TableView(QtGui.QTableView): """ A simple table to demonstrate the QComboBox delegate. """ def __init__(self, *args, **kwargs): QtGui.QTableView.__init__(self, *args, **kwargs) self.setItemDelegateForColumn(4, CheckBoxDelegate(self)) class CheckBoxDelegate(QtGui.QStyledItemDelegate): """ A delegate that places a fully functioning QCheckBox in every cell of the column to which it's applied """ def __init__(self, parent): QtGui.QItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): ''' Important, otherwise an editor is created if the user clicks in this cell. ** Need to hook up a signal to the model ''' return None def paint(self, painter, option, index): ''' Paint a checkbox without the label. ''' checked = index.data().toBool() check_box_style_option = QtGui.QStyleOptionButton() if (index.flags() & QtCore.Qt.ItemIsEditable) > 0: check_box_style_option.state |= QtGui.QStyle.State_Enabled else: check_box_style_option.state |= QtGui.QStyle.State_ReadOnly if checked: check_box_style_option.state |= QtGui.QStyle.State_On else: check_box_style_option.state |= QtGui.QStyle.State_Off check_box_style_option.rect = self.getCheckBoxRect(option) # this will not run - hasFlag does not exist #if not index.model().hasFlag(index, QtCore.Qt.ItemIsEditable): #check_box_style_option.state |= QtGui.QStyle.State_ReadOnly check_box_style_option.state |= QtGui.QStyle.State_Enabled QtGui.QApplication.style().drawControl(QtGui.QStyle.CE_CheckBox, check_box_style_option, painter) def editorEvent(self, event, model, option, index): ''' Change the data in the model and the state of the checkbox if the user presses the left mousebutton or presses Key_Space or Key_Select and this cell is editable. Otherwise do nothing. ''' print 'Check Box editor Event detected : ' print event.type() if not (index.flags() & QtCore.Qt.ItemIsEditable) > 0: return False print 'Check Box editor Event detected : passed first check' # Do not change the checkbox-state if event.type() == QtCore.QEvent.MouseButtonPress: return False if event.type() == QtCore.QEvent.MouseButtonRelease or event.type() == QtCore.QEvent.MouseButtonDblClick: if event.button() != QtCore.Qt.LeftButton or not self.getCheckBoxRect(option).contains(event.pos()): return False if event.type() == QtCore.QEvent.MouseButtonDblClick: return True elif event.type() == QtCore.QEvent.KeyPress: if event.key() != QtCore.Qt.Key_Space and event.key() != QtCore.Qt.Key_Select: return False else: return False # Change the checkbox-state self.setModelData(None, model, index) return True def setModelData (self, editor, model, index): ''' The user wanted to change the old state in the opposite. ''' print 'SetModelData' newValue = not index.data().toBool() print 'New Value : {0}'.format(newValue) model.setData(index, newValue, QtCore.Qt.EditRole) def getCheckBoxRect(self, option): check_box_style_option = QtGui.QStyleOptionButton() check_box_rect = QtGui.QApplication.style().subElementRect(QtGui.QStyle.SE_CheckBoxIndicator, check_box_style_option, None) check_box_point = QtCore.QPoint (option.rect.x() + option.rect.width() / 2 - check_box_rect.width() / 2, option.rect.y() + option.rect.height() / 2 - check_box_rect.height() / 2) return QtCore.QRect(check_box_point, check_box_rect.size()) ############################################################################################################################### class Dataframe(dict): def __init__(self, columns, values): if len(values) != len(columns): raise Exception("Bad values") self.columns = columns self.values = values self.index = values[0] super(Dataframe, self).__init__(dict(zip(columns, values))) pass def iget_value(self, i, j): return(self.values[j][i]) def iset_value(self, i, j, value): self.values[j][i] = value if __name__=="__main__": from sys import argv, exit class Widget(QtGui.QWidget): """ A simple test widget to contain and own the model and table. """ def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) l=QtGui.QVBoxLayout(self) cdf = self.get_data_frame() self._tm=TableModel(self) self._tm.update(cdf) self._tv=TableView(self) self._tv.setModel(self._tm) for row in range(0, self._tm.rowCount()): self._tv.openPersistentEditor(self._tm.index(row, 4)) self.setGeometry(300, 300, 550, 200) l.addWidget(self._tv) def get_data_frame(self): if has_pandas: df = pd.DataFrame({'Name':['a','b','c','d'], 'First':[2.3,5.4,3.1,7.7], 'Last':[23.4,11.2,65.3,88.8], 'Class':[1,1,2,1], 'Valid':[True, False, True, False]}) else: columns = ['Name', 'First', 'Last', 'Class', 'Valid'] values = [['a','b','c','d'], [2.3,5.4,3.1,7.7], [23.4,11.2,65.3,88.8], [1,1,2,1], [True, False, True, False]] df = Dataframe(columns, values) return df a=QtGui.QApplication(argv) w=Widget() w.show() w.raise_() exit(a.exec_()) ```
Here's a port of the same code above for PyQt5. Posting here as there doesn't appear to be another example of a working CheckBox Delegate in QT5, and i was tearing my hair out trying to get it working. Hopefully it's useful to someone. ``` from PyQt5 import QtCore, QtWidgets from PyQt5.QtCore import QModelIndex from PyQt5.QtGui import QStandardItemModel from PyQt5.QtWidgets import QApplication, QTableView class CheckBoxDelegate(QtWidgets.QItemDelegate): """ A delegate that places a fully functioning QCheckBox cell of the column to which it's applied. """ def __init__(self, parent): QtWidgets.QItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): """ Important, otherwise an editor is created if the user clicks in this cell. """ return None def paint(self, painter, option, index): """ Paint a checkbox without the label. """ self.drawCheck(painter, option, option.rect, QtCore.Qt.Unchecked if int(index.data()) == 0 else QtCore.Qt.Checked) def editorEvent(self, event, model, option, index): ''' Change the data in the model and the state of the checkbox if the user presses the left mousebutton and this cell is editable. Otherwise do nothing. ''' if not int(index.flags() & QtCore.Qt.ItemIsEditable) > 0: return False if event.type() == QtCore.QEvent.MouseButtonRelease and event.button() == QtCore.Qt.LeftButton: # Change the checkbox-state self.setModelData(None, model, index) return True return False def setModelData (self, editor, model, index): ''' The user wanted to change the old state in the opposite. ''' model.setData(index, 1 if int(index.data()) == 0 else 0, QtCore.Qt.EditRole) if __name__ == '__main__': import sys app = QApplication(sys.argv) model = QStandardItemModel(4, 3) tableView = QTableView() tableView.setModel(model) delegate = CheckBoxDelegate(None) tableView.setItemDelegateForColumn(1, delegate) for row in range(4): for column in range(3): index = model.index(row, column, QModelIndex()) model.setData(index, 1) tableView.setWindowTitle("Check Box Delegate") tableView.show() sys.exit(app.exec_()) ```
PyQt - Column of Checkboxes in a QTableView
[ "", "python", "python-2.7", "pyqt", "pandas", "" ]
Here is an example: ``` # class.py class MyString: def __init__(self, str): self.str = str def __div__(self, sep): return self.str.split(sep) >>> m = MyString('abcdabcdabcd') >>> print m / 'b' ['a', 'cda', 'cda', 'cd'] ``` The `__init__` method takes two parameters: the first one, `self`, is the instance object itself and `str`, the second, is a parameter passed in by the call. Is using `__init__` the only way to get values into the instance of my class? Or, if I don't declare the method `__init__`, will expressions like `m = MyString('abcdabcdabcd')` cease to work?
By default , when an object is created without parameter as follows ``` a = Class() ``` then the `__init__` method without parameter is called . If you are not using `__init__` method , then the instances should be created without parameter as follows ``` class MyString: def __div__(self, sep): return self.str.split(sep) m = MyString() ``` But if you want to add a parameter to your instance , you are bound to use **init** with parameter as in your program . You can add class variable as follows ``` class MyString: str = '' def __init__(self,str): MyString.str = str def __div__(self, sep): return self.str.split(sep) m = MyString('aSAA') print(MyString.str) #print(m.str) ['a', 'cda', 'cda', 'cd'] ``` BUT a class variable is static and it is property of the class itself not particular to the object .
The **initializer** (`Class.__init__()`) is *always* used to capture the arguments passed to the **constructor** (`Class()`). Without it, the constructor won't work as desired.
Is there any way besides __init__ to receive values when constructing a class?
[ "", "python", "class", "parameters", "constructor", "initialization", "" ]
The question is pretty much in the title, but say I have a list L ``` L = [1,2,3,4,5] ``` min(L) = 1 here. Now I remove 4. The min is still 1. Then I remove 2. The min is still 1. Then I remove 1. The min is now 3. Then I remove 3. The min is now 5, and so on. I am wondering if there is a good way to keep track of the min of the list at all times without needing to do min(L) or scanning through the entire list, etc. There is an efficiency cost to actually removing the items from the list because it has to move everything else over. Re-sorting the list each time is expensive, too. Is there a way around this?
To remove a random element you need to know what elements have not been removed yet. To know the minimum element, you need to sort or scan the items. A min heap implemented as an array neatly solves both problems. The cost to remove an item is O(log N) and the cost to find the min is O(1). The items are stored contiguously in an array, so choosing one at random is very easy, O(1). The min heap is described [on this Wikipedia page](http://en.wikipedia.org/wiki/Binary_heap) BTW, if the data are large, you can leave them in place and store pointers or indexes in the min heap and adjust the comparison operator accordingly.
Google for self-balancing binary search trees. Building one from the initial list takes O(n lg n) time, and finding and removing an arbitrary item will take O(lg n) (instead of O(n) for finding/removing from a simple list). A smallest item will always appear in the root of the tree. [This question](https://stackoverflow.com/q/2298165/1126841) may be useful. It provides links to several implementation of various balanced binary search trees. The advice to use a hash table does not apply well to your case, since it does not address maintaining a minimum item.
Given a list L labeled 1 to N, and a process that "removes" a random element from consideration, how can one efficiently keep track of min(L)?
[ "", "python", "algorithm", "list", "min", "" ]
I have for example an a column that starts with string values in capital letters and then continues in lower case: ``` THIS SENTENCE IS IN UPPERCASE and this in lower case ``` Is there any way to select the substring that contains uppercase letters?
``` DECLARE @searchtext VARCHAR(100) = 'THIS SENTENCE IS IN UPPERCASE and this in lower case' DECLARE @i INT = 1, @l INT = LEN(@searchtext) WHILE (@i <= @l AND 1 = CHARINDEX(UPPER(LEFT(@searchtext,@i)),@searchtext COLLATE Latin1_General_CS_AS)) BEGIN SET @i = @i+1 END SELECT RTRIM(LEFT(@searchtext, @i-1)) ``` I can't get it to work with PATINDEX btw., no matter where I put the collation info.
The above solution account for only words for one sentence in upper case followed by lower case words. Jeff Moden et al have written a string spliter using a tally table. I copied this function and installed it in my database. The cte\_Split\_On\_Spaces divides out all words. Does not account for punctuation. Then, the strings are collated to case sensitive, accent sensitive words. If the upper case matches the normal word, it is in upper case. This solution finds all upper case words in a string and list them by order. You can easily put it back into a string. Sincerely John Miner The Crafty Dba www.craftydba.com ![enter image description here](https://i.stack.imgur.com/7eZ8z.jpg) -- ## -- Use splitter on paragraph, select upper case words -- <http://www.sqlperformance.com/2012/08/t-sql-queries/splitting-strings-follow-up> ; with cte\_Split\_On\_Spaces as ( select \* from [dbo].[DelimitedSplitN4K] ('THIS SENTENCE IS IN UPPERCASE and this in lower case', ' ') ) select s.ItemNumber, s.Item from cte\_Split\_On\_Spaces s where s.Item COLLATE SQL\_Latin1\_General\_CP1\_CS\_AS = UPPER(s.Item COLLATE SQL\_Latin1\_General\_CP1\_CS\_AS)
SQL Select only the words that are in Capital
[ "", "sql", "sql-server", "" ]
I have data which is of the gaussian form when plotted as histogram. I want to plot a gaussian curve on top of the histogram to see how good the data is. I am using pyplot from matplotlib. Also I do NOT want to normalize the histogram. I can do the normed fit, but I am looking for an Un-normalized fit. Does anyone here know how to do it? Thanks! Abhinav Kumar
As an example: ``` import pylab as py import numpy as np from scipy import optimize # Generate a y = np.random.standard_normal(10000) data = py.hist(y, bins = 100) # Equation for Gaussian def f(x, a, b, c): return a * py.exp(-(x - b)**2.0 / (2 * c**2)) # Generate data from bins as a set of points x = [0.5 * (data[1][i] + data[1][i+1]) for i in xrange(len(data[1])-1)] y = data[0] popt, pcov = optimize.curve_fit(f, x, y) x_fit = py.linspace(x[0], x[-1], 100) y_fit = f(x_fit, *popt) plot(x_fit, y_fit, lw=4, color="r") ``` ![enter image description here](https://i.stack.imgur.com/jCyLH.png) This will fit a Gaussian plot to a distribution, you should use the `pcov` to give a quantitative number for how good the fit is. A better way to determine how well your data is Gaussian, or any distribution is the [Pearson chi-squared test](https://en.wikipedia.org/wiki/Pearson's_chi-squared_test). It takes some practise to understand but it is a very powerful tool.
An old post I know, but wanted to contribute my code for doing this, which simply does the 'fix by area' trick: ``` from scipy.stats import norm from numpy import linspace from pylab import plot,show,hist def PlotHistNorm(data, log=False): # distribution fitting param = norm.fit(data) mean = param[0] sd = param[1] #Set large limits xlims = [-6*sd+mean, 6*sd+mean] #Plot histogram histdata = hist(data,bins=12,alpha=.3,log=log) #Generate X points x = linspace(xlims[0],xlims[1],500) #Get Y points via Normal PDF with fitted parameters pdf_fitted = norm.pdf(x,loc=mean,scale=sd) #Get histogram data, in this case bin edges xh = [0.5 * (histdata[1][r] + histdata[1][r+1]) for r in xrange(len(histdata[1])-1)] #Get bin width from this binwidth = (max(xh) - min(xh)) / len(histdata[1]) #Scale the fitted PDF by area of the histogram pdf_fitted = pdf_fitted * (len(data) * binwidth) #Plot PDF plot(x,pdf_fitted,'r-') ```
Un-normalized Gaussian curve on histogram
[ "", "python", "matplotlib", "histogram", "gaussian", "" ]
If I have a query that has a WHERE clause like: ``` where date1 > date2 ``` What will happen if date2 is null? Do I need to specify that date1 and date2 both be not null? The types are DATE()
It will try to compare `date1` to `NULL` and it will evaluate to unknown. ``` WHERE '2013-07-18' > NULL ``` is *unknown*. See my blog post on [`NULL` behavior in 3 valued logic](http://www.jadito.us/2013/01/07/null-behavior-for-three-valued-logic). You will want to use a function like `ISNULL` around `date2` or explicitly write out the logic. Using `ISNULL` will prevent an index from being used, however. You could write: ``` WHERE (date1 > date2 OR date2 IS NULL) ```
always UNKNOWN. NULL value must be treated with IS NULL statement Try this example: ``` declare @d1 datetime declare @d2 datetime set @d1 = GETDATE() select case when @d1 > @d2 then 'OK' else 'KO' end ```
If I have a query that compares two dates in SQL Server, what will happen if one of the dates is null?
[ "", "sql", "sql-server", "" ]