Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am working with a schedule table where the an office has appointments in the morning, then blocked off during lunch and then more appointments in the afternoon. this office is looking for the ability to change its frequency and quantity of appointments on the fly based on start and end times it already has.
for exam... | I was able to complete this using a CTE for the AMtimes and PMTimes
```
IF EXISTS (SELECT * FROM sys.procedures WHERE Name = 'InsertAppointmentDay' AND [type_desc] = 'SQL_STORED_PROCEDURE')
DROP PROCEDURE InsertAppointmentDay;
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[InsertAppoi... | Assuming your answer is that appointments cannot overlap, I would approach the problem like this.
Create a CTE with a starting and ending time for every slot in the work-day, according to your (new) definition of slot-duration, and according to the time the office opens in the morning (and closes, of course).
Then in... | recursively fill a sql table based on data in the table | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I want to do join the current directory path and a relative directory path `goal_dir` somewhere up in the directory tree, so I get the absolute path to the `goal_dir`. This is my attempt:
```
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
```
Now, if the current directory is `C:/here/I/am/`, it joins ... | Lately, I discovered pathlib.
```
from pathlib import Path
cwd = Path.cwd()
goal_dir = cwd.parent.parent / "my_dir"
```
Or, using the file of the current script:
```
cwd = Path(__file__).parent
goal_dir = cwd.parent.parent / "my_dir"
```
In both cases, the absolute path in simplified form can be found like this:
`... | You can use [normpath](http://docs.python.org/2/library/os.path.html#os.path.normpath), [realpath](http://docs.python.org/2/library/os.path.html#os.path.realpath) or [abspath](http://docs.python.org/2/library/os.path.html#os.path.abspath):
```
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
print goal_d... | Python joining current directory and parent directory with os.path.join | [
"",
"python",
"os.path",
""
] |
The table and column names are vague because I am in the healthcare industry and unable to share specific details. I am using this Query to show the amount of savings to a customer if they purchase a product from my company(Table 1) instead of their current vendor (table2).
I have 2 tables like this on an MSQL Server ... | You can use `ROW_NUMBER` to find the "best" matching row from `Table1`:
```
SELECT
T1.ProductID,
T1.Description,
T1.Vendor,
T1.Price,
T2.ProductID,
T2.Description,
T2.Price,
(T1.Price - T2.Price) as 'Amount Saved'
FROM Table2 T2
LEFT JOIN (
SELECT ProductID, Descr... | It's not clear, what you mean with "best price". Just adjust the MAX() function to MIN() function if it's not what you want.
```
SELECT T1.ProductID, T1.Description, Vendor, T1.Price, T2.ProductID,
T2.Description, T2.Price, (T1.Price - T2.Price) as 'Amount Saved'
FROM (
SELECT
ProductID, Vendor, Description, Price
FRO... | SQL Comparing 2 tables while limiting data | [
"",
"sql",
"sql-server-2008",
"select",
""
] |
I have a simple table:
```
create table test (i int4 primary key);
```
where there is million rows, with i >= 1 and i <= 1000000.
I want to remove ~ 80% of the rows - so something like: `delete from test where random() < 0.8`, but I want the delete to have higher chance of removal for lower `i` values.
Technically:... | With normally-distributed data, starting at 1, this works:
```
delete from test where random() + 0.1 * (500000 - id) / 500000 > 0.2;
```
This should have about a 90% chance to remove the lowest ID, and a 70% chance to remove the highest.
If your data is not distributed normally you can accomplish the same thing by u... | Something like this ?
```
create table ztest (val int4 primary key);
INSERT INTO ztest (val) SELECT gs FROM generate_series(1,1000) gs;
DELETE FROM ztest
WHERE (val >0 AND val <= 10 and random() < 0.1)
OR (val >10 AND val <= 100 and random() < 0.5)
OR (val >100 AND val <= 1000 and random() < 0.9)
;
SELECT *... | Randomly select rows with chance depending on order? | [
"",
"sql",
"postgresql",
"math",
""
] |
I have the following:
```
Select Coalesce(Other,Industry) Ind from registration
```
The thing is that `Other` can be an empty string or `NULL`.
How do I get `coalesce` to work such that if `Other` is an empty string, `Coalesce` still returns `Industry`? | Use a `CASE` expression or `NULLIF`:
```
SELECT COALESCE(NULLIF(Other,''),Industry) Ind FROM registration
``` | try this
```
Select Coalesce(nullif(Other,''),Industry) Ind from registration
``` | SQL Coalesce with empty string | [
"",
"sql",
"sql-server",
""
] |
OK, i'm using Python 2.7.3 and here is my code:
```
def lenRecur(s):
count = 0
def isChar(c):
c = c.lower()
ans=''
for s in c:
if s in 'abcdefghijklmnopqrstuvwxyz':
ans += s
return ans
def leng(s):
global count
if len(s)==0:
... | `count` in `lenRecur` is *not* a global. It is a scoped variable.
You'll need to use Python 3 before you can make that work in this way; you are looking for the [`nonlocal` statement](http://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement) added to Python 3.
In Python 2, you can work around this ... | I think You can pass count as second argument
```
def anything(s):
def leng(s, count):
if not s:
return count
return leng(s[1:], count + 1)
return leng(isChar(s), 0)
```
this should work better than muting objects from outer scope such as using mutable objects (`list` or `dict`) o... | Global variables in recursion. Python | [
"",
"python",
"variables",
"recursion",
"global",
""
] |
First thanks in advance , still pretty new to python.
I have the following list:
```
GroceryList = ['apples', 'oranges', 'strawberries and grapes', 'blueberries']
```
I have tried using .replace with the code:
```
GroceryList = [f.replace('and', '\'' + ',' + '\'') for f in GroceryList]
```
This replaces 'and' but ... | Use `str.split` and `str.join` here:
```
>>> GroceryList = ['apples', 'oranges', 'strawberries and grapes', 'blueberries']
>>> [", ".join(x.split(' and ')) for x in GroceryList]
['apples', 'oranges', 'strawberries, grapes', 'blueberries']
```
or may be you wanted this:
```
>>> [y for x in GroceryList for y in x.spl... | The problem is that you are manually altering the string to look like two separate list items. This is not the same as splitting the string into multiple objects. Use the [`str.split`](http://docs.python.org/2/library/stdtypes.html#str.split) method for that.
```
new_grocery_list = []
for item in GroceryList:
new_... | Python: turn one item in list into two items | [
"",
"python",
""
] |
```
ID RANGE_ID START_DATE END_DATE BAND_TYPE FLAG_LINE
3 1 01/03/2013 31/03/2013 R 1
4 1 01/03/2013 31/03/2013 R 0
5 2 01/03/2013 31/03/2013 R 1
6 ... | try like this...
```
Select * from tablename where flag=1
union
(Select * from tablename a where (Select count(*) from tablename b
where a.Range_id=b.RANGE_ID and b.flag=1)<1)
```
[**SQL FIDDLE Demo**](http://sqlfiddle.com/#!4/69e37/1) | Try this.
```
select * from myTable
where flag_line = 1
or
(range_id, start_date, end_date, band_type) in (
select range_id, start_date, end_date, band_type
from myTable
group by range_id, start_date, end_date, band_type
having max(... | Conditional selecting rows based on a column value | [
"",
"sql",
"oracle",
"plsql",
"oracle10g",
""
] |
I've done my research and got very close to solving my issue but I need a bit of help to cross the finish line!
I have two lists:
```
Countries = ["Germany", "UK", "France", "Italy"]
Base = ["2005","1298",1222","3990"]
```
Expected outcome:
```
"Germany (2005)", "UK (1298)", "France (1222)", "Italy (3990)"
```
My ... | You were almost there, you just need to use [string formatting](http://docs.python.org/2/library/string.html#formatspec):
```
>>> ["{} ({})".format(x,y) for x,y in zip(Countries, Base)]
['Germany (2005)', 'UK (1298)', 'France (1222)', 'Italy (3990)']
```
Use `str.join`:
```
>>> print ", ".join('"{} ({})"'.format(x,y... | In addition to [Ashwini's solution](https://stackoverflow.com/a/17339608/1907098), you can take advantage of the implicit zipping that [`map`](http://docs.python.org/2/library/functions.html#map) performs on its arguments.
```
>>> ', '.join(map('"{} ({})"'.format, Countries, Base))
'"Germany (2005)", "UK (1298)", "Fra... | Python: Merging two lists and present them as a string | [
"",
"python",
"list",
"merge",
"zip",
""
] |
I have a table which looks like
```
col1 col2 col3
x y 0.1
y x 0.1
y z 0.2
z y 0.2
.......
```
(x,y,0.1) is equivalent to (y,x,0.1) therefore one of them has to be removed.
Basically the table is like a matrix. I need to get rid of all the entries... | Well, if you know that both entries are there, you can do:
```
delete from t
where col1 > col2;
```
If some of them might already be missing and you want to keep the other one:
```
delete from t
where col1 > col2 and
exists (select 1
from (select 1
from t t2
... | The solution from Sylvain should work. Here is an alternative using SubQ.
```
delete from mytable where (col1,col2)in(sel col2,col1 from mytable where col1>col2);
``` | remove duplicates from SQL table | [
"",
"mysql",
"sql",
""
] |
I'm just wondering. Is there any chance to create section in \*.ini file to store only values without keys? I'm to store list of used ports in localhost and other servers and my list looks like this:
```
[servers]
localhost:1111
localhost:2222
localhost:3333
someserver:2222
someserver:3333
```
For now python treats s... | You could store the servers in a comma separated list,
```
[servers]
server_list = localhost:1111, localhost:2222, localhost:3333, someserver:2222, someserver:3333
```
the read it into a list like
```
from ConfigParser import ConfigParser
cp = ConfigParser()
cp.read('derp.config')
print cp.items('servers')[0][1].s... | You have the option allow\_no\_value, but you can not avoid ":" being a value separator, this is at ConfigParser.py:
```
OPTCRE = re.compile(
r'(?P<option>[^:=\s][^:=]*)' # very permissive!
r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
# fol... | ConfigParser and section with values without keys | [
"",
"python",
"configparser",
""
] |
We had this code and it worked fine. After doing a refactor, it doesn't work anymore. Like the comment says, we only want to inherit from a base page if the request isn't an ajax request. To do this, we pass a parameter to the template, and, based on the parameter, we inherit or not.
View.py
```
class Router(object):... | Just ran into the same problem, same use case as well actually (render layout or not depending the request being an XHR).
You can apparently access the `request` through `context`, so you can avoid having to split this tiny bit of logic over two places (view and template):
```
<%!
def inherit( context ):
if... | We did a pretty sizable refactor and the above code is working again. I'm guessing the context passed in wasn't initialized or there was a syntax error in one of the templates.
As an aside, the request object has a property called is\_xhr which is true if the request is asynchronous. We're using this property to deter... | Mako Dynamic Template Inheritance | [
"",
"python",
"django-templates",
"pyramid",
"mako",
""
] |
I am trying to flatten a list using list comprehension in python. My list is somewhat like
```
[[1, 2, 3], [4, 5, 6], 7, 8]
```
just for printing then individual item in this list of list I wrote this function:
```
def flat(listoflist):
for item in listoflist:
if type(item) != list:
print(ite... | ```
>>> from collections import Iterable
>>> from itertools import chain
```
One-liner:
```
>>> list(chain.from_iterable(item if isinstance(item,Iterable) and
not isinstance(item, basestring) else [item] for item in lis))
[1, 2, 3, 4, 5, 6, 7, 8]
```
A readable version:
```
>>> def func(x): ... | No-one has given the usual answer:
```
def flat(l):
return [y for x in l for y in x]
```
There are dupes of this question floating around StackOverflow. | flatten list of list through list comprehension | [
"",
"python",
"list",
"python-2.7",
"list-comprehension",
""
] |
I've got a set of many astrophotos taken with the camera on a tripod. Used a bubble level to make sure that the long side of the frame is parallel to the horizon, and I know the alt/az (and equatorial) coordinates of the center of each photo.
Now I'm writing some python code to overlay an indicator over each image to ... | I would try to create a "World Coordinate System" (WCS) for each of your images, this is essentially a mapping between your pixel coordinates and sky coordinates (i.e. RA and Dec). You can use a tools such as one available at <http://astrometry.net> to automatically solve your images based on the star patterns visible ... | Whether you want to mark the North Celestial Pole with a cross or dot, or put a mark at the north point on the horizon, you are asking a question that is really a question about your camera lens: how does your particular lens, when at the exact focal length that you used when taking the picture, map the curved expanse ... | How to find the angle between North and horizon for given altaz coords using pyephem? | [
"",
"python",
"coordinates",
"astronomy",
"pyephem",
""
] |
When I run the following script in IDLE
```
import os
print(os.getcwd())
```
I get output as
```
D:\testtool
```
but when I run from cmd prompt, I get
```
c:\Python33>python D:\testtool\current_dir.py
c:\Python33
```
How do I get same result which I got using IDLE ? | It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.
To change current working dir to the one containing your script you can use:
```
import os
os.chdir(os.path.dirname(__file__))
print(os.get... | Using pathlib you can get the folder in which the current file is located. `__file__` is the pathname of the file from which the module was loaded.
Ref: [docs](https://docs.python.org/3/reference/datamodel.html)
```
import pathlib
current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)
```
... | How can I make my program have a consistent initial current working directory? | [
"",
"python",
"python-3.x",
"working-directory",
"file-location",
""
] |
I have a table with 2 columns. UTCTime and Values.
The UTCTime is in 15 mins increment. I want a query that would compare the value to the previous value in one hour span and display a value between 0 and 4 depends on if the values are constant. In other words there is an entry for every 15 minute increment and the val... | Below is the query you need and a [working solution](http://www.sqlfiddle.com/#!6/5bf99/5) Note: I changed the timeframe to 24 hrs
```
;with SourceData(HourTime, Value, RowNum)
as
(
select
datepart(hh, UTCTime) HourTime,
Value,
row_number() over (partition by datepart(hh, UTCTime) o... | ```
select SUBSTRING_INDEX(UTCTime,':',1) as time,value, count(*)-1 as total
from foo group by value,time having total >= 1;
```
[fiddle](http://www.sqlfiddle.com/#!2/179cf8/11) | SQL Query Compare values in per 15 minutes and display the result per hour | [
"",
"sql",
"t-sql",
"ssms",
""
] |
I created a script of my database.
But When I run it, the script does not create the database. It skips the "Create db" statement, and only creates the tables (on the database I have selected at the moment, so not ideal....)
(query executes with no errors by the way.)
Why is this happening? why cant you create a dat... | You must use GO after CREATE DATABASE [EthicsDB]. | If you run the SQL as provided you get an error message on the line
```
USE [EthicsDB]
```
This occurs as when SQL Servers runs SQL commands via SQL CMD it process the SQL in batches.
As you have no GO statement after the Create database statement it maybe that SQL Server does not yet recognise that a new database E... | SQL Generate Script Not Creating Database | [
"",
"sql",
"sql-server",
""
] |
I'm writting a Word document and I'd like to paste a formatted code-snippets directly from clipboard.
At this moment I am able to write these snippets into an .html file to the harddisk. My goal is to extend my Python script and load this .html file on the clipboard in "formatted text" to directly paste at Word.
Does... | Well, I've found a solution for this.
<http://code.activestate.com/recipes/474121-getting-html-from-the-windows-clipboard/>
It's work pretty well... if anyone wants more information about the clipboard just take a look here:
<http://msdn.microsoft.com/en-us/library/windows/desktop/ms649013(v=vs.85).aspx>
Download t... | Nobody mentioned yet [klembord](https://github.com/OzymandiasTheGreat/klembord). It works on Linux and Windows, and supports [HTML clipboard format](https://learn.microsoft.com/en-us/windows/win32/dataxchg/html-clipboard-format).
### Installation
```
pip install klembord
```
### Usage
```
import klembord
klembord.i... | How can I copy from an html file to the clipboard in Python in formatted text? | [
"",
"python",
"html",
"windows",
"clipboard",
"richtext",
""
] |
How do I export/import large database on MAMP ? Using PHPMyAdmin does not work as it supposed to be. | It should be done via terminal as below.
* In the terminal navigate to `bin` folder of MAMP using below command `cd /Applications/MAMP/library/bin`
* Use this command to export the file `./mysqldump -u [USERNAME] -p [DATA_BASENAME] > [PATH_TO_FILE]`. EG would be `./mysqldump -u root -p my_database_name > /Applications... | **Turn on MAMP!**
Then, for both operations, open the terminal and type:
---
**EXPORTING:**
**`/Applications/MAMP/library/bin/mysqldump -u [USERNAME] -p [DATABASE_NAME] > [PATH_TO_SQL_FILE]`**
Then type your password in prompter (default **`root`**) and press enter.
*Example:*
`/Applications/MAMP/library/bin/mys... | How To Export/Import Large Database On MAMP | [
"",
"mysql",
"sql",
"export",
"mamp",
"dump",
""
] |
I'm making a django application and I'm facing an issue. I am trying to define a model where one `ForeignKey` would be depending on another `ForeignKey`.
## Description part
My application is about making choices.
So let's say you have a `decision` to make, a `decision` has multiple `choice`s, and a `choice` has a `... | I'm not familiar with Django, but I if you are trying to solve the "same one the choice is linked to" part of the problem, this is how it can be done at the database level:

Note the usage of identifying relationships, so the `DecisionId` is migrated... | What you're asking is not possible, at least not within the boundaries you've set (no forms, no external libraries). The `status` field of your `Choice` model is a Foreign Key, a relationship between two tables… it doesn't deal with filtering itself, simply put – it doesn't have this feature. And this isn't a *django* ... | How to restrict Foreign Key choices to another Foreign Key in the same model | [
"",
"python",
"django",
"database-design",
"django-models",
""
] |
In python, I am trying to replace a single backslash ("\") with a double backslash("\"). I have the following code:
```
directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\")
```
However, this gives an error message saying it doesn't like the double backslash. Can anyone help? | No need to use `str.replace` or `string.replace` here, just convert that string to a raw string:
```
>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
```
Below is the `repr` version of the above string, that's why you're seeing `\\` here.
But, in fact the actual string cont... | Let me make it simple and clear. Lets use the re module in python to escape the special characters.
**Python script :**
```
import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)
```
**Output :**
```
C:\Users\Josh\Desktop
C:\\Users\\Josh\\Desktop
```
**Explanation :**
Now observe that *re.escape* functi... | python replace single backslash with double backslash | [
"",
"python",
"string",
"replace",
"backslash",
""
] |
First off, I know that the `__init__()` function of a class in Python cannot return a value, so sadly this option is unavailable.
Due to the structure of my code, it makes sense to have data assertions (and prompts for the user to give information) inside the `__init__` function of the class. However, this means that ... | You could raise an exception when either assertio fail, or -, if you really don't want or can't work with exceptions, you can write the `__new__` method in your classes -
in Python, `__init__` is technically an "initializer" method - and it should fill in he attributes and acquire some of the resources and others your ... | Have you considered raising an exception? That is the usual way to signal a failure. | Python __init__ return failure to create | [
"",
"python",
"return",
"init",
""
] |
I have a python class, for example:
```
class Book(models.Model):
enabled = models.BooleanField(default=False)
full_title = models.CharField(max_length=256)
alias = models.CharField(max_length=64)
author = models.CharField(max_length=64)
status = models.CharField(max_length=64)... | If you have no control over what the decorator does, then in general, you can not identify decorated methods.
However, since you can modify `serializable`, then you could add an attribute to the wrapped function which you could later use to identify serialized methods:
```
import inspect
def serializable(func):
d... | Generally speaking, *you can't*. A decorator is just syntactic sugar for applying a callable. In your case the decorator syntax translates to:
```
def pretty_status(self):
return [b for a, b in BOOK_STATUS_CHOICES if a == self.status][0]
pretty_status = serializable(pretty_status)
```
That is, `pretty_status` is ... | Discover decorated class instance methods in python | [
"",
"python",
"reflection",
"decorator",
"python-decorators",
""
] |
I need to list all elements in my `<product>` item, because the elements of `<product>` is variable.
XML file :
```
<catalog>
<product>
<element1>text 1</element1>
<element2>text 2</element2>
<element..>text ..</element..>
</produc>
</catalog>
```
Python parser :
I use fast\_iter because my x... | ```
def process_element(catalog, *args, **kwargs):
for child in catalog.getchildren():
print(child.text)
``` | This the solution to my problem :
```
def process_element(catalog):
for product in catalog.findall('product'):
for element in product.findall('*'):
print(element.tag)
print(element.text)
``` | Python xml : list all elements in item | [
"",
"python",
"xml",
"python-3.x",
"lxml",
""
] |
I want to search a CSV file and print either `True` or `False`, depending on whether or not I found the string. However, I'm running into the problem whereby it will return a false positive if it finds the string embedded in a larger string of text. E.g.: It will return `True` if string is `foo` and the term `foobar` i... | when you look inside a csv file using the `csv` module, it will return each row as a list of columns. So if you want to lookup your string, you should modify your code as such:
```
import csv
username = input()
with open('Users.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',') # good point by @paco
f... | I have used the top comment, it works and looks OK, but it was too slow for me.
I had an array of many strings that I wanted to check if they were in a large csv-file. No other requirements.
For this purpose I used (simplified, I iterated through a string of arrays and did other work than print):
```
with open('my_c... | Check whether string is in CSV | [
"",
"python",
"csv",
""
] |
I want to be able to compare Decimals in Python. For the sake of making calculations with money, clever people told me to use Decimals instead of floats, so I did. However, if I want to verify that a calculation produces the expected result, how would I go about it?
```
>>> a = Decimal(1./3.)
>>> a
Decimal('0.33333333... | You are not using `Decimal` the right way.
```
>>> from decimal import *
>>> Decimal(1./3.) # Your code
Decimal('0.333333333333333314829616256247390992939472198486328125')
>>> Decimal("1")/Decimal("3") # My code
Decimal('0.3333333333333333333333333333')
```
In "your code", you actually perfor... | Your verbiage states you want to to monetary calculations, minding your round off error. Decimals are a good choice, as they yield EXACT results under addition, subtraction, and multiplication with other Decimals.
Oddly, your example shows working with the fraction "1/3". I've never deposited exactly "one-third of a d... | Compare decimals in python | [
"",
"python",
"testing",
"decimal",
""
] |
I've found an example code in python that gives out all prime numbers upto `n` but I simply don't get it, Why does it does what it does?
I've read the wikipedia article about the [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) but simply have no idea about how this works.
```
pp = 2
ps = [... | That code is an attempt at using trial division to produce a sequence of primes.
To correct it:
```
pp = 2
ps = [pp]
lim = raw_input("Generate prime numbers up to what number? : ")
while pp < int(lim):
pp += 1
for a in ps:
if pp%a==0:
break
else: # unindent
ps.ap... | Since no one has yet to show a true sieve or explain it, I will try.
The basic method is to start counting at 2 and eliminate 2\*2 and all higher multiples of 2 (ie 4, 6, 8...) since none of them can be prime. 3 survived the first round so it is prime and now we eliminate 3\*3 and all higher multiples of 3 (ie 9, 12, ... | Understanding Sieve of Eratosthenes in Python | [
"",
"python",
"primes",
"sieve-of-eratosthenes",
""
] |
```
junctions = [2,9,15,20]
seq_1 = 'sauron'
seq_2 = 'corrupted'
seq_3 = 'numenor'
combined = 'sauroncorruptednumenor' #seq_1 + seq_2 + seq_3
count_1 = 1
count_2 = 1
count_3 = 2
```
I have a list of 3 strings (seq\_1-3). I combine them to create 1 long string (combined)
I have a list of indices (junctions). I have 3... | You could try something basic like
```
L_1 = len(seq_1)
L_2 = len(seq_2)
L_3 = len(seq_3)
junctions = [2, 9, 15, 20]
c_1, c_2, c_3 = (0, 0, 0)
for j in junctions:
if j < L_1:
c_1 += 1
elif j < L_1 + L_2:
c_2 += 1
elif j < L_1 + L_2 + L_3:
c_3 += 1
else:
Raise error
``` | You can use `collections.Counter` and `bisect.bisect_left` here:
```
>>> from collections import Counter
>>> import bisect
>>> junctions = [2,9,15,20]
>>> seq_1 = 'sauron'
>>> seq_2 = 'corrupted'
>>> seq_3 = 'numenor'
>>> lis = [seq_1, seq_2, seq_3]
```
Create a list containing the indexes at which at each `seq_` en... | Combine strings. Count how many indices (from list) are in original strings. Python | [
"",
"python",
"string",
"count",
"indexing",
""
] |
I am currently running the following query.( See below) However when I run this query the active users and Suspended users are bring back a far greater result then that's in the database.
I just wondered if you could possibly shed light on the reason why and correct me where I'm going wrong?
```
SELECT c.[Status],
... | In each of your sub queries you have two tables, one is being joined to the outer query but there is no join between the two inner tables. All of those sub queries are a bit unnecessary, I would rewrite as a simpler query, something like so:
```
SELECT
Company.[Status]
,Company.CompanyId
,Company.Name
,COUNT... | I don't know your data (it could cause duplicates), but couldnt you use a standard group by and not use sub queries?
```
Select
c.[Status],
c.CompanyId,
c.Name,
count(distinct usr.UserID) as TotalUsers,
sum(case when usr.Status = 2 then 1 else 0 end) as ActiveUsers,
sum(case when usr.Status = 3... | Sub sum query bringing back more results then possible | [
"",
"sql",
"sql-server",
""
] |
Please find the sample data:
```
h_company_id company_nm mainphone1 phone_cnt
20816 800 Flowers 5162377000 3
20816 800 Flowers 5162377131 1
20820 1st Source Corp. 5742353000 3
20821 1st United Bancorp 5613633400 2
20824 3D... | Transforming from rows into columns is called a PIVOT and there are several different ways that this can be done in SQL Server.
**Aggregate / CASE:** You can use an aggregate function along with a CASE expression. This will work by applying the `row_number()` windowing function to the data in your table:
```
select h... | The following could work (assuming your table is called `company`):
```
SELECT
c1.h_company_id,
c1.company_nm,
c1.mainphone1,
c1.phone_cnt,
c2.mainphone1 AS mainphone2,
c2.phone_cnt AS phone_cnt2
FROM
company AS c1
LEFT JOIN
company AS c2 ON c2.h_company_id = c1.h_company_id
```
Howeve... | How to transform records data into columns | [
"",
"sql",
"sql-server",
"sql-server-2008",
"pivot",
""
] |
I have been given the task to remove all non numeric characters including spaces from either a text file or a string and then print the new result, for example:
Before:
```
sd67637 8
```
After:
```
676378
```
As I am a beginner I do not know where to start with this task. | The easiest way is with a regexp
```
import re
a = 'lkdfhisoe78347834 (())&/&745 '
result = re.sub('[^0-9]','', a)
print result
>>> '78347834745'
``` | Loop over your string, char by char and only include digits:
```
new_string = ''.join(ch for ch in your_string if ch.isdigit())
```
Or use a regex on your string (if at some point you wanted to treat non-contiguous groups separately)...
```
import re
s = 'sd67637 8'
new_string = ''.join(re.findall(r'\d+', s))
# 676... | Removing non numeric characters from a string in Python | [
"",
"python",
"string",
"digits",
""
] |
So I have the following code:
```
user_input = raw_input("Enter an integer, string or float:")
input_type = type(user_input)
if input_type == "str":
print "Your string was %s." % user_input
elif input_type == "int":
input_type = int(input_type)
print "Your integer was %d." % user_input
elif input_type =... | There are a number of problems here.
---
```
user_input = raw_input("Enter an integer, string or float:")
input_type = type(user_input)
```
Since `raw_input` always returns a string, `input_type` will always be `str` here.
---
```
if input_type == "str":
print "Your string was %s." % user_input
```
`input_typ... | First of all, "does not work" is not useful. Please in the future explain exactly how it's not working, what you expect and what you get that is unsatisfactory.
Now to your problem: `raw_input` will always return a string. It is up to you to see if contents of that string conform to something that looks like an intege... | Python's type() function and its 'if' related problems | [
"",
"python",
"function",
"if-statement",
"python-2.7",
""
] |
Searching here and on the internet, there are a lot of examples to how to mark a message as SEEN, even though this is automatic with imap.
But how can I mark an email as `UNSEEN` or `UNREAD`.
I have a script in python which receives `UNSEEN` messages, and it works great. But after reading them, imap automatically mar... | You can easily clear the `\Seen` flags with this command:
```
tag UID STORE -FLAGS (\Seen)
```
but your software will probably be more robost if you only set the `\Seen` flag in the first place after you have successfully processed a message. That way, if anything goes wrong while you are processing a message (even i... | ```
`imap = imaplib.IMAP4_SSL(server)
imap.login(username, password)
imap.select("inbox", readonly=False)`
```
if readonly="True" you can't change any flags.
But,if it is false, you can do as follow,
```
imap.store(id, '-FLAGS', '\Seen')
```
**THEN EMAIL WILL MARK AS UNREAD**
(-) means REMOVE flag and (+) means A... | python imaplib - mark email as unread or unseen | [
"",
"python",
"imap",
""
] |
Here are the files in this test:
```
main.py
app/
|- __init__.py
|- master.py
|- plugin/
|- |- __init__.py
|- |- p1.py
|- |_ p2.py
```
The idea is to have a plugin-capable app. New .py or .pyc files can be dropped into plugins that adhere to my API.
I have a `master.py` file at the app level that contains g... | I never did find a solution, so I ended up deciding to restructure the program.
What I did was set up the main app as a class. Then, I also changed each plugin into a class. Then, as I load plugins using **import**, I also instantiate the class inside each plugin which has a predefined name, and pass in the reference ... | I've had a similar problem.
`__import__` only imports submodules if all parent `__init__.py` files are empty.
You should use importlib instead
```
import importlib
p2 = importlib.import_module('plugin.p2')
``` | Python: perform relative import when using __import__? | [
"",
"python",
"import",
""
] |
Does Python have a built-in function like min() and max() except that it returns the index rather than the item? | There is no inbuilt function for that. You can just do `your_list.index(min(your_list))`. | There's no builtin, but `min` and `max` take a `key` argument, which lets you do something like this:
```
from operator import itemgetter
index, elem = min(enumerate(iterable), key=itemgetter(1))
```
This works for any iterable, not just lists. | Python min and max functions, but with indices | [
"",
"python",
"max",
"minimum",
""
] |
I have a list comprehension that produces list of odd numbers of a given range:
```
[x for x in range(1, 10) if x % 2]
```
That makes a filter that removes the even numbers. Instead, I'd like to use conditional logic, so that even numbers are treated differently, but still contribute to the list. I tried this code, b... | `x if y else z` is the syntax for the expression you're returning for each element. Thus you need:
```
[ x if x%2 else x*100 for x in range(1, 10) ]
```
The confusion arises from the fact you're using a *filter* in the first example, but not in the second. In the second example you're only *mapping* each value to ano... | ```
[x if x % 2 else x * 100 for x in range(1, 10) ]
``` | How can I use a conditional expression (expression with if and else) in a list comprehension? | [
"",
"python",
"list-comprehension",
"conditional-operator",
""
] |
I have a messed up txt-file, with points as a thousand mark (1.000 or 19.329) and as a decimal mark (10000.3). Two example lines:
```
John;1.952;2003;20.365;1.214
Ryan;2.342;2002;3045.3;345
```
I want to remove the point for the thousand mark and keep the points for the decimals. What is the easiest way to do this? | If you never have exactly three decimal places after the decimal point, the following will do it:
```
>>> import re
>>> re.sub(r"\.(\d\d\d(\D|$))", r"\1", "200.000.5")
'200000.5'
```
The regexp removes a dot if it is followed by exactly three digits. It won't match fewer digits (since it looks for three `\d`), and it... | Assuming that decimals are always only one digit:
```
line = "Ryan;2.342;2002;3045.3;345"
parts = line.split(";")
#Remove the name.
name = parts.pop(0)
def fix(part):
decimal = ""
if part[-2] == '.':
decimal = part[-2:]
part = part[:-2]
part = part.replace('.',',')
return part+decima... | Points for thousand mark and decimal mark | [
"",
"python",
"points",
""
] |
I am writing a series of text menus. With the class and sub class below it runs with no issues. But I am reviewing my coding and I am wondering....is it ok that I didn't use `def __init__(self)` in the classes? Should I have placed the data members in `def __init__(Self):` such as self.images = (), self.options =()? If... | Your code is perfectly fine. You don't *have* to have an `__init__` method.
You can still use `__init__`, even with an ABC. All that the ABC meta tests for is if the *names* have been defined. Setting `images` in an `__init__` does requires that you define a class attribute, but you can set that to `None` at first:
`... | Your code is fine. The example below shows a minimal example.
You can still instantiate a class that doesn't specify the `__init__` method. Leaving it out does not make your class abstract.
```
class A:
def a(self, a):
print(a)
ob = A()
ob.a("Hello World")
``` | Python Classes without using def __init__(self) | [
"",
"python",
"class",
""
] |
I am dynamically forming MySQL statements in PHP and can't figure out why this one is failing to execute:
```
INSERT INTO users ( `email`, `password`, `first_name`, `last_name`, `url`,
`description`, `media`, `tags`, `zip`, `country`, `lat`, `lon`, `city`, `state`,
`datetime_joined`, `API_key`, `verified`, ... | I dug through all of the string manipulation I was doing to dynamically build the query and found that I was using `real_escape_string` for a part of the query not just the values going into it. That explains why when copied from the browser the query worked. | Not sure, but ur lat and long are inserted as strings, try removing the quotes and insert them as numerals. So with all ur numerical fields. | INSERT INTO MySQL statement failing | [
"",
"mysql",
"sql",
""
] |
For this list:
```
['a','a','a,'b','b','c']
```
I would like to have:
```
['a1','a2','a3','b1','b2','c']
```
The purpose is to get a list with different items. (`len(set(my_list)) == len(my_list)`)
It is ok to assume list is sorted.
Not every item must appear more than once (like 'c' here, in this case leave it)
... | Using `collections.Counter` and `itertools.count`:
```
>>> from itertools import count
>>> from collections import Counter
>>> lis = ['a','a','a','b','b','c']
>>> c = Counter(lis)
>>> dic = {k: count(1) for k in c}
>>> [x + ( str(next(dic[x])) if c[x]>1 else '') for x in lis]
['a1', 'a2', 'a3', 'b1', 'b2', 'c']
```
U... | Try this:
```
lst = ['a','a','a','b','b','c']
[ e + str(i) for i, e in enumerate(lst) ]
=> ['a0', 'a1', 'a2', 'b3', 'b4', 'c5']
```
The above will generate unique names for all the values, as long as you don't mind having different numbers for each string (e.g., there won't be a `b1` if the `1` was used before)
**ED... | Best Way to Distinguish Equal List items in Python | [
"",
"python",
"list",
"equality",
""
] |
I want to write an app to shorten url. This is my code:
```
import urllib, urllib2
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = urllib.urlencode({'longUrl':url})
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
... | I tried your code and couldn't make it work either, so I wrote it with [requests](http://docs.python-requests.org/en/latest/user/quickstart/#make-a-request):
```
import requests
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
payload = {'longUrl': url}
hea... | I know this question is old but it is high on Google.
Another thing to try is the pyshorteners library it is very simple to implement.
Here is a link:
<https://pypi.python.org/pypi/pyshorteners> | how to use Google Shortener API with Python | [
"",
"python",
"google-api",
"google-url-shortener",
""
] |
I was hoping to get some kind of advice regarding the use of `sys.exit()`. I have used `sys.exit()` to stop a script from running any further:
My code:
```
if x != 20:
query = raw_input("X does not equal 20. Do you want to continue? (Y/N)")
if query in ['y', 'Y']:
pass
else:
sys.exit()
``... | Since this is used at the beginning of your script (as mentioned by you). Use the coding pattern written below. And use `return` instead of `sys.exit` (actually since you are exiting from the script itself thereby terminating the process altogether `sys.exit` is not a bad practice).
Whether you use `return` or `sys.ex... | Place your code in the main() function:
```
def main():
// your code
if __name__ == '__main__':
main()
```
Then you can exit from your script just by **return** | sys.exit(): is there a less extreme alternative? | [
"",
"python",
""
] |
I want to make three columns are unique in my data table
```
-----------------------------------
Column A | Column B | Column C
----------------------------------
Kasun Cham Nimith
----------------------------------
Kasun Cham Rox - This row ok and must be allowed to add.
-------------... | This code will do that what you want.
```
CREATE UNIQUE CLUSTERED INDEX index_name ON TABLE (col1,col2, col3)
or
CREATE UNIQUE NONCLUSTERED INDEX index_name ON TABLE (col1,col2 , col3)
or
ALTER TABLE [dbo].[TABLE] ADD CONSTRAINT
UNIQUE_Table UNIQUE CLUSTERED
(
col1,
col2,
col3
) ON [PRIMARY]
``` | You can add a unique constraint:
```
ALTER TABLE [TableName] ADD CONSTRAINT [constraintName] UNIQUE ([columns])
```
You can read the documentation [here](http://msdn.microsoft.com/en-us/library/ms186712.aspx). | how to make two 3 columns are unique in SQL server ? | [
"",
"sql",
"sql-server",
""
] |
I have two tables: `COMMENT` and `COMMENTHISTORY`
Now I need to SELECT cells from both tables, like this:
```
SELECT c.Id, c.Userid, ch.Text, ch.Timestamp
FROM COMMENT c, COMMENTHISTORY ch
WHERE ch.CommentId = c.Id
ORDER BY ch.Timestamp DESC
```
Works fine. Only problem is that `COMMENTHISTORY` has several rows for ... | Query:
```
SELECT c.Id,
c.Userid,
ch.Text,
ch.Timestamp
FROM COMMENT c
INNER JOIN COMMENTHISTORY ch
ON ch.CommentId = c.Id
WHERE ch.Timestamp = (SELECT MAX(ch2.Timestamp)
FROM COMMENTHISTORY ch2
WHERE ch2.CommentId = c.Id )
ORDER BY ch.Timestamp DES... | This will fix your issue
```
SELECT c.Id, c.Userid, ch.Text, ch.Timestamp
FROM COMMENT c LEFT JOIN COMMENTHISTORY ch on C.ID = ch.comment_id
WHERE ch.CommentId = c.Id
GROUP BY c.id
ORDER BY ch.Timestamp DESC
``` | SQL, SELECT from two tables without getting all the rows | [
"",
"sql",
"select",
""
] |
Context: I'm a CS n00b working my way through "Cracking the Coding Interview." The first problem asks to "implement an algorithm to determine if a string has all unique characters." My (likely naive) implementation is as follows:
```
def isUniqueChars2(string):
uchars = []
for c in string:
if c in uchars:
... | Here is how I would write this:
```
def unique(s):
return len(set(s)) == len(s)
```
Strings are iterable so you can pass your argument directly to `set()` to get a set of the characters from the string (which by definition will not contain any duplicates). If the length of that set is the same as the length of th... | ## Beautiful is better than ugly.
Your approach is perfectly fine. This is python, when there are a bajillion ways to do something. (Yours is more beautiful too :)). But if you really want it to be more pythonic and/or make it go faster, you could use a set, as F.J's answer has described.
The second solution just loo... | Implementing an algorithm to determine if a string has all unique characters | [
"",
"python",
""
] |
I'm trying to check for a palindrome with Python. The code I have is very `for`-loop intensive.
And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language.
I see on [this](ht... | A pythonic way to determine if a given value is a palindrome:
```
str(n) == str(n)[::-1]
```
Explanation:
* We're checking if the string representation of `n` equals the reversed string representation of `n`
* The `[::-1]` slice takes care of reversing the string
* After that, we compare for equality using `==` | An alternative to the rather unintuitive `[::-1]` syntax is this:
```
>>> test = "abcba"
>>> test == ''.join(reversed(test))
True
```
The `reversed` function returns a reversed sequence of the characters in `test`.
`''.join()` joins those characters together again with nothing in between. | How to check for palindrome using Python logic | [
"",
"python",
"string",
"palindrome",
""
] |
I need the results of this script ie, pygoogle search results, to go like so:
```
name # of results
name # of results
name # of results
```
Here is what I have so far, how can I do this without re writing the file each time:
```
import re
import pygoogle
import csv
from pygoogle import pygoogle
#creates lis... | ## Overcoming confusion on looping behaviour:
The `names` variable will be a list with only one item in it every time you use it. Do this instead:
```
import re
import csv
from pygoogle import pygoogle
names = []
with open('parse2.txt') as fin:
names = [x.strip() for x in fin.read().strip('\'"[]').split(' '*6)]
... | To write appending to the file, without rewriting, add `+` to the mode:
```
for name in names:
with open("output.txt", "wb+") as f:
writer = csv.writer(f)
writer.writerows(A)
```
On the other hand, for better efficiency, you can open the file only once and use the file methods instead the CSV modu... | Writing a results to a .txt file using csv | [
"",
"python",
"list",
"csv",
""
] |
I'm trying to make a random walk in 2d, and plot the 2d walk.
I've been able to make the walk, but the plot is not exactly what I wanted.
Would it be possible to see the walk live in python ? Or just add a label to every point so that you know which point came first and which point came second etc. ?
```
import numpy ... | The built-in [`turtle`](http://docs.python.org/3/library/turtle.html?highlight=turtle#turtle) module could be used to draw the path at a perceptible rate.
```
import turtle
turtle.speed('slowest')
walk = randomWalkb(25)
for x, y in zip(*walk):
#multiply by 10, since 1 pixel differences are hard to see
turtl... | I would visualize the time-information using a color, i.e. try to plot
```
plt.plot(walk[0],walk[1],label= 'Random walk')
plt.scatter(walk[0],walk[1],s=50,c=range(26))
``` | Visualizing a 2d random walk in python | [
"",
"python",
"random-walk",
""
] |
For example:
```
def tofloat(i):
return flt(i)
def addnums(numlist):
total = 0
for i in numlist:
total += tofloat(i)
return total
nums = [1 ,2 ,3]
addnums(nums)
```
The `flt` is supposed to be `float`, but I'm confused whether it is a syntax error or a runtime error. | Actually, it is a runtime error, because Python will try to resolve the `flt` name during runtime (because it's a dynamic language), and it won't find it. When this happens, Python yields and exception saying that it couldn't find the symbol you were using `flt` and all this happens at runtime.
Syntax errors happen wh... | [SyntaxError](http://docs.python.org/2/library/exceptions.html#exceptions.SyntaxError) is raised by parser when it founds that your syntax is not correct, like missing colons, parenthesis, invalid statements etc. It'll not allow you to execute your code until you don't fix that the issue.
Your code will throw only err... | What is the difference between syntax error and runtime error? | [
"",
"python",
"dynamic",
"syntax",
"runtime",
""
] |
If a string contains `foo`, replace `foo` with `bar`. Otherwise, append `bar` to the string. How to write this with one single `re.sub` (or any other function) call? No conditions or other logic.
```
import re
regex = "????"
repl = "????"
assert re.sub(regex, repl, "a foo b") == "a bar b"
assert re.sub(regex... | This is tricky. In Python, replacement text backreferences to groups that haven't participated in the match [are an error](http://www.regular-expressions.info/refreplace.html), so I had to build quite a convoluted construction using [lookahead assertions](http://www.regular-expressions.info/lookaround.html), but it see... | Try this simple one-liner, no regexp, no tricks:
```
a.replace("foo", "bar") + (a.count("foo") == 0) * "bar"
``` | Replace x with y or append y if no x | [
"",
"python",
"regex",
""
] |
I have two tables containing a new and an old `dataset`. I want to see if something happened in the individual records.
**OLD TABLE:**
```
ROW ID FIELD_A FIELD_B FIELD_C
1 101 A B C
2 102 AA BB CC
3 103 AAA BBB CCC
```
**NEW TABLE:**
```
ROW ID FIELD_A FIELD_B FIELD_C
711 101 A... | ```
select * from NewTable
except
select * from OldTable
```
[Ways to compare and find differences for SQL Server tables and data](http://www.mssqltips.com/sqlservertip/2779/ways-to-compare-and-find-differences-for-sql-server-tables-and-data/)
Its a way, if its the best one I am not sure. | If you want to get only matching rows use the following query
```
SELECT * FROM newtable INTERSECT SELECT * FROM oldtable
```
If yuo want to get only different record use the following query
```
SELECT * FROM newtable EXCEPT SELECT * FROM oldtable
``` | How to compare two records | [
"",
"sql",
"sql-server-2008",
""
] |
I understand that `AS` is used to create an alias. Therefore, it makes sense to have one long name aliased as a shorter one. However, I am seeing a `SQL` query `NULL as ColumnName`
What does this imply?
```
SELECT *, NULL as aColumn
``` | Aliasing can be used in a number of ways, not just to shorten a long column name.
In this case, your example means you're returning a column that always contains `NULL`, and it's alias/column name is `aColumn`.
Aliasing can also be used when you're using computed values, such as `Column1 + Column2 AS Column3`. | When unioning or joining datasets using a 'Null AS [ColumnA] is a quick way to make sure create a complete dataset that can then be updated later and a new column does not need to be created in any of the source tables. | SQL: What does NULL as ColumnName imply | [
"",
"sql",
"column-alias",
""
] |
this is a followup question to my previous query. I hope that posting a new question is appropriate in the circumstances: [Selecting a subset of rows from a PHP table](https://stackoverflow.com/questions/17333033/selecting-a-subset-of-rows-from-a-php-table)
I have an sql table that looks like this (for example):
```
... | Just try adding another group by on seller as you want single row for a seller
to final query like
```
SELECT a.* FROM $marketdb a
INNER JOIN
(
SELECT seller, MAX(amount) amount
FROM $marketdb
WHERE price=$minprice
GROUP BY seller
)
b ON a.seller = b.seller AND
a.amount = b.amount group by a.... | Test this **SQL fiddle**:
<http://sqlfiddle.com/#!2/7de03/2/0>
```
CREATE TABLE `sellers` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`seller` VARCHAR(16) NOT NULL,
`price` FLOAT NOT NULL,
`amount` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `sellers` VALUES (1, 'tom', 350, 500);
INSERT INTO ... | Selecting a subset of rows with MySql: conditionally limiting number of entries selected | [
"",
"mysql",
"sql",
""
] |
I have the following tables:
```
Contacts
contact_id, contact_name, etc.
assigned_lists
contact_id, list_id
```
Each contact can be associated with more than 1 list, which is stored in the `assigned_lists` column.
I have a lot of contacts who are not associated with any lists. How would I insert all the ... | Try with:
```
INSERT INTO assigned_lists (contact_id, list_id)
SELECT contact_id, 24
FROM Contacts
WHERE contact_id NOT IN (
SELECT DISTINCT contact_id
FROM assigned_lists
)
``` | ```
INSERT INTO assigned_lists (contact_id, list_id)
SELECT contact_id, @yourNewListID
FROM Contacts
WHERE contact_id NOT IN (SELECT contact_id FROM assigned_lists)
```
SQL Fiddle Example: <http://sqlfiddle.com/#!3/d59d1e/1> | Add rows from a table where they're not in the other table | [
"",
"sql",
"t-sql",
""
] |
I am trying to get day to print either true or false. It currently is only printing False no matter what the integer for "date" is given. I am new to Python so please bear with me if this is a rookie oversight.
```
def date():
date = raw_input("Date (ex. Jun 19): ")
date = date.split(' ')
month = date[0]
... | in python 2 `raw_input` returns a string
then you are comparing a string to an int thats why you're getting false
use the `int` keyword to convert the str to an int
```
if int(day) < 10:
```
like this | `day` is a string, and in Python 2, [any string compares greater than any number](http://docs.python.org/2/library/stdtypes.html#comparisons).
```
>>> "0" > 1
True
>>> "" > 100000000000000000000
True
```
This (consistent but arbitrary) behaviour has been changed in Python 3:
```
>>> "" > 100000000000000000000
Traceb... | If statement only prints False | [
"",
"python",
"if-statement",
""
] |
I have three tables
```
profiles (id, name, deleted)
categories (id, name, deleted)
profiles_categories (id, profile_id, category_id, , deleted)
```
How i can select all `profiles` with `name` in categories?
I trying something like this, but its not works...
```
SELECT *
FROM profiles p
JOIN categories c, profile... | You have several issues with your current query.
First, you are mixing join types. You should use ANSI JOIN syntax between all of the tables. Don't mix ANSI JOIN syntax with some tables and then commas between other tables.
Second, you have two WHERE clauses and you can only have one WHERE clause.
Finally, you shoul... | ```
SELECT *
FROM profiles p
JOIN profiles_categories pc on p.id = pc.profile_id
JOIN categories c on pc.id = c.category_id
```
or
```
SELECT *
FROM profiles p, categories c, profiles_categories pc
WHERE p.id = pc.profile_id
AND pc.id = c.category_id
``` | Make big query from 3 tables | [
"",
"mysql",
"sql",
""
] |
I have two list pairs, each consisting of a list of identifiers and a list of values, where a and b do not have the same length. For example:
```
a_id = [1, 2, 4, 5, 9, 12, 13]
a_val = [13., 32., 5., 9., 32., 4., 8.]
b_id = [1, 3, 4, 6, 9]
b_val = [12., 27., 1., 3., 19.]
```
Now, I need to know wich values correspond... | ```
>>> common_id = [i for i in a_id if i in b_id]
>>> common_id
[1, 4, 9]
>>> common_a_val = [a_val[a_id.index(i)] for i in common_id]
>>> common_a_val
[13.0, 5.0, 32.0]
>>> common_b_val = [b_val[b_id.index(i)] for i in common_id]
>>> common_b_val
[12.0, 1.0, 19.0]
``` | ```
>>> a_d = dict(zip(a_id,a_val))
>>> b_d = dict(zip(b_id,b_val))
>>> common_ids = a_d.viewkeys() & b_d.viewkeys()
set([1, 4, 9])
>>> common_a_val = [a_d[key] for key in common_ids]
[13.0, 5.0, 32.0]
>>> common_b_val = [b_d[key] for key in common_ids]
[12.0, 1.0, 19.0]
``` | cross-identification (overlap) of two lists in Python by common identifier | [
"",
"python",
"list",
"match",
"overlap",
""
] |
I'm a beginner in python and using v2.7.2 here's what i tried to execute in the command prompt
```
p = 2
while(p>0):
for i in range(10):
print i+1 , p
p-=1
```
The **expected** output was
```
1 2
2 1
```
However the **actual** output is
```
1 2
2 1
3 0
4 -1
5 -2
6 -3
7 -4
8 -5
9 -6
10 -7... | The while condition is only tested again after the for loop finishes. You could do this instead
```
p = 2
for i in range(10):
if p <= 0:
break
print i+1 , p
p-=1
``` | This is the [output I get](http://ideone.com/VvKjAI):
```
1 2
2 1
3 0
4 -1
5 -2
6 -3
7 -4
8 -5
9 -6
10 -7
```
Your question as to why it runs. Your **outer most conditional** is a `while` loop, which is true upon the first execution, however it runs right into a **nested for loop**. When this happens the `while`, wil... | Python: Why does this code execute? | [
"",
"python",
"for-loop",
"scope",
"while-loop",
""
] |
I have two lists of elements that look like
```
a=[['10', 'name_1'],['50','name_2'],['40','name_3'], ..., ['80', 'name_N']]
b=[(10,40),(40,60),(60,90),(90,100)]
```
`a` contains a set of data, and `b` defines some intervals, my aim is to create a list `c` with as many list as the intervals in `b`. Each list in `c` co... | You can use `collections.defaultdict` and `bisect` module here:
As the ranges are continuous so it would be better to convert the list `b` into something like this first:
```
[10, 40, 60, 90, 100]
```
The advantage of this is that we can now use `bisect` module to find the index where the items from a list can fit i... | ```
c = []
for r in b:
l = []
rn = range(*r)
for element in a:
if int(element[0]) in rn:
l.append(element)
c.append(l)
```
If your intervals are extremely large, consider using `xrange` instead of `range`. Actually, if your intervals are even moderately large, consider the following... | Grouping of element in a list given a list of intervals | [
"",
"python",
"arrays",
"grouping",
""
] |
I have written the following query to get the employees tenure yearwise.
Ie. grouped by "less than 1 year", "1-2 years", "2-3 years" and "greater than 3 years".
To get this, I compare with employee staffed `end_date`.
But I am not able to get the correct result when comparing with staffed `end_date`.
I have pasted ... | ```
SELECT FK_Project_ID,E.Emp_ID,MIN(Start_Date) AS Emp_Start_Date ,MAX(End_Date) AS Emp_End_Date,
E.Competency,E.First_Name+' '+E.Last_Name+' ('+E.Emp_Id+')' as Name,'Period'=
CASE
WHEN DATEDIFF(MONTH,MIN(Start_Date),MAX(End_Date))<=12 THEN '<1 Year'
WHEN DATEDIFF(MONTH,MIN(Start_... | i think [this](http://msdn.microsoft.com/de-de/library/ms186819.aspx) will solve the problem
as you can see, you should use is like this:
```
DATEADD(year, -1, GETDATE())
```
you should also get the `GETDATE()` to a parameter | Find employee tenure for a company | [
"",
"sql",
"sql-server-2008",
""
] |
Say I have a column in a database that consists of a comma separated list of IDs (please don't ask why :( ), i.e. a column like this:
```
id | ids
----------
1 | 1,3,4
2 | 2
3 | 1,2,5
```
And a table the ids relate to:
```
id | thing
---------------
1 | fish
2 | elephant
3 | monkey
4 | mongo... | Try this
```
SELECT ID, things = STUFF(
(
SELECT ',' + t2.thing
FROM Table2 AS t2
INNER JOIN Table1 AS ti
ON ',' + ti.ids + ',' LIKE '%,' + CONVERT(VARCHAR(12), t2.id) + ',%'
WHERE ti.ID = tout.ID
FOR XML PATH, TYPE
).value('.[1]', 'nvarchar(max)'), 1, 1, '')
FROM Table1 AS tout
ORDER BY ID
```... | Basically this will be the whole query:
```
WITH CTE AS
(
SELECT t1.id, t2.thing
FROM Table1 t1
CROSS APPLY dbo.DelimitedSplit8K(ids,',') x
INNER JOIN Table2 t2 ON x.item = t2.id
)
SELECT DISTINCT id,
STUFF ((SELECT ',' + c1.thing FROM CTE c1
WHERE c1.id = c2.id
... | CSV of IDs to CSV of Values | [
"",
"sql",
"sql-server",
"csv",
""
] |
Input is nvarchar that varies in format from `m/d/yy` to `mm/dd/yyyy`. How can this be converted to `mm/dd/yyyy` in SQL? So far the `CONVERT()` function works for the format `m/d/yyyy` but errors for `m/d/yy`. | Cast it as a date like so:
```
cast(@m + '/' + @d + '/' + @y as datetime)
```
or similarly
```
cast('m/d/yy' as datetime)
cast(Fieldnamehere as datetime)
``` | `update table_name set column_name = convert(varchar,cast(column_name as date),101)` or if a select statment `select convert(varchar,cast(column_name as date),101)` | How to convert nvarchar m/d/yy to mm/dd/yyyy in SQL Server? | [
"",
"sql",
"sql-server",
"type-conversion",
""
] |
I'm new to Oracle PL/SQL and have been trying to run this code but only getting the following message - PL/SQL procedure successfully completed.
```
SQL> DECLARE
v_num NUMBER:=10;
BEGIN
FOR v_num IN 1..3
LOOP
DBMS_OUTPUT.PUT_LINE(v_num);
END LOOP;
DBMS_OUTPUT.PUT_LINE(v_num);
END;
``` | SQL/Plus doesn't print output by default; you have to enable it:
```
set serveroutput on
```
Afterwards, DBMS\_OUTPUT.PUT\_LINE will print output as expected. | If you want you can add the line
```
set serveroutput on
```
to the file
```
$ORACLE_HOME/sqlplus/admin/glogin.sql
```
This will cause the server output to be `on` after you login to SQL\*Plus -- you won't have to type it in each time you login.
HTH | PL/SQL procedure issue | [
"",
"sql",
"plsql",
"sqlplus",
""
] |
I've written a Python script, but running it is taking a lot longer than I had anticipated, and I've no obvious candidate for particuklar lines in the script taking up runtime.
Is there anything I can put in my code to check how long its taking to run through each line?
Many thanks. | Have you tried running python with profiling?
```
python -m cProfile --sort cumulative your_single_thread_script.py &> out.log
```
You can find more details in this question [How can you profile a python script?](https://stackoverflow.com/q/582336/1714410)
You can read more about the profiling utility [here](https:/... | Use a profiler such as [hotshot](http://docs.python.org/2/library/hotshot.html). It's easy!
1) run your code with the profiles:
```
import hotshot
prof = hotshot.Profile("hotshot_stats.prof")
prof.runcall(my_function)
prof.close()
```
2) Read the resulting file:
```
from hotshot import stats
s = stats.load("hotsh... | Check running time per line in python | [
"",
"python",
"performance",
"profiling",
""
] |
How can we get the length of a hexadecimal number in the Python language?
I tried using this code but even this is showing some error.
```
i = 0
def hex_len(a):
if a > 0x0:
# i = 0
i = i + 1
a = a/16
return i
b = 0x346
print(hex_len(b))
```
Here I just used 346 as the hexadecimal n... | Use the function `hex`:
```
>>> b = 0x346
>>> hex(b)
'0x346'
>>> len(hex(b))-2
3
```
or using string formatting:
```
>>> len("{:x}".format(b))
3
``` | While using the string representation as intermediate result has some merits in simplicity it's somewhat wasted time and memory. I'd prefer a mathematical solution (returning the pure number of digits without any 0x-prefix):
```
from math import ceil, log
def numberLength(n, base=16):
return ceil(log(n+1)/log(ba... | Length of hexadecimal number | [
"",
"python",
"counting",
""
] |
I want to get the count of dataframe rows based on conditional selection. I tried the following code.
```
print df[(df.IP == head.idxmax()) & (df.Method == 'HEAD') & (df.Referrer == '"-"')].count()
```
output:
```
IP 57
Time 57
Method 57
Resource 57
Status 57
Bytes 57
Referrer 5... | You are asking for the condition where all the conditions are true,
so len of the frame is the answer, unless I misunderstand what you are asking
```
In [17]: df = DataFrame(randn(20,4),columns=list('ABCD'))
In [18]: df[(df['A']>0) & (df['B']>0) & (df['C']>0)]
Out[18]:
A B C D
12 ... | In Pandas, I like to use the `shape` attribute to get number of rows.
```
df[df.A > 0].shape[0]
```
gives the number of rows matching the condition `A > 0`, as desired. | get dataframe row count based on conditions | [
"",
"python",
"pandas",
""
] |
I have a 20 Column in a Table Col1, Col2, Col3 .... Col20.
RowNo column is a primary column, Col1 to Col20 is a not null int column
in each Column has unique data for single row(means Col1 has 10 so in Col2 to Col20 values is not repeat). table has approx 100000 records.
i have a 10 values like 18, 3, 15, 16, 11, 5, ... | ```
SELECT * FROM
yourTable
WHERE
CASE WHEN 18 IN (col1, col2, col3, ...col20) THEN 1 ELSE 0 END
+ CASE WHEN 3 IN (col1, col2, col3, ...col20) THEN 1 ELSE 0 END
+ CASE WHEN 15 IN (col1, col2, col3, ...col20) THEN 1 ELSE 0 END
+ CASE WHEN 16 IN (col1, col2, col3, ...col20) THEN 1 ELSE 0 END
+ CASE WHEN 11 IN (col1, c... | An Alternative: Copy your data into a query-friendly table.
The table:
```
CREATE TABLE [dbo].[tblX](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ColN] [int] NULL,
[Value] [int] NULL,
[RowNo] [int] NULL
);
```
Copy data over:
```
INSERT INTO tblX(RowNo, ColN, Value)
SELECT Row... | Match Data in a Multiple Column | [
"",
"sql",
""
] |
Have been googling this question for quite a while now, but cannot seem to find a solution. I use the excelfiles-function to create a list of all excelfiles including "tst" in their name in a specified directory. After that I want to read certain cells from each document with the locate\_vals-function, but I can't seem... | The problem showed by your traceback is indeed that this:
```
weightvalue = file_list.sheet.cell(3, 3).value
```
should be this:
```
weightvalue = sheet.cell(3, 3).value
```
However, there were more problems in your code. I've made minor fixes and marked them in the comments:
```
import xlrd
import os, fnmatch
st... | The error says everything you need:
> AttributeError: 'list' object has no attribute 'sheet'
`file_list` is a list of filenames, list doesn't have `sheet` attribute in python.
So, you just need to replace:
```
weightvalue = file_list.sheet.cell(3, 3).value
```
with
```
weightvalue = sheet.cell(3, 3).value
``` | Read files from list of files | [
"",
"python",
"list",
"xlrd",
""
] |
Okay, an ongoing project (in MS ACCESS) I've had is computing the number of each extra 'option' purchased by customers for a car company. To that end, I've created the following query to put every option into one column, and then sum the totals for each option in the next column(edited for readability and anonymity).
... | The syntax backwards. It's
```
Select <your columns>
Into <destination table>
From <source table>
```
So you should have:
```
SELECT a.options, Count(*)
INTO TBL_OPTION_ALL
FROM(
SELECT TBL.Des1 AS options FROM TBL UNION ALL
SELECT TBL.Des2 AS options FROM TBL UNION ALL
SELECT TBL.Des3 AS options FROM TBL UNION AL... | Try the below code, you aliased the table not the field.
```
SELECT a.options, Count(*)
FROM(
SELECT TBL.Des1 AS options FROM TBL UNION ALL
SELECT TBL.Des2 AS options FROM TBL UNION ALL
SELECT TBL.Des3 AS options FROM TBL UNION ALL
SELECT TBL.Des4 AS options FROM TBL UNION ALL
SELECT TBL.Des5 AS options FROM TBL UN... | 'FROM' syntax error involved with huge UNION clause | [
"",
"sql",
"ms-access",
""
] |
I'm trying to make a format string variable based on number of items in a list
```
d = {1: ['Spices', 39], 2: ['Cannons', 43], 3: ['Tea', 31], 4: ['Contraband', 46], 5: ['Fruit', 38], 6: ['Textiles', 44]}
d_max = [2, 11, 3]
for k,v in d.items():
list_var = [k, v[0], v[1]]
print(("{:<{}} " * 3).format(list_va... | I was under the impression that you also wanted to to be able to randomly add new items to the lists for each key. I was bored so I said why not and wrote the following code up. It will find the longest length of each entry of each key-value and put it in d\_max, doesn't matter what type it is, as long as it can be con... | do you mean you want to do something like:
```
list_var = [k] + v[:2]
```
This will work if the values list has too many items (It'll just remove the excess). | Variable number of format arguments | [
"",
"python",
"python-3.x",
""
] |
i'm making an e-store, so i have 3 tables:
1) `goods`
```
id | title
--------+-----------
1 | Toy car
2 | Toy pony
3 | Doll
```
2) `tags`
```
id | title
--------+-----------
1 | Toy
2 | Boys
3 | Girls
```
3) `links`
```
goods_id| tag_id
--------+-----------
1 ... | This query will return all items that have the maximum number of tags in common:
```
SET @item = 1;
SELECT
goods_id
FROM
links
WHERE
tag_id IN (SELECT tag_id FROM links WHERE goods_id=@item)
AND goods_id!=@item
GROUP BY
goods_id
HAVING
COUNT(*) = (
SELECT
COUNT(*)
FROM
links
WHERE
... | When you want to show the goods with goods id = 2
```
SELECT DISTINCT
goods.*
FROM
goods
LEFT JOIN links ON links.goods_id = goods.id
WHERE links.tag_id IN (SELECT links.tag_id
FROM links
WHERE links.goods_id = 2)
```
when you did not include goods\_id = 2
```
SEL... | sql query to determine the most similar goods by tags | [
"",
"mysql",
"sql",
"join",
""
] |
I have this query:
```
SELECT count(*) from
(
SELECT custid, count(*) as OrderCount
FROM orderinfo
WHERE preparedate between '2011-06-01' and '2011-12-31'
GROUP by CUSTID
) COUNTDB
WHERE Ordercount > '20'
```
Returns: 901 CustID's
If I run:
```
SELECT * from
(
SELECT custid, count(*) as OrderCount
FROM orderinfo
WH... | > Let me see if I can describe this another way. I need to see the total
> count of CustID's that have placed more than 20 orders in 2011
> (provided date range). Then, the second step would be to see how many
> of those SAME customers have placed an order in 2012 date range of the
> same days @AlexandreP.Levasseur
Pl... | I'm assuming your schema looks like this:
```
OrderInfo ( CustId, PrepareDate )
```
(hmm, simple, eh?)
So if I understand you correctly, you want the list of customers who have placed an order between two dates AND they've placed more than 20 orders. That's simple enough:
```
SELECT
CustId,
Count(*) AS Orde... | QUERY help for a learning SQL admin | [
"",
"sql",
""
] |
This question is probably answered before but i cant find how to get the latest records of the months.
The problem is that I have a table with sometimes 2 row for the same month. I cant use the aggregate function(I guess) cause in the 2 rows, i have different data where i need to get the latest.
Example:
```
name ... | Use SQL Server [ranking functions](http://msdn.microsoft.com/en-us/library/ms189798%28v=sql.90%29.aspx).
```
select name, Date, nuA, nuB, nuC, nuD from
(Select *, row_number() over (partition by name, datepart(year, Date),
datepart(month, Date) order by Date desc) as ranker from Table
) Z
where ranker = 1
``` | Try this
```
SELECT t1.* FROM Table1 t1
INNER JOIN
(
SELECT [name],MAX([date]) as [date] FROM Table1
GROUP BY [name],YEAR([date]),MONTH([date])
) t2
ON t1.[date]=t2.[date] and t1.[name]=t2.[name]
ORDER BY t1.[name]
``` | Sql get latest records of the month for each name | [
"",
"sql",
"sql-server-2005",
""
] |
How can I modify the join clause with a case clause; for example I want the table to join another column if column1 is null such as:
```
SELECT * FROM MYTABLE
LEFT JOIN OTHERTABLE ON
CASE WHEN MYTABLE.A IS NULL THEN MYTABLE.B = OTHERTABLE.A
ELSE MYTABLE.A IS NOT NULL THEN MYTABLE.A = OTHERTABLE.A
```
(totally made ... | Try this one:
```
SELECT *
FROM MyTable M
LEFT JOIN OtherTable O ON(CASE WHEN M.A IS NULL THEN M.B ELSE M.A END) = O.A
``` | ```
SELECT * FROM MYTABLE
LEFT JOIN OTHERTABLE ON COALESCE(MYTABLE.A, MYTABLE.B) = OTHERTABLE.A
``` | SQL join with case | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
In documentation of Django Wizard i found code like this:
```
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
```
So I am wondering how can i add multi... | Make one of your forms a `Formset` containing the rest of the forms you need. You don't need to necessarily use a `ModelFormset`, you can subclass the base class and create the forms manually. | This is now deprecated use this link: <https://github.com/vikingco/django-formtools-addons>
I wanted to share my settings if would be any help to anyone:
```
class BaseImageFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super(BaseImageFormSet, self).__init__(*args, **kwargs)
self.... | Django Wizard, multiple forms in one step | [
"",
"python",
"django",
"django-forms",
""
] |
I noticed a very interesting (and unexpected as well) thing yesterday. I was given a task (on production environment) to update three columns of TableA (I am changing the table and column names due to some obvious reasons) by getting all the values present in dummytable. The primary key of both the tables is column A. ... | For your first question:
> 1) What's wrong (or missing) in this stored procedure? (Dummy table had
> thousands of records as well)
I guess you forgot to `CLOSE` the `CURSOR`. Right after you end the `LOOP`, you should `CLOSE` the `CURSOR`.
```
END LOOP claimlistloop;
CLOSE claimlist;
END
```
> 2) What could be th... | Forget the cursor. In fact you should never use a cursor if it's avoidable. Cursors are incredibly slow.
Simply do
```
UPDATE
yourTable yt
INNER JOIN dummyTable dt ON yt.A = dt.A
SET
yt.B = dt.B,
yt.C = dt.C;
```
and you're fine. | MySql Procedure Producing Wrong Results | [
"",
"mysql",
"sql",
"stored-procedures",
""
] |
I am reading a file containing single precision data with 512\*\*3 data points. Based on a threshold, I assign each point a flag of 1 or 0. I wrote two programs doing the same thing, one in fortran, the other in python. But the one in fortran takes like 0.1 sec while the one in python takes minutes. Is it normal? Or ca... | In general Python is an interpreted language while Fortran is a compiled one. Therefore you have some overhead in Python. But it shouldn't take that long.
One thing that can be improved in the python version is to replace the for loop by an index operation.
```
#create flag filled with zeros with same shape as data
f... | Your two programs are totally different. Your Python code repeatedly changes the size of a structure. Your Fortran code does not. You're not comparing two languages, you're comparing two algorithms and one of them is obviously inferior. | Huge difference between python and fortran difference for a small program | [
"",
"python",
"fortran",
""
] |
How can i use a for loop inside a while loop?
Here is my code:
```
def avoids(word,forbidden):
for fl in forbidden:
for letter in word:
if letter == fl:
return False
return True
fin= open('words.txt')
u=97
v=97
w=97
x=97
y=97
minim=100
while u <= 122:
while v <= 122:
... | The reason it is executing the for loop just one time is that you are exhausting the buffer you created for your "words.txt" file during the first iteration of the for loop.
If you want to go through the words in that file multiple times you need to reopen it each time (which, as you noted, creates a lot of overhead).... | Your code would look a lot less indented like this:
```
from string import ascii_lowercase
from itertools import product
for u, v, w, x, y in product(ascii_lowercase, repeat=5):
...
```
I'm not sure what the `avoids()` function is supposed to do. It's unlikely to be useful in it's current form. Did you test it a... | for loop inside a while loop | [
"",
"python",
"python-3.x",
""
] |
I am trying to generate an pdf using Reportlab. It is acceptably easy. I have a function like the one below that returns the image and I just add it to the document.
```
def create_logo(bsolute_path):
image = Image(absolute_path)
image.drawHeight = 1 * inch
image.drawWidth = 2 * inch
return [image]
```
It... | I found this also :
[Image aspect ratio using Reportlab in Python](https://stackoverflow.com/questions/5327670/image-aspect-ratio-using-reportlab-in-python/17232649#17232649)
but in the end i used this method :
```
def create_logo(absolute_path):
image = Image(absolute_path)
image._restrictSize(2 * inch, 1 *... | This worked for me:
```
image = Image(absolute_path,width=2*inch,height=1*inch,kind='proportional')
``` | How do i set the max size for an image in Reportlab, without rescaling? | [
"",
"python",
"image",
"pdf",
"reportlab",
""
] |
I asked a question a little while ago ([Python splitting unknown string by spaces and parentheses](https://stackoverflow.com/questions/17134225/python-splitting-unknown-string-by-spaces-and-parentheses)) which worked great until I had to change my way of thinking. I have still not grasped regex so I need some help with... | The answer was simply:
```
re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+',strs)
``` | This is pushing what regexps can do. Consider using `pyparsing` instead. It does recursive descent. For this task, you could use:
```
from pyparsing import *
import string, re
RawWord = Word(re.sub('[()" ]', '', string.printable))
Token = Forward()
Token << ( RawWord |
Group('"' + OneOrMore(RawWord) + '"'... | Python splitting string by parentheses | [
"",
"python",
"string",
"split",
""
] |
I have table (T-SQL) with 2 attributes - Code and Range.
```
Code Range
-------------------- ----------
5000_RANGE 5001..5003
5001 NULL
5002 NULL
5003 NULL
5802 NULL
5802_RANGE 5802..5804
5803 NULL
5804 ... | You can get the list using a self-join:
```
select range.code, c.code
from (select code, range
from t
where code like '%RANGE'
) range left outer join
(select t.*
from t
where code not like '%RANGE'
) c
on c.code between left(range.range, 4) and right(range.range, 4)
```
Ge... | Try this. Create a function like below:
```
ALTER FUNCTION GetRangeText
(
@Value VARCHAR(50)
) RETURNS VARCHAR(100)
AS
BEGIN
DECLARE @Start AS INT
DECLARE @End AS INT
DECLARE @RangeText AS VARCHAR(200)
SET @RangeText = ''
SET @Start = CAST(SUBSTRING(@Value, 0, CHARINDEX('...', @Value)) AS INT)... | T-SQL - multiple comma-separated values on a single line | [
"",
"sql",
"t-sql",
""
] |
I have a table `orders` like this -
```
id | bookId
------------
1 3
2 2
3 1
```
and this `books` -
```
bookId | book
---------------
1 bookA
2 bookB
3 bookC
```
is their any way i can get `book` column under `bookId` when i do
`select * from ... | You will need to [JOIN](http://en.wikipedia.org/wiki/Join_%28SQL%29) the tables on the `bookid` column in the `orders` table to the `bookid` column in the `books` table:
```
select o.id, b.book as bookId
from orders o
inner join books b
on o.bookid = b.bookid
where o.id = 1;
``` | After doing a `JOIN`, to fetch the column under a different name you just need to say you want to get `b.book AS bookId`
```
SELECT o.id, b.book as bookId
FROM orders o
INNER JOIN books b
ON o.bookId = b.id
WHERE o.id = 1
```
(Untested, the DBMS may complain about the similarity in column names) | get result from multiple tables | [
"",
"mysql",
"sql",
"database",
""
] |
This is *not* off-topic. [The link to on-topic](https://stackoverflow.com/help/on-topic) says: `...if your question generally covers...software tools commonly used by programmers...then you’re in the right place to ask your question!`
---
I have SQL Server 2012 installed on my PC, and usually don't need it. It's only... | To start, stop, pause, resume, or restart the an instance of the SQL Server Database Engine:
> 1. On the Start menu, point to All Programs, point to Microsoft SQL Server 2012 , point to Configuration Tools, and then click SQL Server
> Configuration Manager. If the User Account Control dialog box appears,
> click... | The best way is to setup se SQL service to manual, from run type “services.msc” to access windows services and change startup type to “manual” you can change all services started by SQL\*.
Doing so your computer starts faster because will not start SQL Server on boot.
If you need just go again to services.msc and sta... | Stop SQL Server from running until needed | [
"",
"sql",
"sql-server",
"windows-7",
"sql-server-2012",
"ssms",
""
] |
So in my scrapy project I was able to isolate some particular fields, one of the field return something like:
```
[Rank Info] on 2013-06-27 14:26 Read 174 Times
```
which was selected by expression:
```
(//td[@class="show_content"]/text())[4]
```
I usually do post-processing to extract the datetime information, i.e... | Scrapy uses XPath 1.0 which has very limited string manipulation capabilities, especially does not support regular expressions. There are two ways to cut down a string, I demonstrate both with an example to strip down to the substring you're looking for.
### By Character Index
This is fine if the character indices do... | In all of the other answers so far, not only is the `/text()` not helpful, it is potentially (or even likely) a problem. For readers of the archive, they should be aware of the problems using `/text()` in addresses for arguments of a function. In my professional work, there are very (very!) few requirements for address... | xpath: string manipulation | [
"",
"python",
"xpath",
"scrapy",
""
] |
I'm learning Python and I'm having a little bit of a problem. Came up with this short script after seeing something similar in a course I'm taking. I've used "or" with "if" before with success (it doesn't show much here). For some reason I can't seem to get this working:
```
test = raw_input("It's the flying circus! C... | Boolean expressions in most programming languages don't follow the same grammar rules as English. You have to do separate comparisons with each string, and connect them with `or`:
```
if x == "monkey" or x == "monkeys":
print "You're right, they are awesome!!"
else:
print "I'm sorry, you're incorrect.", x[0].u... | gkayling is correct. Your first if statement returns true if:
x == "monkey"
or
"monkeys" evaluates to true (it does since it's not a null string).
When you want to test if x is one of several values, it's convenient to use the "in" operator:
```
test = raw_input("It's the flying circus! Cool animals but which is t... | "or" conditional in Python troubles | [
"",
"python",
"conditional-statements",
"conditional-operator",
""
] |
I have two different versions of python installed on my machine: 2.4 and 2.7. I'm trying to install OpenCV(2.4.5) for the 2.7 version.
```
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON ..
```
It detects the python 2.4 as the current installati... | There are some Cmake flags which allow you to explicitly specify which version of Python to use. You will need to set the values of these flags to the correct location for your installation of Python.
The flag names and likely locations are below:
```
PYTHON_EXECUTABLE=/usr/bin/python2.7/
PYTHON_INCLUDE=/usr/include/... | Use [virtualenv](http://www.virtualenv.org/en/latest/)
```
virtualenv -p python2.7 env
source env/bin/activate
python --version # prints «Python 2.7.3»
pip install pyopencv
```
If you need support of 2.4 (or other version), just create new environment. | Install OpenCV for Python (multiple python versions) | [
"",
"python",
"opencv",
"python-2.7",
""
] |
I'm attempting to read and write files from a User Directory, (C:\Users\USERNAME\Test Source) But I've been unsuccessful in finding any resources on how I can auto detect the name of the user, USERNAME in the above example, or anyway that I can have it read and write to the directory without knowledge off what a users ... | You can use in windows command line
```
echo %username%
```
or
```
whoami
```
for getting the username of the user who is currently logged in .
Store it in a variable and then append it to the path name.
You can also use
```
‘C:\users\%username%\file‘
```
directly .To check through `whoami` do
```
l=`whoami`... | The simplest way is this:
```
import os
print os.path.expanduser('~')
```
Append your folder to the path like so:
```
userdir = os.path.expanduser('~')
print os.path.join(userdir, 'Test Source')
```
Besides requiring the least lines of code, this method has the advantage of working under every OS (Linux, Windows XP... | How do I read/write files to an unknown user directory? | [
"",
"python",
"windows",
"python-2.7",
"directory",
""
] |
I am trying to write a query to implement pagination, my basic requirements is that I need a query where I can give min and max range of rows to return for e.g. for page 1 I need record from 1 – 10 for page to 11-20 and so on and so forth.
Through some help form internet and here at SO I have written down the followin... | Your whole query logic + `ROW_NUMBER` should go in the sub-query. You use outer `WHERE` just for paging.
`ROW_NUMBER` must have `ORDER BY` on which paging is to be implemented.
```
SELECT a.id ,
a.title ,
a.name
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY b.dtetme DESC) AS RowNum, b.*
... | I think the problem is with th addition of `[student] b` in the `FROM`, try moving the join into the subquery.
```
SELECT a.id, a.title, a.name
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY (select NULL as noorder)) AS RowNum, *
FROM [student] b
JOIN [class] c ON c.id = b.class
WHERE b.[status]=1
AND ... | Getting rows within a specified range for pagination | [
"",
"sql",
"sql-server",
"pagination",
""
] |
Here is my sp codes. I want to select next different 6 rows from result of this sp. How can I do that?
```
SELECT N.NewsId,
N.HeadCaption,
(SELECT Name FROM NewsCategory
WHERE NewsCategoryId = N.HeadLineCategoryId) Category,
N.PicUrl,
N.Creation,
SUBSTRING((fnStripTag... | Okay, Okay, just like this
```
SELECT N.NewsId,
N.HeadCaption,
(SELECT Name FROM NewsCategory
WHERE NewsCategoryId = N.HeadLineCategoryId) Category,
N.PicUrl,
N.Creation,
SUBSTRING((fnStripTags(N.Description)),1,75) AS ShortDescription
FROM News N
INNER JOIN
... | Try with SELECT DISTINCT instead of SELECT | how to skip rows in mysql query | [
"",
"mysql",
"sql",
"stored-procedures",
""
] |
I have a Table with 4 Columns
Each Column will be A,B,C,D
Column A is the Primary key.
Column B has unique name constraint.
Now I want to remove the unique constraint for column B and give a unique constraint by combining the columns B, C and D. So the table will allow only one row with a particular value in columns... | Create a unique key on those columns
```
ALTER TABLE YourTable
add CONSTRAINT YourTable_unique UNIQUE (B, C, D);
```
[Oracle/PLSQL: Unique Constraints](http://www.techonthenet.com/oracle/unique.php) | > First of all you should drop an existing Constraint by using below ALTER Query.
```
ALTER TABLE table_name
DROP CONSTRAINT myUniqueConstraint;
```
> Now, you can create a [UNIQUE](http://www.tutorialspoint.com/sql/sql-unique.htm) Constraint by using the keyword UNIQUE with the combination of required Columns.
*... | How to give a unique constraint to a combination of columns in Oracle? | [
"",
"sql",
"oracle",
"constraints",
"unique-constraint",
"composite-key",
""
] |
This may be really easy but T-SQL is far from my forte.
I have a bunch of really long strings that contain a segment that looks like this:
```
~GS^PO^007941230X^107996118^20130514^
```
I'd like to extract 007941230X out of this. The length of this substring will vary but the format will always be:
```
~xxxx^..... | Here's a working example
```
declare @var varchar(1000) = '~xxxx^.....^xxxxx^~GS^PO^jjjjjjjj^xxx^xxxx^....'
declare @start_position int, @end_position int
declare @temp_string varchar(100)
select @start_position = PATINDEX('%GS^PO^%', @var)
print @start_position
select @temp_string = SUBSTRING(@var, @start_position + ... | If the string always starts at the 8th position and then varies in length, you can do:
```
with t as (
select '~GS^PO^007941230X^107996118^20130514^' as val
)
select substring(val, 8,
charindex('^', substring(val, 8, len(val)))-1
)
from t;
```
If you don't know that it beg... | Find a substring after a matched pattern in t-sql | [
"",
"sql",
"sql-server",
"regex",
"t-sql",
""
] |
So I have an interesting problem.
I'm trying to write some word jumbles, and I need to know which letters I've used and which I haven't. So far I have the code below:
```
def remove_common(x,y):
sort = sort = lambda x: "".join(c for c in sorted(x.lower()) if c.isalpha())
x,y = sort(x), sort(y)
//some code t... | You can use `collections.Counter` objects, which can be subtracted from each other:
```
import collections
def remove_common(x,y):
count = lambda x: collections.Counter(c for c in x.lower() if c.isalpha())
cx, cy = count(x), count(y)
diff = cx - cy
rev_diff = cy - cx
assert len(rev_diff) == 0, "%... | `collections.Counter` will not let any count go below zero if you use the `-` operator. However, if you use c.subtract(d), then it will allow you to do so. Further, when using c.elements(), values with negative counts are ignored.
Here is an implementation which is based on collections.Counter:
```
import collections... | Remove common letters in strings | [
"",
"python",
"string",
""
] |
In Python 2.7 I want to print datetime objects using string formatted template. For some reason using left/right justify doesn't print the string correctly.
```
import datetime
dt = datetime.datetime(2013, 6, 26, 9, 0)
l = [dt, dt]
template = "{0:>25} {1:>25}" # right justify
print template.format(*l) #print items in... | The problem here is that `datetime` objects have a `__format__` method which is basically just an alias for `datetime.strftime`. When you do the formatting, the format function gets passed the string `'>25'` which, as you've seen, `dt.strftime('>25')` just returns `'>25'`.
The workaround here it to specify that the fi... | `datetime.datetime` has [**format** method](http://docs.python.org/2/library/datetime.html#datetime.datetime.__format__). You need to convert it str.
```
>>> '{:%Y/%m/%d}'.format(dt)
'2013/06/26'
>>> '{:>20}'.format(dt)
'>20'
>>> '{:>20}'.format(str(dt))
' 2013-06-26 09:00:00'
```
---
```
>>> import datetime
>>> dt ... | Datetime string format alignment | [
"",
"python",
"datetime",
"string-formatting",
""
] |
See below for 50 tweets about "apple." I have hand labeled the positive matches about Apple Inc. They are marked as 1 below.
Here are a couple of lines:
```
1|“@chrisgilmer: Apple targets big business with new iOS 7 features http://bit.ly/15F9JeF ”. Finally.. A corp iTunes account!
0|“@Zach_Paull: When did green skit... | I would do it as follows:
1. Split the sentence into words, normalise them, build a dictionary
2. With each word, store how many times they occurred in tweets about the company, and how many times they appeared in tweets about the fruit - these tweets must be confirmed by a human
3. When a new tweet comes in, find eve... | What you are looking for is called [Named Entity Recognition](http://en.wikipedia.org/wiki/Named-entity_recognition). It is a statistical technique that (most commonly) uses [Conditional Random Fields](http://en.wikipedia.org/wiki/Conditional_random_field) to find named entities, based on having been trained to learn t... | How can I build a model to distinguish tweets about Apple (Inc.) from tweets about apple (fruit)? | [
"",
"python",
"machine-learning",
"classification",
""
] |
I am trying to figure out the very best way, (probably doesn't matter in this case) to find the rows of one table, based on the existence of a flag, and an relational id in a row in another table.
here are the schemas:
```
CREATE TABLE files (
id INTEGER PRIMARY KEY,
dirty INTEGER NOT NULL);
CREATE TABLE res... | TL;DR: The best query and index is:
```
create index uniqueFiles on resume_points (scan_file_id);
select * from (select distinct scan_file_id from resume_points) d join files on d.scan_file_id = files.id and files.dirty = 1;
```
Since I typically work with SQL Server, at first I thought that surely the query optimize... | Since `files.id` is the primary key, try `GROUP`ing `BY` this field rather than checking `DISTINCT files.*`
```
SELECT f.*
FROM resume_points rp
INNER JOIN files f on rp.scan_file_id = f.id
WHERE f.dirty = 1
GROUP BY f.id
```
Another option to consider for performance is adding an index to `resume_points.scan_file_id... | SQLite3 query optimization join vs subselect | [
"",
"sql",
"database",
"sqlite",
"query-optimization",
""
] |
I have a text file that I am parsing one column of data from and the result is one big list (50 elements):
```
CLB, HNRG, LPI, MTDR, MVO, NRGY, PSE, PVR, RRC, WES, ACMP, ATLS, ATW, BP, BWP, COG, DGAS, DNR, EPB, EPL, EXLP, NOV, OIS, PNRG, SEP, APL, ARP, CVX, DMLP, DRQ, DWSN, EC, ECA, FTI, GLOG, IMO, LINE, NFX, OILT, PN... | You could do this:
```
import csv
from itertools import izip_longest
with open('/tmp/line.csv','r') as fin:
cr=csv.reader(fin)
n=10
data=izip_longest(*[iter(list(cr)[0])]*n,fillvalue='')
print '\n'.join(', '.join(t) for t in data)
```
With your data, prints:
```
CLB, HNRG, LPI, MTDR, MVO, NRGY, PSE,... | Ok Using a file called rawdata.txt that looks like this:
```
CLB, HNRG, LPI, MTDR, MVO, NRGY, PSE, PVR, RRC, WES, ACMP, ATLS, ATW, BP, BWP, COG, DGAS, DNR, EPB, EPL, EXLP, NOV, OIS, PNRG, SEP, APL, ARP, CVX, DMLP, DRQ, DWSN, EC, ECA, FTI, GLOG, IMO, LINE, NFX, OILT, PNG, QRE, RGP, RRMS, SDRL, SNP, TLP, VNR, XOM, XTXI,... | How to create a new list or new line after a certain number of iterations | [
"",
"python",
"file",
"list",
""
] |
I'd like to know how I can do matrix addition in `Python`, and I'm running into quite a number of roadblocks trying to figure out the best way.
Here's the problem, written as best as I can formulate it right now.
I have a data set, which is an adjacency matrix for a directed graph, in which isolates of an biological ... | Here is a straightforward method (you can `reset_index()` at the end if you want)
Create with a multi-index on id1 and id2
```
In [24]: df1 = DataFrame([['ID1','ID2',1],['ID1','ID3',1],['ID2','ID4',1]],columns=['id1','id2','value']).set_index(['id1','id2'])
In [25]: df2 = DataFrame([['ID1','ID2',1],['ID1','ID3',1],[... | Assuming you have the adjacency data as a list of connections:
```
import itertools
from collections import defaultdict
adj1 = [
('A', 'B'),
('A', 'C'),
('B', 'D')
]
adj2 = [
('A', 'B'),
('A', 'C'),
('A', 'D')
]
result = defaultdict(int)
for adjacency in itertools.chain(adj1, adj2):
resu... | Matrix addition using triples representation in Python | [
"",
"python",
"python-2.7",
"matrix",
"pandas",
"adjacency-matrix",
""
] |
`a` and `b` are 1 dimensional numpy arrays (or python lists):
I am doing this:
```
>>> c = [x/y for x,y in zip(a,b)]
```
Occasionally `b` has a zero in it - so a division by zero error occurs.
How can I conditionally check for a 0 value in `b` and set the corresponding element of `c` to 0? | You can use [`if-else` condition](http://docs.python.org/2/reference/expressions.html#conditional-expressions) inside list comprehension:
```
>>> c = [x/y if y else 0 for x,y in zip(a,b)]
``` | You can use a [ternary expression](http://docs.python.org/2/reference/expressions.html#conditional-expressions) inside the list comprehension:
```
[x/y if y!= 0 else 0 for x,y in zip(a,b)]
``` | Python - List comphrehension with test to avoid division by zero | [
"",
"python",
"list",
"numpy",
""
] |
I am running into an issue with returning the month and day variables to use in other functions.
```
def date():
date = raw_input("Date (ex. Jun 19): ")
date = date.split(' ')
month = date[0]
month = month[:3].title()
day = date[1]
return (month, day)
def clone(month,day):
print month day
... | You're probably wondering how to use a variable in the global space when it is declared in a local space. use `global`:
```
def myfunc():
global a
a = 5
print a
# NameError: name 'a' is not defined
myfunc()
print a
# 5
``` | Since you're returning a `tuple` from `date()` I will be assuming that this would be the thing you want to do
```
month_day = date()
clone(month_day[0], month_day[1])
```
And also the following line in `clone()`
```
print month day
```
should be
```
print month, day
``` | Returning variables to use in other functions in python | [
"",
"python",
"function",
"return",
""
] |
I have a problem with my code in the try block.
To make it easy this is my code:
```
try:
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
except:
pass
```
Is something like this possible? | You'll have to make this *separate* `try` blocks:
```
try:
code a
except ExplicitException:
pass
try:
code b
except ExplicitException:
try:
code c
except ExplicitException:
try:
code d
except ExplicitException:
pass
```
This assumes you want to run ... | You can use [fuckit](https://github.com/ajalt/fuckitpy#as-a-decorator) module.
Wrap your code in a function with `@fuckit` decorator:
```
@fuckit
def func():
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
``` | Multiple try codes in one block | [
"",
"python",
"exception",
"try-catch",
"except",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.