qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
47,064,278 | I've been working on this script today and have made some really good progress with looping through the data and importing it to an external database. I'm trying to troubleshoot a field that I'm having an issue with and it doesn't make much sense. Whenever I attempt to run it, I get the following error `KeyError: 'manu... | 2017/11/01 | [
"https://Stackoverflow.com/questions/47064278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257896/"
] | my guess is that one of the items in your data does not have a 'manufacturer' key set.
replace
item['manufacturer']
by
item.get('manufacturer', None)
or replace None by a default manufacturer... | Here are two ways of doing getting around a dictionary not having a key. Both work but the first one is probably easier to use and will work as a drop in for your current code.
This is a way of doing it using python's `dictionary.get()` method. [Here is a page with more examples of how it works](https://www.tutorials... | 5,369 |
65,364,425 | I'm trying to pass primary key as URL argument from CreatePost to UploadImage view but I'm constantly getting an error even if I see primary key in URL. I'm new to Django, so please help me :)
**views.py**
```
class CreatePost(CreateView):
model=shopModels.UserPost
template_name='shop/create_post.html'
... | 2020/12/18 | [
"https://Stackoverflow.com/questions/65364425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14852796/"
] | I think you are not including `user_post` key in html form, you should include it in jinja style
`<a class="btn btn-success" href="{% url 'image_upload' user_post=user_post_key %}">`
And if you want to do some operations based on that `user_post` You should override the `form_valid(self)` method and access the `int:u... | Your path explicitly expects and integer for user\_post:
```
path('image_upload/<int:user_post>',views.UploadImage.as_view(),name="image_upload"),
```
If you call reverse(...) and you handover 123 you meed to make sure that 123 is a type integer and not e.g. string. | 5,372 |
37,103,682 | I am only starting out programming and currently making a text game. I know there is no goto command in python and after doing some research I understood that I have to use loops to replace that command but it just isn't doing what i was hoping it would do. Here's my code:
```
print('Welcome to my bad game!')
print('P... | 2016/05/08 | [
"https://Stackoverflow.com/questions/37103682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6307467/"
] | If you mean to the beginning to the loop, just leave out the call to `quit`. If you mean to the beginning of the *program*, then you'll need a loop around that as well. | Instead of quit you could use 'continue' to loop back to your while. But it's not clear from this example what you want the while to do. | 5,373 |
4,619,580 | With python, I can use [logging](http://docs.python.org/library/logging.html) library.
What do you use for the logging library with C++? | 2011/01/06 | [
"https://Stackoverflow.com/questions/4619580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260127/"
] | I personally like: <http://code.google.com/p/google-glog/>
You have many options though. This one is pretty similar to what you are used to. | Maybe you will want to take a look at <https://github.com/gabime/spdlog>, they used a Python style syntax to compose log messages, and is pretty fast and safe. | 5,374 |
45,386,035 | I run several python subprocesses to migrate data to S3. I noticed that my python subprocesses often drops to 0% and *this condition lasts more than one minute*. This significantly decreases the performance of the migration process.
Here is the pic of the sub process:
[) and especially about [TSR](https://en.wikipedia.org/wiki/Terminate_and_stay_resident_p... | 5,378 |
54,509,350 | I want to write aws lambda function to fetch data from on premises oracle db and migrate to aurora db.
I tried :
```
var oracledb = require('oracledb-for-lambda');
var os = require('os');
var fs = require('fs');
'use strict';
str_host = os.hostname() + ' localhost\n';
fs.appendFile(process.env.HOSTALIASES,str_host ... | 2019/02/04 | [
"https://Stackoverflow.com/questions/54509350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951102/"
] | ***KeyNotFoundException ... Why?***
The distilled, core reason is that the `Equals` and `GetHashCode` methods are inconsistent. This situation is fixed by doing 2 things:
* Override `Equals` in `TestClass`
* Never modify a dictionary during iteration
+ It's that the key object/value is being modified
---
**`GetHa... | That is the expected behavior with your code. Then what is your wrong with your code?
Look at your Key Class. You are overriding your `GetHashCode()` and on top of that you are using a mutable value to calculate the `GetHashCode()` method (very very bad :( ).
```
public class TestClass
{
public int MyProperty { ... | 5,379 |
33,630,400 | How do I extract two `i32`s from a single line of input in Rust? In Python I can read two `int`s like:
```python
a, b = map(int, input().split()) # "2 3" => a=2 and b=3
```
As of Rust 1.3.0, I can run the following to read one i32:
```rust
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok().expect... | 2015/11/10 | [
"https://Stackoverflow.com/questions/33630400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2370748/"
] | `&str` has a [`split_whitespace()`](http://doc.rust-lang.org/std/primitive.str.html#method.split_whitespace) method which returns an iterator yielding parts of the target string separated by an arbitrary amount of whitespace, much like `split()` in Python. You can use the [`map()`](http://doc.rust-lang.org/std/iter/tra... | The Rust code is always going to be more verbose than the Python one. But since version 1.26, Rust also supports slice patterns as shown below. The code looks more readable in my opinion.
```
fn main() {
let a = "2 3";
if let [Ok(aa), Ok(aaa)] = &a.split(" ")
.map(|a| a.parse::... | 5,381 |
14,259,660 | I am calling a python script from within a shell script. The python script returns error codes in case of failures.
How do I handle these error codes in shell script and exit it when necessary? | 2013/01/10 | [
"https://Stackoverflow.com/questions/14259660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202325/"
] | The exit code of last command is contained in `$?`.
Use below pseudo code:
```
python myPythonScript.py
ret=$?
if [ $ret -ne 0 ]; then
#Handle failure
#exit if required
fi
``` | You mean [the `$?` variable](http://tldp.org/LDP/abs/html/exit-status.html)?
```
$ python -c 'import foobar' > /dev/null
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named foobar
$ echo $?
1
$ python -c 'import this' > /dev/null
$ echo $?
0
``` | 5,384 |
21,517,740 | I am new to Python having come from mainly Java programming.
I am currently pondering over how classes in Python are instantiated.
I understand that `__init__()`: is like the constructor in Java. However, sometimes python classes do not have an `__init__()` method which in this case I assume there is a default const... | 2014/02/02 | [
"https://Stackoverflow.com/questions/21517740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020869/"
] | >
> I understand that `__init__()`: is like the constructor in Java.
>
>
>
To be more precise, in Python `__new__` is the constructor method, `__init__` is the initializer. When you do `SomeClass('foo', bar='baz')`, the `type.__call__` method basically does:
```
def __call__(cls, *args, **kwargs):
instance = ... | This answer pertains to new-style Python classes, which subclass `object`. New-style classes were added in 2.2, and they're the only kind of class available in PY3.
```
>>> print object.__doc__
The most base type
```
The class itself is an instance of a metaclass, which is usually `type`:
```
>>> print type.__doc_... | 5,386 |
56,760,023 | I am trying yo use a PyTorch library SparseConvNet (<https://github.com/facebookresearch/SparseConvNet>) in Google Colaboratory. In order to install it properly, you need to first install Conda, and then using Conda install the SparseConvNet package. Here is the code I am using (following the instructions from scn read... | 2019/06/25 | [
"https://Stackoverflow.com/questions/56760023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11627002/"
] | You can specify the directory for conda to install to using
```
conda install -p path_to_your_dir
```
So, you can mount your google drive and conda install there to make it permanent. | The whole environment that Google Colaboratory runs your notebooks is not permanent, it is one of their premises. If you need a persistent environment consider running Jupyter directly on a Google Cloud Compute Engine VM, they have pre-built images with everything configured [here](https://cloud.google.com/deep-learnin... | 5,389 |
58,131,697 | While reading a file in python, I was wondering how to get the next `n` lines when we encounter a line that meets my condition.
Say there is a file like this
```
mangoes:
1 2 3 4
5 6 7 8
8 9 0 7
7 6 8 0
apples:
1 2 3 4
8 9 0 9
```
Now whenever we find a line starting with mangoes, I want to be able to read all the... | 2019/09/27 | [
"https://Stackoverflow.com/questions/58131697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/886357/"
] | just repeat what you did
```
if (line.startswith("mangoes:")):
for i in range(n):
print(next(ifile))
``` | Unless it's a huge file and you don't want to read all lines into memory at once you could do something like this
```py
n = 4
with open(fn) as f:
lines = f.readlines()
for idx, ln in enumerate(lines):
if ln.startswith("mangoes"):
break
mangoes = lines[idx:idx+n]
```
This would give you a list of ... | 5,391 |
27,528,566 | I am trying to return a python dictionary to the view with AJAX and reading from a JSON file, but so far I am only returning `[object Object],[object Object]`...
and if I inspect the network traffic, I can indeed see the correct data.
So here is how my code looks like. I have a class and a method which based on the... | 2014/12/17 | [
"https://Stackoverflow.com/questions/27528566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1731280/"
] | I think you're getting confused because you actually have two tables of
data linked by a common ID:
```
library(dplyr)
df <- tbl_df(df)
years <- df %>%
filter(attributes == "YR") %>%
select(id = ID, year = values)
years
#> Source: local data frame [6 x 2]
#>
#> id year
#> 1 1 2014
#> 2 2 2013
#> 3 3 2... | I misunderstood the structure of your dataset initially. Thanks to the comments below I realize your data needs to be restructured.
```
# split the data out
df1 <- df[df$attributes == "AU",]
df2 <- df[df$attributes == "YR",]
# just keeping the columns with data as opposed to the label
df3 <- merge(df1, df2, by="ID")[... | 5,393 |
56,924,174 | I'm importing files from the following folder inside a python code:
```
Mask_RCNN
-mrcnn
-config.py
-model.py
-__init__.py
-utils.py
-visualize.py
```
I'm using the following imports:
These work ok:
from Mask\_RCNN.mrcnn.config import Config
from Mask\_RCNN. mrcnn import utils
These give me... | 2019/07/07 | [
"https://Stackoverflow.com/questions/56924174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10028453/"
] | You get an error for the 2nd import, where you omit `Mask_RCNN` from the package name.
Try changing the lines to:
```
from Mask_RCNN.mrcnn import visualize
import Mask_RCNN.mrcnn.model as modellib
``` | Use this line before importing the libraries
```
sys.path.append("Mask_RCNN/")
``` | 5,396 |
25,012,210 | Steps I followed to build WebRTC for Android in UBUNTU 13.10 env.
Check out the code:
```
gclient config https://webrtc.googlecode.com/svn/trunk
echo "target_os = ['android', 'unix']" >> .gclient
gclient sync --nohooks
cd trunk
source ./build/android/envsetup.sh
export GYP_DEFINES="build_with_libjingle=1 build_with_c... | 2014/07/29 | [
"https://Stackoverflow.com/questions/25012210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3580291/"
] | I don't think you're doing anything wrong.
your error is mentioned [here](https://code.google.com/p/webrtc/issues/detail?id=3622) and i guess it will be fixed.
```
"Yes, chrome has moved to BoringSSL from OpenSSL, which causes some problems in WebRTC Android. We are looking into it."
```
You can try an older revisi... | Follow this [example](http://simonguest.com/2013/08/06/building-a-webrtc-client-for-android/), i have tried it and work success fully.
Only need to make one change is the link provided in this example for gclient config command is older one. Follow your link gclient config <http://webrtc.googlecode.com/svn/trunk>
Als... | 5,397 |
20,712,314 | I have a simple python code
```
path1 = //path1/
path2 = //path2/
write_html = """
<form name="input" action="copy_file.php" method="get">
"""
Outfile.write(write_html)
```
Now copy\_file.php copies files from one folder to another. I want the python path1 and path2 variable values to be passed to php script. **H... | 2013/12/20 | [
"https://Stackoverflow.com/questions/20712314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538688/"
] | ```
write_html = """
<form name="input" action="copy_file.php" method="get">
<input type="hidden" name="path1" value="{0}" />
<input type="hidden" name="path2" value="{1}" />
<input type="button" name="button" value="onClick="copyfile('{0}', '{1}')"/>
<script> function moveFile(path1, path2){ ...} </script>
""".f... | >
> I want the python path1 and path2 variable values to be passed to php script.
>
>
>
Doable:
```
write_html = """
<form name="input" action="copy_file.php" method="get">
<input type="hidden" name="path1" value="%s" />
<input type="hidden" name="path2" value="%s" />
""" % (path1, path2)
```
My python is a b... | 5,398 |
55,494,430 | Plz suggest how to create dictionary from the following file contetns
```
2,20190327.1.csv.gz
3,20190327.23.csv.gz
4,20190327.21302.csv.gz
2,20190327.24562.csv.gz
```
my required output is
```
{2:20190327.1.csv.gz:982, 3:20190327.23.csv.gz, 4:20190327.21302.csv.gz, 2:20190327.24562.csv.gz}
```
I am new to python... | 2019/04/03 | [
"https://Stackoverflow.com/questions/55494430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619226/"
] | You could use
`$"color".isin("GREEN","RED","YELLOW")`
Code example:
```
val df2 = df.withColumn("Ind",
when($"color".isin("GREEN","RED","YELLOW"), 1).otherwise(0))
df2.show(false)
```
Outputs:
```
+------+---+
| color|Ind|
+------+---+
| RED| 1|
| GREEN| 1|
|YELLOW| 1|
| PINK| 0|
+------+---+
```
A quic... | You should be able to check the column against a list with:
```
val result = df.withColumn("Ind",
when($"color".in("GREEN", "RED", "YELLOW"), 1).otherwise(0))
``` | 5,400 |
3,902,608 | I'm pretty new to python and am trying to grab the ropes and decided a fun way to learn would be to make a cheesy MUD type game. My goal for the piece of code I'm going to show is to have three randomly selected enemies(from a list) be presented for the "hero" to fight. The issue I am running into is that python is cop... | 2010/10/10 | [
"https://Stackoverflow.com/questions/3902608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/471561/"
] | Change
```
genENE.insert(i,enemies[0])
```
to
```
genENE.insert(i,enemies[0][:])
```
This will force the list to be copied rather than referenced. Also, I would use append rather than insert in this instance. | `they all subtract that value` What do you mean do they all? If you mean both lists, you're problem is because you're only referencing the list NOT creating a second one. | 5,401 |
58,931,845 | My Airflow DAGs mainly consist of PythonOperators, and I would like to use my Python IDEs debug tools to develop python "inside" airflow. - I rely on Airflow's database connectors, which I think would be ugly to move "out" of airflow for development.
I have been using Airflow for a bit, and have so far only achieved d... | 2019/11/19 | [
"https://Stackoverflow.com/questions/58931845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152989/"
] | It might be somewhat of a hack, but I found one way to set up PyCharm:
* Use `which airflow` to the local airflow environment - which in my case is just a pipenv
* Add a new run configuration in PyCharm
* Set the python "Script path" to said airflow script
* Set Parameters to test a task: `test dag_x task_y 2019-11-19... | I debug `airflow test dag_id task_id`, run on a vagrant machine, using PyCharm. You should be able to use the same method, even if you're running airflow directly on localhost.
[Pycharm's documentation on this subject](https://www.jetbrains.com/help/pycharm/remote-debugging-with-product.html#remote-debug-config) shoul... | 5,402 |
55,515,401 | I have a python script that dynamically create task (airflow operator) and DAG basing on a JSON file that maps every option desired.
The script also dedicated function to create any operator needed.
Sometimes i want to activate some conditional options based on the mapping... for example in a bigqueryOperator sometime... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55515401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4626682/"
] | Change `bqOperator` as below to handle that case, basically it would pass None when it won't find that field in your json:
```
def bqOperator(mappedTask):
try:
return BigQueryOperator(
task_id=mappedTask.get('task_id'),
sql=mappedTask.get('sql'),
destination_dataset_table="{}.{}.{... | There is no private methods or fields in python, so you can directly set and get fields like
```py
op.use_legacy_sql = True
```
Given that I strongly discourage from doing this, as this a real code smell. Instead you could modify you factory class to apply some defaults to your json data.
Or even better, apply def... | 5,407 |
63,979,298 | So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out?
[ are intercepter by ToolbarItem and converted into appropriate internal representation. But custom view (eg. shape based)... is not. So see below a demo of possible approach.
Demo prepared & tested with Xcode 12 / iOS 14.
[ -> ()
func makeUIView(context: Context) -> UIButton {
let b = UIButton()
let largeConfig = UIImage.SymbolConfiguration(scal... | 5,408 |
7,451,347 | I'm programming an iOS application which needs to communicate with a python app in a very effecient way thru UDP sockets.
In the middle I have a bonjour service which serves as a bridge for my iOS app and host python app to communicate.
I'm building my own protocol which is a simple C structure. The code that I had... | 2011/09/16 | [
"https://Stackoverflow.com/questions/7451347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/933104/"
] | Yes, it is possible.
Read the [Archives and Serializations Programming Guide](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Archiving/Archiving.html), everything is explained here with samples, including this case, especially the part [Encoding and decoding C Data Types](http://developer.apple... | Rather than use NSData - and if the struct contains simple data items, rather than objects pointers you can use NSValue
```
NSValue valueFromStruct = [[NSValue value:&aStruct withObjCType:@encode(YourStructType)] retain];
```
As NSValue conforms to the NSCoding protocol you can use the methods that you want to use. | 5,417 |
68,382,302 | I am using a MacOS 10.15 and Python version 3.7.7
I wanted to upgrade pip so I ran `pip install --upgrade pip`, but it turns out my pip was gone (it shows `ImportError: No module named pip` when I want to use `pip install ...`)
I tried several methods like `python3 -m ensurepip`, but it returns
```
Looking in links:... | 2021/07/14 | [
"https://Stackoverflow.com/questions/68382302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14438351/"
] | Try the following:
```sh
python3 -m pip --upgrade pip
```
The `-m` flag will run a library module as a script. | The pip used by python3 is called pip3. Since you're using python3, you want to do `pip3 install --upgrade pip`. | 5,418 |
62,451,944 | ```
class TempClass():
def __init__(self,*args):
for i in range(len(args)):
self.number1=args[0]
self.number2=args[1]
print(self.number1,self.number2)
temp1=TempClass(10,20)
```
output: 10 20
```
class TempClass2():
def __init__(self,*args):
for i in range(len(args)):
self.number... | 2020/06/18 | [
"https://Stackoverflow.com/questions/62451944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5985980/"
] | You first need to initialize `self.number1` with `[None] * 2` (or similar) before using it.
However, I would use `args` directly:
```
class TempClass3():
def __init__(self,*args):
self.number1 = list(args)
print(self.number1)
temp3=TempClass3(10,20)
``` | When you are calling self.number1[0]=args[0], you are asking python to first open the list self.number1 which doesn't exist, then find an element in this non-existent list.
If it doesn't exist but you pass it a value, like self.number1=args[0], python will create self.number1 and define self.number1 as args[0].
You c... | 5,420 |
53,107,475 | I am trying to install kdb on the jupyter-notebook. First I download the 64-bit windows version on <https://ondemand.kx.com/> and also download the licence in the email.
Then I open it using window command prompt. I set QHOME and PATH using the following code in command prompt:
```
setx QHOME "C:\q"
setx PATH "%PATH... | 2018/11/01 | [
"https://Stackoverflow.com/questions/53107475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10105915/"
] | You didn't give us the requirements for the individual filenames, but here is an example that uses a sequential number for each given filename.
```
count = 0
for item in all_news:
count += 1
filename = '{}.txt'.format(count)
with open(filename, 'w') as f_out:
f.write('{}\n'.format(item))
``` | You have to open a new file on each element of the list, and you will need a counter to ensure have separated filenames (or a second list).
```
counter=0
for item in all_news:
with open('your_file_'+str(counter)+'.txt', 'w') as f:
f.write("%s\n" % item)
counter = counter + 1
```
This will write e... | 5,422 |
33,340,749 | I have registered on Google Developers Console, but my project is not a billed project. I did the steps of “initialized environment.” and “Build and Run
”as the web pages <https://github.com/GoogleCloudPlatform/datalab/wiki/Development-Environment> and <https://github.com/GoogleCloudPlatform/datalab/wiki/Build-and-Run>... | 2015/10/26 | [
"https://Stackoverflow.com/questions/33340749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5488148/"
] | If you are looking to run Datalab container locally instead of running it in Google Cloud, that is also possible as described here:
<https://github.com/GoogleCloudPlatform/datalab/wiki/Build-and-Run>
However, that is developer setup for building/changing Datalab code and not currently geared towards a data scientist /... | If your project does not have billing enabled you cannot run queries against BigQuery, which is what it looks like you are trying to do. | 5,424 |
32,260,538 | So i have this script in python.
It uses models from django to get some (to be precise: a lot of) data from database.
A quick 'summary' of what i want to achieve (it might be not so important, so you can as well get it just by looking at the code):
There are objects of A type.
For each A object there are related... | 2015/08/27 | [
"https://Stackoverflow.com/questions/32260538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3915216/"
] | Alright so my main problem was that I couldn't get the \_id of the document I inserted without not being able to check whether if it was updated/found or inserted. However I learned that you can generate your own Id's.
```
id = mongoose.Types.ObjectId();
Chatrooms.findOneAndUpdate({Roomname: room.Roomname},{ $set... | I'm afraid Using **FindOneAndUpdate** can't do what you whant because it doesn't has middleware and setter and it mention it the docs:
Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied:
* defaults
* Setters
* validators
* middleware
<http://mongoo... | 5,426 |
26,975,539 | I thought that the standalone PsychoPy install could coexist happily if Python was installed separately on the PC to but I can't get it to, nor can I find any docs. (I'm using Windows 7)
I have the lastest standalone version installed and the shortcut to run it is
```
"D:\Program Files (x86)\PsychoPy2\pythonw.exe" "D... | 2014/11/17 | [
"https://Stackoverflow.com/questions/26975539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/765827/"
] | It is not a button documented by Qt. You can detect this by catching events and checking event type:
<http://qt-project.org/doc/qt-5/qevent.html#Type-enum>
There are different types as `QEvent::EnterWhatsThisMode` `QEvent::WhatsThisClicked` and so on. I achieved something similar to what are you looking for using eve... | Based on Chernobyl's answer, this is how I did it in Python (PySide):
```
def event(self, event):
if event.type() == QtCore.QEvent.EnterWhatsThisMode:
print "click"
return True
return QtGui.QDialog.event(self, event)
```
That is, you reimplement `event` when app enters 'WhatsThisMode'. Other... | 5,434 |
59,598,620 | I am creating my first Django project. I have successfully installed Django version 2.1. When I created the project, the project was successfully launched at the url 127.0.0.1:8000.
Then I ran the command **python manage.py startapp products**.
Products folder was also successfully created in the project. Then inside t... | 2020/01/05 | [
"https://Stackoverflow.com/questions/59598620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12655703/"
] | In you **settings.py** add the app to the **INSTALLED\_APPS** list as:
```py
INSTALLED_APPS =
[
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products' # <-- your product a... | Check if you had ran the command below:
`python manage.py runserver`
If you had run the above command and the error persists, try to run on the global address 0.0.0.0
```
python manage.py runserver 0.0.0.0:8000
```
OR on a different port
```
python manage.py runserver 0.0.0.0:8001
``` | 5,437 |
46,368,459 | I have different types of `ISO 8601` formatted date strings, using `datetime library`, i want to obtain a `datetime object` from these strings.
Example of the input strings:
1. `2017-08-01` (1st august 2017)
2. `2017-09` (september of 2017)
3. `2017-W20` (20th week)
4. `2017-W37-2` (tuesday of 37th week)
I am able t... | 2017/09/22 | [
"https://Stackoverflow.com/questions/46368459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6374328/"
] | You can escape the Twig tags (as described [here](https://twig.symfony.com/doc/2.x/templates.html#escaping)) using `{{ '{{' }}`, `{{ '}}' }}`, `{{ '{%' }}` and `{{ '%}' }}`.
```
$input = '<h1>{{ pageTitle }}</h1>
<div class="row">
{% for product in products %}
<span class="mep"></span>
{% endfor %}
</div>... | My regex solution (better solution still welcome):
```
$input = '<h1>{{ pageTitle }}</h1>
<div class="row">
{% for product in products %}
<span class="mep"></span>
{% endfor %}
</div>';
$search = '/({{.+}})|({%.+%})/si';
$replace = '';
echo preg_replace($input, $search, $replace);
``` | 5,438 |
31,768,128 | I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this?
```
Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py
The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cach... | 2015/08/02 | [
"https://Stackoverflow.com/questions/31768128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2414957/"
] | I'm guessing you have two python installs, or two pip installs, one of which has been partially removed.
Why do you use `sudo`? Ideally you should be able to install and run everything from your user account instead of using root. If you mix root and your local account together you are more likely to run into permissi... | For me, on centOS 7
I had to remove the old pip link from /bin by
```sh
rm /bin/pip2.7
rm /bin/pip
```
then relink it with
```sh
sudo ln -s /usr/local/bin/pip2.7 /bin/pip2.7
```
Then if
```sh
/usr/local/bin/pip2.7
```
Works, this should work | 5,439 |
10,529,461 | I just noticed the problem with process terminate (from `multiprocessing` library) method on Linux. I have application working with `multiprocessing` library but... when I call `terminate` function on Windows everything works great, on the other hand Linux fails with this solution. As a replacement of process killing I... | 2012/05/10 | [
"https://Stackoverflow.com/questions/10529461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/611982/"
] | From the [docs](http://docs.python.org/py3k/library/multiprocessing.html#multiprocessing.Process.terminate):
>
> terminate()
>
>
> Terminate the process. On Unix this is done using the
> SIGTERM signal; on Windows TerminateProcess() is used. Note that exit
> handlers and finally clauses, etc., will not be execute... | Not exactly a direct answer to your question, but since you are dealing with the threads this could be helpful as well for debugging those threads:
<https://stackoverflow.com/a/10165776/1019572>
I recently found a bug in cherrypy using this code. | 5,449 |
3,182,009 | I'm trying to upload an image (just a random picture for now) to my MediaWiki site, but I keep getting this error:
>
> "Unrecognized value for parameter 'action': upload"
>
>
>
Here's what I did (site url and password changed):
```
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5... | 2010/07/05 | [
"https://Stackoverflow.com/questions/3182009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383971/"
] | You need at least MediaWiki 1.16 (which is currently in begta) to be able to upload files via the API. Or you can try [mwclient](http://mwclient.sf.net/), which automatically falls back to uploading via Special:Upload if an older version of MediaWiki is used (with reduced functionality, such as no error handling etc.) | Maybe you have to "obtain a token" first?
>
> To upload files, a token is required. This token is identical to the edit token and is the same regardless of target filename, but changes at every login. Unlike other tokens, it cannot be obtained directly, so one must obtain and use an edit token instead.
>
>
>
See... | 5,450 |
29,922,373 | I'm doing a fair amount of parallel processing in Python using the multiprocessing module. I know certain objects CAN be pickle (thus passed as arguments in multi-p) and others can't. E.g.
```
class abc():
pass
a=abc()
pickle.dumps(a)
'ccopy_reg\n_reconstructor\np1\n(c__main__\nabc\np2\nc__builtin__\nobject\np3\n... | 2015/04/28 | [
"https://Stackoverflow.com/questions/29922373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1415450/"
] | From the [docs](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled):
>
> The following types can be pickled:
>
>
> * `None`, `True`, and `False`
> * integers, long integers, floating point numbers, complex numbers
> * normal and Unicode strings
> * tuples, lists, sets, and dictionaries ... | The general rule of thumb is that "logical" objects can be pickled, but "resource" objects (files, locks) can't, because it makes no sense to persist/clone them. | 5,455 |
65,346,545 | I have two dense matrices with the sizes (2500, 208) and (208, 2500). I want to calculate their product. It works fine and fast when it is a single process but when it is in a multiprocessing block, the processes stuck in there for hours. I do sparse matrices multiplication with even larger sizes but I have no problem.... | 2020/12/17 | [
"https://Stackoverflow.com/questions/65346545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13575728/"
] | All you need to do is pass the function 'add transaction' from 'Page 2' to 'Page 3'. You have to make sure that the function 'add transaction' accepts 'Trans' as a parameter and it also calls setState for Page 2. In Page 3 you have to pass your 'Trans(true, -50)' as the parameter to the 'add transaction' function that ... | Usually there are two methods of widget interaction: callbacks (when one widget provides a callback and other one call it back) or streams (when one widget provides a stream controller and other one uses those controller to send events to stream). Callbacks and events are processed by widget-initiator.
1. Create a `Va... | 5,460 |
45,597,031 | I've looked at several other questions and none of them seem to help with my solution. I think I'm just not very intelligent sadly.
Basic question I know. I decided to learn python and I'm making a basic app with tkinter to learn.
Basically it's an app that stores and displays people's driving licence details (name a... | 2017/08/09 | [
"https://Stackoverflow.com/questions/45597031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140751/"
] | I'm guessing you're running into problems since you didn't specify a layout manager and passed `console` instead of `self`:
```
import tkinter as tk
class Search(tk.Frame):
def __init__(self, parent=None, controller=None):
tk.Frame.__init__(self, parent)
self.pack() # specify layout manager
... | First of all, using `from tkinter import *` is a more efficient way of importing Tkinters libraries without having to import specific things when needed. To answer your question though, here is the code for entering a text box.
`t1 = Text(self)`
To insert text into the text box: `t1.insert()`
An example of this w... | 5,461 |
17,964,475 | Hey I'm trying to install some packages from a `requires` file on a new virtual environment (2.7.4), but I keep running into the following error:
```
CertificateError: hostname 'pypi.python.org' doesn't match either of '*.addvocate.com', 'addvocate.com'
```
I cannot seem to find anything helpful on the error whe... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17964475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2637052/"
] | The issue is being documented on the python status site at <http://status.python.org/incidents/jj8d7xn41hr5> | When I try to connect to pypi I get the following error:
```
pypi.python.org uses an invalid security certificate.
The certificate is only valid for the following names:
*.addvocate.com , addvocate.com
```
So either pypi is using the wrong ssl certificate or somehow my connection is being routed to the wrong serv... | 5,462 |
48,174,011 | I'm running apache2 web server on raspberry pi3 model B. I'm setting up smart home running with Pi's and Uno's. I have a php scrypt that executes python program>index.php. It has rwxrwxrwx >I'll change that late becouse i don't fully need it.
And i want to real-time display print from python script.
`exec('sudo pytho... | 2018/01/09 | [
"https://Stackoverflow.com/questions/48174011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8882678/"
] | shell\_exec returns the output of your script. so use
```
$cmd = escapeshellcmd('sudo python3 piUno.py');
$output = shell_exec($cmd);
echo $output;
```
should work! let me know if it doesn't
edit: oh hey! your question got me looking at doc to check myself and exec actually returns the last line of output if you ... | First make sure you have permissions to **write read execute for web user**.
You can you user `sudo sudo chmod 777 /path/to/your/directory/file.xyz`
For php file and file you want to run. `$output = exec('sudo pytho3 piUno'); echo $output;`
**Credits ---> Ralph Thomas Hopper** | 5,467 |
14,346,177 | I'm trying to use factory\_boy to help generate some MongoEngine documents for my tests. I'm having trouble defining `EmbeddedDocumentField` objects.
Here's my MongoEngine `Document`:
```py
class Comment(EmbeddedDocument):
content = StringField()
name = StringField(max_length=120)
class Post(Document):
t... | 2013/01/15 | [
"https://Stackoverflow.com/questions/14346177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387163/"
] | I'm not sure if this is what you want but I just started looking at this problem and this seems to work:
```
from mongoengine import EmbeddedDocument, Document, StringField, ListField, EmbeddedDocumentField
import factory
class Comment(EmbeddedDocument):
content = StringField()
name = StringField(max_length=1... | The way that I'm doing it right now is to prevent the Factories based on EmbeddedDocuments from building. So, I've setup up an EmbeddedDocumentFactory, like so:
```
class EmbeddedDocumentFactory(factory.Factory):
ABSTRACT_FACTORY = True
@classmethod
def _prepare(cls, create, **kwargs): ... | 5,468 |
66,517,764 | ### What is the pythonic way to remove all the parts of string upto and including dot from a set
```
theSet={'products.add_product','products.add_category','books.view_books','cats.change_cats'}
#desired output
newSet = {'add_product','add_category','view_books', 'change_cats'}
``` | 2021/03/07 | [
"https://Stackoverflow.com/questions/66517764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8047262/"
] | You can use `yearmon`function from `zoo`. Then search for string Jun with R `grepl` function in Date column and apply desired condition with `case_when`from `dplyr` package.
```
library(zoo)
library(dplyr)
# your data
Date <- c("2000-01", "2000-02", "2000-03", "2000-04", "2000-05", "2000-06",
"2000-07", "2000-08", "... | Why not simply this?
```
FF5_class$HOLD <- ifelse(substr(FF5_class$Date, 6,7) =="06", FF5_class$Value, NA)
Date Permno Value HOLD
1 2000-01 10026 Big, Growth <NA>
2 2000-02 10026 Small, Value <NA>
3 2000-03 10026 Neutral, Neutral <NA>
4 2000-04 ... | 5,469 |
3,434,048 | I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed.
Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, ... | 2010/08/08 | [
"https://Stackoverflow.com/questions/3434048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388350/"
] | Since you're working on windows with VB, it's worth mentioning that [IronPython](http://ironpython.net/) might be one option. Since both VB and IronPython can interact through .NET, you could wrap up your script in an assembly and expose a function which you call with the required arguments. | Have you taken a look at the [getopt module](http://docs.python.org/library/getopt.html)? It's designed to make working with command line options easier. See also the examples at [Dive Into Python](http://www.faqs.org/docs/diveintopython/kgp_commandline.html).
If you are working with Python 2.7 (and not lower), than y... | 5,470 |
5,574,649 | I need a scalable `NoSql` solution to store data as *arrays* for many fields & time stamps, where the key is a combination of a `field` and a `timestamp`.
Data would be stored in the following scheme:
**KEY** --> "FIELD\_NAME.YYYYMMDD.HHMMSS"
**VALUE** --> [v1, v2, v3, v4, v5, v6] (v1..v6 are just `floats`)
For i... | 2011/04/07 | [
"https://Stackoverflow.com/questions/5574649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/540009/"
] | Sounds like MongoDB would be a good fit. [PyMongo](http://api.mongodb.org/python/1.10+/index.html) is the api. | Your data is highly structured and regular; what benefit do you see in NoSQL vs a more traditional database?
I think [MySQL Cluster](http://dev.mysql.com/downloads/cluster/) sounds tailor-made for your problem.
**Edit:**
@user540009: I agree that there are serious slowdowns on single-machine or mirrored instances of... | 5,480 |
12,672,629 | >
> **Possible Duplicate:**
>
> [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime)
>
>
>
I am parsing an XML file that gives me the time in the respective isoformat:
```
tc1 = 2012-09-28T16:41:12.9976565
tc2 = 2012-09-28T23:57:44.6636597
```
But it ... | 2012/10/01 | [
"https://Stackoverflow.com/questions/12672629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/966739/"
] | You can use the [python-dateutil `parse()` function](http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2), it's more flexible than strptime. Hope this help you. | Use the [`datetime` module](http://docs.python.org/library/datetime.html).
```
td = datetime.strptime('2012-09-28T16:41:12.997656', '%Y-%m-%dT%H:%M:%S.%f') -
datetime.strptime('2012-09-28T23:57:44.663659', '%Y-%m-%dT%H:%M:%S.%f')
print td
# => datetime.timedelta(-1, 60208, 333997)
```
There is only one small p... | 5,481 |
42,044,619 | I'm working on a project of my own, and I'm at a point where i don't know anymore what to do..
I'm trying to implement some sounds into my project where i press some tact. switches and they should make sounds.. I'm a complete newbie with python so i found a piece of code doing something similar...
```
import os
from ... | 2017/02/04 | [
"https://Stackoverflow.com/questions/42044619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7516655/"
] | Based on <https://github.com/Unitech/pm2/blob/master/lib/API/Extra.js#L436>, I managed to get this working
Put it as the last item in your ecosystem file, and it will always have the highest id
Make sure that the script path is correct, it was the default on MY system, it might not be on your
I'm running 2.9.3, and ... | not sure, but you can try to specify `interpreter`. It should be your PM2 (check it with `whereis`).
Try smth like
`{
"apps": [{
"name": "web",
"script": "",
"interpreter": "/usr/local/bin/pm2",
"args": "web"
}]
}`
Please note - i didnot checked it at all, it just suggestion | 5,484 |
63,201,965 | Hi I have made my flask app and I have exposed port 5001 in Docker file.
I pushed it to dockerhub repo and ran on different machine by
```
docker container run --name XYZ <username>/<repo_name>:<tag>
```
The log says that app is running on <http://127.0.0.1:5001/>
But if I open that localtion in browser its says
`... | 2020/08/01 | [
"https://Stackoverflow.com/questions/63201965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5687866/"
] | This sounds like `insert . . . on duplicate key update`. First, though, you need a unique index or constraint:
```
create unique index unq_stocks_ticker on stocks(ticker);
```
Then you can use:
```
insert into stocks (ticker, marketcap)
values (?, ?)
on duplicate key update marketcap = values(marketcap);
`... | An UPDATE query is incapable of creating a new row, so perhaps like:
```
UPDATE stocks SET marketcap = 300000000000 WHERE symbol = '$MMM'
```
Your footnote "unless it doesn't exist" means you probably then need to examine how many rows this altered and if it's 0 then run:
```
INSERT INTO stocks(marketcap, symbol) ... | 5,485 |
52,458,754 | I want to compare two dictionary keys in python and if the keys are equal, then print their values.
For example,
```
dict_one={'12':'fariborz','13':'peter','14':'jadi'}
dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'}
```
and after comparing the keys, print
```
'fariborz', 'daei'
'jadi', jafar'
``` | 2018/09/22 | [
"https://Stackoverflow.com/questions/52458754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9287224/"
] | You're asking for the intersection of the two dictionaries.
Using the builtin type `set`
----------------------------
You can use the builtin type `set` for this, which implements the `intersection()` function.
You can turn a list into a set like this:
```
set(my_list)
```
So, in order to find the intersection be... | ```
for key, val1 in dict_one.items():
val2 = dict_two.get(key)
if val2 is not None:
print(val1, val2)
``` | 5,486 |
68,425,073 | I have a list like this:
```
list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?']
```
I want for example to replace ‘hello’ and ‘halo’ with ‘welcome’, and ‘goodbye’ and ‘bye bye’ with ‘greetings’ so the list will be like this:
```
list1 or newlist = ['welcome', 'welcome', 'greetings', 'greetings', 'how a... | 2021/07/17 | [
"https://Stackoverflow.com/questions/68425073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16431450/"
] | if the substitutions can easily be grouped then this works:
```py
list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?']
new_list = []
group1 = ('hello', 'halo')
group2 = ('goodbye', 'bye bye')
for word in list1:
if word in group1:
new_list.append('welcome')
elif word in group2:
new_l... | I see this question is marked with the re tag, so I will answer using regular expressions. You can replace text using re.sub.
```
>>> import re
>>> list1 = ",".join(['hello', 'halo', 'goodbye', 'bye bye', 'how are you?'])
>>> list1 = re.sub(r"hello|halo", r"welcome", list1)
>>> list1 = re.sub(r"goodbye|bye bye", r"gre... | 5,496 |
14,976,968 | I am trying to run a c++ program from python. My problem is that everytime i run:
```
subprocess.Popen(['sampleprog.exe'], stdin = iterate, stdout = myFile)
```
it only reads the first line in the file. Every time I enclose it with a while loop it ends up crushing because of the infinite loop. Is there any other way... | 2013/02/20 | [
"https://Stackoverflow.com/questions/14976968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2090597/"
] | Your line of code
```
10 open (23,file=outfile,status='old',access='append',err=10)
```
specifies that the `open` statement should transfer control to itself (label 10) in case an error is encountered, so any error could trigger an infinite loop. It also suppresses the output of error messages. If you want to just c... | The `err=` argument in your `open` statement specifies a statement label to branch to should the `open` fail for some reason. Your code specifies a branch to the line labelled `10` which happens to be the line containing the `open` statement. This is probably not a good idea; a better idea would be to branch to a line ... | 5,498 |
47,959,991 | I have gathered obligatory data from the scopus website. my outputs have been saved in a list named "document". when I use type method for each element of this list, the python returns me this class:
```
"<class'selenium.webdriver.firefox.webelement.FirefoxWebElement'>"
```
In continius in order to solve this issu... | 2017/12/24 | [
"https://Stackoverflow.com/questions/47959991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8461493/"
] | As you have used the following line of code :
```
document=driver.find_elements_by_tag_name('td')
```
and see the output on Console as :
```
"<class'selenium.webdriver.firefox.webelement.FirefoxWebElement'>"
```
This is the expected behavior as **`Selenium`** prints the reference of the **`Nodes`** matching your... | My code was correct. But, the selected elements for displaying were space. By select another element, the result was shown. | 5,499 |
51,976,580 | I am trying to change month name to date in python but i m getting an error:
```
ValueError: time data 'October' does not match format '%m/%d/%Y'
```
My CSV has values such as October in it which I want to change it to 10/01/2018
```
import pandas as pd
import datetime
f = pd.read_excel('test.xlsx', 'Sheet1', inde... | 2018/08/22 | [
"https://Stackoverflow.com/questions/51976580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488647/"
] | Can't you just write a function mapping to each? In fact, a dictionary will do.
```
def convert_monthname(monthname):
table = {"January": datetime.datetime(month=1, day=1, year=2018),
"February": datetime.datetime(month=2, day=1, year=2018),
...}
return table.get(monthname, monthname... | The whole point of passing a format string like `%m/%d/%y` to `strftime` is that you're specifying what format the input strings are going to be in.
You can see [the documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior), but it's pretty obvious that a format like `%m/%d/%y` is ... | 5,500 |
45,686,298 | I have followed [official doc](https://learn.microsoft.com/en-us/visualstudio/python/debugging-cross-platform-remote) to install ptvsd 3.2.0, and put below code in the very beginning of target code.
```
import ptvsd
ptvsd.enable_attach('my_secret')
```
If run this code, I got error:
```
File "~/.virtualenvs/py3/lib... | 2017/08/15 | [
"https://Stackoverflow.com/questions/45686298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4198142/"
] | I had the same problem today. I've checked the [last version](https://pypi.python.org/pypi/ptvsd/3.2.0) and was released yesterday. I've decided to roll back to version 3.1.0, and that is working fine for me.
I've reported the problem to the [gitter room](https://gitter.im/Microsoft/PTVS). I'll update this answer as s... | The `ptvsd` module is not using semantic versioning, which means you cannot safely update it whenever you like. The plan is to switch to semantic versioning when it is fully decoupled from Visual Studio.
`ptvsd==3.2.0` was released at the same time that Visual Studio 2017 Update 15.3 because they have dependencies on ... | 5,508 |
65,046,032 | I'm trying to create an .exe from my python script. The script uses the cloudscraper package. When I create the .exe and I execute it, it shows the following error:
```
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\...\\MEI1....\\cloudscraper\\user_agent\\browsers.json'
```
The error ONLY APPEARS WHEN... | 2020/11/28 | [
"https://Stackoverflow.com/questions/65046032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14134850/"
] | The found solution is to copy the required folder inside the .exe path but as for now a days, **I found that this could not be achieved if you're using the** `--onefile` **modifier to create the .exe**, instead you should not use it and copy the cloudscraper folder inside such .exe path, and that should work
**NOTE:**... | Your .exe file is looking for browsers.json, but you didn't move that file to the same path as the .exe file. Working with pyinstaller requires good experience handling relative and absolute paths, otherwise, you will face that kind of errors.
If cloudscraper is not part of your project tree (maybe is a hidden import)... | 5,510 |
60,609,578 | I have two sets `set([1,2,3]` and `set([4,5,6]`. I want to add them in order to get set `1,2,3,4,5,6`.
I tried:
```
b = set([1,2,3]).add(set([4,5,6]))
```
but it gives me this error:
```
Traceback (most recent call last):
File "<ipython-input-27-d2646d891a38>", line 1, in <module>
b = set([1,2,3]).add(set([... | 2020/03/09 | [
"https://Stackoverflow.com/questions/60609578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601703/"
] | You can take the union of sets with `|`
```
> set([1, 2, 4]) | set([5, 6, 7])
{1, 2, 4, 5, 6, 7}
```
Trying to use `add(set([4,5,6]))` is not working because it tries to add the entire set as a single element rather than the elements in the set — and since it's not hashable, it fails. | You should use the union operation with the `.union` method or the `|` operator:
```py
>>> a = set([1, 2, 3])
>>> b = set([4, 5, 3])
>>> c = a.union(b)
>>> print(c)
{1, 2, 3, 4, 5}
>>> d = a | b
>>> print(d)
{1, 2, 3, 4, 5}
```
See the complete list of operations for [set](https://docs.python.org/3/library/stdtypes.... | 5,513 |
1,899,412 | I have a web site where there are links like `<a href="http://www.example.com?read.php=123">` Can anybody show me how to get all the numbers (123, in this case) in such links using python? I don't know how to construct a regex. Thanks in advance. | 2009/12/14 | [
"https://Stackoverflow.com/questions/1899412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | "If you have a problem, and decide to use regex, now you have two problems..."
If you are reading one particular web page and you know how it is formatted, then regex is fine - you can use S. Mark's answer. To parse a particular link, you can use Kimvai's answer. However, to get all the links from a page, you're bett... | This will work irrespective of how your links are formatted (e.g. if some look like `<a href="foo=123"/>` and some look like `<A TARGET="_blank" HREF='foo=123'/>`).
```
import re
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
p = re.compile('^.*=([\d]*)$')
for a in soup.findAll('a'):
m = p.match... | 5,514 |
62,163,714 | `which python` returns:
`/Library/Frameworks/Python.framework/Versions/2.7/bin/python`
When I open my shell, the first couple lines of the shell read:
`Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "lic... | 2020/06/03 | [
"https://Stackoverflow.com/questions/62163714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12304196/"
] | CSS:
```
.bi-headphones::before {
display: inline-block;
content: "";
background-image: url("data:image/svg+xml,%3Csvg width='1em' height='1em' viewBox='0 0 16 16' class='bi bi-headphones' fill='currentColor' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill-rule='evenodd' d='M8 3a5 5 0 0 0-5 5v4.5H2V8a6 6 0 1 1... | i cant find in the doc that bootstrap icon is fontawesome icon
after you install it you use it as a svg like this one
```
<svg class="bi bi-app" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M11 2H5a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h6a3 ... | 5,524 |
17,461,134 | I am using Python2.7.5 in Windows 7. I'm new to command line arguments. I am trying to do this exercise:
Write a program that reads in a string on the command line and returns a table of the letters which occur in the string with the number of times each letter occurs. For example:
```
$ python letter_counts.py "ThiS... | 2013/07/04 | [
"https://Stackoverflow.com/questions/17461134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547317/"
] | You want to use the [`sys.argv`](http://docs.python.org/2/library/sys.html#sys.argv) list from the [sys](http://docs.python.org/2/library/sys.html#module-sys) module. It lets you access arguments passed in the command line.
For example, if your command line input was `python myfile.py a b c`, `sys.argv[0]` is myfile.p... | You can do something along these lines:
```
#!/usr/bin/python
import sys
print sys.argv
counts={}
for st in sys.argv[1:]:
for c in st:
counts.setdefault(c.lower(),0)
counts[c.lower()]+=1
for k,v in sorted(counts.items(), key=lambda t: t[1], reverse=True):
print "'{}' {}".format(k,v)
```
Whe... | 5,525 |
47,069,829 | This may be a repeated question of attempting to run a mysql query on a remote machine using python.
Im using pymysql and SSHTunnelForwarder for this.
The mysqldb is located on different server (192.168.10.13 and port 5555).
Im trying to use the following snippet:
```
with SSHTunnelForwarder(
(host, ssh_port... | 2017/11/02 | [
"https://Stackoverflow.com/questions/47069829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4670651/"
] | Found this to be working after some digging.
```
with SSHTunnelForwarder(
("192.168.10.13", 22),
ssh_username = ssh_user,
ssh_password = ssh_pass,
remote_bind_address=('127.0.0.1', 5555)) as server:
with pymysql.connect('127.0.0.1', user, password, port=server.local_bind_port) as c... | you can do it like this:
```
conn = MySQLdb.connect(
host=host,
port=port,
user=username,
passwd=password,
db=database
charset='utf8',)
cur = conn.cursor()
cur.execute("select * from billing_cdr limit 1")
rows = cur.fetchall()
for row in rows:
a=row[0]
b=row[1]
conn.close()
``` | 5,526 |
16,784,154 | With the help of joksnet's programs [here](https://stackoverflow.com/questions/4460921/extract-the-first-paragraph-from-a-wikipedia-article-python) I've managed to get plaintext Wikipedia articles that I'm looking for.
The text returned includes Wiki markup for the headings, so for example, the sections of the [Albert... | 2013/05/28 | [
"https://Stackoverflow.com/questions/16784154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/728286/"
] | I think the best way here would be to let MediaWiki take care of the parsing. I don't know the library you're using, but basically this is the difference between
<http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Albert%20Einstein&rvprop=content>
which returns the raw wikitext and
<http://en.wikip... | You can use regex and scraping modules like Scrapy and Beautifulsoup to parse and scrape wiki pages.
Now that you clarified your question I suggest you use the py-wikimarkup module that is hosted on github. The link is <https://github.com/dcramer/py-wikimarkup/> . I hope that helps. | 5,527 |
19,542,883 | I'm trying to make a program that repeatedly asks an user for an input until the input is of a specific type. My code:
```
value = input("Please enter the value")
while isinstance(value, int) == False:
print ("Invalid value.")
value = input("Please enter the value")
if isinstance(value, int) == True:
... | 2013/10/23 | [
"https://Stackoverflow.com/questions/19542883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2826154/"
] | The reason your code doesn't work is because `input()` will always return a string. Which will always cause `isinstance(value, int)` to always evaluate to `False`.
You probably want:
```
value = ''
while not value.strip().isdigit():
value = input("Please enter the value")
``` | `input` always returns a string, you have to convert it to `int` yourself.
Try this snippet:
```
while True:
try:
value = int(input("Please enter the value: "))
except ValueError:
print ("Invalid value.")
else:
break
``` | 5,529 |
49,993,687 | Let's say I am running multiple python processes(not threads) on a multi core CPU (say 4). GIL is process level so GIL within a particular process won't affect other processes.
My question here is if the GIL within one process will take hold of only single core out of 4 cores or will it take hold of all 4 cores?
If o... | 2018/04/24 | [
"https://Stackoverflow.com/questions/49993687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4510252/"
] | Python doesn't do anything to [bind processes or threads to cores](https://en.wikipedia.org/wiki/Processor_affinity); it just leaves things up to the OS. When you spawn a bunch of independent processes (or threads, but that's harder to do in Python), the OS's scheduler will quickly and efficiently get them spread out a... | Process to CPU/CPU core allocation is handled by the Operating System. | 5,534 |
54,193,625 | I'm trying to fetch data for facebook account using selenium browser python but can't able to find the which element I can look out for clicking on an export button.
See attached screenshot[](https://i.stack.imgur.com/fd2Mf.png)
I tried but it seems ... | 2019/01/15 | [
"https://Stackoverflow.com/questions/54193625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7684584/"
] | Well, I'm able to resolve it by using xpath.
Here is the solution
```
self.driver.find_element_by_xpath("//*[contains(@class, '_271k _271m _1qjd layerConfirm')]").click()
``` | to run automation scripts on applications like facebook, youtube quite a hard because they are huge coporations and their web applications are developed by the worlds best developers but its not impossible to run automation scripts sometimes elements are generated dynamically sometimes hidden or inactive you cant just ... | 5,535 |
55,915,109 | Im trying to create a more dynamic program where I define a function's name based on a variable string.
Trying to define a function using a variable like this:
```py
__func_name__ = "fun"
def __func_name__():
print('Hello from ' + __func_name__)
fun()
```
Was wanting this to output:
```
Hello from fun
```
Th... | 2019/04/30 | [
"https://Stackoverflow.com/questions/55915109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6828625/"
] | You can update `globals`:
```
>>> globals()["my_function_name"] = lambda x: x + 1
>>> my_function_name(10)
11
```
But usually is more convinient to use a dictionary that have the functions related:
```
my_func_dict = {
"__func_name__" : __func_name__,
}
def __func_name__():
print('Hello')
```
And then use ... | This should do it as well, using the `globals` to update function name on the fly.
```
def __func_name__():
print('Hello from ' + __func_name__.__name__)
globals()['fun'] = __func_name__
fun()
```
The output will be
```
Hello from __func_name__
``` | 5,538 |
47,912,701 | There is a solution posted [here](https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) to create a stoppable thread. However, I am having some problems understanding how to implement this solution.
Using the code...
```
import threading
class StoppableThread(threading.Thread):
... | 2017/12/20 | [
"https://Stackoverflow.com/questions/47912701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9124164/"
] | There are a couple of problems with how you are using the code in your original example. First of all, you are not passing any constructor arguments to the base constructor. This is a problem because, as you can see in the plain-Thread example, constructor arguments are often necessary. You should rewrite `StoppableThr... | Inspired by above solution I created a small library, ants, for this problem.
Example
```
from ants import worker
@worker
def do_stuff():
...
thread code
...
do_stuff.start()
...
do_stuff.stop()
```
In above example do\_stuff will run in a separate thread being called in a `while 1:` loop
You can al... | 5,539 |
71,719,341 | I made a small pygame app that plays certain wav files in keypress using pygame.mixer
All seem to work just fine except the fact that if you minimize the pygame window the program stops working until you open it again. Is there a way to solve this issue or an alternative way to implement sound playing in python?
This ... | 2022/04/02 | [
"https://Stackoverflow.com/questions/71719341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15354246/"
] | Several ways. Here are a couple:
Standard SQL:
```sql
SELECT DISTINCT
CASE WHEN col1 < col2 THEN col1 ELSE col2 END AS col1
, CASE WHEN col1 < col2 THEN col2 ELSE col1 END AS col2
FROM tbl
;
```
or (MySQL supports this one):
```sql
SELECT DISTINCT
LEAST(col1, col2) AS col1
, GREATEST(c... | ```
select distinct least(col_1, col_2), greatest(col_1, col_2)
from the_table
order by 1
``` | 5,542 |
66,239,918 | I wrote this code to return a list of skills. If the user already has a specific skill, the list-item should be updated to `active = false`.
This is my initial code:
```js
setup () {
const user = ref ({
id: null,
skills: []
});
const available_skills = ref ([
... | 2021/02/17 | [
"https://Stackoverflow.com/questions/66239918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7510971/"
] | In JavaScript user or an object is a refence to the object which is the pointer itself will not change upon changing the underling properties hence the computed is not triggered
kid of like computed property for an array and if that array get pushed with new values, the pointer of the array does not change but the unde... | `slice` just returns a copy of the changed array, it doesn't change the original instance..hence computed property is not reactive
Try using below code
```
user.skills = user.skills.splice(index, 1);
``` | 5,543 |
66,670,964 | I have the following python code:
```
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("example.com", 443))
client.send(b'POST /api HTTPS/1.1\r\nHost: example.com\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0\r\nAccept-Encoding: gzip, deflate\r... | 2021/03/17 | [
"https://Stackoverflow.com/questions/66670964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15414108/"
] | It will **not overwrite** the secret if you create it manually in the console or using AWS SDK. The `aws_secretsmanager_secret` creates only the secret, but not its value. To set value you have to use [aws\_secretsmanager\_secret\_version](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/secr... | You could have Terraform [generate random secret values](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/secretsmanager_random_password) for you using:
```
data "aws_secretsmanager_random_password" "dev_password" {
password_length = 16
}
```
Then create [the secret metadata](http... | 5,545 |
52,277,877 | I'm trying to scrape this website using python and selenium. However all the information I need is not on the main page, so how would I click the links in the 'Application number' column one by one go to that page scrape the information then return to original page?
Ive tried:
```
def getData():
data = []
select ... | 2018/09/11 | [
"https://Stackoverflow.com/questions/52277877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10347887/"
] | To open multiple hrefs within a webtable to scrape through selenium you can use the following solution:
* Code Block:
```
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
f... | What you can do is the following:
```
import selenium
from selenium.webdriver.common.keys import Keys
from selenium import Webdriver
import time
url = "url"
browser = Webdriver.Chrome() #or whatever driver you use
browser.find_element_by_class_name("views-field views-field-title").click()
# or use this browser.find_e... | 5,546 |
20,952,629 | I am trying to install Python Cassandra Driver and constantly getting error "vcvarsall.bat not found"
I tried using lots of solutions posted already in stackoverflow but non of them are working.
here is what i tried-
1. Using mingw gcc compiler.I followed every step, setting the path variable etc.
and then tried usin... | 2014/01/06 | [
"https://Stackoverflow.com/questions/20952629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2640953/"
] | You will need to shorten the `memo` field to be able to use it in this manner. Try:
```
CAST(Desc AS NVARCHAR(2000))
``` | Use Having clause instead of where condition in query.
```
Select count(*) as NBoccurrence,descr
From tbl_nm
Group by descr
Having your condition
``` | 5,548 |
25,996,880 | This should be easy, but as ever Python's wildly overcomplicated datetime mess is making simple things complicated...
So I've got a time string in HH:MM format (eg. '09:30'), which I'd like to turn into a datetime with today's date. Unfortunately the default date is Jan 1 1900:
```
>>> datetime.datetime.strptime(time... | 2014/09/23 | [
"https://Stackoverflow.com/questions/25996880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218340/"
] | The [function signature](https://docs.python.org/3/library/datetime.html#datetime.datetime.combine) says:
```
datetime.combine(date, time)
```
so pass a `datetime.date` object as the first argument, and a `datetime.time` object as the second argument:
```
>>> import datetime as dt
>>> today = dt.date.today()
>>> ti... | `pip install python-dateutil`
```
>>> from dateutil import parser as dt_parser
>>> dt_parser.parse('07:20')
datetime.datetime(2016, 11, 25, 7, 20)
```
<https://dateutil.readthedocs.io/en/stable/parser.html> | 5,549 |
56,893,578 | I am trying to make a python program(python 3.6) that writes commands to terminal to download a specific youtube video(using youtube-dl).
If I go on terminal and execute the following command:
```
cd; cd Desktop; youtube-dl "https://www.youtube.com/watch?v=b91ovTKCZGU"
```
It will download the video to my desktop... | 2019/07/04 | [
"https://Stackoverflow.com/questions/56893578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11303221/"
] | Binary pattern matching can dissect the string:
```
data = ["AM00", "CC11", "CB11"]
for <<key::binary-size(2), value::binary>> <- data, into: %{} do
{key, value}
end
```
output:
```
%{"AM" => "00", "CB" => "11", "CC" => "11"}
```
That only works for single byte characters.
To handle `UTF-8` chara... | >
> I need to transform this list [into a] map...I tried with `Enum.map`.
>
>
>
You can also use [Enum.reduce](https://hexdocs.pm/elixir/Enum.html#reduce/3) instead of `Enum.map` when you want the result to be a map. The following example uses `Enum.reduce` and it can handle single byte `ASCII` characters as well ... | 5,550 |
9,227,859 | I'm using the code below (Python 2.7 and Python 3.2) to show an Open Files dialog that supports multiple-selection. On Linux filenames is a python list, but on Windows filenames is returned as `{C:/Documents and Settings/IE User/My Documents/VPC_EULA.txt} {C:/Documents and Settings/IE User/My Documents/VPC_ReadMe.txt}`... | 2012/02/10 | [
"https://Stackoverflow.com/questions/9227859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94078/"
] | The problem is an “interesting” interaction between Tcl, Tk and Python, each of which is doing something sensible on its own but where the combination isn't behaving correctly. The deep issue is that Tcl and Python have *very* different ideas about what types mean, and this is manifesting itself as a value that Tcl see... | This fix works for me:
```
if sys.hexversion >= 0x030000F0:
import tkinter.filedialog as filedialog
string_type = str
else:
import tkFileDialog as filedialog
string_type = basestring
options = {}
options['filetypes'] = [('vnote files', '.vnt') ,('all files', '.*')]
options['multiple'] = 1
filenames = ... | 5,552 |
28,515,972 | Currently I am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
>
> Error: pg\_config executable not found.
>
>
>
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bi... | 2015/02/14 | [
"https://Stackoverflow.com/questions/28515972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3964833/"
] | Here's a fix that worked for me on El Capitan that doesn't require restarting to work around the OS X El Capitan System Integrity Protection (SIP):
```
brew unlink postgresql && brew link postgresql
brew link --overwrite postgresql
```
[H/T Farhan Ahmad](http://www.thebitguru.com/blog/view/432-psycopg2%20on%20El%20C... | well, I'd like to give my solution, the problem is related with the version of c. So, I just typed:
```
CFLAGS='-std=c99' pip install psycopg2==2.6.1
``` | 5,557 |
43,424,895 | I have created a virtualenv using the following command:
`python3 -m venv --without-pip ./env_name`
I am now wondering if it is possible to add PIP to it manually. | 2017/04/15 | [
"https://Stackoverflow.com/questions/43424895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5969463/"
] | Once you opened the file, use this one-liner using `split` as you mentionned and nested list comprehension:
```
with open(f, encoding="UTF-8") as file: # safer way to open the file (and close it automatically on block exit)
result = [[int(x) for x in l.split()] for l in file]
```
* the inner listcomp splits & ... | You can do like this,
```
[map(int,i.split()) for i in filter(None,open('abc.txt').read().split('\n'))]
```
Line by line execution for more information
```
In [75]: print open('abc.txt').read()
3 2 7 4
1 8 9 3
6 5 4 1
1 0 8 7
```
`split` with newline.
```
In [76]: print open('abc.txt').read().split('\n')
['3 ... | 5,567 |
22,845,913 | I am trying to implement a function to generate java hashCode equivalent in node.js and python to implement redis sharding. I am following the really good blog @below mentioned link to achieve this
<http://mechanics.flite.com/blog/2013/06/27/sharding-redis/>
But i am stuck at the difference in hashCode if string conta... | 2014/04/03 | [
"https://Stackoverflow.com/questions/22845913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3230928/"
] | ```py
def java_string_hashcode(s):
"""Mimic Java's hashCode in python 2"""
try:
s = unicode(s)
except:
try:
s = unicode(s.decode('utf8'))
except:
raise Exception("Please enter a unicode type string or utf8 bytestring.")
h = 0
for c in s:
h = in... | Python 2 will assume ASCII encoding unless told otherwise. Since [PEP 0263](http://legacy.python.org/dev/peps/pep-0263/), you can specify utf-8 encoded strings with the following at the top of the file.
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
``` | 5,572 |
12,311,226 | I am new to python and am having difficulties with an assignment for a class.
Here's my code:
```
print ('Plants for each semicircle garden: ',round(semiPlants,0))
```
Here's what gets printed:
```
('Plants for each semicircle garden:', 50.0)
```
As you see I am getting the parenthesis and apostrophes, which I d... | 2012/09/07 | [
"https://Stackoverflow.com/questions/12311226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1355158/"
] | You're clearly using python2.x when you think you're using python3.x. In python 2.x, the stuff in the parenthesis is being interpreted as a `tuple`.
One fix is to use string formatting to do this:
```
print ( 'Plants for each semicircle garden: {0}'.format(round(semiPlants,0)))
```
which will work with python2.6 an... | You've tagged this question Python-3.x, but it looks like you are actually running your code with Python 2.
To see what version you're using, run, "python -V". | 5,573 |
57,169,454 | My dataset is a set of 2 columns with Spanish and English sentences. I created a training dataset using the Dataset API using the below code:
```
train_examples = tf.data.experimental.CsvDataset("./Data/train.csv", [tf.string, tf.string])
val_examples = tf.data.experimental.CsvDataset("./Data/validation.csv", [tf.str... | 2019/07/23 | [
"https://Stackoverflow.com/questions/57169454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8382950/"
] | You can perform ordering on the job\_set queryset, for example. Is something like this what you are looking for?
```
for worker in Worker.objects.all():
latest_job = worker.job_set.latest('start_date')
print(worker.name, latest_job.location, latest_job.start_date)
``` | You can use the `last` method on the filtered and ordered (by `start_date`, in ascending order) queryset of a worker.
For example, if the name of the worker is `foobar`, you can do:
```
Job.objects.filter(worker__name='foobar').order_by('start_date').last()
```
this will give you the last `Job` (based on `start_dat... | 5,575 |
1,043,735 | I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has ... | 2009/06/25 | [
"https://Stackoverflow.com/questions/1043735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | The most secure encryption is no encryption. Passwords should be reduced to a hash. This is a one-way transformation, making the password (almost) unrecoverable.
When giving someone a code, you can do the following to be *actually* secure.
(1) generate some random string.
(2) give them the string.
(3) save the has... | If it's a web game, can't you store the codes server side and send them to the client when he completed a task? What's the architecture of your game?
As for encryption, maybe try something like [pyDes](http://twhiteman.netfirms.com/des.html)? | 5,577 |
24,497,121 | I ask because the examples in the Facebook Ads API (<https://developers.facebook.com/docs/reference/ads-api/adimage/#create>) for creating an Ad Image all use curl, but I want to do it with python requests. Or if someone can answer the more specific question of how to create an Ad Image on the Facebook Ads API from pyt... | 2014/06/30 | [
"https://Stackoverflow.com/questions/24497121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3391108/"
] | Try `Holders.grailsApplication.config`:
```
@TestMixin(GrailsUnitTestMixin)
class TicketRequestEmailInfoSpec extends Specification {
def setup() {
Holders.grailsApplication.config.acme.purchase.trsUrlBase = "http://localhost:8082/purchase/order/"
}
``` | Didn't works injecting `grailsApplication` to test as `def grailsApplication` ?
Also you can import it as `import static grails.util.Holders.config as grailsConfig`.
And then use it as
```
@TestMixin(GrailsUnitTestMixin)
class TicketRequestEmailInfoSpec extends Specification {
def setup() {
grailsConfig... | 5,583 |
55,582,117 | GIMP has a convenient function that allows you to convert an arbitrary color to an alpha channel.
Essentially all pixels become transparent relative to how far away from the chosen color they are.
I want to replicate this functionality with opencv.
I tried iterating through the image:
```
for x in range(rows)... | 2019/04/08 | [
"https://Stackoverflow.com/questions/55582117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6202327/"
] | Here is my attempt only using `numpy` matrix operations.
My input image `colortrans.png` looks like this:
[](https://i.stack.imgur.com/l1ZPc.png)
I want to make the diagonal purple part `(128, 0, 128)` transparent with some tolerance `+/- (25, 0, 25)` to the left an... | I've done a project that converted all pixels that are close to white into transparent pixels using the `PIL` (python image library) module. I'm not sure how to implement your algorithm for "relative to how far away from chosen color they are", but my code looks like:
```
from PIL import Image
planeIm = Image.open('I... | 5,584 |
11,483,366 | >
> **Possible Duplicate:**
>
> [Making a method private in a python subclass](https://stackoverflow.com/questions/451963/making-a-method-private-in-a-python-subclass)
>
> [Private Variables and Methods in Python](https://stackoverflow.com/questions/3385317/private-variables-and-methods-in-python)
>
>
>
How... | 2012/07/14 | [
"https://Stackoverflow.com/questions/11483366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1254709/"
] | Python does not support access protection as C++/Java/C# does. Everything is public. The motto is, "We're all adults here." Document your classes, and insist that your collaborators read and follow the documentation.
The culture in Python is that names starting with underscores mean, "don't use these unless you really... | You can't. Python intentionally does not support access control. By convention, methods starting with an underscore are private, and you should clearly state in the documentation who is supposed to use the method. | 5,589 |
30,061,620 | I am calculating Euclidean Distance with python code below:
```
def getNeighbors(trainingSet, testInstance, k, labels):
distances = []
for x in range(len(trainingSet)):
dist = math.sqrt(((testInstance[0] - trainingSet[x][0]) ** 2) + ((testInstance[1] - trainingSet[x][1]) ** 2))
distances.app... | 2015/05/05 | [
"https://Stackoverflow.com/questions/30061620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2831683/"
] | You can speed this up by converting to NumPy first, then using vector operations, instead of doing the work in a loop, then converting to NumPy. Something like this:
```
trainingArray = np.array(trainingSet)
distances = ((testInstance[0] - trainingArray[:, 0]) ** 2 +
(testInstance[1] - trainingArray[:, 1]... | Writing own sqrt calculator has its own risks, hypot is very safe for resistance to overflow and underflow
```py
x_y = np.array(trainingSet)
x = x_y[0]
y = x_y[1]
distances = np.hypot(
np.subtract.outer(x, x),
np.subtract.outer(y, y)
)
```
Speed wise they are same
```
%%timeit
np.hypot(i, j)
# 1.29 µs ± 13.... | 5,590 |
45,495,753 | After many different ways of trying to install jupyter, it does not seem to install correctly.
May be MacOS related based on how many MacOS system python issues I've been having recently
`pip install jupyter --user`
Seems to install correctly
But then jupyter is not found
`where jupyter`
`jupyter not found`
Not f... | 2017/08/03 | [
"https://Stackoverflow.com/questions/45495753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] | Short answer: Use `python -m notebook`
After updating to OS Catalina, I installed a brewed python: `brew install python`.
It symlinks the Python3, but not the `python` command, so I added to my `$PATH` variable the following:
```
/usr/local/opt/python/libexec/bin
```
to make the brew python the default python com... | You need to add the local python install directory to your path. Apparently this is not done by default on MacOS.
Try:
```
export PATH="$HOME/Library/Python/<version number>/bin:$PATH"
```
and/or add it to your `~/.bashrc`. | 5,591 |
4,710,037 | I'm having trouble with SWIG, shared pointers, and inheritance.
I am creating various c++ classes which inherit from one another, using
Boost shared pointers to refer to them, and then wrapping these shared
pointers with SWIG to create the python classes.
My problem is the following:
* B is a subclass of A
* sA is a... | 2011/01/17 | [
"https://Stackoverflow.com/questions/4710037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1229275/"
] | The following change appears to solve the problem.
In **swig\_shared\_ptr.i** the two lines:
```
%template(base_sptr) boost::shared_ptr<Base>;
%template(derived_sptr) boost::shared_ptr<Derived>;
```
are moved so that they are above the line
```
%include <swig_shared_ptr.h>
```
and are then replaced (in SWIG 1.3)... | SWIG doesn't know anything about the `boost::shared_ptr<T>` class. It therefore can't tell that `derived_sptr` can be "cast" (which is, I believe, implemented with some crazy constructors and template metaprogramming) to `derived_sptr`. Because SWIG requires fairly simple class definitions (or inclusion of simple files... | 5,597 |
2,400,605 | I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want... | 2010/03/08 | [
"https://Stackoverflow.com/questions/2400605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235131/"
] | PHP is the best to start, but as experienced programmer you may want to look at Python, because PHP is a C style language. Python would be easier after Pascal, I think.
Take a look at examples:
On PHP: <http://en.wikipedia.org/wiki/Php#Syntax>
On Python: <http://en.wikipedia.org/wiki/Python_(programming_language)#Sy... | Only good answer - C# ;) Seriously ;)
Why? Anders Hejlsberg. He made it. It is the direct continuation of his work that started with Turbo Pascal and went over to Delphi... then Microsoft hired him and he moved from Pascal to C (core langauge) and made C#.
Read it up on <http://en.wikipedia.org/wiki/Anders_Hejlsberg>... | 5,598 |
31,682,981 | I am a newbie in Django un I want to write a Test for Django Web-poll application (<https://docs.djangoproject.com/en/1.8/intro/tutorial01/>)
but I got this error:
```
devuser@localhost:~/Django-apps/poolApp$ django-admin shell --plain --no-startup
Traceback (most recent call last):
File "/usr/local/bin/django-admi... | 2015/07/28 | [
"https://Stackoverflow.com/questions/31682981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4450024/"
] | Use `manage.py`, not `django-admin`. | What does work is using
```
django-admin shell --plain --no-startup --pythonpath "." --settings "myproject.settings"
```
while you are in the root of your django app.
However `manage.py shell` (or the amazing `shell_plus` from django\_extensions <https://github.com/django-extensions/django-extensions>) is recommend... | 5,608 |
46,034,924 | When I try to run python manage.py runserver I get this error:
```
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/user/lokvi/lokvi_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_l... | 2017/09/04 | [
"https://Stackoverflow.com/questions/46034924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3565829/"
] | You need to import `settings` module
```
from django.conf import settings
``` | Oh, It was not the python path specific question, sorry. I just needed `__init__.py` in settings module inside of my project, since there were no settings it tried to find it in python lib itself and couldn't, I believe. | 5,609 |
2,134,941 | For a package of mine, I have a README.rst file that is read into the setup.py's long description like so:
```
readme = open('README.rst', 'r')
README_TEXT = readme.read()
readme.close()
setup(
...
long_description = README_TEXT,
....
)
```
This way that I can have the README file show up on my [git... | 2010/01/25 | [
"https://Stackoverflow.com/questions/2134941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | Another option is to side-step the issue completely by adding a paragraph that works in both environments: "The latest unstable code is on github. The latest stable kits are on pypi."
After all, why assume that pypi people don't want to be pointed to github? This would be more helpful to both audiences, and simplifies... | You could always do this:
```
GITHUB_ALERT = 'This document reflects a pre-release version...'
readme = open('README.rst', 'r')
README_TEXT = readme.read().replace(GITHUB_ALERT, '')
readme.close()
setup(
...
long_description = README_TEXT,
....
)
```
But then you'd have to keep that `GITHUB_ALERT` s... | 5,610 |
64,375,499 | ```
def save_weights(self, filename = "./" + str(timestamp) + "-tfsave"):
### save model weights
saver = tf.train.Saver()
saver.save(self.sess, filename)
print("saved to:",filename)
```
---
UnknownError Traceback (most recent call last)
~\Anaconda3\envs\tf\lib\site-packages\tensorflow\_core\pyt... | 2020/10/15 | [
"https://Stackoverflow.com/questions/64375499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12137831/"
] | You can achieve this without javascript by using a [media-query](https://www.w3schools.com/css/css_rwd_mediaqueries.asp):
```css
#show-nav {
display: none;
background-color: red;
}
/* if screen width is smaller than 720px, #show-nav will be a block */
@media only screen and (max-width: 720px) {
#show-nav {
... | You could use only css to do so.
DEMO (make it full page)
------------------------
```css
body{
margin: 0;
}
nav{
width: 100vw;
background:yellow;
}
@media only screen and (min-width: 720px){
nav{
background:red;
}
}
```
```html
<nav>
<ul>
<li>Welcome</li>
</ul>
</nav
``` | 5,613 |
50,539,199 | So I am trying to find a way to "merge" a dependency list which is in the form of a dictionary in python, and I haven't been able to come up with a solution. So imagine a graph along the lines of this: (all of the lines are downward pointing arrows in this directed graph)
```
1 2 4
\ / / \
3 5 8
\ / \ ... | 2018/05/26 | [
"https://Stackoverflow.com/questions/50539199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9849681/"
] | You can use a chained `dict comprehension` with `list comprehension` for up to two nodes.
```
>>> {k: v + [item for i in v for item in d.get(i, [])] for k,v in d.items()}
{3: [1, 2],
5: [4],
6: [3, 5, 1, 2, 4],
7: [5, 4],
8: [4],
9: [8, 4],
1: [],
2: [],
4: []}
```
---
For unlimited depth, you can use a r... | Here's a really simple way to do it.
```
In [22]: a
Out[22]: {1: [], 2: [], 3: [1, 2], 4: [], 5: [4], 6: [3, 5], 7: [5], 8: [4], 9: [8]}
In [23]: final = {}
In [24]: for key in a:
...: nodes = set()
...:
...: for val in a[key]:
...: nodes.add(val)
...: if val ... | 5,615 |
24,635,064 | Here is my problem with urllib in python 3.
I wrote a piece of code which works well in Python 2.7 and is using urllib2. It goes to the page on Internet (which requires authorization) and grabs me the info from that page.
The real problem for me is that I can't make my code working in python 3.4 because there is no u... | 2014/07/08 | [
"https://Stackoverflow.com/questions/24635064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3816874/"
] | Thankfully to you guys I finally figured out the way it works.
Here is my code:
```
request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string = base64.b64encode(bytes('%s:%s' % ('login', 'password'),'ascii'))
request.add_header("Authorization", "Basic %s" % base64string.decode('utf-8'))
... | What about [urllib.request](https://docs.python.org/dev/library/urllib.request.html) ? It seems it has everything you need.
```
import base64
import urllib.request
request = urllib.request.Request('http://mysite/admin/index.cgi?index=127')
base64string = bytes('%s:%s' % ('login', 'password'), 'ascii')
request.add_he... | 5,616 |
57,073,765 | I'm writing API results to CSV file in python 3.7. Problem is it adds double quotes ("") to each row when it writes to file.
I'm passing format as csv to API call, so that I get results in csv format and then I'm writing it to csv file, store to specific location.
Please suggest if there is any better way to do this.
... | 2019/07/17 | [
"https://Stackoverflow.com/questions/57073765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8449329/"
] | This is maybe the same as your original code, but use `prop()` instead of `attr()`.
>
> [`attr()`](https://api.jquery.com/attr/) - As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of for... | You can try to bind the change event on the `.form-check-input` class, and inside that event you can check wheter if the checkboxes are "empty" or not.
```js
$('.form-check-input').on("change", function(){
var noChecked = $('.form-check-input:checked').length;
if(noChecked === 0){
console.log("0 checkboxes... | 5,619 |
19,736,625 | I'm trying to write my first python script. I want to write a program that will get information out of a website.
I managed to open the website, read all the data and transform the data from bytes to a string.
```
import urllib.request
response = urllib.request.urlopen('http://www.imdb.com/title/tt0413573/episodes?... | 2013/11/01 | [
"https://Stackoverflow.com/questions/19736625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2904861/"
] | When dealing with structured texts like HTML/XML it is a good idea to use existing tools that leverage this structure. Instead of using regex or searching by hand, this gives a much more reliable and readable solution. In this case, I suggest to install [lxml](http://lxml.de/) to parse the HTML.
Applying this principl... | Would that work?
```
lines = website.splitlines()
lines.append('')
for index, line in enumerate(lines):
for keyword in ["airdate","episodeNumber"]:
if keyword in line:
print(lines[index + 1])
```
It prints the next line if the keyword is found in the line. | 5,620 |
61,370,108 | I have a data input pipeline that has:
* input datapoints of types that are not castable to a `tf.Tensor` (dicts and whatnot)
* preprocessing functions that could not understand tensorflow types and need to work with those datapoints; some of which do data augmentation on the fly
I've been trying to fit this into a `... | 2020/04/22 | [
"https://Stackoverflow.com/questions/61370108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5235369/"
] | Please read the documentation first before post any questions. Visit <https://react-bootstrap.github.io/components/toasts/>
change
>
> import { Toast } from 'react-bootstrap';
>
>
>
with
>
> import Toast from 'react-bootstrap/Toast'
>
>
> | Change your import to
import { Toast } from 'react-bootstrap/Toast' | 5,622 |
25,056,700 | I am trying to connect to cassandra from python , I have installed `cassandra` as `pip install pycassa`.When i am trying to connect to the `cassandra` i am getting the following exception
```
from pycassa.pool import ConnectionPool
pool = ConnectionPool('Keyspace1')
Traceback (most recent call last):
File "<stdin>", ... | 2014/07/31 | [
"https://Stackoverflow.com/questions/25056700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531707/"
] | Perhaps the best known is the *branchless absolute value*:
```
int m = x >> 31;
int abs = x + m ^ m;
```
Which uses an arithmetic shift to copy the signbit to all bits. Most uses of arithmetic shift that I've encountered were of that form. Of course an arithmetic shift is not *required* for this, you could replace a... | In C when writing device drivers, bit shift operators are used extensively since bits are used as switches that need to be turned on and off. Bit shift allow one to easily and correctly target the right switch.
Many hashing and cryptographic functions make use of bit shift. Take a look at [Mercenne Twister](https://en... | 5,623 |
45,920,527 | I would like to download a subset of a WAT archive segment from Amazon S3.
**Background:**
Searching the Common Crawl index at <http://index.commoncrawl.org> yields results with information about the location of WARC files on AWS S3. For example, searching for [url=www.celebuzz.com/2017-01-04/\*&output=json](http://... | 2017/08/28 | [
"https://Stackoverflow.com/questions/45920527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861935/"
] | The Common Crawl index does not contain offsets into WAT and WET files. So, the only way is to search the whole WAT/WET file for the desired record/URL. Eventually, it would be possible to estimate the offset because the record order in WARC and WAT/WET files is the same. | After many trial and error I had managed to get a range from a warc file in python and boto3 the following way:
```
# You have this form the index
offset, length, filename = 2161478, 12350, "crawl-data/[...].warc.gz"
import boto3
from botocore import UNSIGNED
from botocore.client import Config
# Boto3 anonymous logi... | 5,633 |
52,898,576 | I am trying to read a json data from an input file, and to pass it as the request to make a http call in python.
Here is the highlights in my python code:
```
with open('input.json') as f:
raw_data = json.load(f)
cookies = ...
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Accept': ... | 2018/10/19 | [
"https://Stackoverflow.com/questions/52898576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3595231/"
] | When you pass a `dict` (which is what `raw_data` is) as the `data` argument to `requests.put`, it will be form-encoded, which does not make for valid JSON. Either pass serialized JSON to `data`:
```
requests.put(..., data=json.dumps(raw_data), ...)
```
or use the `json` keyword and let `requests` do the serializatio... | ```
with open('input.json') as f:
```
did you mean
```
with open('input.json','r') as f:
```
or
```
with open('input.json','rb') as f:
```
if the data is stored as bytes, you have to read it in as 'rb'. | 5,634 |
58,660,173 | Given a list of dictionaries like:
```
history = [
{
"actions": [{"action": "baz", "people": ["a"]}, {"action": "qux", "people": ["d", "e"]}],
"events": ["foo"]
},
{
"actions": [{"action": "baz", "people": ["a", "b", "c"]}],
"events": ["foo", "bar"]
},
]
```
What is the most efficient (whilst... | 2019/11/01 | [
"https://Stackoverflow.com/questions/58660173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4007992/"
] | You can use `collections.defaultdict` with `itertools.groupby`:
```
from collections import defaultdict
from itertools import groupby as gb
d = defaultdict(list)
for i in history:
for b in i['events']:
d[b].extend(i['actions'])
new_d = {a:[(j, list(k)) for j, k in gb(sorted(b, key=lambda x:x['action']), key=lam... | It is not a less verbose answer, but maybe a bit better readable. Also it does not depend on anything else and is just standard python.
```
tmp_dict = {}
for d in history:
for event in d["events"]:
if event not in tmp_dict:
tmp_dict[event] = {}
for actions in d["actions"]:
... | 5,635 |
25,043,982 | i'm having some trouble to handle jpeg files on Python under AWS Elastic Beanstalk.
I have this on .ebextensions/python.config file:
```
packages:
yum:
libjpeg-turbo-devel: []
libpng-devel: []
freetype-devel: []
...
```
So i believe i have libjpeg installed and working (i tried libjpeg-devel, but yum can't f... | 2014/07/30 | [
"https://Stackoverflow.com/questions/25043982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541615/"
] | Following the general advice from [here](https://stackoverflow.com/questions/8915296/python-image-library-fails-with-message-decoder-jpeg-not-available-pil?rq=1), I solved this by adding the following in my .ebextensions configuration and re-deploying.
```
packages:
yum:
libjpeg-turbo-devel: []
libpng-devel... | As suggested, I SSHed again into the instance and reinstalled Pillow through pip (/opt/python/run/venv/bin/pip), not before I has had sure libjpeg-devel was on environment before Pillow.
I ran selftest.py and it confirmed that I had support for jpeg. So, in a last try, I went to "Restart App Server" on Elastic Beansta... | 5,636 |
25,087,111 | I'm running a simulation on a 2D space with periodic boundary conditions. A continuous function is represented by its values on a grid. I need to be able to evaluate the function and its gradient at any point in the space. Fundamentally, this isn't a hard problem -- or to be precise, it's an almost already solved probl... | 2014/08/01 | [
"https://Stackoverflow.com/questions/25087111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672942/"
] | It appears that the python function that comes closest is scipy.signal.cspline2d. This is exactly what I want, *except* that it assumes mirror-symmetric boundary conditions. Thus, it appears that I have three options:
1. Write my own cubic spline interpolation function that works with periodic boundary conditions, per... | Another function that could work is `scipy.ndimage.interpolation.map_coordinates`.
It does spline interpolation with periodic boundary conditions.
It does not not directly provide derivatives, but you could calculate them numerically. | 5,637 |
27,214,053 | I am getting an error when trying to install uinput
I tried PIP and `easy_install`. I also tried to install 'manually' from tar package.
I always get an error. Below is the error I get when installing with easy\_install.
Can you guide me on how to fix it ?
```
rpi@torpi ~/scripts $ sudo easy_install python-uinput
Sea... | 2014/11/30 | [
"https://Stackoverflow.com/questions/27214053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308766/"
] | Had this problem and fixed it with
```
sudo apt-get install libudev-dev
``` | I could not get input to install properly so, I ended up using [evdev](https://pypi.python.org/pypi/evdev) instead. | 5,642 |
49,741,030 | I am building a RESTful API using Python 3.6, the Falcon Framework, Google App Engine, and Firebase Cloud Firestore. At runtime I am receiving the following error ...
```
File "E:\Bill\Documents\GitHubProjects\LetsHang-BackEnd\lib\google\cloud\firestore_v1beta1\_helpers.py", line 24, in <module> import grpc
File "E... | 2018/04/09 | [
"https://Stackoverflow.com/questions/49741030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7183052/"
] | You seem to be mixing up the GAE standard and flexible environments:
* using Python 3.6 is only possible in the flexible environment (which, BTW, is fundamentally Docker-based)
* installing app dependencies in the `lib` directory and using `dev_appserver.py` for local development are only applicable to the standard en... | Ok. I will write up my findings just in case there's another fool like me.
First, [Dan's](https://stackoverflow.com/users/4495081/dan-cornilescu) response is correct. I was mixing standard and flexible environments. I had looked up a method for using the Falcon Framework with App Engine; as it turns out, the only arti... | 5,645 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.