qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
48,835,934 | Installing Google Cloud SDK I get the response below:
Note - I checked, and `C:\Users\jonat\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython`
does indeed lead to a python `2.7` that runs fine.
```
Output folder: C:\Users\jonat\AppData\Local\Google\Cloud SDK
Downloading Google Cloud SDK core.
Ext... | 2018/02/16 | [
"https://Stackoverflow.com/questions/48835934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9371800/"
] | Here is a piece of code that may help:
```
mat = cbind(1:3, 4:6, 7)
layout(mat, width = c(1,1,.25))
pal = colorRampPalette(c("white", "black"))(100)
# empty plots
for (i in 1:6) image(matrix(runif(100), 10), col = pal)
# color scale
par(las=1, mar = c(4, 1, 4, 5))
image(t(1:100), col = pal, axes = F, ann = F)
axis(4)... | Okay, figured it out with the help of [this post](https://stackoverflow.com/questions/9314658/colorbar-from-custom-colorramppalette) that uses a customised function to plot scales. I just had to remove the `dev.new()` call to avoid plotting the colour scale in a new device. The function is flexible but you still need t... |
4,250,939 | I started programming in january of this year and have covered a lot of ground. I have learnt javascript, ruby on rails, html, css, jquery and every now and then i like to try out some clojure but i will really get into that in the middle of next yr. I really didnt like rails and prefer using netbeans with pure javaScr... | 2010/11/22 | [
"https://Stackoverflow.com/questions/4250939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/390129/"
] | Not sure why you don't like rails, but you might want to try the newly released "Rails for Zombies" tutorials by Envy Labs: <http://railsforzombies.org/>. Or if you like books instead of online stuff, check out [Agile Web Development with Rails](http://pragprog.com/titles/rails4/agile-web-development-with-rails)
As b... | If you like ruby as programming language, but find rails to be just too much to take in it once, I'd recommend trying [Sinatra](http://www.sinatrarb.com/). It's also a ruby-based web framework, but it's a lot simpler than rails, and offers you a lot more control over how you want to set things up. For smaller projects,... |
4,250,939 | I started programming in january of this year and have covered a lot of ground. I have learnt javascript, ruby on rails, html, css, jquery and every now and then i like to try out some clojure but i will really get into that in the middle of next yr. I really didnt like rails and prefer using netbeans with pure javaScr... | 2010/11/22 | [
"https://Stackoverflow.com/questions/4250939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/390129/"
] | Not sure why you don't like rails, but you might want to try the newly released "Rails for Zombies" tutorials by Envy Labs: <http://railsforzombies.org/>. Or if you like books instead of online stuff, check out [Agile Web Development with Rails](http://pragprog.com/titles/rails4/agile-web-development-with-rails)
As b... | [`Python`](http://www.python.org/) language and [`Django`](http://www.djangoproject.com/) web framework are another good alternative. Both elegant and easy to get started with. |
22,585,176 | This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is:
```
John M
John M
Jim M
Jim M
Jim M
Jim M
Sally... | 2014/03/22 | [
"https://Stackoverflow.com/questions/22585176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3451030/"
] | You can use parameter android:showAsAction="Always" for each menu item in menu.xml to show your items in action bars
```
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_add_size"
android:title="@string/menu_add_item"
android:orderInCategory="10"
... | in your **menu/main.xml:**
```
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/settings"
android:title="@string/settings"
android:orderInCategory="0"
android:showAsAction="always"
/>
<item android:id="@+id/action_compose"
android:title="hello"
... |
22,585,176 | This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is:
```
John M
John M
Jim M
Jim M
Jim M
Jim M
Sally... | 2014/03/22 | [
"https://Stackoverflow.com/questions/22585176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3451030/"
] | You can use parameter android:showAsAction="Always" for each menu item in menu.xml to show your items in action bars
```
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_add_size"
android:title="@string/menu_add_item"
android:orderInCategory="10"
... | Govtart is generally right, but I can see that you have dependency on appcompat-v7 library. So you should use another namespace for actionbar-specific attributes:
```
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="@... |
22,585,176 | This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is:
```
John M
John M
Jim M
Jim M
Jim M
Jim M
Sally... | 2014/03/22 | [
"https://Stackoverflow.com/questions/22585176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3451030/"
] | You can use parameter android:showAsAction="Always" for each menu item in menu.xml to show your items in action bars
```
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_add_size"
android:title="@string/menu_add_item"
android:orderInCategory="10"
... | First of all, to get your options to show in the action bar, you can use `android:showAsAction="always"` or (the better solution) you can use `android:showAsAction="ifRoom"` and that way, it will only be in the action bar if it can fit.
So your `menu/main.xml` would be this:
```
<menu xmlns:android="http://schemas.an... |
22,585,176 | This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is:
```
John M
John M
Jim M
Jim M
Jim M
Jim M
Sally... | 2014/03/22 | [
"https://Stackoverflow.com/questions/22585176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3451030/"
] | Govtart is generally right, but I can see that you have dependency on appcompat-v7 library. So you should use another namespace for actionbar-specific attributes:
```
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="@... | in your **menu/main.xml:**
```
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/settings"
android:title="@string/settings"
android:orderInCategory="0"
android:showAsAction="always"
/>
<item android:id="@+id/action_compose"
android:title="hello"
... |
22,585,176 | This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is:
```
John M
John M
Jim M
Jim M
Jim M
Jim M
Sally... | 2014/03/22 | [
"https://Stackoverflow.com/questions/22585176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3451030/"
] | First of all, to get your options to show in the action bar, you can use `android:showAsAction="always"` or (the better solution) you can use `android:showAsAction="ifRoom"` and that way, it will only be in the action bar if it can fit.
So your `menu/main.xml` would be this:
```
<menu xmlns:android="http://schemas.an... | in your **menu/main.xml:**
```
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/settings"
android:title="@string/settings"
android:orderInCategory="0"
android:showAsAction="always"
/>
<item android:id="@+id/action_compose"
android:title="hello"
... |
22,585,176 | This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is:
```
John M
John M
Jim M
Jim M
Jim M
Jim M
Sally... | 2014/03/22 | [
"https://Stackoverflow.com/questions/22585176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3451030/"
] | First of all, to get your options to show in the action bar, you can use `android:showAsAction="always"` or (the better solution) you can use `android:showAsAction="ifRoom"` and that way, it will only be in the action bar if it can fit.
So your `menu/main.xml` would be this:
```
<menu xmlns:android="http://schemas.an... | Govtart is generally right, but I can see that you have dependency on appcompat-v7 library. So you should use another namespace for actionbar-specific attributes:
```
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="@... |
33,679,414 | Suppose I have two types of axis aligned rectangles:
a) Defined by left-up and right-bottom points: (x1, y1), (x2, y2)
b) Defined by (x1, y1) and (width, height)
The aim is to create pythonic-way code, that allows for conversion between these types. E.g. if there is a function, that performs calculations only in o... | 2015/11/12 | [
"https://Stackoverflow.com/questions/33679414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2864143/"
] | Create one class, and give it two constructors. One the default `__init__` method, the other a classmethod accepting the other form to specify a rectangle:
```
class Rectangle(Shape):
def __init__(self, x1, y1, x2, y2):
# ....
@classmethod
def fromSize(cls, x1, y1, width, height):
return c... | I recommend creating one class and handling the inputs during your init to determine what is present/not present. Then add all the missing parameters based on a calculation. Here is a working example for your situation:
```
class RectangleClass:
def __init__(self, x1, y1, x2=None, y2=None, width=None, height=None)... |
18,269,672 | I mean the situation when lua is run not as embedded in another app but as standalone scripting language.
I need something like `PHP_BINARY` or `sys.executable` in python. Is that possible with LUA ? | 2013/08/16 | [
"https://Stackoverflow.com/questions/18269672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393087/"
] | Note that the the solution given by lhf is not the most general. If the interpreter has been called with additional command line parameters (if this may be your case) you will have to search `arg`.
In general the interpreter name is stored at the most negative integer index defined for `arg`. See this test script:
``... | Try `arg[-1]`. But note that `arg` is not defined when Lua is executed interactively. |
18,269,672 | I mean the situation when lua is run not as embedded in another app but as standalone scripting language.
I need something like `PHP_BINARY` or `sys.executable` in python. Is that possible with LUA ? | 2013/08/16 | [
"https://Stackoverflow.com/questions/18269672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393087/"
] | Try `arg[-1]`. But note that `arg` is not defined when Lua is executed interactively. | If the directory that contains your Lua interpreter is in your PATH environment variable, and you invoked the Lua interpreter by its file name:
```
lua myprog.lua
```
then `arg[-1]` contains "lua", not the absolute path of the Lua interpreter.
The following Lua program works for me on z/OS UNIX:
```
-- Print the p... |
18,269,672 | I mean the situation when lua is run not as embedded in another app but as standalone scripting language.
I need something like `PHP_BINARY` or `sys.executable` in python. Is that possible with LUA ? | 2013/08/16 | [
"https://Stackoverflow.com/questions/18269672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393087/"
] | Note that the the solution given by lhf is not the most general. If the interpreter has been called with additional command line parameters (if this may be your case) you will have to search `arg`.
In general the interpreter name is stored at the most negative integer index defined for `arg`. See this test script:
``... | If the directory that contains your Lua interpreter is in your PATH environment variable, and you invoked the Lua interpreter by its file name:
```
lua myprog.lua
```
then `arg[-1]` contains "lua", not the absolute path of the Lua interpreter.
The following Lua program works for me on z/OS UNIX:
```
-- Print the p... |
29,321,077 | I am trying to write a function to mix strings in python but I am getting stuck at the end. So for this example, I have 2 words, mix and pod. I would like to create a function that returns: pox mid
My code only returns pox mix
Code:
```
def mix_up(a, b):
if len(a and b)>1:
b=str.replace(b,b[2],a[2:3])
... | 2015/03/28 | [
"https://Stackoverflow.com/questions/29321077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120266/"
] | Little play on [string slicing](https://docs.python.org/2/tutorial/introduction.html#strings)
```
def mix_up(first, second):
new_first = second[:2] + first[2:]
new_second = first[:2] + second[2:]
return " ".join((new_first, new_second))
assert mix_up('mix','pod') == 'pox mid'
assert mix_up('dog','dinner')... | If you simply wanted to put the 2nd word before the first word all the time:
```
def mix_up(a,b):
return " ".join([b,a]) # Should return pod mix
```
Give that you aimed for `pox mix` suggests that you probably wanted to:
1) Replace the last character of word `b` with x
2) Place b before a.
In that case, the ... |
29,321,077 | I am trying to write a function to mix strings in python but I am getting stuck at the end. So for this example, I have 2 words, mix and pod. I would like to create a function that returns: pox mid
My code only returns pox mix
Code:
```
def mix_up(a, b):
if len(a and b)>1:
b=str.replace(b,b[2],a[2:3])
... | 2015/03/28 | [
"https://Stackoverflow.com/questions/29321077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120266/"
] | Little play on [string slicing](https://docs.python.org/2/tutorial/introduction.html#strings)
```
def mix_up(first, second):
new_first = second[:2] + first[2:]
new_second = first[:2] + second[2:]
return " ".join((new_first, new_second))
assert mix_up('mix','pod') == 'pox mid'
assert mix_up('dog','dinner')... | ```js
def mix_up(a, b):
if len(a) < 2 or len(b) < 2: return
return (b[:2] + a[2:] + " " + a[:2] + b[2:])
``` |
5,385,238 | I've got a timestamp in a log file with the format like:
```
2010-01-01 18:48:14.631829
```
I've tried the usual suspects like strptime, and no matter what i do, I'm getting that it doesn't match the format I specify. `("%Y-%m-%d %H:%M:%S" OR "%Y-%m-%d %H:%M:%S.%f")`
I've even tried splitting the value by "." so I ... | 2011/03/22 | [
"https://Stackoverflow.com/questions/5385238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669983/"
] | You can use `strptime` like so (Python 2.6+ only):
```
>>> import datetime
>>> s = "2010-01-01 18:48:14.631829"
>>> datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f")
datetime.datetime(2010, 1, 1, 18, 48, 14, 631829)
```
Docs: <http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior>
>
> ...... | Of course, splitting the string *does* work:
```
>>> print s
2010-01-01 18:48:14.631829
>>> time.strptime(s.split('.')[0], "%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2010, tm_mon=1, tm_mday=1, tm_hour=18, tm_min=48, tm_sec=14, tm_wday=4, tm_yday=1, tm_isdst=-1)
>>>
``` |
5,385,238 | I've got a timestamp in a log file with the format like:
```
2010-01-01 18:48:14.631829
```
I've tried the usual suspects like strptime, and no matter what i do, I'm getting that it doesn't match the format I specify. `("%Y-%m-%d %H:%M:%S" OR "%Y-%m-%d %H:%M:%S.%f")`
I've even tried splitting the value by "." so I ... | 2011/03/22 | [
"https://Stackoverflow.com/questions/5385238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669983/"
] | You can use `strptime` like so (Python 2.6+ only):
```
>>> import datetime
>>> s = "2010-01-01 18:48:14.631829"
>>> datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f")
datetime.datetime(2010, 1, 1, 18, 48, 14, 631829)
```
Docs: <http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior>
>
> ...... | The following works for me (Python 2.6):
```
>>> import datetime
>>> string1 = '2010-01-01 18:48:14.631829'
>>> string2 = '2010-01-09 13:04:39.540268'
>>> time1 = datetime.datetime.strptime(string1, '%Y-%m-%d %H:%M:%S.%f')
>>> time2 = datetime.datetime.strptime(string2, '%Y-%m-%d %H:%M:%S.%f')
>>> time2 - time1
dateti... |
27,929,400 | I am trying to make a program in python that will accept an argument of text input, then randomly change each letter to be a different color
This is what I have:
```
color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'];
```
I want to be able to have a program that can let me... | 2015/01/13 | [
"https://Stackoverflow.com/questions/27929400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4450564/"
] | This works for me:
```
from random import choice
color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white']
l = len(color)
str = "Hit Here"
html = ''
for x in str:
html += '[color=' + choice(color) + ']' + x + '[/color]' if len(x.strip()) > 0 else x
print(html)
```
Sample o... | try like this:
```
import random
#console color
W = '\033[0m' # white (normal)
R = '\033[31m' # red
G = '\033[32m' # green
O = '\033[33m' # orange
B = '\033[34m' # blue
P = '\033[35m' # purple
my_color = [W, R, G, O, B, P]
a = raw_input("Enter your text to be colourful: ")
new_text =""
for x in a:
new_te... |
27,929,400 | I am trying to make a program in python that will accept an argument of text input, then randomly change each letter to be a different color
This is what I have:
```
color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'];
```
I want to be able to have a program that can let me... | 2015/01/13 | [
"https://Stackoverflow.com/questions/27929400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4450564/"
] | This works for me:
```
from random import choice
color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white']
l = len(color)
str = "Hit Here"
html = ''
for x in str:
html += '[color=' + choice(color) + ']' + x + '[/color]' if len(x.strip()) > 0 else x
print(html)
```
Sample o... | pip install pygments, then try this:
```
import random
from pygments.console import codes
string='some string here'
print ''.join([random.choice(codes.values())+x+codes['reset'] for x in string])
``` |
27,929,400 | I am trying to make a program in python that will accept an argument of text input, then randomly change each letter to be a different color
This is what I have:
```
color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'];
```
I want to be able to have a program that can let me... | 2015/01/13 | [
"https://Stackoverflow.com/questions/27929400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4450564/"
] | pip install pygments, then try this:
```
import random
from pygments.console import codes
string='some string here'
print ''.join([random.choice(codes.values())+x+codes['reset'] for x in string])
``` | try like this:
```
import random
#console color
W = '\033[0m' # white (normal)
R = '\033[31m' # red
G = '\033[32m' # green
O = '\033[33m' # orange
B = '\033[34m' # blue
P = '\033[35m' # purple
my_color = [W, R, G, O, B, P]
a = raw_input("Enter your text to be colourful: ")
new_text =""
for x in a:
new_te... |
12,135,555 | I am trying to build my first Django project from scratch and am having difficulty setting the background image. I am new to programming in general so forgive me if this is a stupid question.
I have read the documentation [here](https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles) on static file implementati... | 2012/08/27 | [
"https://Stackoverflow.com/questions/12135555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1611337/"
] | Your css file is not rendered by Django template engine and so {{ STATIC\_URL }} is not being replaced. You'll have to use /static/img/IMG\_0002.jpg in the CSS file or move that bit of CSS in your html file's style tag. | Try this
settings.py
```
MEDIA_URL = '/static_media/'
```
urly.py
```
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'^static_media/(?P<path>.*)$',
'serve', {
'document_root': '/path/to/static_media',
'show_indexes': True }),)
```
your css and jquery on te... |
39,675,898 | I am reading [The Hitchhiker’s Guide to Python](http://docs.python-guide.org/en/latest/writing/structure/#mutable-and-immutable-types) and there is a short code snippet
```
foo = 'foo'
bar = 'bar'
foobar = foo + bar # This is good
foo += 'ooo' # This is bad, instead you should do:
foo = ''.join([foo, 'ooo'])
```
... | 2016/09/24 | [
"https://Stackoverflow.com/questions/39675898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/534298/"
] | Is it bad practice?
-------------------
It's reasonable to assume that it isn't bad practice for this example because:
* The author doesn't give any reason. Maybe it's just disliked by him/her.
* Python documentation doesn't mention it's bad practice (from what I've seen).
* `foo += 'ooo'` is just as readable (accord... | If the number of string is small and strings are known in advance, I would go :
```
foo = f"{foo}ooo"
```
Using [f-strings](https://docs.python.org/fr/3/tutorial/inputoutput.html#formatted-string-literals). However, this is valid only since python 3.6. |
73,453,875 | Few days ago I uninstalled and then reinstalled python due to some error related to pip . Since then whenever I start my pc it shows python modify setup window 2 or 3 times [you can see popup here](https://i.stack.imgur.com/nrsLv.png)
Though I can close these windows ; Whenever I open vs code it can be upwards of 10 p... | 2022/08/23 | [
"https://Stackoverflow.com/questions/73453875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19825726/"
] | If there's code I'm likely to use repeatedly (like checking whether a radio button is selected or not), I like to put it in a method so it's easily reusable. This method takes the parent DIV of the radio button and counts the number of SVG circles inside. If there's more than one, the radio button is selected. This way... | Most important thing a circle tag represents the one circle, not the svg tag. So svg tag which looks like selected radiobutton contains two circle tags.
You can measure number of circle tags in svg tag and based on that consider the svg as un/selected.
**Code:**
```
List<WebElement> svgTags = driver.findElements... |
25,504,738 | I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular.
To demonstrate, this is my fixture
```
@yield_fixture
def a_fixture(a_dependency):
do_setup_work()
yield
do... | 2014/08/26 | [
"https://Stackoverflow.com/questions/25504738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440380/"
] | In your situation you can use `display:table` in container(`#option_one_div`) in your example and `display:table-cell` in children elements(`#ldiv`, `#rdiv`) like this:
```
<div style="padding:25px; width:400px;">
<div style="background-color:#bf5b5b;">
<span>Yes</span>
<span>No</span></div>
<div... | use width with float in div
```
<div id="rdiv" style="float:right; background-color: #74d4dd; /* margin-left: 151px; */ padding-left: 20px; width: 210px;padding-right: 20px">
<span>Label of first group of Radio Buttons radio buttons.</span>
</div>
```
[plz check](http://jsfiddle.net/akash4pj... |
25,504,738 | I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular.
To demonstrate, this is my fixture
```
@yield_fixture
def a_fixture(a_dependency):
do_setup_work()
yield
do... | 2014/08/26 | [
"https://Stackoverflow.com/questions/25504738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440380/"
] | use width with float in div
```
<div id="rdiv" style="float:right; background-color: #74d4dd; /* margin-left: 151px; */ padding-left: 20px; width: 210px;padding-right: 20px">
<span>Label of first group of Radio Buttons radio buttons.</span>
</div>
```
[plz check](http://jsfiddle.net/akash4pj... | the main problem is you didn't add width to the `id="rdiv"` and used `margin-left:151px`
when you use some element with float, you have to add its width
```
<div>
<div style="float: left;width: 110px;height: 90px;margin: 5px;">a</div>
<div style="float: left;width: 110px;height: 90px;margin: 5px;">b</div>
... |
25,504,738 | I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular.
To demonstrate, this is my fixture
```
@yield_fixture
def a_fixture(a_dependency):
do_setup_work()
yield
do... | 2014/08/26 | [
"https://Stackoverflow.com/questions/25504738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440380/"
] | In your situation you can use `display:table` in container(`#option_one_div`) in your example and `display:table-cell` in children elements(`#ldiv`, `#rdiv`) like this:
```
<div style="padding:25px; width:400px;">
<div style="background-color:#bf5b5b;">
<span>Yes</span>
<span>No</span></div>
<div... | the total width of the elements (incl. margin/border) can not be greater than the surrounding divs width of 400px else the floating elements will be put into the next line ... see akz's answer for a quick fix |
25,504,738 | I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular.
To demonstrate, this is my fixture
```
@yield_fixture
def a_fixture(a_dependency):
do_setup_work()
yield
do... | 2014/08/26 | [
"https://Stackoverflow.com/questions/25504738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440380/"
] | the total width of the elements (incl. margin/border) can not be greater than the surrounding divs width of 400px else the floating elements will be put into the next line ... see akz's answer for a quick fix | the main problem is you didn't add width to the `id="rdiv"` and used `margin-left:151px`
when you use some element with float, you have to add its width
```
<div>
<div style="float: left;width: 110px;height: 90px;margin: 5px;">a</div>
<div style="float: left;width: 110px;height: 90px;margin: 5px;">b</div>
... |
25,504,738 | I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular.
To demonstrate, this is my fixture
```
@yield_fixture
def a_fixture(a_dependency):
do_setup_work()
yield
do... | 2014/08/26 | [
"https://Stackoverflow.com/questions/25504738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440380/"
] | In your situation you can use `display:table` in container(`#option_one_div`) in your example and `display:table-cell` in children elements(`#ldiv`, `#rdiv`) like this:
```
<div style="padding:25px; width:400px;">
<div style="background-color:#bf5b5b;">
<span>Yes</span>
<span>No</span></div>
<div... | Just remove `float:right`. It will work.
```
<div id="rdiv" style="background-color:#74d4dd; margin-left:151px; padding-left: 20px; padding-right: 20px">
```
[**DEMO**](http://jsfiddle.net/41209azo/2/) |
25,504,738 | I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular.
To demonstrate, this is my fixture
```
@yield_fixture
def a_fixture(a_dependency):
do_setup_work()
yield
do... | 2014/08/26 | [
"https://Stackoverflow.com/questions/25504738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440380/"
] | Just remove `float:right`. It will work.
```
<div id="rdiv" style="background-color:#74d4dd; margin-left:151px; padding-left: 20px; padding-right: 20px">
```
[**DEMO**](http://jsfiddle.net/41209azo/2/) | the main problem is you didn't add width to the `id="rdiv"` and used `margin-left:151px`
when you use some element with float, you have to add its width
```
<div>
<div style="float: left;width: 110px;height: 90px;margin: 5px;">a</div>
<div style="float: left;width: 110px;height: 90px;margin: 5px;">b</div>
... |
25,504,738 | I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular.
To demonstrate, this is my fixture
```
@yield_fixture
def a_fixture(a_dependency):
do_setup_work()
yield
do... | 2014/08/26 | [
"https://Stackoverflow.com/questions/25504738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2440380/"
] | In your situation you can use `display:table` in container(`#option_one_div`) in your example and `display:table-cell` in children elements(`#ldiv`, `#rdiv`) like this:
```
<div style="padding:25px; width:400px;">
<div style="background-color:#bf5b5b;">
<span>Yes</span>
<span>No</span></div>
<div... | the main problem is you didn't add width to the `id="rdiv"` and used `margin-left:151px`
when you use some element with float, you have to add its width
```
<div>
<div style="float: left;width: 110px;height: 90px;margin: 5px;">a</div>
<div style="float: left;width: 110px;height: 90px;margin: 5px;">b</div>
... |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | The last time I saw a similar error it was because I was using the wrong version of `npm` and/or `node` for one of my dependencies. Try upgrading these and try again.
Before trying again remove your `node_modules` directory.
You may need to investigate what versions of `npm` and `node` your dependencies need. You c... | Install python2 and try running `npm install` again.
This approach worked for me. |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | Based on the **node-gyp README**, update npm `npm i npm -g`, and will bring in a newer version of node-gyp.
Hint: if you are on **windows** perform `npm install --global --production windows-build-tools` from an elevated PowerShell or CMD.exe (run as Administrator). | I am using yarn so I just ran `yarn global add node-gyp` to globally install `node-gyp` without using npm and it worked. I'm no more facing the error
For those using npm can do it using `npm install -g node-gyp`.
Make sure you know that running these commands will globally install node-gyp in your environment, probab... |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | The error messages have caused confusion for me and have not helped me in resolving the errors completely.
The [README.md](https://github.com/nodejs/node-gyp/blob/master/README.md "README.md") for [node-gyp](https://github.com/nodejs/node-gyp "node-gyp") project does a better job of listing down the installation instr... | For Windows 8 or 10:
Assuming node and npm installed already.
My node and npm version (At the time of writing this answer) :
node : 8.9.4
npm : 5.6.0
1. First install [python 2.x](https://www.python.org/downloads/release/python-2714/)
2. Make sure it is available on path
3. Install
[Visual Studio Installer](https:... |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | Try to install again with `--force option`:
```
npm install --force
```
If this doesn't work try to update npm globally:
```
npm update -g npm
```
and try again with the `--force` option. | Try delete current node\_modules folder and run Command as regular user, non administrator or root |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | If you are using "node-sass", upgrade it to version 5.0.0, make sure that you have build tools 2017 and Python 3 installed, and issue these commands prior to npm install
`npm config set msvs_version 2017`
`npm config set python npm config set python C:\Users\username\AppData\Local\Programs\Python\Python39\python.exe` | I was stuck with the same error on my windows machine after a lot of troubleshooting with various stack answers I was not able to fix it, later did the following which made it work properly now.
1. npm cache clear --force
2. open explorer in address bar paste %appdata%, then delete the folders npm,npm-cache
3. uninsta... |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | Try to install again with `--force option`:
```
npm install --force
```
If this doesn't work try to update npm globally:
```
npm update -g npm
```
and try again with the `--force` option. | Post my solution here in case anyone like me using **Windows 10** still has the error after installing many Microsoft associated build tools.
All you need are:
>
> Windows 10 64 bit
>
>
> python 2.7.x
>
>
> [Visual Studio 2013](https://www.microsoft.com/en-gb/download/details.aspx?id=44914)
>
>
>
I've tried ... |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | Based on the **node-gyp README**, update npm `npm i npm -g`, and will bring in a newer version of node-gyp.
Hint: if you are on **windows** perform `npm install --global --production windows-build-tools` from an elevated PowerShell or CMD.exe (run as Administrator). | Delete **package-lock.json**
Then restart your machine(if there were changes made to take effect)
then run
```
npm install --legacy-peer-deps
``` |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | If you are using "node-sass", upgrade it to version 5.0.0, make sure that you have build tools 2017 and Python 3 installed, and issue these commands prior to npm install
`npm config set msvs_version 2017`
`npm config set python npm config set python C:\Users\username\AppData\Local\Programs\Python\Python39\python.exe` | Edit or remove your package-lock.json and run npm install |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | Try delete current node\_modules folder and run Command as regular user, non administrator or root | I am using yarn so I just ran `yarn global add node-gyp` to globally install `node-gyp` without using npm and it worked. I'm no more facing the error
For those using npm can do it using `npm install -g node-gyp`.
Make sure you know that running these commands will globally install node-gyp in your environment, probab... |
33,896,511 | We are having problems running **"npm install"** on our project. A certain file cannot be found :
```
fatal error C1083: Cannot open include file: 'windows.h'
```
It appears to be coming from the **node-gyp** module :
>
> c:\Program
> Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo
> ad\_h... | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1022330/"
] | for this solved it ( OS X ):
```sh
rm -rf ~/.node_gyp and
sudo npm install -g [email protected]
cd /usr/local/lib
sudo ln -s ../../lib/libSystem.B.dylib libgcc_s.10.5.dylib
brew install gcc
npm install
``` | I was stuck with the same error on my windows machine after a lot of troubleshooting with various stack answers I was not able to fix it, later did the following which made it work properly now.
1. npm cache clear --force
2. open explorer in address bar paste %appdata%, then delete the folders npm,npm-cache
3. uninsta... |
16,007,094 | I'm having problems with this method in python called findall. I'm accessing a web pages HTML and trying to return the name of a product in this case `'bread'` and print it out to the console. | 2013/04/15 | [
"https://Stackoverflow.com/questions/16007094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2051382/"
] | Don't use regex for HTML parsing.
There are a few solutions. I suggest BeautifulSoup (<http://www.crummy.com/software/BeautifulSoup/>)
Having said so, however, in this particular case, RE will suffice. Just relax it a notch. There might be more or less spaces or maybe those are tabs. So instead of literal spaces use t... | In case you still want to use regexps, here's a working one for your case:
```
product = re.findall(r'<br>\s*Item:\s+is\s+in\s+lane 12\s+(\w*)[^<]*<br>', content)
```
It takes into account DSM's space flexibility suggestion and non-letters after `(\w*)` that might appear before `<br>`. |
21,790,203 | I want to remove double open quotes and double close quotes from the text.
By Double opening quotes i mean **“** not **"**
I am trying to do it with python. But is unable to read **“** | 2014/02/14 | [
"https://Stackoverflow.com/questions/21790203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3288929/"
] | how about...
```
>>> s = "“hello“"
>>> s.replace('“','')
'hello'
>>>
``` | Well, since you didn't want to say how you initially did it in excel, here's how you remove those:
* Option 1:
Use the Find/Replace with find `“` and replace with nothing then find `”` and replace with nothing.
* Option 2:
In excel, use `CHAR(147)` to have `“` and `CHAR(148)` to have `”`. Then `SUBSTITUTE` to remov... |
60,229,299 | If you're a python coder you may encounter looking for a way to comments your code better on subcategory code. My meaning by the subcategory code is you may have blocks of codes and then again blocks of codes that relate to the previous block. Here is an example (pay more attention to comments):
```
# Drink some water... | 2020/02/14 | [
"https://Stackoverflow.com/questions/60229299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7643771/"
] | I think what you will find, is if you run your application, it will log an error like `requried a single bean but 2 were found`.
What you can do however is remove the ambiguity using the @Qualifier where you need it injected and naming your bean definitions, i.e. for your example.
```
@Configuration
public class Con... | Actually, you cannot have both configuration classes, because you'll get a bean name conflict. To fix this, rename the method name:
```
@Bean
@Qualifier("restTemplateB")
public RestTemplate restTemplateB() {
RestTemplate restTemplate = new RestTemplate();
//setting some restTemplate properties... |
60,229,299 | If you're a python coder you may encounter looking for a way to comments your code better on subcategory code. My meaning by the subcategory code is you may have blocks of codes and then again blocks of codes that relate to the previous block. Here is an example (pay more attention to comments):
```
# Drink some water... | 2020/02/14 | [
"https://Stackoverflow.com/questions/60229299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7643771/"
] | **Case1:** Same method (bean) names in configuration classes.
```
@Configuration
public class ConfigurationA {
@Bean
@Qualifier("restTemplateA")
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
//setting some restTemplate properties
return rest... | Actually, you cannot have both configuration classes, because you'll get a bean name conflict. To fix this, rename the method name:
```
@Bean
@Qualifier("restTemplateB")
public RestTemplate restTemplateB() {
RestTemplate restTemplate = new RestTemplate();
//setting some restTemplate properties... |
72,587,334 | In .Net c# there is a function Task.WhenAll that can take a list of tasks to await them. What should I use in python? I am trying to do the same with this:
```
tasks = ... #list of coroutines
for task in tasks:
await task
``` | 2022/06/11 | [
"https://Stackoverflow.com/questions/72587334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11660685/"
] | After adding tasks to a list, you should use [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) that gives coroutines as an argument list and executes them asynchronously. Also, you could use [`asyncio.create_task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_t... | Use [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) if you're on Python 3.7 or above. From the docs:
>
> Run awaitable objects in the aws sequence concurrently.
> If any awaitable in aws is a coroutine, it is automatically scheduled as a Task.
> If all awaitables are completed s... |
16,808,349 | I've installed following packages <https://github.com/zacharyvoase/django-postgres> via pip and virtualenv.:
```
pip install git+https://github.com/zacharyvoase/django-postgres.git
```
It was installed succesfully. I used it in my model(As described in its documentaion)
```
from django.db import models
import djang... | 2013/05/29 | [
"https://Stackoverflow.com/questions/16808349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1089202/"
] | In order for management commands to work, the app has to be added to `INSTALLED_APPS`. However, a basic problem that you have is that the module doesn't support [`ENUM`](http://www.postgresql.org/docs/9.1/static/datatype-enum.html) yet. Its still a work in progress. | After adding new app:
1. add app to INSTALLED\_APPS in settings.py
2. run python manage.py syncdb
3. add urls to urls.py
Perhaps you should go through this (again?) <https://docs.djangoproject.com/en/dev/intro/tutorial01/> |
32,533,820 | ``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list.
example\_List = [1,2,2,3,4]
It should return True. So far I have this
```
def checkList(List1):
for i in range(len(List1 - 1)):
if ... | 2015/09/12 | [
"https://Stackoverflow.com/questions/32533820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The issue is with this part:
```
len(List1 - 1)
```
You should change it into
```
len(List1) - 1
```
And you should use the same case for variable List1.
Change
```
if list1[i] == 2 and list1[i+1] == 2:
```
to:
```
if List1[i] == 2 and List1[i+1] == 2:
``` | Replace
```
len(List1 - 1)
```
for
```
len(List1) - 1
``` |
32,533,820 | ``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list.
example\_List = [1,2,2,3,4]
It should return True. So far I have this
```
def checkList(List1):
for i in range(len(List1 - 1)):
if ... | 2015/09/12 | [
"https://Stackoverflow.com/questions/32533820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The issue is with this part:
```
len(List1 - 1)
```
You should change it into
```
len(List1) - 1
```
And you should use the same case for variable List1.
Change
```
if list1[i] == 2 and list1[i+1] == 2:
```
to:
```
if List1[i] == 2 and List1[i+1] == 2:
``` | first of all, the error you are getting is because of
```
for i in range(len(List1 - 1)):
```
this should be
```
for i in range(len(List1) - 1)):
```
here is an example of code you can use
```
def checkList(List1):
for i in range(len(List1) - 1)):
if List1(i) == List(i+1):
return True
``... |
32,533,820 | ``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list.
example\_List = [1,2,2,3,4]
It should return True. So far I have this
```
def checkList(List1):
for i in range(len(List1 - 1)):
if ... | 2015/09/12 | [
"https://Stackoverflow.com/questions/32533820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The issue is with this part:
```
len(List1 - 1)
```
You should change it into
```
len(List1) - 1
```
And you should use the same case for variable List1.
Change
```
if list1[i] == 2 and list1[i+1] == 2:
```
to:
```
if List1[i] == 2 and List1[i+1] == 2:
``` | Here is also a one liner:
```
def check( l,i ): return i in l and l[-1] != i and l[l.index(i)+1] == i
```
Admittedly not the nicest one but I guess still better than the nested loops |
32,533,820 | ``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list.
example\_List = [1,2,2,3,4]
It should return True. So far I have this
```
def checkList(List1):
for i in range(len(List1 - 1)):
if ... | 2015/09/12 | [
"https://Stackoverflow.com/questions/32533820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Replace
```
len(List1 - 1)
```
for
```
len(List1) - 1
``` | first of all, the error you are getting is because of
```
for i in range(len(List1 - 1)):
```
this should be
```
for i in range(len(List1) - 1)):
```
here is an example of code you can use
```
def checkList(List1):
for i in range(len(List1) - 1)):
if List1(i) == List(i+1):
return True
``... |
32,533,820 | ``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list.
example\_List = [1,2,2,3,4]
It should return True. So far I have this
```
def checkList(List1):
for i in range(len(List1 - 1)):
if ... | 2015/09/12 | [
"https://Stackoverflow.com/questions/32533820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Here is also a one liner:
```
def check( l,i ): return i in l and l[-1] != i and l[l.index(i)+1] == i
```
Admittedly not the nicest one but I guess still better than the nested loops | first of all, the error you are getting is because of
```
for i in range(len(List1 - 1)):
```
this should be
```
for i in range(len(List1) - 1)):
```
here is an example of code you can use
```
def checkList(List1):
for i in range(len(List1) - 1)):
if List1(i) == List(i+1):
return True
``... |
50,205,683 | I'm using Ubuntu 14.04 with Django 2.0.5 with Django Cookiecutter. I am trying to start a Django server on DigitalOcean and trying to bind gunicorn to 0.0.0.0:8000. python manage.py runserver works fine, but the issue is that it says it can't import environ. Any tips are greatly appreciated, Thanks.
I've ran
>
> pip... | 2018/05/07 | [
"https://Stackoverflow.com/questions/50205683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907366/"
] | You need to run your manage.py file with the local settings
```
python manage.py runserver --settings=config.settings.production
``` | you need to set environment variables for you database :
if you are on linux machine :
```
$ export DATABASE_URL=postgres://postgres:<password>@127.0.0.1:5432/<DB name given to createdb>
```
cookiecutter doc can help you more for all this :
link : <https://cookiecutter-django.readthedocs.io/en/latest/developing-loc... |
22,882,125 | I updated my system to Mavericks and I have a python code using pgdb. How can I install pgdb on my new mac?
I tried
```
sudo pip install git+git://github.com/cancerhermit/pgdb.py.git
```
And
```
sudo pip install pgdb
```
And
```
brew install pgdb
```
And I have even tried to install it from PyCharm directly (... | 2014/04/05 | [
"https://Stackoverflow.com/questions/22882125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/762435/"
] | **Assuming that you want to:**
* Replace lower-case letters with lower-case letters
* Replace upper-case letters with upper-case letters
* Leave spaces and any other non-alphabetic characters as is
---
```
void encrypt (std::string &e)
{
int size = e.size();
for (int i=0; i<size; i++)
{
char c = ... | You could do something like this:
```
char _character='X';
int _value=static_cast<int>(_character);
if(_value!=32)//not space
{
int _newValue=((_value+11)%90);
(_newValue<65)?_newValue+=65:_newValue+=0;
char _newCharacter=static_cast<char>(_newValue);
}
``` |
38,958,697 | I am working on script in python with BeautifulSoup to find some data from html. I got a stacked and so much confused, my brain stopped working, I don't have any idea how to scrape full address of these elements:
```
<li class="spacer">
<span>Location:</span>
<br>Some Sample Street<br>
Abbeville, AL 00000
</li>
```
... | 2016/08/15 | [
"https://Stackoverflow.com/questions/38958697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6285753/"
] | You can choose names for the nodes in your model by passing the optional `name="myname"` argument to pretty much any Tensorflow operator that builds a node. Tensorflow will pick names for graph nodes automatically if you don't specify them, but if you want to identify those nodes to a tool like freeze\_graph.py, then i... | You can get all of the node names in your model with something like:
```py
node_names = [node.name for node in tf.get_default_graph().as_graph_def().node]
```
Or with restoring the graph:
```py
saver = tf.train.import_meta_graph(/path/to/meta/graph)
sess = tf.Session()
saver.restore(sess, /path/to/checkpoints)
grap... |
45,489,388 | I am working on a Python/Django project, and we need to use two databases. Following the documentation I added a second database like this:
```
DATABASE_URL = os.getenv('DATABASE_URL', 'postgres://*******:********@aws-us-***********:*****/*****')
CURRENCIES_URL = os.getenv('CURRENCIES_URL', 'postgres://*******:*******... | 2017/08/03 | [
"https://Stackoverflow.com/questions/45489388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7776359/"
] | There is a small but fatal typo in your code. It should be `django.db.connections` instead of your `connection` (you have not specified where that comes from).
Quoting from <https://docs.djangoproject.com/en/1.11/topics/db/sql/#executing-custom-sql-directly>
>
> If you are using more than one database, you can use
>... | You can't access `connection` using bracket notation.
Perhaps this will work:
```
currencies = DATABASES['currencies'].cursor()
``` |
52,306,134 | I am pretty new to Django. I think I cannot run django application as sudo since all pip related modules are installed for the user and not for the sudo user. So, it's a kind of basic question like how do I run django app that can listen for port 80 as well as port 443.
So, far I have tried following option - i.e pre-... | 2018/09/13 | [
"https://Stackoverflow.com/questions/52306134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10318265/"
] | Ideally module should go into your site packages. Do you see it there?
If its there then check your package path. You package may be steplib, but have you checked if you are importing right package and module there. For example within your steplib folder you might have additional package and module within it. Say pack... | Did you install the package in the python directory under Lib? |
23,909,292 | I am new to mqtt and still discovering this interesting protocol.
I want to create a client in python that publishes every 10 seconds a message. Until now I succeed to publish only one message and keep the client connected to the broker.
How can I make the publishing part a loop ?
Below is my client:
```
import mosq... | 2014/05/28 | [
"https://Stackoverflow.com/questions/23909292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3683176/"
] | You can sleep between calls:
```
import mosquitto
import time # import time module
mqttc=mosquitto.Mosquitto("ioana")
mqttc.connect("127.0.0.1",8000,60,True)
mqttc.subscribe("test/", 2)
while mqttc.loop() == 0:
mqttc.publish("test","Hello")
time.sleep(10)# sleep for 10 seconds before next call
``` | I would suggest:
```
import paho.mqtt.client as mqtt # mosquitto.py is deprecated
import time
mqttc = mqtt.Client("ioana")
mqttc.connect("127.0.0.1", 1883, 60)
#mqttc.subscribe("test/", 2) # <- pointless unless you include a subscribe callback
mqttc.loop_start()
while True:
mqttc.publish("test","Hello")
time.... |
62,287,967 | I have just started python. I am trying to web scrape a website to fetch the price and title from it. I have gone through multiple tutorial and blog, the most common libraries are beautiful soup and `scrapy`. `My question is that is there any way to scrape a website without using any library?`
If there is a way to scra... | 2020/06/09 | [
"https://Stackoverflow.com/questions/62287967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instead of using `scrapy` you can use `urllib`.
Instead of `beautifulsoup` you can use `regex`.
But `scrapy` and `beautifulsoup` do your life easier.
`Scrapy`, not easy library so you can use `requests` or `urllib`. | i think the best, popular and easy to learn and use libraries in python web scraping are requests, lxml and BeautifulSoup which has the latest version is bs4 in summary ‘Requests’ lets us make HTML requests to the website’s server for retrieving the data on its page. Getting the HTML content of a web page is the first ... |
62,287,967 | I have just started python. I am trying to web scrape a website to fetch the price and title from it. I have gone through multiple tutorial and blog, the most common libraries are beautiful soup and `scrapy`. `My question is that is there any way to scrape a website without using any library?`
If there is a way to scra... | 2020/06/09 | [
"https://Stackoverflow.com/questions/62287967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instead of using `scrapy` you can use `urllib`.
Instead of `beautifulsoup` you can use `regex`.
But `scrapy` and `beautifulsoup` do your life easier.
`Scrapy`, not easy library so you can use `requests` or `urllib`. | I think it's not possible to scrap websites without using any library. You can refer bellow the blog to learn more about web scraping using python. here explain how anyone can scrap websites using python in an easy manner.
<https://spurqlabs.com/how-to-do-web-scraping-crawling-using-python-with-selenium/> |
62,287,967 | I have just started python. I am trying to web scrape a website to fetch the price and title from it. I have gone through multiple tutorial and blog, the most common libraries are beautiful soup and `scrapy`. `My question is that is there any way to scrape a website without using any library?`
If there is a way to scra... | 2020/06/09 | [
"https://Stackoverflow.com/questions/62287967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | i think the best, popular and easy to learn and use libraries in python web scraping are requests, lxml and BeautifulSoup which has the latest version is bs4 in summary ‘Requests’ lets us make HTML requests to the website’s server for retrieving the data on its page. Getting the HTML content of a web page is the first ... | I think it's not possible to scrap websites without using any library. You can refer bellow the blog to learn more about web scraping using python. here explain how anyone can scrap websites using python in an easy manner.
<https://spurqlabs.com/how-to-do-web-scraping-crawling-using-python-with-selenium/> |
73,071,481 | **edit** using utf-16 seems to get me closer in the right direction, but I have csv values that include commas such as "one example value is a description, which is long and can include commas, and quotes"
So with my current code:
```
filepath="csv_input/frups.csv"
rows = []
with open(filepath, encoding='utf-16') as... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73071481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18283635/"
] | No token expiration date is there for security reasons.
If someone steals a token which has no expiration date that token will be able to be used forever. This can be extremely dangerous. Especially if the token is valuable.
If a token has expired, the token should be refreshed and then you can request again. | I would say your frontend should manage valid token state properly. Good auth libs have config where you can define when before token expiration is token refreshed. So it should be configured in that way that token won't be never expired on the backend side. |
11,203,167 | I'm building a site in django that interfaces with a large program written in R, and I would like to have a button on the site that runs the R program. I have that working, using `subprocess.call()`, but, as expected, the server does not continue rendering the view until `subprocess.call()` returns. As this program cou... | 2012/06/26 | [
"https://Stackoverflow.com/questions/11203167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1134853/"
] | ```
subprocess.Popen(['R', 'CMD', 'BATCH', '/path/to/script.R'])
```
The process will be started asynchronously.
Example:
```
$ cat 1.py
import time
import subprocess
print time.time()
subprocess.Popen(['sleep', '1000'])
print time.time()
$ python 1.py
1340698384.08
1340698384.08
```
You must note that the chil... | You may use a wrapper for subprocess.call(), that wrapper would have its own thread within which it will call subprocess.call() method. |
58,455,611 | Currently I’m working on a corpus/dataset. It’s in xml format as you can see the picture below. I’m facing a problem.
I want to access all **‘ne’** elements one by one as shown in below picture. Then I want to access the **text of the ‘W’ elements** which are inside the ‘ne’ elements. Then I want to **concatenate** thy... | 2019/10/18 | [
"https://Stackoverflow.com/questions/58455611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5067040/"
] | The expression `let rec c_write = "printf(\" %d \");\n"` is not a function. It is a value of type `string` which is bound to a variable named `c_write`. So you're not using any I/O functions in your code.
When entered in the interactive toplevel, this value is printed by the interpreter evaluation loop for user conven... | Since you are somehow using the toplevel printer for printing, and that you somehow needs a very specific format, you need to install a custom printer.
The following would work:
```
# #install_printer Format.pp_print_string;;
# " This \" is not escaped " ;;
- : string = This " is not escaped
```
However, it seems ... |
1,460,559 | I'm using Django's `render_to_response` to write data out to an html page, but I'd also like that render\_ to \_response call to load a python dictionary into a javascript associative array. What's the best way to do this? | 2009/09/22 | [
"https://Stackoverflow.com/questions/1460559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72106/"
] | Convert it to JSON and include, in your template.html, inside a `<script>` tag, something like
```
var my_associative_array = {{ json_data }}
```
after having JSON-encoded your Python dict into a string and put it in the context using key `json_data`. | What does that mean exactly? If you mean you think data in the template is in JavaScript terms, it isn't: You can use python objects in the template directly. If you mean, how do I embed a JSON literal from a Python dictionary or list into my template: Encode it with simplejson, which is included with Django.
But, you... |
1,460,559 | I'm using Django's `render_to_response` to write data out to an html page, but I'd also like that render\_ to \_response call to load a python dictionary into a javascript associative array. What's the best way to do this? | 2009/09/22 | [
"https://Stackoverflow.com/questions/1460559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72106/"
] | Vinay Sajip is close however you add to add the safe filter to avoid django from auto escaping the json data, so this would work (there are other ways to stop the auto escaping but this is the easiest one):
```
var my_associative_array = {{ json_data|safe }}
``` | What does that mean exactly? If you mean you think data in the template is in JavaScript terms, it isn't: You can use python objects in the template directly. If you mean, how do I embed a JSON literal from a Python dictionary or list into my template: Encode it with simplejson, which is included with Django.
But, you... |
1,460,559 | I'm using Django's `render_to_response` to write data out to an html page, but I'd also like that render\_ to \_response call to load a python dictionary into a javascript associative array. What's the best way to do this? | 2009/09/22 | [
"https://Stackoverflow.com/questions/1460559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72106/"
] | Vinay Sajip is close however you add to add the safe filter to avoid django from auto escaping the json data, so this would work (there are other ways to stop the auto escaping but this is the easiest one):
```
var my_associative_array = {{ json_data|safe }}
``` | Convert it to JSON and include, in your template.html, inside a `<script>` tag, something like
```
var my_associative_array = {{ json_data }}
```
after having JSON-encoded your Python dict into a string and put it in the context using key `json_data`. |
20,658,451 | I've opened Aptana Studio 3 (Ubuntu 10.04) just like I did it hundreds times before (last time was yesterday). But this time I see EMPTY workspace. No projects. No error messages. Nothing. Screen attached.
I have not changed anything since the last time I used Aptana Studio (yesterday). I have not switched workspace ... | 2013/12/18 | [
"https://Stackoverflow.com/questions/20658451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367181/"
] | I had this problem and after freaking out I looked around and found
File -> Switch Workspace
and choosing my workspace loaded everything as normal. | I solved the problem by manually adding the projects back to workspace. Wasn't that bad. I still don't know why they disappeared. |
63,442,415 | I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size.
Ho... | 2020/08/16 | [
"https://Stackoverflow.com/questions/63442415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12946401/"
] | Qt Stylesheets
--------------
This is probably the easiest way to do in your situation, you are really trying to apply a specific "style" to all your QLabels. You can apply a style to your whole application, or a specific window, and this will affect all children that match the selectors.
So in your case, to apply to... | Completing Adrien's answer, you can use `QFont` class and perform `.setFont()` method for every button.
```py
my_font = QFont("Times New Roman", 12)
my_button.setFont(my_font)
```
Using this class you can also change some font parameters, see <https://doc.qt.io/qt-5/qfont.html>
Yeah, documentation for C++ is okay t... |
63,442,415 | I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size.
Ho... | 2020/08/16 | [
"https://Stackoverflow.com/questions/63442415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12946401/"
] | To change the font of all QLabels then there are several options:
* Use Qt StyleSheet
```css
app.setStyleSheet("QLabel{font-size: 18pt;}")
```
* Use [`QApplication::setFont()`](https://doc.qt.io/qt-5/qapplication.html#setFont)
```py
custom_font = QFont()
custom_font.setWeight(18);
QApplication.setFont(custom_font, ... | Qt Stylesheets
--------------
This is probably the easiest way to do in your situation, you are really trying to apply a specific "style" to all your QLabels. You can apply a style to your whole application, or a specific window, and this will affect all children that match the selectors.
So in your case, to apply to... |
63,442,415 | I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size.
Ho... | 2020/08/16 | [
"https://Stackoverflow.com/questions/63442415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12946401/"
] | While the provided answers should have already given you enough suggestions, I'd like to add some insight.
Are there python sources for Qt?
================================
First of all, you cannot find "the class written in python", because (luckily) there's none. PyQt is a [*binding*](https://en.wikipedia.org/wiki/... | Qt Stylesheets
--------------
This is probably the easiest way to do in your situation, you are really trying to apply a specific "style" to all your QLabels. You can apply a style to your whole application, or a specific window, and this will affect all children that match the selectors.
So in your case, to apply to... |
63,442,415 | I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size.
Ho... | 2020/08/16 | [
"https://Stackoverflow.com/questions/63442415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12946401/"
] | To change the font of all QLabels then there are several options:
* Use Qt StyleSheet
```css
app.setStyleSheet("QLabel{font-size: 18pt;}")
```
* Use [`QApplication::setFont()`](https://doc.qt.io/qt-5/qapplication.html#setFont)
```py
custom_font = QFont()
custom_font.setWeight(18);
QApplication.setFont(custom_font, ... | Completing Adrien's answer, you can use `QFont` class and perform `.setFont()` method for every button.
```py
my_font = QFont("Times New Roman", 12)
my_button.setFont(my_font)
```
Using this class you can also change some font parameters, see <https://doc.qt.io/qt-5/qfont.html>
Yeah, documentation for C++ is okay t... |
63,442,415 | I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size.
Ho... | 2020/08/16 | [
"https://Stackoverflow.com/questions/63442415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12946401/"
] | While the provided answers should have already given you enough suggestions, I'd like to add some insight.
Are there python sources for Qt?
================================
First of all, you cannot find "the class written in python", because (luckily) there's none. PyQt is a [*binding*](https://en.wikipedia.org/wiki/... | Completing Adrien's answer, you can use `QFont` class and perform `.setFont()` method for every button.
```py
my_font = QFont("Times New Roman", 12)
my_button.setFont(my_font)
```
Using this class you can also change some font parameters, see <https://doc.qt.io/qt-5/qfont.html>
Yeah, documentation for C++ is okay t... |
18,048,232 | I get satchmo to try, but I have a great problem at first try, and I don't understand whats wrong.
When I making `$ python clonesatchmo.py` into clear django project, it trows an error:
```
$ python clonesatchmo.py
Creating the Satchmo Application
Customizing the files
Performing initial data synching
Traceback (most ... | 2013/08/04 | [
"https://Stackoverflow.com/questions/18048232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768419/"
] | Replace the contents of manage.py with the following (from a new django 1.6 project).
```
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<app>.settings")
from django.core.management import execute_from_command_line
execute_from_comm... | `execute_manager` was put on the deprecation path as part of the project layout refactor in Django 1.4 <https://docs.djangoproject.com/en/1.4/releases/1.4/#django-core-management-execute-manager>. Per the deprecation policy that means that the code for `execute_manager` has been completely removed in 1.6. If you are se... |
58,176,203 | In python, I have gotten quite used to container objects having truthy behavior when they are populated, and falsey behavior when they are not:
```py
# list
a = []
not a
True
a.append(1)
not a
False
# deque
from collections import deque
d = deque()
not d
True
d.append(1)
not d
False
# and so on
```
However, [que... | 2019/09/30 | [
"https://Stackoverflow.com/questions/58176203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7867968/"
] | According to the definition of the [truth value testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) procedure, the behavior is expected:
>
> Any object can be tested for truth value, for use in an if or while
> condition or as operand of the Boolean operations below.
>
>
> By default, an ... | I'm going to leave the accepted answer as is, but as far as I can tell, the reason is that `if _queue: # do something` *would* be a race condition, since `Queue` is designed to be passed between threads and therefore possesses dubious state as far as tasks go.
From the source:
```py
class Queue:
~snip~
def q... |
39,367,963 | I did python script:
```
from string import punctuation
from collections import Counter
import urllib
from stripogram import html2text
myurl = urllib.urlopen("https://www.google.co.in/?gfe_rd=cr&ei=v-PPV5aYHs6L8Qfwwrlg#q=samsung%20j7")
html_string = myurl.read()
text = html2text( html_stri... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39367963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6708233/"
] | What do you mean with "webpage text"?
It seems you don't want the full HTML-File. If you just want the text you see in your browser, that is not so easily solvable, as the parsing of a HTML-document can be very complex, especially with JavaScript-rich pages.
That starts with assessing if a String between "<" and ">" i... | ```
import urllib
urllib.urlretrieve("http://www.example.com/test.html", "test.txt")
``` |
39,367,963 | I did python script:
```
from string import punctuation
from collections import Counter
import urllib
from stripogram import html2text
myurl = urllib.urlopen("https://www.google.co.in/?gfe_rd=cr&ei=v-PPV5aYHs6L8Qfwwrlg#q=samsung%20j7")
html_string = myurl.read()
text = html2text( html_stri... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39367963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6708233/"
] | You dont need to write any hard algorithms to extract data from search result. Google has a API to do this.
Here is an example:
<https://github.com/google/google-api-python-client/blob/master/samples/customsearch/main.py>
But to use it, first you must to register in google for API Key.
All information you ca... | ```
import urllib
urllib.urlretrieve("http://www.example.com/test.html", "test.txt")
``` |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | While `.get()` is a nice idiom, it's slower than `if/else` (and slower than `try/except` if presence of the key in the dictionary can be expected most of the time):
```
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10")
0.07691968797894333
>>> timeit.timeit(setup... | (this is a late answer)
An alternative is to subclass the `dict` class and implement the [`__missing__()`](https://docs.python.org/3/reference/datamodel.html?highlight=__missing__#object.__missing__) method, like this:
```
class ConnectionDetails(dict):
def __missing__(self, key):
if key == 'host':
... |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | Like this:
```
host = connectionDetails.get('host', someDefaultValue)
``` | You can use a lamba function for this as a one-liner. Make a new object `connectionDetails2` which is accessed like a function...
```
connectionDetails2 = lambda k: connectionDetails[k] if k in connectionDetails.keys() else "DEFAULT"
```
Now use
```
connectionDetails2(k)
```
instead of
```
connectionDetails[k]... |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | This is not exactly the question asked for but there is a method in python dictionaries: `dict.setdefault`
```py
host = connectionDetails.setdefault('host',someDefaultValue)
```
However this method sets the value of `connectionDetails['host']` to `someDefaultValue` if key `host` is not already defined, unlike wh... | You can use a lamba function for this as a one-liner. Make a new object `connectionDetails2` which is accessed like a function...
```
connectionDetails2 = lambda k: connectionDetails[k] if k in connectionDetails.keys() else "DEFAULT"
```
Now use
```
connectionDetails2(k)
```
instead of
```
connectionDetails[k]... |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | Like this:
```
host = connectionDetails.get('host', someDefaultValue)
``` | Testing @Tim Pietzcker's suspicion about the situation in PyPy (5.2.0-alpha0) for Python 3.3.5, I find that indeed both `.get()` and the `if`/`else` way perform similar. Actually it seems that in the if/else case there is even only a single lookup if the condition and the assignment involve the same key (compare with t... |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | While `.get()` is a nice idiom, it's slower than `if/else` (and slower than `try/except` if presence of the key in the dictionary can be expected most of the time):
```
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10")
0.07691968797894333
>>> timeit.timeit(setup... | Testing @Tim Pietzcker's suspicion about the situation in PyPy (5.2.0-alpha0) for Python 3.3.5, I find that indeed both `.get()` and the `if`/`else` way perform similar. Actually it seems that in the if/else case there is even only a single lookup if the condition and the assignment involve the same key (compare with t... |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | You can also use the [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) like so:
```
from collections import defaultdict
a = defaultdict(lambda: "default", key="some_value")
a["blabla"] => "default"
a["key"] => "some_value"
```
You can pass any ordinary function instead of la... | You can use `dict.get()` for default values.
```
d = {"a" :1, "b" :2}
x = d.get("a",5)
y = d.get("c",6)
# This will give
# x = 1, y = 6
# as the result
```
Since "a" is in the keys, `x = d.get("a",5)` will return associated value `1`. Since "c" is not in the keys, `y = d.get("c",6)` will return the default value `6... |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | You can also use the [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) like so:
```
from collections import defaultdict
a = defaultdict(lambda: "default", key="some_value")
a["blabla"] => "default"
a["key"] => "some_value"
```
You can pass any ordinary function instead of la... | You can use a lamba function for this as a one-liner. Make a new object `connectionDetails2` which is accessed like a function...
```
connectionDetails2 = lambda k: connectionDetails[k] if k in connectionDetails.keys() else "DEFAULT"
```
Now use
```
connectionDetails2(k)
```
instead of
```
connectionDetails[k]... |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | Like this:
```
host = connectionDetails.get('host', someDefaultValue)
``` | I am sure that all these answers are ok but it shows that there is no 'nice' way of doing this. I use dictionaries instead of case statements all the time and to add a default clause I just call the following function:
```
def choose(choise, choises, default):
"""Choose a choice from the choises given
"""
... |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | For multiple different defaults try this:
```
connectionDetails = { "host": "www.example.com" }
defaults = { "host": "127.0.0.1", "port": 8080 }
completeDetails = {}
completeDetails.update(defaults)
completeDetails.update(connectionDetails)
completeDetails["host"] # ==> "www.example.com"
completeDetails["port"] # =... | I am sure that all these answers are ok but it shows that there is no 'nice' way of doing this. I use dictionaries instead of case statements all the time and to add a default clause I just call the following function:
```
def choose(choise, choises, default):
"""Choose a choice from the choises given
"""
... |
9,358,983 | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | 2012/02/20 | [
"https://Stackoverflow.com/questions/9358983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940208/"
] | Like this:
```
host = connectionDetails.get('host', someDefaultValue)
``` | For multiple different defaults try this:
```
connectionDetails = { "host": "www.example.com" }
defaults = { "host": "127.0.0.1", "port": 8080 }
completeDetails = {}
completeDetails.update(defaults)
completeDetails.update(connectionDetails)
completeDetails["host"] # ==> "www.example.com"
completeDetails["port"] # =... |
15,728,081 | I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database.
The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; tha... | 2013/03/31 | [
"https://Stackoverflow.com/questions/15728081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1929999/"
] | In case you feel that Celery is a bit oversized for your needs you could also define a [custom management command](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) that lives forever and waits for your incoming packet. | I suggest you to use Celery which works with Django and has support for long running tasks among other features.
<http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html>
<http://docs.celeryproject.org/en/latest/getting-started/introduction.html> |
15,728,081 | I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database.
The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; tha... | 2013/03/31 | [
"https://Stackoverflow.com/questions/15728081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1929999/"
] | I suggest you to use Celery which works with Django and has support for long running tasks among other features.
<http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html>
<http://docs.celeryproject.org/en/latest/getting-started/introduction.html> | <https://github.com/lukedupin/django_posix_spawn>
Using management commands in conjunction with this allows you to run django tasks that don't block your website. |
15,728,081 | I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database.
The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; tha... | 2013/03/31 | [
"https://Stackoverflow.com/questions/15728081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1929999/"
] | I suggest you to use Celery which works with Django and has support for long running tasks among other features.
<http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html>
<http://docs.celeryproject.org/en/latest/getting-started/introduction.html> | If you need a loop that is "django-aware" and already using celery for async tasks then
[celery-eternal](http://celery-eternal.readthedocs.io) might be a good fit. Only caveat is that you must use redis as the celery results backend. |
15,728,081 | I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database.
The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; tha... | 2013/03/31 | [
"https://Stackoverflow.com/questions/15728081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1929999/"
] | In case you feel that Celery is a bit oversized for your needs you could also define a [custom management command](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) that lives forever and waits for your incoming packet. | <https://github.com/lukedupin/django_posix_spawn>
Using management commands in conjunction with this allows you to run django tasks that don't block your website. |
15,728,081 | I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database.
The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; tha... | 2013/03/31 | [
"https://Stackoverflow.com/questions/15728081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1929999/"
] | In case you feel that Celery is a bit oversized for your needs you could also define a [custom management command](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) that lives forever and waits for your incoming packet. | If you need a loop that is "django-aware" and already using celery for async tasks then
[celery-eternal](http://celery-eternal.readthedocs.io) might be a good fit. Only caveat is that you must use redis as the celery results backend. |
61,256,730 | I'm writing a python code that converts a binary to decimal.
```
def bin_dec (binary):
binary_list = list(str(binary))
**for bit in binary_list:
if int(bit) > 1 or int(bit) < 0:
print('Invalid Binary')
print('')
exit()**
total = 0
argument = 0
binary_... | 2020/04/16 | [
"https://Stackoverflow.com/questions/61256730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13332906/"
] | ```
$agent = $this->request->getUserAgent();
if ($agent->isBrowser())
{
if($this->input->cookie('country')) {
$countryId = $this->input->cookie('country');
}else{
redirect(base_url());
}
}
``` | HTTP 302 response code means that the URL of requested resource has been changed temporarily. Further changes in the URL might be made in the future. Therefore, this same URI should be used by the client in future requests.[You can check this out to learn more](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/3... |
25,844,794 | While executing below code, I am getting error as mentioned.
I downloaded the required package from <http://www.cs.unm.edu/~mccune/prover9/download/> and configure. But still same issue.
I am getting this error:
```
>>> import nltk
>>> dt = nltk.DiscourseTester(['A student dances', 'Every student is a person'])
>>... | 2014/09/15 | [
"https://Stackoverflow.com/questions/25844794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2518644/"
] | Try following code:
```
.mini1 {
width: 100%;
height: 6.7%;
margin-top: -2%;
background-image: url('../images/footer1.jpg');
z-index: 10;
background-size: 100% 100%;
}
```
Please see to it that, image path is correct. Go in console to check for any errors. | Well here is a working JSfiddle: <http://jsfiddle.net/knftvt6v/4/>
I believe it is your file path that's causing the error, can you make a JS fiddle
```
.mini1 {
width: 100%;
height: 2em;
margin-top: -2%;
background: url('http://www.serenitybaumer.com/main_images/footer.jpg');
z-index: 10;
co... |
62,221,721 | I have created GuI in Visual Studio 2019.
[](https://i.stack.imgur.com/g21cN.png)
There user will enter username and password and that i have to pass to python script. That when user will click on login button, python script will be triggered and out... | 2020/06/05 | [
"https://Stackoverflow.com/questions/62221721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11699581/"
] | You could use arguments to call your Python Script.
Change the python script:
```
import paramiko
import time
import sys # Used to get arguments
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
hostname = sys.argv[1] # Skip 0th arg, since it is just the filename
usern... | There are multiple approaches to incorporating a Python script with .NET C# code
================================================================================
I will try and give a basic overview, along with my suggestion, but ultimately, it will be up to you to figure out what works best.
IronPython
----------
I... |
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | Adjacent strings are concatenated at compile time:
```
if True:
print ("this is the first line of a very long string"
" this is the second line")
```
Output:
```
this is the first line of a very long string this is the second line
``` | You can use a trailing backslash to join separate strings like this:
```
if True:
print "long test long test long test long test long " \
"test long test long test long test long test long test"
``` |
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | Adjacent strings are concatenated at compile time:
```
if True:
print ("this is the first line of a very long string"
" this is the second line")
```
Output:
```
this is the first line of a very long string this is the second line
``` | ```
if True:
print "long test long test long test long test long"\
"test long test long test long test long test long test"
``` |
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | Adjacent strings are concatenated at compile time:
```
if True:
print ("this is the first line of a very long string"
" this is the second line")
```
Output:
```
this is the first line of a very long string this is the second line
``` | ```
if True:
print "long test long test long test "+
"long test long test long test "+
"long test long test long test "
```
And so on. |
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | Adjacent strings are concatenated at compile time:
```
if True:
print ("this is the first line of a very long string"
" this is the second line")
```
Output:
```
this is the first line of a very long string this is the second line
``` | Why isn't anyone recommending triple quotes?
```
print """ blah blah
blah .............."""
``` |
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | ```
if True:
print "long test long test long test long test long"\
"test long test long test long test long test long test"
``` | You can use a trailing backslash to join separate strings like this:
```
if True:
print "long test long test long test long test long " \
"test long test long test long test long test long test"
``` |
1,104,762 | How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case.
Correct ouptut but strangely indented:
```
if True:
print "long test long test long test long test long \
tes... | 2009/07/09 | [
"https://Stackoverflow.com/questions/1104762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] | You can use a trailing backslash to join separate strings like this:
```
if True:
print "long test long test long test long test long " \
"test long test long test long test long test long test"
``` | ```
if True:
print "long test long test long test "+
"long test long test long test "+
"long test long test long test "
```
And so on. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.