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
|
|---|---|---|---|---|---|---|
73,027,674
|
I have a Vertex AI notebook that contains a lot of python and jupyter notebook as well as pickled data files in it. I need to move these files to another notebook. There isn't a lot of documentation on google's help center.
Has someone had to do this yet? I'm new to GCP.
|
2022/07/18
|
[
"https://Stackoverflow.com/questions/73027674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5917787/"
] |
Can you try these steps in this [article](https://cloud.google.com/vertex-ai/docs/workbench/user-managed/migrate). It says you can copy your files to a [Google Cloud Storage Bucket](https://cloud.google.com/storage/) then move it to a new notebook by using gsutil tool.
In your notebook's terminal run this code to copy an object to your Google Cloud storage bucket:
```
gsutil cp -R /home/jupyter/* gs://BUCKET_NAMEPATH
```
Then open a new terminal to the target notebook and run this command to copy the directory to the notebook:
```
gsutil cp gs://BUCKET_NAMEPATH* /home/jupyter/
```
Just change the `BUCKET_NAMEPATH` to the name of your cloud storage bucket.
|
I'm assuming that both notebooks are on the same GC project and that you have the same permissions on both, ok?
There are many ways to do that... Listing some here:
1. The hardest to execute, but the simplest by concept: You can download everything for your computer/workstation from the original notebook instance, then go to the second notebook instance and upload everything
2. You can use [Google Cloud Storage](https://cloud.google.com/storage/), the object storage service to be used as the medium for the files movement. To do that you need to (1) [create a storage bucket](https://cloud.google.com/storage/docs/creating-buckets), (2) then using your notebook instance terminal, [copy the data from the instance to the bucket](https://cloud.google.com/storage/docs/uploading-objects), (3) and finally use the console on the target notebook instance and [copy the data from the bucket to the instance](https://cloud.google.com/storage/docs/downloading-objects)
| 10,468
|
1,997,327
|
Given this python code:
```
import webbrowser
webbrowser.open("http://slashdot.org",new=0)
webbrowser.open("http://cnn.com",new=0)
```
I would expect a browser to open up, load the first website, then load the second website *in the same window*. However, it opens up in a new window (or new tab depending on which browser I'm using).
Tried on Mac OSX with Safari, Firefox and Chrome and on Ubuntue with Firefox. I'm inclined to believe that *new=0* isn't honored. Am I just missing something?
tia,
|
2010/01/04
|
[
"https://Stackoverflow.com/questions/1997327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83879/"
] |
Note that the documentation specifically avoids guarantees with the language *if possible*: <http://docs.python.org/library/webbrowser.html#webbrowser.open>
Most browser settings by default specify tab behavior and will not allow Python to override it. I have seen it in the past using Firefox and tried your example on Chrome to the same effect.
On Windows, it is not possible to specify the tab behavior at all, as suggested by my comment below. The url opening code ignores `new`:
```
if sys.platform[:3] == "win":
class WindowsDefault(BaseBrowser):
def open(self, url, new=0, autoraise=True):
try:
os.startfile(url)
```
|
I added a delay between successive invocations of `webbrowser.open()`. Then each was opened in a new tab instead of a separate window (on my Windows 10 machine).
```py
import time
...
time.sleep(0.5)
```
| 10,469
|
27,214,901
|
Please consider the following short Python 2.x script:
```
#!/usr/bin/env python
class A(object):
class B(object):
class C(object):
pass
def __init__(self):
self.c = A.B.C()
def __init__(self):
self.b = A.B()
def main():
a = A()
print "%s: %r" % (type(a).__name__, type(a))
print "%s: %r" % (type(a.b).__name__, type(a.b))
print "%s: %r" % (type(a.b.c).__name__, type(a.b.c))
if __name__ == "__main__":
main()
```
The output of which, when run in Python 2.7.6, is:
```
A: <class '__main__.A'>
B: <class '__main__.B'>
C: <class '__main__.C'>
```
---
I was expecting a different output here. Something more along the lines of:
```
A: <class '__main__.A'>
A.B: <class '__main__.A.B'>
A.B.C: <class '__main__.A.B.C'>
```
In particular I expected to see the same qualified name that I have to give to instantiate `A.B` and `A.B.C` classes respectively.
Could anyone shed any light on why those new type classes identify themselves as rooted in `__main__` instead of how they were nested in the code?
Also: is there a way to fix this by naming the nested classes explicitly, such that they will identify themselves as `A.B` and `A.B.C` respectively (or possibly in the type representation as `__main__.A.B` and `__main__.A.B.C` respectively)?
|
2014/11/30
|
[
"https://Stackoverflow.com/questions/27214901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/476371/"
] |
Here are two demonstrative programs one for C++ 2003 and other for C++ 2011 that do the search
**C++ 2003**
```
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
struct FindName : std::unary_function<bool,
const std::pair<std::string, std::string>>
{
FindName( const std::pair<std::string, std::string> &p ) : p( p ){}
bool operator ()( const std::vector<std::string> &v ) const
{
return v.size() > 1 &&
v[0] == p.first && v[1] == p.second;
}
protected:
const std::pair<std::string, std::string> p;
};
int main()
{
const size_t N = 5;
std::vector<std::vector<std::string>> v;
v.reserve( N );
const char * initial[N][3] =
{
{ "Joan", "Williams", "30" },
{ "Mike", "Williams", "40" },
{ "Joan", "Smith", "30" },
{ "William", "Anderson", "20" },
{ "Sara", "Jon", "33" }
};
for ( size_t i = 0; i < N; i++ )
{
v.push_back( std::vector<std::string>( initial[i], initial[i] + 3 ) );
}
std::pair<std::string, std::string> p( "Joan", "Williams" );
typedef std::vector<std::vector<std::string>>::iterator iterator;
iterator it = std::find_if( v.begin(), v.end(), FindName( p ) );
if ( it != v.end() )
{
for ( std::vector<std::string>::size_type i = 0; i < it->size(); ++i )
{
std::cout << ( *it )[i] << ' ';
}
}
std::cout << std::endl;
}
```
**C++ 2011**
```
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
int main()
{
std::vector<std::vector<std::string>> v =
{
{ "Joan", "Williams", "30" },
{ "Mike", "Williams", "40" },
{ "Joan", "Smith", "30" },
{ "William", "Anderson", "20" },
{ "Sara", "Jon", "33" }
};
std::pair<std::string, std::string> p( "Joan", "Williams" );
auto it = std::find_if( v.begin(), v.end(),
[&]( const std::vector<std::string> &row )
{
return row.size() > 1 &&
row[0] == p.first && row[1] == p.second;
} );
if ( it != v.end() )
{
for ( const auto &s : *it ) std::cout << s << ' ';
}
std::cout << std::endl;
}
```
The both programs' putput is
Joan Williams 30
|
I strongly advise you to use a data structure with an overloaded equality operator instead of `vector<string>` (especially since it seems like the third element should be saved in an integer, not a string).
Anyway, this is one possibility:
```
auto iter = std::find_if( std::begin(a_words), std::end(a_words),
[] (std::vector<std::string> const& vec)
{ return vec[0] == "Joan" && vec[1] == "Williams";};
```
If the list is lexicographically sorted by the first or second column, a binary search can be used instead.
| 10,470
|
24,804,667
|
I'm trying to wrap a C library for python using SWIG. I'm on a linux 64-bit sytem (Gentoo) using the standard system toolchain. The library (SUNDIALS) is installed on my system with shared libraries in `/usr/local/lib`
My interface file is simple (to start with)
```
%module nvecserial
%{
#include "sundials/sundials_config.h"
#include "sundials/sundials_types.h"
#include "sundials/sundials_nvector.h"
#include "nvector/nvector_serial.h"
%}
%include "sundials/sundials_config.h"
%include "sundials/sundials_types.h"
%include "sundials/sundials_nvector.h"
%include "nvector/nvector_serial.h"
```
Given the interface file above, I run
```
$ swig -python -I/usr/local/include nvecserial.i
$ gcc -O2 -fPIC -I/usr/include/python2.7 -c nvecserial_wrap.c
$ gcc -shared /usr/local/lib/libsundials_nvecserial.so nvecserial_wrap.o -o _nvecserial.so
$ python -c "import nvecserial"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "nvecserial.py", line 28, in <module>
_nvecserial = swig_import_helper()
File "nvecserial.py", line 24, in swig_import_helper
_mod = imp.load_module('_nvecserial', fp, pathname, description)
ImportError: ./_nvecserial.so: undefined symbol: N_VLinearSum
```
A little digging to double check things shows
```
$ objdump -t /usr/local/lib/libsundials_nvecserial.so |grep Linear
0000000000001cf0 g F .text 00000000000002e4 N_VLinearSum_Serial
$ objdump -t _nvecserial.so |grep Linear
00000000000097e0 l F .text 0000000000000234 _wrap_N_VLinearSum
000000000000cd10 l F .text 0000000000000234 _wrap_N_VLinearSum_Serial
0000000000000000 *UND* 0000000000000000 N_VLinearSum
0000000000000000 F *UND* 0000000000000000 N_VLinearSum_Serial
```
As far as I can tell, N\_VLinearSum is a wrapper around N\_VLinearSum\_Serial (there's a parallel implementation too, so presumably, N\_VLinearSum in nvecparallel would wrap N\_VLinearSum\_Parallel). Where I'm lost though is what to do next. Is this a problem with my interface definition, or a problem with my compilation?
|
2014/07/17
|
[
"https://Stackoverflow.com/questions/24804667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184986/"
] |
We'll I've got it working by linking in an extra library. It seems `libsundials_nvecserial.so` and brethren don't contain the symbol N\_VLinearSum. The SUNDIALS make process places functions and symbols from `sundials_nvector.h` into different .so files, somewhat counter intuitively.
For now, I got this working with
```
$ gcc -shared -L/usr/local/lib nvecserial_wrap.o -o _nvecserial.so\
-lsundials_nvecserial -lsundials_cvode
$ python -c "import nvecserial"
$
```
I'll continue playing around with actual .o files from the source distribution, but considering the intent to distribute the wrapped module eventually using distutils, and that not everyone will have access to the SUNDIALS source on their systems, I'll probably stick with linking in the extra shared library.
|
Instead of
```
gcc -shared /usr/local/lib/libsundials_nvecserial.so nvecserial_wrap.o -o _nvecserial.so
```
try
```
gcc -shared -L/usr/local/lib nvecserial_wrap.o -o _nvecserial.so -lsundials_nvecserial
```
The -l should be at end otherwise the lib may not be searched for symbols. This is explained in the ld man page.
| 10,473
|
38,791,685
|
I want to generate a single executable file from my python script.
For this I use pyinstaller. I had issues with mkl libraries because I use numpy in the script.
I used this [hook](https://github.com/pyinstaller/pyinstaller/issues/1881 "hook") so solve the issue, it worked fine. But it does not work if I copy the single executable file to another directory and execute it. I guess I have to copy the hook also. But I just want to have one single file that I can use at other computers without copying `.dll's` or the hook.
I also changed the `.spec` file as described [here](https://pythonhosted.org/PyInstaller/spec-files.html) and added the necessary files to the `binaries`-variable. That also works as long as the `.dll's` are in the provided directory for the `binaries`-variable , but that won't work when I use the executable on a computer that doesn't have these `.dll's`.
I tried using the `--hidden-import= FILENAME` option. This also solves the issue, but just when the `.dll's` are provided somewhere.
What I'm looking for is a possibility to bundle the `.dll's` into the single executable file so that I have one file that works independently.
|
2016/08/05
|
[
"https://Stackoverflow.com/questions/38791685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5521383/"
] |
When I faced problem described here
<https://github.com/ContinuumIO/anaconda-issues/issues/443>
my workaround was
`pyinstaller -F --add-data vcruntime140.dll;. myscript.py`
`-F` - collect into one *\*.exe* file
`.` - Destination path of dll in exe file
from docs
<http://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-data-files>
|
As the selected answer didn't work for the case of using **libportaudio64bit.dll**, I put my working solution here.
For me, the working solution is to add **\_sounddevice\_data** folder where the .exe file is located then making a **portaudio-binaries** folder in it and finally putting **libportaudio64bit.dll** in the recently created folder.
Hope it helps!
| 10,474
|
10,550,870
|
I have some Pickled data, which is stored on disk, and it is about 100 MB in size.
When my python program is executed, the picked data is loaded using the `cPickle` module, and all that works fine.
If I execute the python multiple times using `python main.py` for example, each python process will load the same data multiple times, which is the correct behaviour.
How can I make it so, all new python process share this data, so it is only loaded a single time into memory?
|
2012/05/11
|
[
"https://Stackoverflow.com/questions/10550870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/406930/"
] |
If you're on Unix, one possibility is to load the data into memory, and then have the script use [`os.fork()`](http://docs.python.org/library/os.html#os.fork) to create a bunch of sub-processes. As long as the sub-processes don't attempt to *modify* the data, they would automatically share the parent's copy of it, without using any additional memory.
Unfortunately, this won't work on Windows.
P.S. I [once asked](https://stackoverflow.com/questions/6270849/placing-python-objects-in-shared-memory) about placing Python objects into shared memory, but that didn't produce any easy solutions.
|
Depending on how seriously you need to solve this problem, you may want to look at memcached, if that is not overkill.
| 10,479
|
41,612,654
|
I got an error after I modified the User Model in django.
when I was going to create a super user, it didn't prompt for username, instead it skipped it, anyway the object propery username still required and causing the user creation to failed.
```
import jwt
from django.db import models
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager,
PermissionsMixin)
from datetime import datetime, timedelta
from django.conf import settings
# from api.core.models import TimeStampedModel
class AccountManager(BaseUserManager):
def create_user(self, username, email, password=None, **kwargs):
if not email:
raise ValueError('Please provide a valid email address')
if not kwargs.get('username'):
# username = 'what'
raise ValueError('User must have a username')
account = self.model(
email=self.normalize_email(email), username=kwargs.get('username'))
account.set_password(password)
account.save()
return account
def create_superuser(self,username, email, password, **kwargs):
account = self.create_user(username, email, password, **kwargs)
account.is_admin = True
account.save()
return account
class Account(AbstractBaseUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length =40, blank=True)
tagline = models.CharField(max_length=200, blank=True)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELD = ['username']
objects = AccountManager()
def __str__(self):
return self.username
@property
def token(self):
return generate_jwt_token()
def generate_jwt_token(self):
dt = datetime.now + datetime.timedelta(days=60)
token = jwt.encode({
'id': self.pk,
'exp': int(dt.strftime('%s'))
}, settings.SECRET_KEY, algorithm='HS256')
return token.decode('utf-8')
def get_full_name(self):
return ' '.join(self.first_name, self.last_name)
def get_short_name(self):
return self.username
```
it results this :
```
manage.py createsuperuser
Running 'python /home/gema/A/PyProject/janet_x/janet/manage.py createsuperuser' command:
Email: admin@nister.com
Password:
Password (again):
Traceback (most recent call last):
File "/home/gema/A/PyProject/janet_x/janet/manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
return super(Command, self).execute(*args, **options)
File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/home/gema/.virtualenvs/JANET/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'
```
When I use the shell :
```
Account.objects.create(u'administer', u'admin@ister.com', u'password123')
```
it returns :
```
return getattr(self.get_queryset(), name)(*args, **kwargs)
TypeError: create() takes 1 positional argument but 3 were given
```
What could possibly be wrong ?
Thank you.
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41612654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3465227/"
] |
`REQUIRED_FIELD` should be `REQUIRED_FIELDS` (plural), otherwise you won't be prompted for a username (or any other required fields) because Django did not find anything in `REQUIRED_FIELDS`.
As an example, I use this UserManager in one of my projects:
```
class UserManager(BaseUserManager):
def create_user(self, email, password=None, first_name=None, last_name=None, **extra_fields):
if not email:
raise ValueError('Enter an email address')
if not first_name:
raise ValueError('Enter a first name')
if not last_name:
raise ValueError('Enter a last name')
email = self.normalize_email(email)
user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, first_name, last_name):
user = self.create_user(email, password=password, first_name=first_name, last_name=last_name)
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
```
`USERNAME_FIELD` is set to `email` and `REQUIRED_FIELDS` to `('first_name', 'last_name')`. You should be able to adapt this example to fit your needs.
|
This bit doesn't make sense:
```
USERNAME_FIELD = 'email'
REQUIRED_FIELD = ['username']
```
Why have you set `USERNAME_FIELD` to "email"? Surely it should be "username".
| 10,480
|
48,617,779
|
I am receiving the error: `ImportError: No module named MySQLdb` whenever I try to run my local dev server and it is driving me crazy. I have tried everything I could find online:
1. `brew install mysql`
2. `pip install mysqldb`
3. `pip install mysql`
4. `pip install mysql-python`
5. `pip install MySQL-python`
6. `easy_install mysql-python`
7. `easy_install MySQL-python`
8. `pip install mysqlclient`
I am running out of options and can't figure out why I continue to receive this error. I am attempting to run my local dev server from using Google App Engine on a macOS Sierra system and I am using python version 2.7. I am also running: `source env/bin/activate` at the directory my project files are and am installing all dependencies there as well. My path looks like this:
`/usr/local/bin/python:/usr/local/mysql/bin:/usr/local/opt/node@6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/2.7/bin`
Does anyone have further ideas I can attempt to resolve this issue?
|
2018/02/05
|
[
"https://Stackoverflow.com/questions/48617779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918575/"
] |
When you are in the virtual env (`source venv/bin/activate`), just run in terminal:
```
sudo apt-get install python3-mysqldb
sudo apt-get install libmysqlclient-dev
pip install mysqlclient
```
You don't have to import anything in your py files.
The first one is just in case, but the other two work perfectly by themselves.
If you don't run `libmysqlclient-dev`, you won't be able to run any other mysql installation command while in the virtual environment.
|
Turns out I had the wrong python being pointed to in my virtualenv. It comes preinstalled with its own default python version and so, I created a new virtualenv and used the `-p` to set the python path to my own local python path.
| 10,481
|
21,807,660
|
I am trying to run the first example [here](http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html), but I am getting this error. I am using Ubuntu 13.10.
```
Failed to load OpenCL runtime
OpenCV Error: Unknown error code -220 (OpenCL function is not available: [clGetPlatformIDs]) in opencl_check_fn, file /home/cristi/opencv/modules/core/src/opencl/runtime/opencl_core.cpp, line 204
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /home/cristi/opencv/modules/imgproc/src/color.cpp, line 3159
Traceback (most recent call last):
File "/home/cristi/opencv1/src/video.py", line 11, in <module>
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: /home/cristi/opencv/modules/imgproc/src/color.cpp:3159: error: (-215) scn == 3 || scn == 4 in function cvtColor
Process finished with exit code 1
```
Also, this is the line that is causing the trouble (line 11 in my code):
```
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
```
What should I do?
|
2014/02/16
|
[
"https://Stackoverflow.com/questions/21807660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1852142/"
] |
As for the OpenCL failure, try installing required packages:
`sudo apt-get install ocl-icd-opencl-dev`
Worked for me. My guess is that OCL is a part of the `opencv_core` module, and if it failed to initialise, then many other components might behave strange.
|
>
> Failed to load OpenCL runtime
>
>
>
Most probably there is some problem with your installation. If you are not working with GPU, then I recommend you to turn off all CUDA/OpenCL modules in OpenCV during compilation.
>
> error: (-215) scn == 3 || scn == 4 in function cvtColor
>
>
>
This error says your input image should have 3 channel (BGR/color image) or 4 channel(RGBA image). So please check number of channels in `frame` by executing `print frame.shape`.
Since you are working with video, there is a high chance that your camera is not opened for capture, so that frame is not captured. In that case, `print frame.shape` will say it is `NoneType` data.
I recommend you to run the same code with an image instead of video. Even then if the error of OpenCL shows up, it is most likely a problem with your installation. If it works fine, problem may be with VideoCapture. You can check it as mentioned in the same tutorial:
>
> Sometimes, **cap** may not have initialized the capture. In that case,
> this code shows error. You can check whether it is initialized or not
> by the method **cap.isOpened()**. If it is True, OK.
>
>
>
| 10,483
|
54,140,922
|
I want to create a multiprocessing echo server. I am currently using telnet as my client to send messages to my echo server.Currently I can handle one telnet request and it echos the response. I initially, thought I should intialize the pid whenever I create a socket. Is that correct?
How do I allow several clients to connect to my server using multiprocessing.
```
#!/usr/bin/env python
import socket
import os
from multiprocessing import Process
def create_socket():
# Create socket
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Port for socket and Host
PORT = 8002
HOST = 'localhost'
# bind the socket to host and port
sockfd.bind((HOST, PORT))
# become a server socket
sockfd.listen(5)
start_socket(sockfd)
def start_socket(sockfd):
while True:
# Establish and accept connections woth client
(clientsocket, address) = sockfd.accept()
# Get the process id.
process_id = os.getpid()
print("Process id:", process_id)
print("Got connection from", address)
# Recieve message from the client
message = clientsocket.recv(2024)
print("Server received: " + message.decode('utf-8'))
reply = ("Server output: " + message.decode('utf-8'))
if not message:
print("Client has been disconnected.....")
break
# Display messags.
clientsocket.sendall(str.encode(reply))
# Close the connection with the client
clientsocket.close()
if __name__ == '__main__':
process = Process(target = create_socket)
process.start()
```
|
2019/01/11
|
[
"https://Stackoverflow.com/questions/54140922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9005618/"
] |
It's probably a good idea to understand which are blocking system calls and which are not. `listen` for example is not blocking and `accept` is blocking one. So basically - you created one process through `Process(..)`, that blocks at the `accept` and when a connection is made - handles that connection.
Your code should have a structure - something like following (pseudo code)
```
def handle_connection(accepted_socket):
# do whatever you want with the socket
pass
def server():
# Create socket and listen to it.
sock = socket.socket(....)
sock.bind((HOST, PORT))
sock.listen(5)
while True:
new_client = sock.accept() # blocks here.
# unblocked
client_process = Process(target=handle_connection, args=(new_client))
client_process.start()
```
I must also mention, while this is a good way to just understand how things can be done, it is not a good idea to start a new process for every connection.
|
The initial part of setting up the server, binding, listening etc (your `create_socket`) should be in the master process.
Once you `accept` and get a socket, you should spawn off a separate process to take care of that connection. In other words, your `start_socket` should be spawned off in a separate process and should loop forever.
| 10,485
|
23,922,691
|
I am trying to add argv[0] as variable to the SQL query below and running into compilation error below,what is the syntax to fix this?
```
#!/usr/bin/python
import pypyodbc as pyodbc
from sys import argv
component_id=argv[0]
server_name='odsdb.company.com'
database_name='ODS'
cnx = pyodbc.connect("DRIVER={SQL Server};SERVER="+server_name+";DATABASE="+database_name)
db_cursor=cnx.cursor()
SQL = 'SELECT Top 1 cr.ReleaseLabel ' + \
'FROM [ODS].[v000001].[ComponentRevisions] cr ' + \
'WHERE cr.ComponentId=' + component_id + \
'ORDER BY cr.CreatedOn DESC'
resp_rows_obj=db_cursor.execute(SQL)
print '('+', '.join([column_heading_tuple[0] for column_heading_tuple in resp_rows_obj.description])+')'
for row in resp_rows_obj:
print row
```
Error:-
```
pypyodbc.ProgrammingError: (u'42000', u"[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'BY'.")
```
|
2014/05/28
|
[
"https://Stackoverflow.com/questions/23922691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3654069/"
] |
Don't use string interpolation. Use SQL parameters; these are placeholders in the query where your database will insert values:
```
SQL = '''\
SELECT Top 1 cr.ReleaseLabel
FROM [ODS].[v000001].[ComponentRevisions] cr
WHERE cr.ComponentId = ?
ORDER BY cr.CreatedOn DESC
'''
resp_rows_obj = db_cursor.execute(SQL, (component_id,))
```
Values for the `?` placeholders are sourced from the second argument to the `cursor.execute()` function, a sequence of values. Here you only have one value, so I used a one-element tuple.
Note that you probably want `argv[1]`, **not** `argv[0]`; the latter is the script name, not the first argument.
|
to retrieve 1st command line argument do `component_id=argv[1]` instead of 0 which is the script name...
better yet, look at [argparse](https://docs.python.org/2/howto/argparse.html)
| 10,486
|
24,093,888
|
I am looking to do a large number of reverse DNS lookups in a small amount of time. I currently have implemented an asynchronous lookup using socket.gethostbyaddr and concurrent.futures thread pool, but am still not seeing the desired performance. For example, the script took about 22 minutes to complete on 2500 IP addresses.
I was wondering if there is any quicker way to do this without resorting to something like adns-python. I found this <http://blog.schmichael.com/2007/09/18/a-lesson-on-python-dns-and-threads/> which provided some additional background.
Code Snippet:
```
ips = [...]
with concurrent.futures.ThreadPoolExecutor(max_workers = 16) as pool:
list(pool.map(get_hostname_from_ip, ips))
def get_hostname_from_ip(ip):
try:
return socket.gethostbyaddr(ip)[0]
except:
return ""
```
I think part of the issue is that many of the IP addresses are not resolving and timing out. I tried:
```
socket.setdefaulttimeout(2.0)
```
but it seems to have no effect.
|
2014/06/07
|
[
"https://Stackoverflow.com/questions/24093888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2521829/"
] |
Because of the [Global Interpreter Lock](https://docs.python.org/dev/glossary.html#term-global-interpreter-lock), you should use `ProcessPoolExecutor` instead.
<https://docs.python.org/dev/library/concurrent.futures.html#processpoolexecutor>
|
please, use [asynchronous DNS](http://code.google.com/p/adns-python/), everything else will give you a very poor performance.
| 10,488
|
61,380,858
|
I want to create pandas data frame with multiple lists with different length. Below is my python code.
```
import pandas as pd
A=[1,2]
B=[1,2,3]
C=[1,2,3,4,5,6]
lenA = len(A)
lenB = len(B)
lenC = len(C)
df = pd.DataFrame(columns=['A', 'B','C'])
for i,v1 in enumerate(A):
for j,v2 in enumerate(B):
for k, v3 in enumerate(C):
if(i<random.randint(0, lenA)):
if(j<random.randint(0, lenB)):
if (k < random.randint(0, lenC)):
df = df.append({'A': v1, 'B': v2,'C':v3}, ignore_index=True)
print(df)
```
My lists are as below:
```
A=[1,2]
B=[1,2,3]
C=[1,2,3,4,5,6,7]
```
In each run I got different output and which is correct. But not covers all list items in each run. In one run I got below output as:
```
A B C
0 1 1 3
1 1 2 1
2 1 2 2
3 2 2 5
```
In the above output 'A' list's all items (1,2) are there. But 'B' list has only (1,2) items, the item 3 is missing. Also list 'C' has (1,2,3,5) items only. (4,6,7) items are missing in 'C' list. My expectation is: in each list each item should be in the data frame at least once and 'C' list items should be in data frame only once. My expected sample output is as below:
```
A B C
0 1 1 3
1 1 2 1
2 1 2 2
3 2 2 5
4 2 3 4
5 1 1 7
6 2 3 6
```
Guide me to get my expected output. Thanks in advance.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61380858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1999109/"
] |
You can add random values of each list to total length and then use [`DataFrame.sample`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html):
```
A=[1,2]
B=[1,2,3]
C=[1,2,3,4,5,6]
L = [A,B,C]
m = max(len(x) for x in L)
print (m)
6
a = [np.hstack((np.random.choice(x, m - len(x)), x)) for x in L]
df = pd.DataFrame(a, index=['A', 'B', 'C']).T.sample(frac=1)
print (df)
A B C
2 2 2 3
0 2 1 1
3 1 1 4
4 1 2 5
5 2 3 6
1 2 2 2
```
|
You can use transpose to achieve the same.
EDIT: Used random to randomize the output as requested.
```
import pandas as pd
from random import shuffle, choice
A=[1,2]
B=[1,2,3]
C=[1,2,3,4,5,6]
shuffle(A)
shuffle(B)
shuffle(C)
data = [A,B,C]
df = pd.DataFrame(data)
df = df.transpose()
df.columns = ['A', 'B', 'C']
df.loc[:,'A'].fillna(choice(A), inplace=True)
df.loc[:,'B'].fillna(choice(B), inplace=True)
```
This should give the below output
```
A B C
0 1.0 1.0 1.0
1 2.0 2.0 2.0
2 NaN 3.0 3.0
3 NaN 4.0 4.0
4 NaN NaN 5.0
5 NaN NaN 6.0
```
| 10,491
|
47,726,664
|
I am trying to send messages from one python script to another using MQTT. One script is a publisher. The second script is a subscriber. I send messages every 0.1 second.
Publisher:
```
client = mqtt.Client('DataReaderPub')
client.connect('127.0.0.1', 1883, 60)
print("MQTT parameters set.")
# Read from all files
count = 0
for i in range(1,51):
payload = "Hello world" + str(count)
client.publish(testtopic, payload, int(publisherqos))
client.loop()
count = count+1
print(count, ' msg sent: ', payload)
sleep(0.1)
```
Subscriber:
```
subclient = mqtt.Client("DynamicDetectorSub")
subclient.on_message = on_message
subclient.connect('127.0.0.1')
subclient.subscribe(testtopic, int(subscriberqos))
subclient.loop_forever()
```
mosquitto broker version - 3.1
mosquitto.conf has max inflight messages set to 0, persistence true.
publisher QOS = 2
subscriber QOS = 2
topic = 'test' in both scripts
When I run subscriber and publisher in the same script, the messages are sent and received as expected. But when they are in separate scripts, I do not receive all the messages and sometimes no messages. I run subscriber first and then publisher. I have tried subscriber with loop.start() and loop.stop() with waiting for few minutes.
I am unable to debug this problem. Any pointers would be great!
EDIT:
1. I included client.loop() after publish. -> Same output as before
2. When I printed out statements in 'on\_connect' and 'on\_disconnect', I noticed that client mqtt connection gets established and disconnects almost immediately. This happens every second. I even got this message once -
[WinError 10053] An established connection was aborted by the software in your host machine
Keep Alive = 60
Is there any other parameter I should look at?
|
2017/12/09
|
[
"https://Stackoverflow.com/questions/47726664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2892909/"
] |
You need to call the network loop function in the publisher as well so the client actually gets some time to do the IO (And the dual handshake for the QOS2).
Add `client.loop()` after the call to `client.publish()` in the client:
```
import paho.mqtt.client as mqtt
import time
client = mqtt.Client('DataReaderPub')
client.connect('127.0.0.1', 1883, 60)
print("MQTT parameters set.")
# Read from all files
count = 0
for i in range(1,51):
payload = "Hello world" + str(count)
client.publish("test", payload, 2)
client.loop()
count = count+1
print(count, ' msg sent: ', payload)
time.sleep(0.1)
```
Subscriber code:
```
import paho.mqtt.client as mqtt
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
subclient = mqtt.Client("DynamicDetectorSub")
subclient.on_message = on_message
subclient.connect('127.0.0.1')
subclient.subscribe("test", 2)
subclient.loop_forever()
```
|
When I ran your code, the subscriber was often missing the last packet. I was not otherwise able to reproduce the problems you described.
If I rewrite the publisher like this instead...
```
from time import sleep
import paho.mqtt.client as mqtt
client = mqtt.Client('DataReaderPub')
client.connect('127.0.0.1', 1883, 60)
print("MQTT parameters set.")
client.loop_start()
# Read from all files
count = 0
for i in range(1,51):
payload = "Hello world" + str(count)
client.publish('test', payload, 2)
count = count+1
print(count, ' msg sent: ', payload)
sleep(0.1)
client.loop_stop()
client.disconnect()
```
...then I no longer see the dropped packet. I'm using the `start_loop`/`stop_loop` methods here, which run the mqtt loop asynchronously. I'm not sure exactly what was causing your dropped packet, but I suspect that the final message was still in the publisher's send queue when the code exits.
| 10,492
|
47,486,930
|
The following script generates a 2d list in python:
```
matrix = [[0 for row in range (5)] for col in range (5)]
i = 2
matrix[i][i] = 1
matrix[i+1][i] = 1
matrix[i][i+1] = 1
matrix[i+1][i+1] = 1
for row in matrix:
for item in row:
print(item,end=" ")
print()
print()
```
The generated 2d list looks like this:
```
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
0 0 1 1 0
0 0 0 0 0
```
How can I find if I have a square with the same number (number must be 1) like shown up? The square with the same number must be 2x2
|
2017/11/25
|
[
"https://Stackoverflow.com/questions/47486930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3913519/"
] |
In order for this combination to work you need to make sure your `virtual-repeat-container` is kept in sync. If you write a simple 'refresh' function that gets called on open select:
```
function () {
return $timeout(function () {
$scope.$broadcast("$md-resize");
}, 100);
};
```
it should be enough. Working example:
```js
angular.module("app", ["ngMaterial", "ngSanitize", "ngAnimate"])
.controller("MainController", function($scope, $timeout) {
// refresh virtual container
$scope.refresh = function() {
return $timeout(function() {
$scope.$broadcast("$md-resize");
}, 100);
};
$scope.infiniteItems = {
_pageSize: 10000,
toLoad_: 0,
items: [],
getItemAtIndex(index) {
if (index > this.items.length) {
this.fetchMoreItems_(index);
return null;
}
return this.items[index];
},
getLength() {
return this.items.length + 5;
},
fetchMoreItems_(index) {
if (this.toLoad_ < index) {
this.toLoad_ += this._pageSize;
// simulate $http request
$timeout(angular.noop, 300)
.then(() => {
for (let i = 0; i < this._pageSize; i++) {
this.items.push(i)
}
});
}
}
};
});
```
```css
#vertical-container {
height: 256px;
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>select with md-virtual-repeat</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.0.9/angular-material.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular-aria.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular-animate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.0.9/angular-material.min.js"></script>
</head>
<body>
<div class="main" ng-app="app" ng-controller="MainController" layout="column" layout-align="center center" layout-fill>
<md-input-container>
<label>Select an option</label>
<md-select ng-model="haha" md-on-open="refresh()">
<md-virtual-repeat-container id="vertical-container">
<md-option md-virtual-repeat="item in infiniteItems" md-on-demand="" ng-value="item" ng-selected="haha==item">{{item}}</md-option>
</md-virtual-repeat-container>
</md-select>
</md-input-container>
</div>
</script>
</body>
</html>
```
You can also check out [this](https://stackoverflow.com/questions/34912151/is-there-a-way-to-refresh-virtual-repeat-container) similar answer.
|
According to <https://github.com/angular/material/issues/10868> this post, different angularjs version has different behaviour. Return $timeout function should have also `window.dispatchEvent(new Event('resize'));` statement.
Final $timeout function looks like this.
```
return $timeout(function() {
$scope.$broadcast("$md-resize");
window.dispatchEvent(new Event('resize'));
},100);
```
| 10,494
|
55,399,396
|
My searches lead me to the Pywin32 which should be able to mute/unmute the sound and detect its state (on Windows 10, using Python 3+). I found a way using an AutoHotkey script, but I'm looking for a pythonic way.
More specifically, I'm not interested in playing with the Windows GUI. *Pywin32 works using a Windows DLL*.
so far, I am able to do it by calling an ahk script:
In the python script:
```
import subprocess
subprocess.call([ahkexe, ahkscript])
```
In the AutoHotkey script:
```
SoundGet, sound_mute, Master, mute
if sound_mute = On ; if the sound is muted
Send {Volume_Mute} ; press the "mute button" to unmute
SoundSet 30 ; set the sound level at 30
```
|
2019/03/28
|
[
"https://Stackoverflow.com/questions/55399396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7227370/"
] |
You can use the Windows Sound Manager by paradoxis (<https://github.com/Paradoxis/Windows-Sound-Manager>).
```
from sound import Sound
Sound.mute()
```
Every call to `Sound.mute()` will toggle mute on or off. Have a look at the `main.py` to see how to use the setter and getter methods.
|
If you're also building a GUI, wxPython (and I would believe other GUI frameworks) have access to the windows audio mute "button".
| 10,495
|
10,868,410
|
I'm a little new to web crawlers and such, though I've been programming for a year already. So please bear with me as I try to explain my problem here.
I'm parsing info from Yahoo! News, and I've managed to get most of what I want, but there's a little portion that has stumped me.
For example: <http://news.yahoo.com/record-nm-blaze-test-forest-management-225730172.html>
I want to get the numbers beside the thumbs up and thumbs down icons in the comments. When I use "Inspect Element" in my Chrome browser, I can clearly see the things that I have to look for - namely, an em tag under the div class 'ugccmt-rate'. However, I'm not able to find this in my python program. In trying to track down the root of the problem, I clicked to view source of the page, and it seems that this tag is not there. Do you guys know how I should approach this problem? Does this have something to do with the javascript on the page that displays the info only after it runs? I'd appreciate some pointers in the right direction.
Thanks.
|
2012/06/03
|
[
"https://Stackoverflow.com/questions/10868410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1433227/"
] |
The page is being generated via JavaScript.
Check if there is a mobile version of the website first. If not, check for any APIs or RSS/Atom feeds. If there's *nothing* else, you'll either have to manually figure out what the JavaScript is loading and from where, or use [Selenium](http://seleniumhq.org/) to automate a browser that renders the JavaScript for you for parsing.
|
Using the Web Console in Firefox you can pretty easily see what requests the page is actually making as it runs its scripts, and figure out what URI returns the data you want. Then you can request that URI directly in your Python script and tease the data out of it. It is probably in a format that Python already has a library to parse, such as JSON.
Yahoo! may have some stuff on their server side to try to prevent you from accessing these data files in a script, such as checking the browser (user-agent header), cookies, or referrer. These can all be faked with enough perseverance, but you should take their existence as a sign that you should tread lightly. (They may also limit the number of requests you can make in a given time period, which is impossible to get around.)
| 10,496
|
46,382,384
|
I'm playing around with [Chalice](http://chalice.readthedocs.io/en/latest/) for the first time as I am trying to evaluate it as a possible replacement framework to migrate my existing Python Flask APIs from EC2 to Lambda.
From an Amazon Linux EC2 instance, I added some dependencies to a virtualenv I'm playing with. I then created a requirements.txt:
```
botocore==1.7.11
chalice==1.0.2
click==6.6
docutils==0.14
jmespath==0.9.3
MySQL-python==1.2.5
PyMySQL==0.7.11
python-dateutil==2.6.1
six==1.10.0
SQLAlchemy==1.1.14
typing==3.5.3.0
```
I then tried to deploy with `chalice deploy` and got:
```
Creating deployment package.
Could not install dependencies:
MySQL-python==1.2.5
typing==3.5.3.0
You will have to build these yourself and vendor them in
the chalice vendor folder.
Your deployment will continue but may not work correctly
if missing dependencies are not present. For more information:
http://chalice.readthedocs.io/en/latest/topics/packaging.html
........
```
I then tried to follow linked the [docs](http://chalice.readthedocs.io/en/latest/topics/packaging.html) and for the first problematic dependency `MySQL-python==1.2.5` I did the following:
```
cd vendor/
pip download MySQL-python==1.2.5
pip wheel MySQL-python-1.2.5.zip
rm rm MySQL-python-1.2.5.zip
unzip MySQL_python-1.2.5-cp27-cp27mu-linux_x86_64.whl
rm MySQL_python-1.2.5-cp27-cp27mu-linux_x86_64.whl
```
My vendor folder looks like:
```
ls vendor
MySQLdb _mysql_exceptions.py MySQL_python-1.2.5.dist-info _mysql.so
```
and now when I run chalice deploy I get:
```
(test)[ec2-user@ip-172-31-26-155 test]$ chalice deploy
Creating deployment package.
Could not install dependencies:
MySQL-python==1.2.5
You will have to build these yourself and vendor them in
the chalice vendor folder.
Your deployment will continue but may not work correctly
if missing dependencies are not present. For more information:
http://chalice.readthedocs.io/en/latest/topics/packaging.html
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: '_mysql.so'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: '_mysql_exceptions.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQL_python-1.2.5.dist-info/RECORD'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQL_python-1.2.5.dist-info/DESCRIPTION.rst'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQL_python-1.2.5.dist-info/WHEEL'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQL_python-1.2.5.dist-info/top_level.txt'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQL_python-1.2.5.dist-info/METADATA'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQL_python-1.2.5.dist-info/metadata.json'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/converters.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/release.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/__init__.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/cursors.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/times.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/connections.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/constants/REFRESH.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/constants/CLIENT.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/constants/ER.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/constants/FIELD_TYPE.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/constants/__init__.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/constants/CR.py'
zipped.write(full_path, zip_path)
/home/ec2-user/test/test/local/lib/python2.7/site-packages/chalice/deploy/packager.py:110: UserWarning: Duplicate name: 'MySQLdb/constants/FLAG.py'
zipped.write(full_path, zip_path)
```
From the documentation, it's not clear to me what I'm doing wrong. Can someone help?
|
2017/09/23
|
[
"https://Stackoverflow.com/questions/46382384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2620746/"
] |
You can remove "MySQL-python==1.2.5" from your requirements.txt (since it's already
present in your vendor directory)
See this [issue](https://github.com/aws/chalice/issues/626) in the Chalice repo for more info.
|
Looking at what you have in your directory listing you provided, I noticed you don't have a **init**.py file. This file identifies the folder as a library file. Put that in your vendors directory.
| 10,497
|
61,874,962
|
Running into installation error in python 3.8 for tensorflow and i'm wondering how to downgrade without losing my environments in pycharm.
|
2020/05/18
|
[
"https://Stackoverflow.com/questions/61874962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13435259/"
] |
1. [Download](https://www.python.org/downloads/) and install Python 3.7
2. In PyCharm, go to 'File' -> 'Settings' -> 'Project: <...>' -> 'Project Interpreter', and select 'Python 3.7' in the 'Project Interpreter' dropdown.
3. If you don't see it, click on the settings icon next to it, go
to the 'System Interpreter' tab, and browse to and select
'python.exe' from the **Python37** folder
|
Step1 : **Go to Preferences:**
[](https://i.stack.imgur.com/IBt7K.png)
Step 2: Go to Python Interpreter
[](https://i.stack.imgur.com/S5bVB.png)
Step 3: click Show All
[](https://i.stack.imgur.com/MmQWL.png)
Step 4: Click on + button
[](https://i.stack.imgur.com/RzSvO.png)
Step 5: select the Version you have installed on your computer.
[](https://i.stack.imgur.com/oNNHa.png)
Step 6: Select the added environment and click ok
[](https://i.stack.imgur.com/6RJGU.png)
| 10,498
|
61,353,951
|
I have tried to install Facebook Prophet in Anaconda on Ubuntu following the instructions at:
<https://facebook.github.io/prophet/docs/installation.html#installation-in-python>.
In Anaconda Navigator, when I click on the environment, fbprophet is listed along with the other installed packages. The problem is that when I try to use fbprophet in Jupyter:
```
from fbprophet import Prophet
```
I get an error: "ModuleNotFoundError: No module named 'fbprophet'". It's bizarre because the fbprophet package seems to be installed in my environment according to Anaconda.
Can anyone help, please?
Thanks!
|
2020/04/21
|
[
"https://Stackoverflow.com/questions/61353951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9415043/"
] |
It seems that you have installed the package in a separate environment in anaconda. I think when you are running jupyter notebook, it is running from the base environment, But actually you need to run it from the library environment. So if the case is this you need to install jupyter notebook in the other environment and then run the jypyter notebook from that environment. So at first make sure that you have installed jupyter notebook correctly on the appropriate environment. If you have installed it correctly then open jupyter notebook and in a code cell write the following commands and execute the cell.
First, execute this command in a code cell-
```
!conda install -c conda-forge fbprophet -y
```
Then in another code cell execute this command-
```
!pip install --upgrade plotly
```
Now try to import the library.
|
Recently the fbprophet project renamed to prophet.
If you are referring to it using old name you should install the old version.
```
pip/conda/mamba/whatever install prophet
```
| 10,500
|
21,866,036
|
When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ?
e.g. this works
```
python -c "import os.path; print os.getcwd()"
```
Shouldn't I explicitly `import os` for `os.getcwd` to be available ?
|
2014/02/18
|
[
"https://Stackoverflow.com/questions/21866036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346286/"
] |
It works and it is reliable. What happens under the hood is when you do
```
import os.path
```
then `os` gets imported and then `os.path`.
|
Yes, you can rely on it always working. Python has to include `os` in the namespace for `os.path` to work.
What won't work is using the `from os import path` notation. In that case, the os module is *not* brought into the namespace, only `path`.
| 10,506
|
57,076,851
|
I want to plot a bode plot of a system with the python control systems library. This is fairly easy. The problem is the plot of the margins. It is no problem to plot the phase margin. But how can I plot the gain margin?
So far, this is a part of my code:
```py
import control as cn
%matplotlib notebook
import matplotlib.pyplot as plt
Ks=2
T1=5
T2=0.3
T3=0.1
Gs=cn.tf(Ks,[T1*T2*T3, T1*T2+T1*T3+T2*T3, T1+T2+T3, 1])
Vr=1
Tn=1
plt.close()
R=cn.tf([Vr*Tn, Vr],[1, 0])
L=Gs*R
gm, pm, wg, wp = cn.margin(L)
_,_,_ = cn.bode(L,dB=True)
plt.axvline(x = wp,color='r')
```
|
2019/07/17
|
[
"https://Stackoverflow.com/questions/57076851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6883478/"
] |
Not the most elegant solution but hey it works for me.
```
###Import modules
import numpy as np
import control as ctl
import matplotlib.pyplot as plt
##Functions
def plot_margins(sys):
mag,phase,omega = ctl.bode(sys,dB=True,Plot=False)
magdB = 20*np.log10(mag)
phase_deg = phase*180.0/np.pi
Gm,Pm,Wcg,Wcp = ctl.margin(sys)
GmdB = 20*np.log10(Gm)
##Plot Gain and Phase
f,(ax1,ax2) = plt.subplots(2,1)
ax1.semilogx(omega,magdB)
ax1.grid(which="both")
ax1.set_xlabel('Frequency (rad/s)')
ax1.set_ylabel('Magnitude (dB)')
ax2.semilogx(omega,phase_deg)
ax2.grid(which="both")
ax2.set_xlabel('Frequency (rad/s)')
ax2.set_ylabel('Phase (deg)')
ax1.set_title('Gm = '+str(np.round(GmdB,2))+' dB (at '+str(np.round(Wcg,2))+' rad/s), Pm = '+str(np.round(Pm,2))+' deg (at '+str(np.round(Wcp,2))+' rad/s)')
###Plot the zero dB line
ax1.plot(omega,0*omega,'k--',lineWidth=2)
###Plot the -180 deg lin
ax2.plot(omega,-180+0*omega,'k--',lineWidth=2)
##Plot the vertical line from -180 to 0 at Wcg
ax2.plot([Wcg,Wcg],[-180,0],'r--',lineWidth=2)
##Plot the vertical line from -180+Pm to 0 at Wcp
ax2.plot([Wcp,Wcp],[-180+Pm,0],'g--',lineWidth=2)
##Plot the vertical line from min(magdB) to 0-GmdB at Wcg
ax1.plot([Wcg,Wcg],[np.min(magdB),0-GmdB],'r--',lineWidth=2)
##Plot the vertical line from min(magdB) to 0db at Wcp
ax1.plot([Wcp,Wcp],[np.min(magdB),0],'g--',lineWidth=2)
return Gm,Pm,Wcg,Wcp
#%%%Actuator Dynamics
G = ctl.tf([1],[1,2,1,0])
Gm,Pm,Wcg,Wcp=plot_margins(G)
plt.show()
```
|
Starting in version 0.8 of `control`, the [`bode_plot`](https://python-control.readthedocs.io/en/0.8.3/generated/control.bode_plot.html) function (also aliased as `bode`) has an option to plot margins.
```py
import control
sys = control.tf([1], [1, 1]) # example transfer function
control.bode_plot(sys, margins=True)
# or
control.bode(sys, margins=True)
```
However, this method does not always look how I would like, especially with multiple transfer functions. If you want more control (pun intended), you can do something similar to @monte-carlo's answer, but by plotting the margins directly on the plot produced by the `bode_plot`/`bode` command.
```py
import control
import matplotlib as plt
sys = control.tf([1], [1, 1]) # example transfer function
control.bode(sys, dB=True)
gm, pm, wg, wp = control.margin(sys)
fig = plt.gcf() # Get a handle to the current figure (the bode plot)
mag_axis, phase_axis = fig.axes # Get the magnitude and phase subplots
mag_axis.plot([wg, wg], [0, control.mag2db(gm)])
phase_axis.plot([wp, wp], [-180, pm])
```
| 10,511
|
467,602
|
Following from this [OS-agnostic question](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python), specifically [this response](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291), similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).
|
2009/01/22
|
[
"https://Stackoverflow.com/questions/467602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
There was a similar question asked:
[How to get current CPU and RAM usage in Python?](https://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python)
There are quite a few answers telling you how to accomplish this in windows.
|
You can try using the systeminfo.exe wrapper I created a while back, it's a bit unorthodox but it seems to do the trick easily enough and without much code.
This should work on 2000/XP/2003 Server, and should work on Vista and Win7 provided they come with systeminfo.exe and it is located on the path.
```
import os, re
def SysInfo():
values = {}
cache = os.popen2("SYSTEMINFO")
source = cache[1].read()
sysOpts = ["Host Name", "OS Name", "OS Version", "Product ID", "System Manufacturer", "System Model", "System type", "BIOS Version", "Domain", "Windows Directory", "Total Physical Memory", "Available Physical Memory", "Logon Server"]
for opt in sysOpts:
values[opt] = [item.strip() for item in re.findall("%s:\w*(.*?)\n" % (opt), source, re.IGNORECASE)][0]
return values
```
You can easily append the rest of the data fields to the sysOpts variable, excluding those that provide multiple lines for their results, like CPU & NIC information. A simple mod to the regexp line should be able to handle that.
Enjoy!
| 10,512
|
19,890,824
|
How to store the get Facebook profile picture of a user while logging in through Facebook and saving it in my userprofile model.
I found this link which says how to do so using django-social-auth, <https://gist.github.com/kalamhavij/1662930>. but signals is now deprecated and I have to use pipeline.
Any idea how can I do the same using python-social-auth and pipeline?
|
2013/11/10
|
[
"https://Stackoverflow.com/questions/19890824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683634/"
] |
This is how it worked with me. (from <https://github.com/omab/python-social-auth/issues/80>)
Add the following code to pipeline.py:
```
from requests import request, HTTPError
from django.core.files.base import ContentFile
def save_profile_picture(strategy, user, response, details,
is_new=False,*args,**kwargs):
if is_new and strategy.backend.name == 'facebook':
url = 'http://graph.facebook.com/{0}/picture'.format(response['id'])
try:
response = request('GET', url, params={'type': 'large'})
response.raise_for_status()
except HTTPError:
pass
else:
profile = user.get_profile()
profile.profile_photo.save('{0}_social.jpg'.format(user.username),
ContentFile(response.content))
profile.save()
```
and add to pipelines in settings.py:
```
SOCIAL_AUTH_PIPELINE += (
'<application>.pipelines.save_profile_picture',
)
```
|
Assuming you already configured `SOCIAL_AUTH_PIPELINE`, there aren't many differences with signals approach.
Just create needed pipeline (skipping all imports, they're obvious)
```
def update_avatar(backend, details, response, social_user, uid,\
user, *args, **kwargs):
if backend.__class__ == FacebookBackend:
url = "http://graph.facebook.com/%s/picture?type=large" % response['id']
avatar = urlopen(url)
profile = user.get_profile()
profile.profile_photo.save(slugify(user.username + " social") + '.jpg',
ContentFile(avatar.read()))
profile.save()
```
and add to pipelines:
```
SOCIAL_AUTH_PIPELINE += (
'<application>.pipelines.update_avatar',
)
```
| 10,517
|
70,543,710
|
I am learning C# and have been taking a lot of online courses.
I am looking for a simpler/neater way to enumerate a list within a list.
In python we can do something like this in just one line:
```
newListofList=[[n,i] for n,i in enumerate([List1,List2,List3])]
```
Does it have to involve lambda and Linq in C#? if so, what would be the solution? I tried it with Dictionary in C# but my gut tells me this is not a perfect solution.
```
List<List<string>> familyListss = new List<List<string>>();
familyListss.Add(new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" });
familyListss.Add(new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" });
familyListss.Add(new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" });
Dictionary<int, List<string>> familyData = new Dictionary<int, List<string>>();
for (int i = 0; i < familyListss.Count; i++)
{
familyData.Add(i, familyListss[i]);
}
```
|
2021/12/31
|
[
"https://Stackoverflow.com/questions/70543710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740222/"
] |
Just a *constructor* will be enough:
```
List<List<string>> familyListss = new List<List<string>>() {
new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" },
new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" },
new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" }
};
```
If you want to mimic `enumerate` you can use *Linq*, `Select((value, index) => your lambda here)`:
```
using System.Linq;
...
var list = new List<string>() {
"a", "b", "c", "d"};
var result = list
.Select((value, index) => $"item[{index}] = {value}");
Console.Write(string.Join(Environment.NewLine, result));
```
**Outcome:**
```
item[0] = a
item[1] = b
item[2] = c
item[3] = d
```
|
Are you taking about something like this?
```
int i = 0;
familyListss.ForEach(f => { familyData.Add(i, f);i++; });
```
This is refactored from
```
int i = 0;
foreach (var f in familyListss)
{
familyData.Add(i, f);
i++;
}
```
With a small extension method, you can build in an index to foreach to make it one line. Extension methods are worth exploring, and can take annoying, repeated tasks out of your way.
Also see this question:
[C# Convert List<string> to Dictionary<string, string>](https://stackoverflow.com/questions/11581101/c-sharp-convert-liststring-to-dictionarystring-string)
| 10,520
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
Yes, you can. I started learning Django with very little Python knowledge too. As long as you have another language behind your belt, preferably a web based one (as you do), I don't think you're biting off too much at once.
Python's a pretty easy language to pick up too. Just have to get used to the significant white space and lack of semi-colons :P
|
Sure you can!
Django requires minimal knowledge about using python from the command line, but if you're comfortable with that, then there shouldn't be an issue. Django has excellent documentation and a good tutorial aimed at beginners that does not expect you to be a high-level Python programmer.
Here's the link to the beginner's tutorial for Django: <http://docs.djangoproject.com/en/dev/intro/tutorial01/>
| 10,521
|
33,615,096
|
How can I use single quote and double quote same time as string python?
For example:
```
string = "Let's print "Happines" out"
```
result should be Let's print `"Happines"` out
I tried to use backslash but it prints out a `\` before 's that should be.
|
2015/11/09
|
[
"https://Stackoverflow.com/questions/33615096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5230597/"
] |
In python there's lots of ways to write string literals.
For this example you can:
```
print('Let\'s print "Happiness" out')
print("Let's print \"Happiness\" out")
print('''Let's print "Happiness" out''')
print("""Let's print "Happiness" out""")
```
Any of the above will behave as expected.
|
Taking this string:
```
string = "Let's print "Happines" out"
```
If you want to mix quotes, use the triple single quotes:
```
>>> string = '''Let's print "Happines" out'''
>>> print(string)
Let's print "Happines" out
```
Using triple quotes is acceptable too:
```
>>> string = """Let's print "Happines" out"""
>>> print(string)
Let's print "Happines" out
```
| 10,530
|
61,501,891
|
I have an issue with Rsyslog's 'omprog' module when trying to get it to interact with my python (2.7) code. Rsyslog is supposed to send desired messages to python's stdin, yet it does not receive anything. I wonder if anyone else has had better success with this output module?
**Rsyslog.conf**
```
module(load="omprog")
template(name="sshmsg" type="string" string="%msg%")
if ($programname == "myprogram") then {
action(type="omprog"
binary="/usr/sshtrack.py"
template="sshmsg")
}
```
If I replace the binary with a test shell script containing a line below, it works
**test.sh**
```
!#/bin/sh
cat /dev/stdin >> /var/log/ssh2.log
```
I also tried reading stdin in the shell script into a variable using
```
var="$(</dev/stdin)"
```
**and**
```
var="$(cat /dev/stdin)"
```
Neither of the above resulted *var* containing anything
Finally, when trying to read stdin from python script, I get nothing. Sometimes, it says resource unavailable (errno 11) error message.
**sshtrack.py**
```
#!/usr/bin/python
import sys
f = open("/var/log/ssh2.log", "a", 0)
while True:
f.write("Starting\n")
for line in sys.stdin:
f.flush()
msg = line.strip()
if not msg:
break
f.write(msg)
f.write("\n")
f.close()
```
The issue seems similar to [can not read correctly from STDIN](https://stackoverflow.com/questions/9438200/can-not-read-correctly-from-stdin) except adding a non-block flag did nothing.
|
2020/04/29
|
[
"https://Stackoverflow.com/questions/61501891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10192040/"
] |
Here is one approach using `tidyverse`. You can `group_by(Species)` and set `Method` to "Both" if both Bottom fishing and Trolling are included in Method within that Species. Then afterwards, you can `group_by` both Species and Method, and use `fill` to replace `NA` with known values. In the end, use `slice` to keep one row for each Species/Method. This assumes you would have otherwise 1 row for each Species/Method - please let me know if this is not the case.
```
library(tidyverse)
fish_catch %>%
group_by(Species) %>%
mutate(Method = ifelse(all(c("Bottom fishing", "Trolling") %in% Method), "Both", as.character(Method))) %>%
group_by(Species, Method) %>%
fill(c(Bait, Released, Kept), .direction = "updown") %>%
slice(1)
```
**Output**
```
# A tibble: 9 x 5
# Groups: Species, Method [9]
Species Method Bait Released Kept
<chr> <chr> <int> <int> <int>
1 Aethaloperca rogaa Bottom fishing NA NA 2
2 Aprion virescens Bottom fishing NA NA 1
3 Balistidae spp. Bottom fishing NA NA 1
4 Caranx ignobilis Both NA 1 1
5 Epinephelus fasciatus Bottom fishing NA 3 NA
6 Epinephelus multinotatus Bottom fishing NA NA 5
7 Other species Bottom fishing NA 1 NA
8 Thunnus albacares Trolling NA NA 1
9 Variola louti Bottom fishing NA NA 1
```
|
This should get you started. You can add the other columns to the summarize function.
```
library(tidyverse)
fish_catch %>% select(-Bait, -Released, -Kept) %>%
group_by(Species) %>%
summarize(Method = paste0(Method, collapse = "")) %>%
mutate(Method = fct_recode(Method, "both" = "TrollingBottom fishing"))
# A tibble: 9 x 2
Species Method
<chr> <fct>
1 Aethaloperca rogaa Bottom fishing
2 Aprion virescens Bottom fishing
3 Balistidae spp. Bottom fishing
4 Caranx ignobilis both
5 Epinephelus fasciatus Bottom fishing
6 Epinephelus multinotatus Bottom fishing
7 Other species Bottom fishing
8 Thunnus albacares Trolling
9 Variola louti Bottom fishing
```
| 10,531
|
8,011,017
|
Simple problem, how to find the first non-zero digit after decimal point. What I really need is the distance between the decimal point and the first non-zero digit.
I know I could do it with a few lines but I'd like to have some pythonic, nice and clean way to solve this.
So far I have this
```
>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]
```
|
2011/11/04
|
[
"https://Stackoverflow.com/questions/8011017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181337/"
] |
The easiest way seems to be
```
x = 123.0
dist = int(math.log10(abs(x)))
```
I interpreted the second entry in each pair of the list `t` as your desired result, so I chose `int()` to round the logarithm towards zero:
```
>>> [(int(math.log10(abs(x))), y) for x, y in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, -1), (-4, -4)]
```
|
One way to focus on the digits after the decimal point is to remove the integer part of the number, leaving on the fractional part, with something like `x - int(x)`.
Having isolated the fractional part, you could let python do the counting for you with a `%e` presentation (that also helps take care of rounding issues).
```
>>> '%e' % 0.000125
'1.250000e-04'
>>> int(_.partition('-')[2]) - 1
3
```
| 10,532
|
46,215,954
|
I get a .csv file with values inside and one of the columns contains durations in the format hh:mm:ss for example 06:42:13 (6 hours, 42 minutes and 13 seconds). Now I want to compare this time with a given time for example 00:00:00 because I have to handle the information in that row different.
time is the value I got out of the .csv file
```
if time == 00:00:00:
do something
else:
do something different
```
Thats what I want but it obviously doesn't work how I did it. I thought python stored the time as a String but when i compared it like this:
```
if time == "00:00:00":
```
it didn't work either.
Thats how I get the values out of the .csv file:
```
import csv
import_list = []
with open("input.csv", "r") as csvfile:
inputreader = csv.reader(csvfile, delimiter=';')
for row in inputreader:
import_list.append(row)
```
The .csv file looks like this:
```
Name; Duration; Tests; Warnings; Errors
Test1; 06:42:13; 2000; 2; 1
Test2; 00:00:00; 0; 0; 0
```
and so on.
|
2017/09/14
|
[
"https://Stackoverflow.com/questions/46215954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8592446/"
] |
Do this instead:
```
if time.strip() == "00:00:00":
do something
else:
do something different
```
|
Instead of doing string comparisions, using inbuilt `datetime` library to create datetime objects. Use [`datetime.strptime`](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior) to convert date string.
| 10,538
|
22,599,617
|
How do i fix this error, this is the message that i get:
```none
Traceback (most recent call last):
File "C:\Users\Games\Desktop\hendeagon.py", line 28, in <module>
font = pygame.font.SysFont(None, 48)
File "C:\Python33\lib\site-packages\pygame\sysfont.py", line 614, in SysFont
return constructor(fontname, size, set_bold, set_italic)
File "C:\Python33\lib\site-packages\pygame\sysfont.py", line 537, in font_constructor
font = pygame.font.Font(fontpath, size)
pygame.error: font not initialized
```
i need this error fixed for homework by tomorrow.
```python
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
TEXTCOLOR = (255, 255, 255)
WINDOWWIDTH = 500
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
font = pygame.font.SysFont('comicsansms', 48)
basicFont = pygame.font.SysFont(None, 42)
drawText('8', font, windowSurface, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))
windowSurface.fill(BLACK)
pygame.draw.polygon(windowSurface, GREEN, ((158, 80), (181, 88), (214, 111), (229, 153), (216, 191), (181, 212), (135, 207), (102, 181), (89, 149), (102, 109), (130,88)))
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK
del pixArray
windowSurface.blit(text, textRect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
```
Thank you for attempting to fix this problem that i am having in pygame
|
2014/03/24
|
[
"https://Stackoverflow.com/questions/22599617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3453049/"
] |
[`.attr()`](https://api.jquery.com/attr/) is for HTML attributes, not for CSS properties.
You're looking for [`.css()`](http://api.jquery.com/css/):
```
var cssProp = $(this).css('text-decoration'); // Gets the CSS property's value
$(this).css('text-decoration', 'line-through'); // Sets the CSS property's value
```
|
Text decoration isn't an attribute it's a CSS value. Attributes are things like href, class and id on an HTML element.
Try this:
```
$(this).css("text-decoration", "line-through");
```
| 10,541
|
68,171,360
|
I am trying to create a Neural Network class made up of Neuron objects wired together.
My Neuron class has
1. **Dendrites**
The number of dendrites is specified in the parameters when the class is initialised. The Dendrites are stored in a list whose index stores the voltages of each Dendrite.
eg: `neuron1.dendrites[2]=0.12` volts.
2. **Activation (Threshold) Potential**
The sum of all the dendrite potentials provides the neuron potential. If this potential exceeds the Threshold Potential, my Neuron will fire. There are other neurons connected to the axon of my neuron. The Axon of my Neuron connects to the Dendrites of other Neuron objects. Several Dendrites from other Neurons may connect to the Axon of my Neuron. They will all receive a fixed voltage (outputVoltage) when my Neuron fires. It fires in an All-or-Nothing manner.
3. **Firing state**
When the the Activation Potential is reached, the firing state = on (True)
4. My Neuron class also has a **setConnections()** method. This method receives a python `list` of Dendrites. In this method, I wish to iterate through my internal list of external Dendrites and reset their voltage values. ***This is not working. I cannot figure out why and so seek assistance here.***
I provide a stripped down version of my code below:
```
import threading
class Neuron:
def __init__(self, dendrites, activation_Pot=0.24):
"""
Create a dendrites[] array.
Each element of this array represents the voltage of that dendrite.
We can then loop through the array to sum up the signal strength.
If the signal strength exceeds the Activation potential, then the all-or-nothing threshold has been breached and
we can transmit our signal along the axon.
"""
self.dendrites = [0]*dendrites
self.InputPotential = 0 # This variable will store the sum of all the dendrite voltages. It is being initialised here.
self.activation_Pot = activation_Pot
self.on = True
self.off = False
self.voltsOut = 0.12 # This constant dictates the potential of the axon when the neuron is firing.
self.outputPotential = 0 # This variable SETS the potential of the single axon when the threshold activation potential of the neuron has been reached and the neuron is firing.
self.firing = self.off
self.axonConnections = []
# Launch a thread to check on a timer the sum of all dendrite inputs and fire when output > Activation Potential.
t1 = threading.Thread(target = self.start, args=[])
t1.start()
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
for outputDendrites in self.axonConnections:
outputDendrites = self.outputPotential
def stopFiring(self):
self.outputPotential = 0
self.firing = self.off
print("Neuron has STOPPED firing!")
def setActivation_Pot(self, activation_Pot):
if (activation_Pot >= 0) and (activation_Pot <=1):
self.activation_Pot = activation_Pot
else:
print("activation_Pot value needs to be between 0 and 1")
print("activation_Pot has not been reset.")
print("Please consider re-inputting a valid value.")
def getActivation_Pot(self):
return self.activation_Pot
def setAxonConnections(self, axonConnections):
self.axonConnections = axonConnections
def getAxonConnections(self):
return self.axonConnections
def start(self):
while True:
while True:
self.InputPotential = 0
for dendrite in self.dendrites:
self.InputPotential+=dendrite
if self.InputPotential >= self.activation_Pot:
self.fire()
break
while True:
self.InputPotential = 0
for dendrite in self.dendrites:
self.InputPotential+=dendrite
if self.InputPotential < self.activation_Pot:
self.stopFiring()
break
```
Here is the relevant code from the from the main.py script which is testing the Neuron class:
```
from neuron import Neuron
# Instantiate transmitting neurone...
n0 = Neuron(3, 0.36)
# Instantiate receiving neurones...
n1 = Neuron(3, 0.36)
n2 = Neuron(3, 0.36)
n3 = Neuron(3, 0.36)
# Make the connections: I do this by creating storing my external Dendrites into a list
# and passing that list to the transmitting neuron for it to update the voltages
# of each of these neurons. BUT THESE LIST VARIABLES ARE NOT GETTING UPDATED...
axonConns = [n1.dendrites[0], n2.dendrites[1], n3.dendrites[2]]
n0.setAxonConnections(axonConns) # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED!!
n0.fire() # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED by this fire() method!!
```
I hope that makes sense. In summary: I am passing a list of variables from my main.py script at the line `n0.setAxonConnections(axonConns)`. The variables in this list are not getting updated by the `neuron.fire()` method of my Neuron class. Can someone please explain why? Forgive me, I am a python newbe!
|
2021/06/29
|
[
"https://Stackoverflow.com/questions/68171360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5618307/"
] |
Might not be the best solution, but just my 2c. If you want the other neuron's dendrites to be updated as well, you can declare the connections like so:
```
axonConns = [(n1.dendrites, 0), (n2.dendrites, 1), (n3.dendrites, 2)]
```
You need to pass the list of the dendrites itself, and define which of the dendrites are to be considered in the connection by index. Then change the `fire` method to take the index into account:
```
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
for dendrites, index in self.axonConnections:
dendrites[index] = self.outputPotential
```
EDIT:
To demonstrate why OP's answer is not enough to update neurons outside `fire()`
```
In [1]: x = [1, 2, 3]
...:
...: def foo(val):
...: potential = 100
...: for i in range(len(val)):
...: val[i] = potential
...: return val
...:
...: print(x)
...: print(foo([x[0], x[1], x[2]]))
...: print(x)
...:
[1, 2, 3]
[100, 100, 100]
[1, 2, 3]
```
|
You aren't properly reassigning the values of outputDendrites in your class method.
```
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
# Store the axonConnections into a temporary list for parsing since we'll be changing the values WHILE interating
initial_axonConnections_list = self.axonConnections
for index, outputDendrites in enumerate(initial_axonConnections_list):
outputDendrites = self.outputPotential
# We have stored the value in outputDendrites, but we're not doing anything with it, we have to assign it
self.axonConnections[index] = outputDendrites
```
| 10,542
|
56,577,890
|
I am trying to run GitLab's job using their shared Runners,
I've created a `.gitlab-ci.yml` and kept it at my project's root,
Configured AWS creds as the environment variables -
```
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_DEFAULT_REGION
```
under `Settings -> CI / CD -> Variables`
[](https://i.stack.imgur.com/VUVkp.png)
Double checked the branch I've trying to build from is `protected`
**Following is my .gitlab-ci.yml -**
```
stages:
- build
build:
image: python:latest
stage: build
script:
- apt-get update
- apt-get install -y zip unzip
- pip install awscli
- mkdir ~/.aws/
- touch ~/.aws/credentials
- pip install awscli
- printf "[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\nregion = %s\n" "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" "$AWS_DEFAULT_REGION" >> ~/.aws/credentials
- bash cicdScript.sh
```
**CICD script has the aws command -**
```
$(aws s3 ls)
```
**But I still get the following error -**
```
Unable to locate credentials. You can configure credentials by running "aws configure".
```
**Reference -**
<https://medium.com/faun/continuous-static-upload-to-aws-s3-using-gitlab-runners-17f0260a5af2>
|
2019/06/13
|
[
"https://Stackoverflow.com/questions/56577890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433178/"
] |
You can use
```
- pip install awscli
- aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID
- aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY
- aws configure set region $AWS_DEFAULT_REGION
```
instead of
```
- mkdir ~/.aws/
- touch ~/.aws/credentials
- pip install awscli
- printf "[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\nregion = %s\n" "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" "$AWS_DEFAULT_REGION" >> ~/.aws/credentials
```
|
In your code, the profile is set to 'eb-cli' for your credentials
```
printf "[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\nregion = %s\n" "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" "$AWS_DEFAULT_REGION" >> ~/.aws/credentials
```
The command you should use is
```
aws s3 ls --profile eb-cli
```
If you dont pass the profile, [default] will be picked. Since default was not configured the issue is caused.
| 10,545
|
6,074,034
|
I wish to execute os.system('ls') in python. the return value of this statement is an error code integer..but I want to get the contents of the present directory as a string. How to accomplish this?
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6074034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748051/"
] |
[`os.listdir(".")`](http://docs.python.org/library/os.html#os.listdir)
---
In general, if you want to call a function and get the arguments, you should use [`subprocess.Popen()`](http://docs.python.org/library/subprocess.html#subprocess.Popen). But a lot of the basic directory stuff is in the `os` module so you don't have to do that.
|
Python as build-in functionality like os.listdir() or os.walk() for listing stuff
on the filesystem. Running 'ls' yourself is very bad-style. In general look at the documentation of the subprocess module giving you all flexibility for interacting with external commands.
| 10,546
|
69,563,630
|
I have a huge python list as the following example:
```
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
```
I would like to join this information in this formatting:
```
ls = ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellow cars.']
```
I have tried this code
```
with open ('names.txt', 'r') as text:
lines = text.readlines()
for index,line in enumerate(lines):
if not linha.startswith('name:'):
ls2.append(lines[index]+lines[index+1])
```
But it was not good, since I have something like:
```
ls = ['name: John', 'John has 4 yellow', '4 yellow cars.', 'cars.name: Angelina']
```
Do you have any idea how can I perform this task?
|
2021/10/14
|
[
"https://Stackoverflow.com/questions/69563630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11601412/"
] |
You can use `itertools.groupby`:
```py
import itertools
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
g = itertools.groupby(ls, lambda x: x.startswith('name: '))
output = [''.join(v) for _, v in g]
print(output) # ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellowcars.']
```
It groups the items by whether each item starts with `'name: '`;
1. Items that start with `'name: '` form a group (i.e., `['name: John']`).
2. Next a few items that don't do so form a group (i.e., `['John has ', '4 yellow ', 'cars.']`).
3. Next items that do so form another group (`['name: Angelina']`).
4. ... and so on alternatingly.
Then `join` concatenates the strings in each group.
|
Concatenate all the lines that don't begin with `name:` in a variable, then append that to the result when you get to the next `name:` line.
```
ls2 = []
temp_string = ''
for line in lines:
line = line.rstrip('\n')
if line.startswith('name:'):
if temp_string:
ls2.append(temp_string)
temp_string = ''
ls2.append(line)
else:
temp_string += line
# append the last set of lines
if temp_string:
ls2.append(temp_string)
```
| 10,547
|
70,658,581
|
I am looking to create accounts on Brownie for deploying contracts but I am not sure how to do this. I have looked online how to do this and I havent found it.
I am running python 3.7 and have brownie installed and working as intended. I have also run brownie using a gnache cli. Any help would be great!
|
2022/01/10
|
[
"https://Stackoverflow.com/questions/70658581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17855149/"
] |
To create accounts on brownie use
```
brownie accounts new account-name
```
you can then add your private key as well as password encrypt.
You can check to see if this account was made correctly using
```
brownie accounts list
```
|
I understand that you are trying to add accounts through the brownie ./scripts folder:
add.py
```
from brownie import accounts
def add_account():
print(len(accounts)
for i in range(10):
accounts.add() #adds a random account with mnemonic & address to the network
print(len(accounts))
def main():
add_account()
```
You can then execute this in you shell:
>
> brownie run .\scripts\add.py --network [network]
>
>
>
For further information look here:
<https://eth-brownie.readthedocs.io/en/stable/core-accounts.html>
| 10,550
|
51,666,871
|
I have a flask app with a single file (app.py) a large code base size of 6K lines which i want to modularize by making Separate files for each group of route handlers.
Which one is the proper approach
creating Class for similar routes like user and giving member functions like login, register
user.py
```
class User:
def login():
pass
def register():
pass
```
use it like
```
user = User()
user.login()
```
or create a python file user.py and just droping all the functions inside that
user.py
```
def login():
pass
def register():
pass
```
and use it like
```
import user
user.login()
```
from above mentioned approaches which one will use proper memory and more efficient
|
2018/08/03
|
[
"https://Stackoverflow.com/questions/51666871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547270/"
] |
You should almost never use classes for flask routes as they are inherantly static, and so are not really suited for having instances made of them
The easiest solution is just to separate related routes into modules, as shown in the second part of your question.
If I were you I would also look into Flask's blueprints, which are specifically designed to group routes together:
<http://flask.pocoo.org/docs/1.0/blueprints/>
(I would also recommend doing the tutorial for Flask that is available on the Flask website, where you make a small blogging application and blueprints and modularisation are explained <http://flask.pocoo.org/docs/1.0/tutorial/>)
|
The latter is Pythonic.
Don't use classes when you don't need instance data; use modules.
| 10,551
|
66,421,969
|
I have a main folder with some .xlsx, .ipynb, .jpeg and some subfolders in it.
Now I want to convert all my .xlsx files in my main folder to PDFs.
It is a routine work that I have to do everyday, I would appreciate if you teach me how to do it in python.
\*all the files have some data in the first sheet of the workbook
Thank you
|
2021/03/01
|
[
"https://Stackoverflow.com/questions/66421969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13403801/"
] |
Is there anything you have already tried ?
I suggest testing out pywin32.
1. Download pywin32
```sh
python3 -m pip install pywin32
```
2. Write a script to automate.
```py
import win32com.client
from pywintypes import com_error
# Path to original excel file
WB_PATH = r'~/path/to/file.xlsx'
# PDF path when saving
PATH_TO_PDF = r'~/path/to/file.pdf'
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
try:
print('Start conversion to PDF')
# Open
wb = excel.Workbooks.Open(WB_PATH)
# Specify the sheet you want to save by index. 1 is the first (leftmost) sheet.
ws_index_list = [1,2,3,4,5,6,7,8,9,10,11,12]
wb.WorkSheets(ws_index_list).Select()
# Save
wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)
except com_error as e:
print('failed.')
else:
print('Succeeded.')
finally:
wb.Close()
excel.Quit()
```
|
try like this :
```
saveFormat = self.SaveFormat
workbook = self.Workbook(self.dataDir + "Book1.xls")
#Save the document in PDF format
workbook.save(self.dataDir + "OutBook1.pdf", saveFormat.PDF)
\# Print message
print "\n Excel to PDF conversion performed successfully."
```
| 10,552
|
48,924,007
|
I am trying to compare two `strings` in `python 3.6` and if they are not equal then print a message and exit. My current code is:
```
location = 'United States of America'
if location.lower() != 'united states of america' or location.lower() != 'usa':
print('Location was different = {}'.format(location.lower()))
sys.exit()
else:
#do something
```
But the above code is not able to match the two strings and even though they are equal, it enters the loop and prints that they are different. I know its some silly mistake that I am making but unable to figure it out.
|
2018/02/22
|
[
"https://Stackoverflow.com/questions/48924007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2966197/"
] |
Your condition:
```
if location.lower() != 'united states of america' or location.lower() != 'usa':
```
will never be `False`, since `location.lower()` can't be 2 different strings at the same time.
I suspect you want:
```
if location.lower() != 'united states of america' and location.lower() != 'usa':
```
|
You are looking for an AND condition instead of a OR condition in your if statement. If you change that you should be set
| 10,553
|
13,348,880
|
I am trying to compile the source codes for a simulator which uses C++ and Python. However, it gives me this error:
```
Error: can't find Python.h header in ['path-to-my-python/include/python2.6']
Install Python headers (package python-dev on Ubuntu and RedHat)
```
However, I can see that the header file is there and I have set the path to it. How can I fix or diagnosis the problem?
|
2012/11/12
|
[
"https://Stackoverflow.com/questions/13348880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762469/"
] |
I have written my own AutoCompleteBox control, available at <https://github.com/igorkulman/AutoCompleteBox>
|
I don't think there is anything built in, but have you checked open source? This was the first thing that showed up when I binged for it on google:
<http://autocompleteboxwinrt.codeplex.com/SourceControl/changeset/view/19567>
| 10,554
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Assuming you want to print every 5th line starting from a specific line number:
```
$ seq 20 | awk 'NR==4{c=4} c && !((++c) % 5)'
4
9
14
19
$ seq 20 | awk 'NR==2{c=4} c && !((++c) % 5)'
2
7
12
17
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
```
`c && !((++c) % 5)` says:
>
> If `c` is set then increment `c` and test if that new value modulo
> `5` is zero.
>
>
>
So no line before `NR==4` can be printed as `c` is never populated before that happens, and then when `c` is set to 4, it's then increment to `5` and `5 % 5` is `0` so the line is printed. `c` gets incremented for every line after that and so `c % 5` continually rotates through `1 2 3 4 0` thus printing every 5th line when `0` occurs and so `!0` is true.
To do the above using values set on the command line rather than hard-coded in the script would be:
```
$ seq 20 | awk -v b=4 -v n=5 'NR==b{c=n-1} c && !((++c) % n)'
4
9
14
19
```
---
EDIT - here's why [I asked](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130366892_73829899):
>
> is your question truly `I want to firs print the 4th row and then continue printing every 5th row after the 4th row` as you stated or is
> it the simpler `I want to print the 4th row out of every 5 rows`?
>
>
>
to which [the OP replied](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130367270_73829899)
>
> what I want to do is what I wrote exactly
>
>
>
and the difference between the possible solutions to THAT problem when you generalize to be able to change "4th" to some other number, e.g. "6th":
>
> I want to firs print the 6th row and then continue printing every 5th
> row after the 6th row
>
>
>
```
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
$ seq 20 | awk 'NR%5==6'
$
```
|
Simply
```
awk 'NR%5 == 4' file
```
will do the job.
Alternatively, if you have GNU `sed`:
```
sed -n 4~5p file
```
---
**Edit:**
A general solution to the problem of printing every *n*th line starting with line *s* using `awk` could be, for example, like that:
```
awk -v s=6 -v n=5 'NR>=s && NR%n == s%n' file
```
(`s%n` could be precomputed and assigned to a variable.)
But using GNU `sed` would be much simpler for this task:
```
sed -n "${s}~${n}p" file
```
where `s` and `n` are shell variables (their values must be positive integers).
| 10,556
|
45,182,153
|
I saw at [concurrency is not parallelism](https://blog.golang.org/concurrency-is-not-parallelism) slide that golang can do like this:
```
func main() {
go boring("Boring!")
fmt.Println("I'm listening.")
time.Sleep(2 * time.Second)
fmt.Println("You're boring; I'm leaving.")
}
```
The result look like this
```
I'm listening.
boring 0
boring 1
boring 2
boring 3
boring 4
boring 5
You're boring; I'm leaving.
```
Can Python async loop do like this? I'm stuck it at `loop.run_forever` that it will block the main function:
```
import asyncio
import random
import time
import itertools
async def boring(msg):
for i in itertools.count(0):
print(msg, i)
await asyncio.sleep(random.random() % 1e3)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
asyncio.ensure_future(boring('boring!'))
loop.run_forever()
print('Hello')
time.sleep(2)
print('Bye.')
loop.stop()
```
It will then run
```
boring! 0
boring! 1
boring! 2
boring! 3
boring! 4
boring! 5
boring! 6
boring! 7
boring! 8
boring! 9
```
Can python async loop be async?
|
2017/07/19
|
[
"https://Stackoverflow.com/questions/45182153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8218546/"
] |
Instead of sleeping after running run\_until\_complete, you can use [timeouts](https://docs.python.org/3/library/asyncio-task.html#timeouts). This way, it would be something like:
```
async def main():
print('Hello')
try:
await asyncio.wait_for(boring('boring!'), timeout=2.0)
print('Maybe not that boring!')
except:
print('Bye.')
if __name__ == '__main__':
asyncio.run(main())
```
This will also automatically cancel the running task when the timeout happens. If you don't want the task to be canceled after timeout, use `wait` instead of `wait_for`.
|
`loop.run_forever()` if blocking the execution. As your code is running in a single thread, you need to modify your code to something like this:
```
async def boring(msg):
for i in itertools.count(0):
print(msg, i)
await asyncio.sleep(random.random() % 1e3)
async def hello(task):
print('Hello')
await asyncio.sleep(2)
print('Bye.')
task.cancel()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
t = asyncio.ensure_future(boring('boring!'))
loop.run_until_complete(hello(t))
loop.stop()
```
| 10,566
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
I have high hopes for it.
1. This is being worked on by several people from Google. Seeing as how the BDFL is also employed there, this is a positive.
2. Off the bat, they state that this is a branch, and not a fork. As such, it's within the realm of possibility that this will eventually get merged into trunk.
3. Most importantly, **they have a working version**. They're using a version of unladen swallow **right now** for Youtube stuff.
They seem to have their shit together. They have a relatively detailed plan for a project at this stage, and they have a list of tests they use to gauge performance improvements and regressions.
I'm not holding my breath on GIL removal, but even if they never get around to that, the speed increases alone make it awesome.
|
I'm sorry to disappoint you, but when you read [PEP 3146](http://www.python.org/dev/peps/pep-3146/) things look bad.
The improvement is by now minimal and therfore the compiler-code gets more complicated.
Also removing the GIL has many downsides.
Btw. PyPy seems to be faster then Unladen Swallow in [some tests](http://morepypy.blogspot.com/2010/03/hello.html).
| 10,567
|
53,799,912
|
Iam trying to pre-process text as a part of NLP.I am new to it.I am not getting why i am unable to replace the digits
```
para = "support leaders around the world who do not speak for the big
polluters, but who speak for all of humanity, for the indigenous people of
the world, for the first 100 people.In 90's it seems true."
import re
import nltk
sentences = nltk.sent_tokenize(para)
for i in range(len(sentences)):
words = nltk.word_tokenize(sentences[i])
words = [re.sub(r'\d','',words)]
sentences[i] = ' '.join(words)
```
while doing this i am getting following error:
---
```
TypeError Traceback (most recent call last)
<ipython-input-28-000671b45ee1> in <module>()
2 for i in range(len(sentences)):
3 words = nltk.word_tokenize(sentences[i])
----> 4 words = [re.sub(r'\d','',words)].encode('utf8')
5 sentences[i] = ' '.join(words)
~\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
189 a callable, it's passed the match object and must return
190 a replacement string to be used."""
--> 191 return _compile(pattern, flags).sub(repl, string, count)
192
193 def subn(pattern, repl, string, count=0, flags=0):
TypeError: expected string or bytes-like object
```
How can i convert to byte like object. I am confused as i am new to it.
|
2018/12/16
|
[
"https://Stackoverflow.com/questions/53799912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10464351/"
] |
For replacing all digits from a string, you can the `re` module, for matching and replacing regex patterns. From your last example:
```
import re
processed_words = [re.sub('\d',' ', word) for word in tokenized]
```
|
Is this what you want to do? Or am I missing the point?
```
import re
para = """support leaders around the world who do not speak for the big
polluters, but who speak for all of humanity, for the indigenous people of
the world, for the first 100 people.In 90's it seems true."""
tokenized = para.split(' ')
new_para = []
for w in tokenized:
w = re.sub('[0-9]', '', w)
new_para.append(w)
print(' '.join(new_para))
```
| 10,577
|
47,740,542
|
```
def lines(file):
for line in file:
yield line
yield '\n'
def blocks(file):
block = []
for line in lines(file):
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
with open(r'test_input.txt', 'r') as f:
lines = lines(f)
file = blocks(lines)
for line in file:
print(line)
```
I got this error message:
```
TypeError: 'generator' object is not callable
```
I don't know what happened. Does it because generator in python3.6 is different from 2.X?
|
2017/12/10
|
[
"https://Stackoverflow.com/questions/47740542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9080044/"
] |
Your issue is caused by this line:
```
lines = lines(f)
```
With this assignment, you're overwriting the `lines` generator function with its own return value. That means that when `blocks` tries to call `lines` again (which seems a little buggy to me, but not the main issue), it gets the generator object instead of the function it expected.
Pick a different name for the assignment, or just pass `f` to `blocks`, since it will call `lines` itself.
|
Your problem is not related to Python3. This error exists with Python 2.6.
I do not know exactly what you try to do but your code do not throws error replacing `blocks` function with :
```
def blocks(file):
block = []
for line in file: # here, replace lines(file) with file
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
```
However, I don't understand what you try to do with `lines()`
If this answer is not suitable to you, I encourage you to edit your question with more detail on what the functions are supposed to do.
| 10,580
|
27,224,458
|
I'm using Python's Scrapy to do some web scraping, and I'm trying to get the text in the last td of my last tr in the html below.
```
<table class="infobox" style="float: right; width: 225px; text-align: left; -moz-border-radius:10px; font-size: 85%" cellpadding="2">
<tr style="vertical-align: top;">
<td> <b>Name</b> </td>
<td> Abraham Lincoln
</td>
</tr>
<tr style="vertical-align: top;">
<td> <b>Sex</b> </td>
<td> Male
</td>
</tr>
<tr style="vertical-align: top;">
<td> <b>Occupation </b>
</td>
<td> Former King of <a href="/wiki/Mars" title="Mars">Mars</a>,
<br />Former President of the United States
</td>
</tr>
</table>
```
Currently, I have this written inside my scrapy's parse function.
```
def parse(self, response):
sel = Selector(response)
data = sel.xpath("//table[@class='infobox']")
occupation = data.xpath("tr[td/b[contains(.,'Occupation')]]/td[position()>1]/text()").extract()
print occupation
```
The printed result is:
```
[u' Former King of ', u',', u'Former President of the United States\n']
```
What I'd like to actually get is.. something along the lines of (the most important change would be Mars being added to Former King of):
```
[u'Former King of Mars', u'Former President of the United States']
```
I'm aware of the | union in xpath, and I could have written something more in occupation to capture the "Mars" text in the a tag, however, I want to be able to join the a tag text with the td text to output "Former King of Mars" as one of the elements of the printed list. I think with a union, Mars would appear as it's own element inside the list, which is not quite what I need. Anyway, I was hoping there would be some way in xpath I could join the children text of the parent td so that I could get "Former King of Mars" as an element of the outputted list. Also, there could potentially be multiple a tags within a td like for example.. "King" could be inside an a tag as well. Another requirement would be to keep "Former President of the United States" a separate element (somehow recognize the br tag?). I'm not sure what's the best way to go about handling these cases, but I think if there's a way to do it in xpath, it'll be better than working with a list in python because xpath still has reference to the dom tree. What do you guys think?
Thanks!
|
2014/12/01
|
[
"https://Stackoverflow.com/questions/27224458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3892678/"
] |
You should create user because tests create test database (not your) everytime.
```
User.objects.create_user(username=<client_username>, password=<client_password>)
```
Now create Client and login
```
self.c = django.test.client.Client()
self.c.login(username=<client_username>, password=<client_password>)
```
|
You can override request headers for every client request like this example:
```
def test_report_wrong_password(self):
headers = dict()
headers['HTTP_AUTHORIZATION'] = 'Basic ' + base64.b64encode('user_name:password')
response = self.client.post(
'/report/',
content_type='application/json',
data=json.dumps(JSON_DATA),
**headers)
self.assertEqual(response.status_code, 401)
```
| 10,581
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
Don't confuse "Twisted" with "`twistd`". When you use "`twistd`", you *are* running the program with Python. "`twistd`" is a Python program that, among other things, can load an application from a `.tac` file (as you're doing here).
The "Twisted Command Prompt" is a Twisted installer-provided convenience to help out people on Windows. All it is doing is setting `%PATH%` to include the directory containing the "`twistd`" program. You could run twistd from a normal command prompt if you set your %PATH% properly or invoke it with the full path.
If you're not satisfied with this, perhaps you can expand your question to include a description of the problems you're having when using "`twistd`".
|
Maybe one of `run` or `runApp` in [twisted.scripts.twistd](http://twistedmatrix.com/documents/9.0.0/api/twisted.scripts.twistd.html) modules will work for you. Please let me know if it does, it will be nice to know!
| 10,582
|
57,652,922
|
Say I want to use [black](https://black.readthedocs.io/en/stable/index.html) as an API, and do something like:
```
import black
black.format("some python code")
```
Formatting code by calling the `black` binary with `Popen` is an alternative, but that's not what I'm asking.
|
2019/08/26
|
[
"https://Stackoverflow.com/questions/57652922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2142577/"
] |
You could try using `format_str`:
```
from black import format_str, FileMode
res = format_str("some python code", mode=FileMode())
print(res)
```
|
Use `black.format_file_contents`.
*e.g.*
```py
import black
mode = black.FileMode()
fast = False
out = black.format_file_contents("some python code", fast, mode)
```
<https://github.com/psf/black/blob/19.3b0/black.py#L642>
| 10,592
|
38,788,816
|
I need to install dryscrape for python but I got error, what's the problem?
```
C:\Users\parvij\Anaconda3\Scripts>pip install dryscrape
```
I got this:
```
Collecting dryscrape
Collecting webkit-server>=1.0 (from dryscrape)
Using cached webkit-server-1.0.tar.gz
Collecting xvfbwrapper (from dryscrape)
Requirement already satisfied (use --upgrade to upgrade): lxml in c:\users\parvij\anaconda3\lib\site-packages (from dryscrape)
Building wheels for collected packages: webkit-server
Running setup.py bdist_wheel for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\parvij\AppData\Local\Temp\tmp71w59qv6pip-wheel- --python-tag cp35:
running bdist_wheel
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Failed building wheel for webkit-server
Running setup.py clean for webkit-server
Failed to build webkit-server
Installing collected packages: webkit-server, xvfbwrapper, dryscrape
Running setup.py install for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open',open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Command "c:\users\parvij\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\parvij\AppData\Local\Temp\pip-build-o7nlv0dz\webkit-server\
```
my operating system is windows 8
my python version is 3.5
|
2016/08/05
|
[
"https://Stackoverflow.com/questions/38788816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4042278/"
] |
Need to install <http://www.qt.io>. Also, The 5.6+ version of Qt removes the Qt WebKit module in favor of the new module Qt WebEngine. So far, webkit-server has not been ported to WebEngine (and likely won't be in the near future), so Qt <= 5.5 is a requirement.
|
From the [doc](http://dryscrape.readthedocs.io/en/latest/installation.html), you have to installed also [requirements](https://github.com/niklasb/dryscrape/blob/master/requirements.txt).
You can do this as follow
```
pip install -r requirements.txt
```
After this retry to install **dryscrape**.
| 10,593
|
33,464,208
|
Is there a pythonic/efficient way to carry out a simple decrement operation on each element (or more accurately a subset of the elements) in a list of objects of an arbitrary class?
I potentially have a large-ish (~ 10K) list of objects, each of which is updated periodically on the basis of a countdown "time to update" (TTU) value.
The simple way to handle this would be to decrement this value in each element as below:
```
def BatesNumber(start = 0):
n = start
while True:
yield n
n += 1
class foo:
index = BatesNumber()
def __init__(self, ttu):
self.id = next(foo.index)
self.time = ttu
self.ttu = ttu
def __repr__(self):
return "#{}:{}/{}".format(self.id, self.ttu, self.time)
def Decrement(self):
self.ttu -= 1
def Reset(self):
print("Reset {} to {}".format(self.id, self.time))
self.ttu = self.time
def IsReadyForUpdate(self):
if self.ttu == 0:
return True
else:
return False
bar = [foo(i) for i in range(10, 20, 2)]
for n in range(50):
for p in bar:
if p.IsReadyForUpdate():
print("{} {}".format(n, p))
p.Reset()
else:
p.Decrement()
```
So I guess what I am after is some Pythonic way of "vectorising" the decrement operation - i.e. decrement all the elements in the list in a suitably elegant way; and, ideally, returning those elements which require update/reset.
I could (although it seems a bit unnecessarily horrible) produce a list which is ordered on the TTU value, and have all the TTU values relative to their neighbour. That way I would only require one decrement per cycle, but then when I reset the counter I have the pain of rebuilding the list. I suppose that this would be better for a very long list with quite high TTU values.
I presume the best/Pythonic way to check which of the elements is ready for update is using a list comprehension.
Any advice?
|
2015/11/01
|
[
"https://Stackoverflow.com/questions/33464208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171112/"
] |
Perhaps you could replace your flat list with a priority queue using the `heapq` module. The priorities would be the current time, plus the object's `ttu`. When the current time matched the top element's priority, you'd pop it off, do whatever your updating was, and then push it back into the queue with a new priority.
The code would look something like this:
```
import heapq
items = [foo(i) for i in range(10,20)]
queue = [(f.ttu, f.id, f) for f in items]
heapq.heapify(queue)
for t in range(50):
while t >= queue[0][0]:
_, _, f = heapq.heappop(queue)
# update f here
heapq.heappush(queue, (t + f.ttu, f.id, f))
```
I'm using the object's `id` attribute as a tie breaker when two objects need to be updated at the same time. If you wanted to, you could make the priority queue implementation easier by implementing a `__lt__` operator in the objects to allow them to be compared directly. If you made them track their own update times, the queue could just contain the objects directly (like the `items` list) rather than tuples to make them sort in order of priority.
Something like:
```
class foo:
index = BatesNumber()
def __init__(self, ttu):
self.id = next(index)
self.next_update = ttu
self.ttu = ttu
def __lt__(self, other):
return (self.next_update, self.id) < (other.next_update, other.id)
# ideally you'd also write __eq__, __gt__, etc. methods, but heapq only needs __lt__
def update(self):
self.next_update += self.ttu
# maybe do other update stuff here?
```
By the way, your `BatesNumber` class is essentially identical to `itertools.count`.
|
I think your code is already good; maybe you could add a single method called something like "beat" for performing both things:
* checking if the object is ready to update and in that case handle the update,
* or decrement in the other case;
it would make your loop a little cleaner and simpler. It won't help much for the "vectorization" part of your question but it would go deeper in the "object oriented" way of programming.
For the "vectorization" part; will your list change much during the whole process? One idea could be: have a separate Numpy array containing the values to be decremented and have the table matching your list by the index. Of course it will not be very convenient if you have to suppress instances during the computation but if it isn't the case, it may be the way to go.
| 10,598
|
39,029,068
|
I want to be able to execute the following code:
```
import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=k
```
Which should return the same output as:
```
z=numpy.zeros(4)
for i in range(6):
z[i]=z[i-1]
```
If I execute the first code block, I get an expected error message:
```
File "<ipython-input-982-3ba4e617a74a>", line 1, in <module>
z[i]=(k)
ValueError: could not convert string to float: 'z[i-1]'
```
How can I pass the text from the string into the loop so that it functions as an equation, as if the characters from the string were typed by hand?
|
2016/08/18
|
[
"https://Stackoverflow.com/questions/39029068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5510581/"
] |
I think you're looking for the [builtin `eval()`](https://docs.python.org/2/library/functions.html#eval)
Consider:
```
>>> z = numpy.zeros(4)
>>> k = "10 + z[i-1]"
>>> for i in range(1, 4):
... z[i] = eval(k)
...
>>> z
array([ 0., 10., 20., 30.])
```
I made the expression a little more complex so you could see interesting output.
|
Do it as following:
```
import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=eval(k)
```
But note eval can be a security problem: <http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html>
| 10,599
|
36,716,304
|
Im stuck with this very simple code were I'm trying to create a function that takes a parameter and adds 1 to the result and returns it but somehow this code gives me no results. (I've called the function to see if it works.)
Somebody please help me since I'm very new to python :)
```
def increment(num):
num += 1
a = int(input("Type a number "))
increment(a)`
```
I changed it to
```
def increment(num):
return num + 1
a = int(input("Type a number "))
increment(a)`
```
but still no results are showing after I enter a number, Does anybody know?
|
2016/04/19
|
[
"https://Stackoverflow.com/questions/36716304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6123798/"
] |
Basics: `array[slice(a,b,c)]` is equivalent to `array[a:b:c]`, and to reverse ("flip") an array use `slice(None, None, -1)`, which is the same as `array[::-1]`.
So let's build the random flips for each image:
```
>>> import random
>> flips = [(slice(None, None, None),
... slice(None, None, random.choice([-1, None])),
... slice(None, None, random.choice([-1, None])))
... for _ in xrange(a.shape[0])]
```
The first slice is for the channel, the second is for the Y axis and the third is for the X axis. Let's build some test data:
```
>>> import numpy as np
>>> a = np.array(range(3*2*5*5)).reshape(3,2,5,5)
```
We can apply each random flip individually to each image:
```
>>> flips[0]
(slice(None, None, None), slice(None, None, -1), slice(None, None, None))
>>> a[0]
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]],
[[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39],
[40, 41, 42, 43, 44],
[45, 46, 47, 48, 49]]])
>>> a[0][flips[0]]
array([[[20, 21, 22, 23, 24],
[15, 16, 17, 18, 19],
[10, 11, 12, 13, 14],
[ 5, 6, 7, 8, 9],
[ 0, 1, 2, 3, 4]],
[[45, 46, 47, 48, 49],
[40, 41, 42, 43, 44],
[35, 36, 37, 38, 39],
[30, 31, 32, 33, 34],
[25, 26, 27, 28, 29]]])
```
As you can see, `flips[0]` flips the image vertically. Now it's simple to do it for each image:
```
>>> random_flipped = np.array([img[flip] for img, flip in zip(a, flips)])
```
|
Thanks to the [awesome answer of @BlackBear](https://stackoverflow.com/a/36716579/3250126), I was able to get starting. I noticed, however, such functionality would probably run very often and thus might benefit from some performance tweaks.
In thinking of how to improve the performance I tackled two things:
1. use a "pure `numpy`" implementation
2. (building upon 1.) use just-in-time compilation through `numba`
This is what I came up with:
```py
import numpy as np
from numba import njit
def np_flip(arr: np.ndarray, axis=None) -> np.ndarray:
"""Flip image np arrays with a (batch, row, col, band) configuration."""
forw = np.int64(1)
rev = np.int64(-1)
flip_ax0 = np.random.choice(np.array([forw, rev]))
flip_ax1 = np.random.choice(np.array([forw, rev]))
flips = tuple(
(
slice(None, None, None), # TF batch
slice(None, None, flip_ax0), # image rows
slice(None, None, flip_ax1), # image cols
slice(None, None, None), # image bands
)
)
return arr[flips]
# njit the function, also possible via @njit decorator
njit_np_flip = njit(np_flip)
```
Benchmarks
----------
```py
import scipy.ndimage
arr = np.random.randint(0, 255, size=(2, 4, 4, 3))
print(arr.shape)
# (2, 4, 4, 3)
arr = scipy.ndimage.zoom(input=arr, zoom=(1, 128, 128, 1), order=0)
print(arr.shape)
# (2, 512, 512, 3)
# @BlackBear's answer
def py_np_flip(arr: np.ndarray, axis=None):
"""Python-Heavy version of np_flip."""
# see https://stackoverflow.com/a/36716579/3250126
flips = [
(
slice(None, None, np.random.choice([-1, None])),
slice(None, None, np.random.choice([-1, None])),
slice(None, None, None),
)
for _ in range(arr.shape[0])
]
return np.array([img[flip] for img, flip in zip(arr, flips)])
# @BlackBear's answer
%timeit arr_flipped_np = np.apply_over_axes(py_np_flip, arr, axes=0)
# 2.18 ms ± 34.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# "pure numpy" implementation
%timeit arr_flipped_np = np.apply_over_axes(np_flip, arr, axes=0)
# 19.2 µs ± 2.34 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
# njit(ed) "pure numpy" implementeation
%timeit arr_flipped_np = np.apply_over_axes(njit_np_flip, arr, axes=0)
# 1.7 µs ± 28.9 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
```
1600 x speed increase
---------------------
```
> 2.8 ms / 1.7 µs
(2.8 × millisecond) / (1.7 × microsecond) ≈ 1647.0588
```
| 10,601
|
48,789,294
|
I have a file that contains the raw data for an array of 32-bit floats. I would like to read this data and resemble it to floats and store them in a list.
[](https://i.stack.imgur.com/1p1J9.jpg)
How can I do this using python?
Note: The data originates from an embedded device that may use a different endian than my desktop.
|
2018/02/14
|
[
"https://Stackoverflow.com/questions/48789294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1235291/"
] |
The standard `struct` module is good for dealing with packed binary data like this. Here's a quick example:
```
dataFromFile = "\x67\x66\x1e\x41\x01\x00\x30\x41" # an excerpt from your data
import struct
numFloats = len(dataFromFile) // 4
# Try decoding it as little-endian
print(struct.unpack("<" + "f" * numFloats, dataFromFile))
# Output is (9.90000057220459, 11.000000953674316)
# Try decoding it as big-endian
print(struct.unpack(">" + "f" * numFloats, dataFromFile))
# Output is (1.0867023771258422e+24, 2.354450749630536e-38)
```
The little-endian interpretation looks a lot more meaningful in this case (9.9 and 11, with the usual floating-point inaccuracies), so I guess that's the actual format.
|
you can read it the file, store it in a string then parse the string and convert to float:
```
with open(“testfile.txt”) as file:
data = file.read()
values = data.split(" ")
floatValues = [float(x) for x in values]
```
or you can use some parser from the numpy module or the csv reading files modules
| 10,602
|
54,073,810
|
I was trying to get data(a list) from a file and assign this list to my python script list.
I want to know how to do it without having to assign all varibles manually
```
Variables = [MPDev,WDev,DDev,LDev,PDev,MPAll,WAll,DAll,LAll,PAll,MPBlit,WBlit,DBlit,LBlit,PBlit,MPCour,WCour,DCour,LCour,PCour]
dataupdate = open("griddata.txt","r")
datalist = dataupdate.read()
#Inside the file is written:
#['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0',']
var = 0
for e in Variables:
e = datalist[var]
var += 1
```
I got it working anyways but i would like to know a faster way to improve my skills. Thanks
|
2019/01/07
|
[
"https://Stackoverflow.com/questions/54073810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10236621/"
] |
Get used to using data as a pandas dataframe. It's easy to read, easy to write.
<http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html>
```
import pandas as pd
data = pd.read_csv("griddata.txt", names = ['MPDev',
'WDev',
'DDev',
'LDev',
'PDev',
'MPAll',
'WAll',
'DAll',
'LAll',
'PAll',
'MPBlit',
'WBlit',
'DBlit',
'LBlit',
'PBlit',
'MPCour',
'WCour',
'DCour',
'LCour',
'PCour']
)
```
|
```
import ast
Variables = [MPDev,WDev,DDev,LDev,PDev,MPAll,WAll,DAll,LAll,PAll,MPBlit,WBlit,DBlit,LBlit,PBlit,MPCour,WCour,DCour,LCour,PCour]
dataupdate = open("tmp.txt","r")
datalist = ast.literal_eval(dataupdate.read())
#Inside the file is written:
#['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0',']
for i in Variables:
i=datalist[Variables.index(i)]
```
| 10,603
|
58,869,851
|
I have an issue in using python with matrix multiplication and reshape. for example, I have a column `S` of size `(16,1)` and another matrix `H` of size `(4,4)`, I need to reshape the column `S` into `(4,4)` in order to multiply it with `H` and then reshape it again into `(16,1)`, I did that in matlab as below:
```
clear all; clc; clear
H = randn(4,4,16) + 1j.*randn(4,4,16);
S = randn(16,1) + 1j.*randn(16,1);
for ij = 1 : 16
y(:,:,ij) = reshape(H(:,:,ij)*reshape(S,4,[]),[],1);
end
y = mean(y,3);
```
Coming to python :
```
import numpy as np
H = np.random.randn(4,4,16) + 1j * np.random.randn(4,4,16)
S = np.random.randn(16,) + 1j * np.random.randn(16,)
y = np.zeros((4,4,16),dtype=complex)
for ij in range(16):
y[:,:,ij] = np.reshape(h[:,:,ij]@S.reshape(4,4),16,1)
```
But I get an error here that we can't reshape the matrix y of size 256 into 16x1.
Does anyone have an idea about how to solve this problem?
|
2019/11/15
|
[
"https://Stackoverflow.com/questions/58869851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11082042/"
] |
Simply do this:
```
S.shape = (4,4)
for ij in range(16):
y[:,:,ij] = H[:,:,ij] @ S
S.shape = -1 # equivalent to 16
```
|
There are two issues in your solution
1) reshape method takes a shape in the form of a single tuple argument, but not multiple arguments.
2) The shape of your y-array should be 16x1x16, not 4x4x16. In Matlab, there is no issue since it automatically reshapes `y` as you update it.
The correct version would be the following:
```
import numpy as np
H = np.random.randn(4,4,16) + 1j * np.random.randn(4,4,16)
S = np.random.randn(16,) + 1j * np.random.randn(16,)
y = np.zeros((16,1,16),dtype=complex)
for ij in range(16):
y[:,:,ij] = np.reshape(H[:,:,ij]@S.reshape((4,4)),(16,1))
```
| 10,605
|
31,092,802
|
To install dependences, the [appengine-python-flask-skeleton docs](https://github.com/GoogleCloudPlatform/appengine-python-flask-skeleton) advise running this command:
```
pip install -r requirements.txt -t lib
```
That works simply enough.
Now say I want to add the [Requests package](http://docs.python-requests.org/en/latest/).
Ideally I just add it to the `requirements.txt` file:
```
# This requirements file lists all third-party dependencies for this project.
#
# Run 'pip install -r requirements.txt -t lib/' to install these dependencies
# in `lib/` subdirectory.
#
# Note: The `lib` directory is added to `sys.path` by `appengine_config.py`.
Flask==0.10
requests
```
And then re-run the command:
```
pip install -r requirements.txt -t lib
```
However, as [this Github issue](https://github.com/pypa/pip/issues/1489) for pip notes, pip is not idempotent with the `-T` option recommended by Google here. The existing flask packages will be re-added and this will lead to the following error when running the devapp
```
ImportError: cannot import name exceptions
```
How can I best work around this problem?
|
2015/06/27
|
[
"https://Stackoverflow.com/questions/31092802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1093087/"
] |
Like said, updating pip solves the issue for many, but for what it's worth I think you can get around all of this if the use of [virtualenv](https://virtualenv.pypa.io/en/latest/) is an option. Symlink `/path/to/virtualenv's/sitepackages/` to `lib/` and just always keep an up to date `requirements.txt` file. There are no duplication of packages this way and one won't have to manually install dependencies. See also <https://stackoverflow.com/a/30447848/2295256>
|
Upgrading to the latest version of pip solved my problem (that issue had been closed):
```
pip install -U pip
```
Otherwise, as noted in that thread, you can always just wipe out your `lib` directory and reinstall from scratch. One note of warning: if you manually added additional packages to the `lib` directory not tracked in `requirements.txt`, they would be lost and have to be re-installed manually.
| 10,608
|
54,484,627
|
I want to monitor EC2 by using CloudWatch-SNS-lambda (python)-SNS-Email.
When I testing my python code, i find out that CW alarm "Message" contain escape processing that i cant get specific value from "Message".
I check the format of the alarm with code below.
```
from __future__ import print_function
import json
import boto3
def lambda_handler(event, context):
subject = 'subject'
Messagebody = event['Records'][0]['Sns']['Message']
MY_SNS_TOPIC_ARN = 'XXXXXXXXXXXXXXXXXXXXXXXX'
sns_client = boto3.client('sns')
sns_client.publish(
TopicArn = MY_SNS_TOPIC_ARN,
Subject = subject,
Message = Messagebody
)
```
which find out "Message" contains escape processing.
```
"Sns": {
"Type": "Notification",
"MessageId": "94be4651-8f2e-5039-9a4b-129fff80f9e8",
"TopicArn": "XXXXXXXXXXXXXXXXXXXXXXX",
"Subject": "ALARM: \"CPU_\" in Asia Pacific (Tokyo)",
"Message": "{\"AlarmName\":\"TEST\",\"AlarmDescription\":\"TEST\",\"AWSAccountId\":\"XXXXXXXXXXX\",\"NewStateValue\":\"ALARM\",\"NewStateReason\":\"Threshold Crossed: 1 datapoint [64.633879781421 (01/02/19 15:56:00)] was greater than or equal to the threshold (40.0).\",\"StateChangeTime\":\"2019-02-01T16:06:06.908+0000\",\"Region\":\"Asia Pacific (Tokyo)\",\"OldStateValue\":\"OK\",\"Trigger\":{\"MetricName\":\"CPUUtilization\",\"Namespace\":\"AWS/EC2\",\"StatisticType\":\"Statistic\",\"Statistic\":\"AVERAGE\",\"Unit\":null,\"Dimensions\":[{\"value\":\"i-039c724383acd1a67\",\"name\":\"InstanceId\"}],\"Period\":300,\"EvaluationPeriods\":1,\"ComparisonOperator\":\"GreaterThanOrEqualToThreshold\",\"Threshold\":40.0,\"TreatMissingData\":\"\",\"EvaluateLowSampleCountPercentile\":\"\"}}",
"Timestamp": "2019-02-01T16:06:06.945Z",
"SignatureVersion": "1",
```
I want to get value by using something like
```
MetricName = event['Records'][0]['Sns']['Message']["MetricName"]
```
How can i achieve this with python?
|
2019/02/01
|
[
"https://Stackoverflow.com/questions/54484627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11002216/"
] |
The `Message` is a JSON string. You need to convert it to a Python dictionary first. Then, you can access its properties easily.
```py
Messagebody = event['Records'][0]['Sns']['Message']
message_dict = json.loads(Messagebody)
metric_name = message_dict['Trigger']['MetricName']
```
|
To remove the escape-processing, you should do the following:
>
> MessageBody = event['Records'][0]['Sns']['Message']
>
>
> MessageBody = json.loads(MessageBody)
>
>
>
Then to access the Metric Name, you can do:
>
> MetricName= event['Records'][0]['Sns']['Message']['Trigger']['MetricName']
>
>
>
| 10,609
|
37,991,717
|
Can anyone help me on a Python reverse shell one-liner for Windows (has to be windows one-liner).
I am trying to modify the one for Linux which I have used many times but this is my first time for Windows.
Linux one liner :
```
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```
Taken from [Reverse Shell Cheat Sheet](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet).
So here is what I have been able to do so far:
```
C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\\WINDOWS\\system32\\cmd.exe','-i']);"
```
Well, the thing is I do get a connection back just that the shell dies. Anyone knows how to fix this or offer some suggestions?
```
nc -lvnp 443
listening on [any] 443 ...
connect to [10.11.0.232] from (UNKNOWN) [10.11.1.31] 1036
```
So the parameter to `subprocess call` must be wrong. I can't seem to get it right.
The path to `cmd.exe` is correct. I can't see any corresponding parameter like `-i` in the [cmd man page](http://ss64.com/nt/cmd.html).
Can anyone point me in the correct direction, please?
**EDIT:** Tried without arguments to subprocess call but still the same result. The connection dies immediately.
```
C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\WINDOWS\system32\cmd.exe']);"
```
|
2016/06/23
|
[
"https://Stackoverflow.com/questions/37991717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/803649/"
] |
(@rockstar: I think you and I are studying the same thing!)
Not a one liner, but learning from David Cullen's answer, I put together this reverse shell for Windows.
```
import os,socket,subprocess,threading;
def s2p(s, p):
while True:
data = s.recv(1024)
if len(data) > 0:
p.stdin.write(data)
p.stdin.flush()
def p2s(s, p):
while True:
s.send(p.stdout.read(1))
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("10.11.0.37",4444))
p=subprocess.Popen(["\\windows\\system32\\cmd.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
s2p_thread = threading.Thread(target=s2p, args=[s, p])
s2p_thread.daemon = True
s2p_thread.start()
p2s_thread = threading.Thread(target=p2s, args=[s, p])
p2s_thread.daemon = True
p2s_thread.start()
try:
p.wait()
except KeyboardInterrupt:
s.close()
```
If anybody can condense this down to a single line, please feel free to edit my post or adapt this into your own answer...
|
From the [documentation](https://docs.python.org/2/library/socket.html#socket.socket.fileno) for `socket.fileno()`:
>
> Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does not have this limitation.
>
>
>
I do not think you can use `os.dup2()` on the return value of `socket.fileno()` on Windows unless you are using Cygwin.
I do not think you can do this as a one-liner on Windows because you need a `while` loop with multiple statements.
| 10,610
|
50,100,629
|
When I try to run buildout for a existing project, which used to work perfectly
fine, it now installs the incorrect version of Django, even though the version
is pinned.
For some reason, it's installing Django 1.10 even though I've got 1.6 pinned. (I
know that's an old version, but client doesn't want me to upgrade just yet.)
Here is a very trucated version of the the buildout config file.
```
[buildout]
index = https://pypi.python.org/simple
versions = versions
include-site-packages = false
extensions = mr.developer
unzip = true
newest = false
parts = ...
auto-checkout = *
eggs =
<... Many eggs here ...>
Django
<... Many more eggs ...>
[base-versions]
...
Django = 1.6.1
...
[versions]
<= base-versions
```
The only other thing that I can think of that could possibly make an impact
is that I recently reinstalled my system to Kubuntu 18.04 (Was previously Ubuntu 17.10)
|
2018/04/30
|
[
"https://Stackoverflow.com/questions/50100629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433267/"
] |
The reason it wasn't working is because the `[versions]` part cannot be extended
|
Pip can install a specific version of library using pip, you can try:
pip install django==1.6.1
| 10,615
|
15,114,329
|
How do I save an open excel file using python= I currently read the excel workbook using XLRD but I need to save the excel file so any changes the user inputs are read.
I have done this using a VBA script from within excel which saves the workbook every x seconds, but this is not ideal.
|
2013/02/27
|
[
"https://Stackoverflow.com/questions/15114329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2040544/"
] |
This works on API level 10 for expanding ActionView e.g. SearchView
```
MenuItemCompat.expandActionView(mSearchMenuItem);
```
|
You always have the option of differentiating your solution depending on the current running version:
```
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
// pre honeycomb
} else {
// honeycomb and post
}
```
I know this might not be exactly what you are looking for but it might get you some of the way .
| 10,616
|
29,418,572
|
I am learning python and am stuck on a tutorial which as far as the guide goes should be working but isn't, i have seen similar questions asked but cant understand how they apply to the code i am following, the code fails at the end of the last line.
```
import os
import time
source = ["'C:\Users\Administrator\myfile\myfile 1'"]
target_dir = ['C:\Users\Administrator\myfile']
target = target_dir + os.sep + \
time.strftime('%Y%m%d%H%M%S') + '.zip'
can only concatenate list (not "str") to list
```
i have tried some methods using .append and also changing the code by adding [] and () to the + '.zip' but all to no avail, so i was hoping someone could explain why its failing and how i correct it.
i am using python 2.7.9 on windows
thanks
|
2015/04/02
|
[
"https://Stackoverflow.com/questions/29418572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4707947/"
] |
`target_dir` should not be created with brackets.
```
target_dir = 'C:\Users\Administrator\myfile'
target = target_dir + os.sep + \
time.strftime('%Y%m%d%H%M%S') + '.zip'
```
---
Incidentally, take care with your backslashes, because they are also used to signify special characters in a string. For example, `"c:\new_directory"` would be interpreted as "C colon newline W..." rather than "C colon backslash N W...". In which case you would need to escape the slash yourself with `"c:\\new_directory"`, or use raw strings like `r"c:\new_directory"`, or regular slashes (if your OS allows that as a path separator) like `"c:/new_directory"`
|
target\_dir is a list, so in your example you need to do:
```
target = target_dir[0] + os.sep + \
time.strftime('%Y%m%dT%H%M%S') + '.zip'
```
You see that error because you are trying to add a list (target\_list) and strings together, apples and oranges.
| 10,618
|
56,251,211
|
I have a spark DataFrame consisting of 3 columns: `text1`, `text2` and `number`.
I want to filter this DataFrame based on the following constraint:
```python
(len(text1)+len(text2))>number
```
where `len` returns the number of words in `text1` or in `text2`.
I tried the following:
```python
common_df = common_df.filter((len(common_df["text1"].str.split(" ")) + len(common_df["text2"].str.split(" "))) > common_df["number"])
```
but it is not working. I get the following exception:
>
>
> ```python
> TypeError: 'Column' object is not callable
>
> ```
>
>
Here is a sample of my input:
```python
text1 text2 number
bla bla bla no 2
```
|
2019/05/22
|
[
"https://Stackoverflow.com/questions/56251211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11205562/"
] |
[`pyspark.sql.functions.length()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.length) returns the character length of a string. If you want to count the words, you can use [`split()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.split) and [`size()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.size):
It looks like you're looking for:
```python
from pyspark.sql.functions import col, size, split
common_df.where(
(size(split(col("text1"), "\s+")) + size(split(col("text2"), "\s+"))) > col("number")
).show()
```
First you split the strings on the pattern `\s+` which is any number of whitespace characters. Then you take the size of the resulting array.
You can also define a function if you're planning on calling this repeatedly:
```python
def numWords(column):
return size(split(column, "\s+"))
common_df.where((numWords(col("text1")) + numWords(col("text2"))) > col("number")).show()
```
|
You can use `length` from `pyspark.sql.functions`:
```
common_df[(F.length('text1') + F.length('text2')) > common_df['number']]
```
Note that `[]` is a substitute for `filter()`.
| 10,620
|
35,045,038
|
I installed `pytest` into a virtual environment (using `virtualenv`) and am running it from that virtual environment, but it is not using the packages that I installed in that virtual environment. Instead, it is using the main system packages. (Using `python -m unittest discover`, I can actually run my tests with the right python and packages, but I want to use the py.test framework.)
Is it possible that py.test is actually not running the pytest inside the virtual environment and I have to specify which pytest to run?
How to I get py.test to use only the python and packages that are in my virtualenv?
Also, since I have several version of Python on my system, how do I tell which Python that Pytest is using? Will it automatically use the Python within my virtual environment, or do I have to specify somehow?
|
2016/01/27
|
[
"https://Stackoverflow.com/questions/35045038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4770429/"
] |
In my case I was obliged to leave the venv (deactivate), remove pytest (pip uninstall pytest), enter the venv (source /my/path/to/venv), and then reinstall pytest (pip install pytest). I don't known exacttly why pip refuse to install pytest in venv (it says it already present).
I hope this helps
|
you have to activate your python env every time you want to run your python script, you have several ways to activate it, we assume that your virtualenv is installed under /home/venv :
1- the based one is to run the python with one command line
`>>> /home/venv/bin/python <your python file.py>`
2- add this line on the top of python script file
`#! /home/venv/bin/python` and then run `python <you python file.py>`
3- activate your python env `source /home/venv/bin/activate` and then run you script like `python <you python file.py>`
4- use [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/) to manager and activate your python environments
| 10,622
|
14,279,560
|
>
> **Possible Duplicate:**
>
> [Is it possible to change the Environment of a parent process in python?](https://stackoverflow.com/questions/263005/is-it-possible-to-change-the-environment-of-a-parent-process-in-python)
>
>
>
I am using python 2.4.3. I tried to set my http\_proxy variable. Please see the below example and please let me know what is wrong.
the variable is set according to python, however when i get out of the interactive mode. The http\_proxy variable is still not set. I have tried it in a script and also tried it with other variables but i get the same result. No variable is actually set up in the OS.
```
Python 2.4.3 (#1, May 1 2012, 13:52:57)
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['http_proxy']="abcd"
>>> os.system("echo $http_proxy")
abcd
0
>>> print os.environ['http_proxy']
abcd
>>>
user@host~$ echo $http_proxy
user@host~$
```
|
2013/01/11
|
[
"https://Stackoverflow.com/questions/14279560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1970157/"
] |
When you run this code, you set the environment variables, its working scope is only within the process. After you exit (exit the interactive mode of python), these environment will be disappear.
As your code "os.system("echo $http\_proxy")" indicates, if you want to use these environment variables, you need run external program within the process. These variables will be transfer into the child processes and can be used by them.
|
environment variables are not a "global database of settings"; setting the environment here doesn't have any effect there.
the exception to this is that programs which invoke other programs can provide a different environment to their child programs.
At the shell, when you type
```
[~/]$ FOO=bar baz
```
you're telling the *shell* to invoke the program `baz` with some extra environment `FOO`.
You can do this in python, too, but changing `os.environ` will not have any effect. that variable only contains a regular python dict with whatever environment it was started with. You can change the environment python will use by passing an alternate value for `env` to [`subprocess.Popen`](http://docs.python.org/2/library/subprocess#subprocess.Popen)
| 10,628
|
40,009,858
|
I have a file called fName.txt in a directory. Running the following Python snippet would add 6 numbers into 3 rows and 2 columns into the text file through executing the loop (containing the snippet) three times.
However, I would like to empty the file completely before writing new data into it. (Otherwise running the script for many times would produce more than three rows needed for the simulation which would produce nonsense results; in other words the script needs to *see* only three rows just produced from the simulation).
I have come across the following page [how to delete only the contents of file in python](https://stackoverflow.com/questions/17126037/how-to-delete-only-the-content-of-file-in-python) where it explains how to do it but I am not able to implement it into my example.
In particular, after `pass` statement, I am not sure of the order of statements given the fact that my file is closed to begin with and that it must be closed again once `print` statement is executed. Each time, I was receiving a different error message which I could not avoid in any case. Here is one sort of error I was receiving which indicated that the content is deleted (mostly likely after print statement):
```none
/usr/lib/python3.4/site-packages/numpy/lib/npyio.py:1385: UserWarning: genfromtxt: Empty input file: "output/Images/MW_Size/covering_fractions.txt"
warnings.warn('genfromtxt: Empty input file: "%s"' % fname)
Traceback (most recent call last):
File "Collector2.py", line 81, in <module>
LLSs, DLAs = np.genfromtxt(r'output/Images/MW_Size/covering_fractions.txt', comments='#', usecols = (0,1), unpack=True)
ValueError: need more than 0 values to unpack
```
This is why I decided to leave the snippet in its simplest form without using any one of those suggestions in that page:
```
covering_fraction_data = "output/Images/MW_Size/covering_fractions.txt"
with open(covering_fraction_data, "mode") as fName:
print('{:.2e} {:.2e}'.format(lls_number/grid_number, dla_number/grid_number), file=fName)
fName.close()
```
Each run of the simulation produces 3 rows that should be printed into the file. When `mode` is `'a'`, the three produced lines are added to the existing file producing a text file that would contain more than three rows because it already included some contents. After changing `'a'` to `'w'`, instead of having 3 rows printed in the text file, there is only 1 row printed; the first two rows are deleted unwantedly.
**Workaround:**
The only way around to avoid all this is to choose the `'a'` mode and manually delete the contents of the file before running the code. This way, only three rows are produced in the text file after running the code which is what is expected from the output.
**Question:**
How can I modify the above code to actually do the deletion of the file *automatically* and *before* it is filled with three new rows?
|
2016/10/12
|
[
"https://Stackoverflow.com/questions/40009858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6407935/"
] |
You are using 'append' mode (`'a'`) to open your file. When this mode is specified, new text is appended to the existing file content. You're looking for the 'write' mode, that is `open(filename, 'w')`. This will override the file contents every time you **open** it.
|
Using mode 'w' is able to delete the content of the file and overwrite the file but prevents the loop containing the above snippet from printing two more times to produce two more rows of data. In other words, using 'w' mode is not compatible with the code I have given the fact that it is supposed to print into the file three times (since the loop containing this snippet is executing three times). For this reason, I had to empty the file through the following command line inside the main.py code:
```
os.system("> output/Images/MW_Size/covering_fractions.txt")
```
And only then use the 'a' mode in the code snippet mentioned above. This way the loop is executing AND printing into the empty file three times as expected without deleting the first two rows.
| 10,629
|
56,701,359
|
I cannot install fbprophet or gcc7.
I have manually installed a precompiled ephem.
```
Running setup.py install for fbprophet ... error
```
I have tried with python 3.6 and 3.7. I have tried running as administrator and without.
My anaconda prompt cannot install anything without throwing errors. I would rather use pip.
The problem may be related to pystan.
```
File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper
ImportError: DLL load failed: The specified module could not be found.
```
I am using windows 10.
|
2019/06/21
|
[
"https://Stackoverflow.com/questions/56701359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10005867/"
] |
To solve this problem, I uninstalled my existing python 3.7 and anaconda. I re-installed anaconda *with one key difference.*
I registered Anaconda as my default Python 3.7 during the Anaconda installation. This lets visual studio, PyDev and other programs automatically detect Anaconda as the primary version to use.
|
I tried to import fbprophet on Python Anaconda, however, I got some errors.
This code works for me..
```
conda install -c conda-forge/label/cf201901 fbprophet
```
| 10,630
|
31,478,962
|
So I have an array of numbers, and I want to plot how many times each number occurs in the array. X-axis should be the numbers in the array, and y-axis should be the number of times each number occurs in the array. Is there a way to program this in python? Also I have trouble when I try to import numpy or matplotlib.pyplot, so is there a way I can do this?
|
2015/07/17
|
[
"https://Stackoverflow.com/questions/31478962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5120932/"
] |
```
t = [1, 2, 3, 1, 2, 5, 6, 7, 8] #your original list of numbers
noDuplicates = list(set(t)) #gets rid of duplicates in your list
listOfTuples = []
for number in noDuplicates:
count = t.count(number)
newTuple = [number, count]
listOfTuples.Append(newTuple)
```
This creates a list of tuples where the fist number of the tuple is the number you are trying to count and the second number is the count. this will work for the decimals that my first solution did not because i did not know that you needed it to work with decimals. with this list of tuples you should very easily be able to create your graph.
|
your best bet would be to create a separate list to keep track of the number of occurrences in your first list where the number you are tracking is the index of the second list.
```
listOfNumbers = [2,3,4,2,6,4,2]
listOfOccurrences = range(x) #x-1 is the largest number that should occur in the first list
for number in listOfNumbers:
listOfOccurances[number] += 1
```
then if you want to know how many times a number appears in your original list, just use that number as the index for the second list and the value of that spot is the number that you are looking for. then you can make your 2d array where the x axis is your number then you can set the y axis as the number of occurrences.
| 10,640
|
19,363,736
|
I've tried using the AWS forums to get help but, oh boy, it's hard to get anything over there. In any case, [the original post](https://forums.aws.amazon.com/thread.jspa?threadID=136256&tstart=0) is still there.
Here's the same question.
I deployed a Python (Flask) app using Elastic Beanstalk and the Python container. The directory structure is more or less this (simplified to get to the point):
```
[app root]
- application.py
- requirements.txt
/.ebextensions
- python-container.config
/secrets
- keys.py
- secret_logic.py
/myapp
- __init__.py
/static
- image1.png
- some-other-file.js
/services
- __init__.py
- some-app-logic.py
```
I found that any file in my app can be retrieved by browsing as in the following URLs:
* <http://myapp-env-blablabla.elasticbeanstalk.com/static/requirements.txt>
* <http://myapp-env-blablabla.elasticbeanstalk.com/static/secrets/keys.py>
* <http://myapp-env-blablabla.elasticbeanstalk.com/static/myapp/services/some-app-logic.py>
* etc
I poked around and found that this is caused by this config in the file **/etc/httpd/conf.d/wsgi.conf**:
```
Alias /static /opt/python/current/app/
<Directory /opt/python/current/app/>
Order allow,deny
Allow from all
</Directory>
```
Basically this allows read access to my entire app (deployed at **/opt/python/current/app/**) through the **/static** virtual path.
At this point someone might suggest that it's a simple matter of overriding the default Python container **staticFiles** option (what a terrible default value, by the way) using a .config ebextension file. Well, if you look at my directory structure, you'll see **python-container.config**, which has:
```
"aws:elasticbeanstalk:container:python:staticfiles":
"/static/": "app/myapp/static/"
```
But this file is completely ignored when the Apache configuration files are generated. To (I think) prove that, look at the AWS EB scripts at these files (just the important lines):
**/opt/elasticbeanstalk/hooks/configdeploy/pre/01generate.py**:
```py
configuration = config.SimplifiedConfigLoader().load_config()
config.generate_apache_config(
configuration, os.path.join(config.ON_DECK_DIR, 'wsgi.conf'))
```
**/opt/elasticbeanstalk/hooks/appdeploy/pre/04configen.py**:
```py
configuration = config.SimplifiedConfigLoader().load_config()
config.generate_apache_config(
configuration, os.path.join(config.ON_DECK_DIR, 'wsgi.conf'))
```
**/opt/elasticbeanstalk/hooks/config.py**:
```py
def _generate_static_file_config(mapping):
contents = []
for key, value in mapping.items():
contents.append('Alias %s %s' % (key, os.path.join(APP_DIR, value)))
contents.append('<Directory %s>' % os.path.join(APP_DIR, value))
contents.append('Order allow,deny')
contents.append('Allow from all')
contents.append('</Directory>')
contents.append('')
return '\n'.join(contents)
class SimplifiedConfigLoader(ContainerConfigLoader):
def load_config(self):
parsed = json.loads("path/to/containerconfiguration")
python_section = parsed['python']
converted = {}
#..snip...
static_files = {}
for keyval in python_section['static_files']:
key, value = keyval.split('=', 1)
static_files[key] = value
converted['static_files'] = static_files
#...
return converted
```
**/opt/elasticbeanstalk/deploy/configuration/containerconfiguration**:
```
{
"python": {
//...
"static_files": [
"/static="
],
//...
}
```
I apologize for dumping so much code, but the gist of it is that when `_generate_static_file_config` is called to produce that part of *wsgi.config*, it never uses any of the values specified in those ebextension config files. `SimplifiedConfigLoader` only uses the fixed file *containerconfiguration*, which has the evil default value for the */static* mapping.
I hope I'm missing something because I can't find a way to prevent this without resorting to a custom AMI.
|
2013/10/14
|
[
"https://Stackoverflow.com/questions/19363736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21420/"
] |
I ended up opening a paid case with AWS support and they confirmed it was a bug in the Python container code.
As a result of this problem, they have just released (10/25/2013) a new version of the container and any new environments will contain the fix. To fix any of your existing environments... well, you can't. You'll have to create a new environment from the ground up (don't even use saved configurations) and then switch over from the old one.
Hope this helps the next poor soul.
**Update 2017-01-10**: Back when I answered it wasn't possible to upgrade the container to newer versions. Since then AWS added that feature. You can even let it auto-update with the *Managed Platform Updates* feature.
|
You can also change the value of the said `/static` alias via the configuration console on your Elastic Beanstalk environment. Under the "Static Files" section, map the virtual path */static* to point to your directory *app/myapp/static/*
| 10,641
|
49,911,864
|
I am trying to convert a 16 bit 3-band RGB GeoTIFF file into an 8 bit 3-band JPEG file. It seems like the `gdal` library should work well for this. **My question is how do I specify the conversion to 8-bit output in the python gdal API, and how do I scale the values in that conversion? Also, how do I check to tell whether the output is 8-bit or 16-bit?**
The `gdal.Translate()` function should serve the purpose. However, the only example that I found which will rescale the values to 8 bit involves the C interface. The two posts below provide examples of this, but again they do not suit my purpose because they are not using the Python interface.
<https://gis.stackexchange.com/questions/26249/how-to-convert-qgis-generated-tiff-images-into-jpg-jpeg-using-gdal-command-line/26252>
<https://gis.stackexchange.com/questions/206537/geotiff-to-16-bit-tiff-png-or-bmp-image-for-heightmap/206786>
The python code that I came up with is:
```
from osgeo import gdal
gdal.Translate(destName='test.jpg', srcDS='test.tif')
```
This will work, but I don't think the output is coverted to 8-bit or that the values are rescaled. Does anyone know how to apply those specific settings?
Note that this post below is very similar, but uses the `PIL` package. However the problem is that apparently `PIL` has trouble ingesting 16 bit images. When I tried this code I got errors about reading the data. Hence, I could not use this solution.
[converting tiff to jpeg in python](https://stackoverflow.com/questions/28870504/converting-tiff-to-jpeg-in-python)
|
2018/04/19
|
[
"https://Stackoverflow.com/questions/49911864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610428/"
] |
You could use **options** like this
```
from osgeo import gdal
scale = '-scale min_val max_val'
options_list = [
'-ot Byte',
'-of JPEG',
scale
]
options_string = " ".join(options_list)
gdal.Translate('test.jpg',
'test.tif',
options=options_string)
```
Choose the min and max values you find suitable for your image as `min_val` and `max_val`
If you like to expand scaling to the entire range, you can simply skip min and max value and just use `scale = '-scale'`
|
I think the gdal way is to use [`gdal.TranslateOptions()`](http://gdal.org/python/osgeo.gdal-module.html#TranslateOptions).
```
from osgeo import gdal
translate_options = gdal.TranslateOptions(format='JPEG',
outputType=gdal.GDT_Byte,
scaleParams=[''],
# scaleParams=[min_val, max_val],
)
gdal.Translate(destName='test.jpg', srcDS='test.tif', options=translate_options)
```
| 10,642
|
57,189,055
|
I transferred some code from IDLE 3.5 (64 bits) to pycharm (Python 2.7). Most of the code is still working, for example I can import WD\_LINE\_SPACING from docx.enum.text, but for some reason I can't import WD\_ALIGN\_PARAGRAPH.
At first, nearly non of the imports worked, but after I did
pip install python-docx
instead of
pip install docx
most of the imports worked except for WD\_ALIGN\_PARAGRAPH.
```
# works
from __future__ import print_function
import xlrd
import xlwt
import os
import subprocess
from calendar import monthrange
import datetime
from docx import Document
from datetime import datetime
from datetime import date
from docx.enum.text import WD_LINE_SPACING
from docx.shared import Pt
# does not work
from docx.enum.text import WD_ALIGN_PARAGRAPH
```
I don't get any error messages but Pycharm marks the line as error:
"Cannot find reference 'WD\_ALIGN\_PARAGRAPH' in 'text.py'".
|
2019/07/24
|
[
"https://Stackoverflow.com/questions/57189055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9434244/"
] |
You can use this instead:
```py
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
```
and then substitute `WD_PARAGRAPH_ALIGNMENT` wherever `WD_ALIGN_PARAGRAPH` would have appeared before.
The reason this is happening is that the actual enum object is named `WD_PARAGRAPH_ALIGNMENT`, and a decorator is applied that also allows it to be referenced as `WD_ALIGN_PARAGRAPH` (which is a little shorter, and possibly clearer). I expect the syntax checker in PyCharm is operating on direct module attributes and doesn't pick up the alias, which is resolved by the Python parser/compiler.
Interestingly, I expect your code would work fine either way. But to get rid of the annoying message you can use the base name.
|
If someone uses pylint it can be easily suppressed with `# pylint: disable=E0611` added at the end of the import line.
| 10,643
|
55,648,849
|
I have a problem with a loop in Python. My folder looks like this:
```
|folder_initial
|--data_loop
|--example1
|--example2
|--example3
|--python_jupyter_notebook
```
I would like to loop through all files in data\_loop, open them, run a simple operation, save them with another name and then do the same with the subsequent file. I have created the following code:
```
import pandas as pd
import numpy as np
import os
def scan_folder(parent):
# iterate over all the files in directory 'parent'
for file_name in os.listdir(parent):
if file_name.endswith(".csv"):
print(file_name)
df = pd.read_csv("RMB_IT.csv", low_memory=False, header=None, names=['column1','column2','column3','column4']
df = df[['column2','column4']
#Substitute ND with missing data
df = df.replace('ND,1',np.nan)
df = df.replace('ND,2',np.nan)
df = df.replace('ND,3',np.nan)
df = df.replace('ND,4',np.nan)
df = df.replace('ND,5',np.nan)
df = df.replace('ND,6',np.nan)
else:
current_path = "".join((parent, "/", file_name))
if os.path.isdir(current_path):
# if we're checking a sub-directory, recall this method
scan_folder(current_path)
scan_folder("./data_loop") # Insert parent direcotry's path
```
I get the error:
```
FileNotFoundError
FileNotFoundError: File b'example2.csv' does not exist
```
Moreover, I would like to run the code without the necessity of having the Jupyter notebook in the folder folder\_initial but I would like to have something like this:
```
|scripts
|--Jupiter Notebook
|data
|---csv files
|--example1.csv
|--example2.csv
```
Any idea?
-- Edit:
I create something like this on user suggestion
```
import os
import glob
os.chdir('C:/Users/bedinan/Documents/python_scripts_v02/data_loop')
for file in list(glob.glob('*.csv')):
df = pd.read_csv(file, low_memory=False, header=None, names=[
df = df[[
#Substitute ND with missing data
df = df.replace('ND,1',np.nan)
df = df.replace('ND,2',np.nan)
df = df.replace('ND,3',np.nan)
df = df.replace('ND,4',np.nan)
df = df.replace('ND,5',np.nan)
df = df.replace('ND,6',np.nan)
df.to_pickle(file+"_v02"+".pkl")
f = pd.read_pickle('folder\\data_loop\\RMB_PT.csv_v02.pkl')
```
But the name of the file that results is not properly composed since it has inside the name the extension -csv
|
2019/04/12
|
[
"https://Stackoverflow.com/questions/55648849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11335403/"
] |
let try `margin:0 1px` for `.header` div
|
This code can fixed your problem but make sure that border width will be 1px fixed, if you want to change border-width you can remove border-width:thin to border:2px solid red; and so on.
```
.border {
margin-bottom: 20px;
border-radius: 3px;
border: 1px #d43f3a solid;
border-width: thin;
}
```
| 10,644
|
24,351,087
|
I'm currently in the process of finding a nice GUI framework for my new project - and Kivy looks quite good.
There are many questions here (like [this one](https://stackoverflow.com/questions/15281239/kivy-hello-world-not-working)) about Kivy requiring OpenGL >2.0 (not accepting 1.4) and problems arising from that. As I understood, it's the *graphics drivers* thing to provide a decent OpenGL version.
I'm concerned what problems I'll have deploying my app to users having a certain configuration, that they will not be willing or able to have OpenGL >2.0 on their desktop.
First off, deploying on Windows in regard to OpenGL would not be a problem.. Good support there.
*But* I'm specifially concerned about people (like me) having an Ubuntu installation (14.4 LTS) with the latest *Nvidia binary driver* from Ubuntu. It's just the best driver currently, having the best performance (still far superior to nouveau IMHO)..
And it seems (or am I wrong? that would be great) that this driver only provides OpenGL 1.4
```
name of display: :0
display: :0 screen: 0
direct rendering: Yes
server glx vendor string: NVIDIA Corporation
server glx version string: 1.4
server glx extensions: [...]
```
So my question is two-fold
1. I'm I maybe wrong the nvidia binary driver only supporting OpenGL 1.4?
2. If yes, doesn't that exclude many users having a quite common configuration (all Ubuntu users using Nvidia cards) from people able to use my Kivy application?
Any way to circumvent that?
I know OpenGL 1.4 is silly old stuff, but the driver is current and the hardware too (GTX 770, quite a beast..)..
Installed driver:
```
root@host:/home/user# apt-cache policy nvidia-331-updates
nvidia-331-updates:
Installed: 331.38-0ubuntu7
Candidate: 331.38-0ubuntu7
Version table:
```
Nvidia information:
```
Version: 331.38
Release Date: 2014.1.13
```
I really hope I'm wrong..
**EDIT** There has been said 1.4 is the GLX version, *not* the OpenGL version.. I've seen that now - but I thought it's 1.4 because when I try to execute an example from the dist, I get this error:
```
vagrant@ubuntu-14:/usr/local/share/kivy-examples/guide/firstwidget$ python 1_skeleton.py
[WARNING] [Config ] Older configuration version detected (0 instead of 10)
[WARNING] [Config ] Upgrading configuration in progress.
[INFO ] [Logger ] Record log in /home/vagrant/.kivy/logs/kivy_14-06-28_0.txt
[INFO ] Kivy v1.8.1-dev
[INFO ] [Python ] v2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2]
[INFO ] [Factory ] 169 symbols loaded
[INFO ] [Image ] Providers: img_tex, img_dds, img_pygame, img_gif (img_pil ignored)
[INFO ] [Window ] Provider: pygame(['window_egl_rpi'] ignored)
libGL error: failed to load driver: swrast
[INFO ] [GL ] OpenGL version <1.4 (2.1.2 NVIDIA 331.38)>
[INFO ] [GL ] OpenGL vendor <NVIDIA Corporation>
[INFO ] [GL ] OpenGL renderer <GeForce GTX 770/PCIe/SSE2>
[INFO ] [GL ] OpenGL parsed version: 1, 4
[CRITICAL] [GL ] Minimum required OpenGL version (2.0) NOT found!
OpenGL version detected: 1.4
Version: 1.4 (2.1.2 NVIDIA 331.38)
Vendor: NVIDIA Corporation
Renderer: GeForce GTX 770/PCIe/SSE2
Try upgrading your graphics drivers and/or your graphics hardware in case of problems.
```
So it actually parses my OpenGL version as 1.4..
**EDIT 2**: I'm running Kivy from github (master branch) as of today (28th june), so that should be fairly new ;-)
|
2014/06/22
|
[
"https://Stackoverflow.com/questions/24351087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3762521/"
] |
As mentioned in the comment, I am not going to solve every problem. But the main errors.
Let the player be responsible for its position, not the game. Furthermore, I would make the player responsible for drawing itself, but that goes a bit too far for this answer.
The following code should at least work.
```
public class Player : Microsoft.Xna.Framework.GameComponent
{
public Vector2 Pos { get; set; }
public Player(Game game) : base(game)
{
this.Pos = new Vector2(50, 50);
}
public override void Initialize() { base.Initialize(); }
public override void Update(GameTime gameTime)
{
var ms = Mouse.GetState();
Pos.X = ms.X;
Pos.Y = ms.Y;
base.Update(gameTime);
}
}
```
Then use the player in your game:
```
public class RPG : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D PlayerTex;
Player player;
public RPG()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
player = new Player(this);
Components.Add(player);
}
protected override void Initialize() { base.Initialize(); }
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
PlayerTex = Content.Load<Texture2D>("testChar");
}
protected override void UnloadContent() { }
protected override void Update(GameTime gameTime)
{
if
(
GamePad.GetState(PlayerIndex.One)
.Buttons.Back == ButtonState.Pressed
)
this.Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
spriteBatch.Begin();
spriteBatch.Draw(PlayerTex, player.Pos, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
```
I have removed the texture's size. Don't know if you really need this. If so, you can let `Player` expose a Rectangle, not just a `Vector2`.
|
The key solution which Nico included is just that you using the original rectangle coordinates you made when you draw:
```
Rectangle playerPos = new Rectangle(
Convert.ToInt32(Player.Pos.X),
Convert.ToInt32(Player.Pos.Y), 32, 32);
```
Here you make the rectangle using the players CURRENT starting time position.
Then you ALWAYS draw based on this rectangle you made ages ago and never updated:
```
spriteBatch.Draw(PlayerTex, playerPos, Color.White);
```
The right way as Nico mentioned is just to change the draw to this:
```
playerPos = new Rectangle(
Convert.ToInt32(Player.Pos.X),
Convert.ToInt32(Player.Pos.Y), 32, 32);
spriteBatch.Draw(PlayerTex, playerPos, Color.White);
```
Now you will be drawing at a new place every time. There are better ways to do this (like what nico did) but here is the core idea.
| 10,645
|
18,584,055
|
I've got an Ubuntu 12.04 x64 Server edition VM that I'm running python2.7 on and trying to install the MySQLdb package via the command (I've already got `easy_install` installed and working):
```
$ sudo easy_install MySQL-python
```
but I get the following traceback error when easy\_install tries to compile:
```
Traceback (most recent call last):
File "/usr/local/bin/easy_install", line 9, in <module>
load_entry_point('distribute', 'console_scripts', 'easy_install')()
File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 357, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 2393, in load_entry_point
raise ImportError("Entry point %r not found" % ((group,name),))
ImportError: Entry point ('console_scripts', 'easy_install') not found
```
My `/usr/local/lib/python2.7/dist-packages` shows the following packages installed:
* distribute-0.7.3-py2.7.egg
* easy-install.pth
* pyinotify-0.9.4-py2.7.egg
* setuptools-1.1-py2.7.egg
* setuptools.pth
I'm not really sure where to go from here, or why I'm even getting this error. I also wasn't sure if this question would be better suited for ServerFault; but, since I ran into this issue while working on some code, I thought maybe some other coders had ran into it before too...(seemed logical at the time)
|
2013/09/03
|
[
"https://Stackoverflow.com/questions/18584055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281488/"
] |
You need to use subquery :
```
SELECT (
SELECT SUM(`total_amount`)
FROM `civicrm_contribution`
WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id)
)
-
(
SELECT SUM(`fee_amount`)
FROM `civicrm_participant`
WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id)
) As RemainingPoints
```
|
You should limit the result of the subquery to 1 otherwise it will result in an error, the best way is to match the name using `'='` instead of `'like'`
```
SELECT (
SELECT SUM(`total_amount`)
FROM `civicrm_contribution`
WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id)
)
-
(
SELECT SUM(`fee_amount`)
FROM `civicrm_participant`
WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id)
) As RemainingPoints
```
| 10,646
|
3,292,631
|
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations.
Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably.
So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design.
If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design.
My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right.
Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue?
Note: I've considered properties, but I don't think they're a cleaner solution.
|
2010/07/20
|
[
"https://Stackoverflow.com/questions/3292631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/262271/"
] |
>
> Note: I've considered properties, but I don't think they're a cleaner solution.
>
>
>
[But they are.](http://docs.python.org/library/functions.html#property) By using properties, you'll have the class signature you want, while being able to use the property as an attribute itself.
```
def _get_id(self):
return self._id
def _set_id(self, newid):
self._id = newid
```
Is likely similar to what you have now. To placate your team, you'd just need to add the following:
```
id = property(_get_id, _set_id)
```
You could also use `property` as a decorator:
```
@property
def id(self):
return self._id
@id.setter
def id(self, newid):
self._id = newid
```
And to make it readonly, just leave out `set_id`/the `id.setter` bit.
|
[Only behind a property.](http://www.archive.org/details/SeanKellyRecoveryfromAddiction)
| 10,650
|
4,424,342
|
When using the kwarg-style dict initialization:
```
In [3]: dict(a=1, b=2, c=3)
Out[3]: {'a': 1, 'b': 2, 'c': 3}
```
for some reason, defining the key 'from' raises a syntax error:
```
In [4]: dict(to=0, from=1)
------------------------------------------------------------
File "<ipython console>", line 1
dict(to=0, from=1)
^
SyntaxError: invalid syntax
```
What is special about the key 'from'? Are there any other reserved keys for the kwarg-style initialization?
I am using Python 2.6.
|
2010/12/12
|
[
"https://Stackoverflow.com/questions/4424342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/226037/"
] |
from is a keyword:
```
from threading import Thread
```
Python doesn't have context-sensitive keywords: A name is either a keyword, or can be used as an identifier. There used to be one exception: "as" used to be special-cased in import statements when it was first introduced, but has since been promoted to "full keyword".
Context-sensitive keywords would be a questionable feature. E.g. should
```
print=3
```
work or fail (it could be a syntactically incorrect print statement, or an assignment to a variable named print). Or, what about
```
def print(x):
print x
print(3)
```
Should this define a function print? If so, is the last line a call?
|
you can't use python keywords such as `from` in kwargs
| 10,659
|
52,305,578
|
So I am trying to use:
```
sift = cv2.xfeatures2d.SIFT_create()
```
and it is coming up with this error:
```
cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented)
This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake
option and rebuild the library in function 'cv::xfeatures2d::SIFT::create'
```
I am using `Python 3.5.0` and `opencv(3.4.3)` and I am just using idle. This occured after I tried to install TensorFlow and I have tried looking around and have installed opencv-contrib-python but I am still getting the same error. Thank you in advance and I apologise if I have not included enough info
|
2018/09/13
|
[
"https://Stackoverflow.com/questions/52305578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8573126/"
] |
I had the same problem. It seems that SIRF and SURF are [no longer available in opencv > 3.4.2.16](https://github.com/DynaSlum/satsense/issues/13). I chose an older opencv-python and opencv-contrib-python versions and solved this problem. Here is the [history version](https://pypi.org/project/opencv-python/#history) about opencv-python, and I use the following code :
```
pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16
```
**Edit**
For Anaconda User just this instead of pip
```
conda install -c menpo opencv
```
this will install cv2 3.4.1 and everything you need to run SIFT
good luck~
|
It may be due to a mismatch of opencv version and opencv-contrib version.
If you installed opencv from the source using CMake, and the source version is different from the version of opencv-contrib-python, uninstall the current opencv-contrib-python and do `pip install opencv-contrib-python==<version of the source>.X` or an another compatible version.
One version setup that I have running is opencv source (3.2), opencv-python (3.4.0.14) and opencv-contrib-python (3.4.2.17)
| 10,664
|
1,601,153
|
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly.
How can I achieve this ? I use `/etc/crontab` with:
```
****** root python /path/to/project/myapp/manage.py mycommand
```
|
2009/10/21
|
[
"https://Stackoverflow.com/questions/1601153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151937/"
] |
I think the problem is that cron is going to run your scripts in a "bare" environment, so your DJANGO\_SETTINGS\_MODULE is likely undefined. You may want to wrap this up in a shell script that first defines DJANGO\_SETTINGS\_MODULE
Something like this:
```
#!/bin/bash
export DJANGO_SETTINGS_MODULE=myproject.settings
./manage.py mycommand
```
Make it executable (chmod +x) and then set up cron to run the script instead.
**Edit**
I also wanted to say that you can "modularize" this concept a little bit and make it such that your script accepts the manage commands as arguments.
```
#!/bin/bash
export DJANGO_SETTINGS_MODULE=myproject.settings
./manage.py ${*}
```
Now, your cron job can simply pass "mycommand" or any other manage.py command you want to run from a cron job.
|
**How to Schedule Django custom Commands on AWS EC-2 Instance?**
**Step -1**
```
First, you need to write a .cron file
```
**Step-2**
```
Write your script in .cron file.
```
>
> MyScript.cron
>
>
>
```
* * * * * /home/ubuntu/kuzo1/venv/bin/python3 /home/ubuntu/Myproject/manage.py transfer_funds >> /home/ubuntu/Myproject/cron.log 2>&1
```
Where \* \* \* \* \* means that the script will be run at every minute. you can change according to need ([https://crontab.guru/#\*\_\*\_\*\_\*\_\*](https://crontab.guru/#*_*_*_*_*)). Where /home/ubuntu/kuzo1/venv/bin/python3 is python virtual environment path. Where /home/ubuntu/kuzo1/manage.py transfer\_funds is Django custom command path & /home/ubuntu/kuzo1/cron.log 2>&1 is a log file where you can check your running cron log
**Step-3**
**Run this script**
```
$ crontab MyScript.cron
```
**Step-4**
**Some useful command**
```
1. $ crontab -l (Check current running cron job)
2. $ crontab -r (Remove cron job)
```
| 10,669
|
3,236,983
|
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6.
I know that it's possible to specify the interpreter in Unix `#!/usr/bin/python2.6`. But what if I use Windows? Does any way to specify the interpreter exist in Windows?
Edit: I want to be able to use both interpreters simultaneously.
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3236983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248814/"
] |
If you want to mix in the same runtime both 2.6 and 3.1 you may be interested in [execnet](http://codespeak.net/execnet/).
Never tested directly, however
* Edit: looking at you comments on another answer, I understood better the question
|
Maybe "Open with..." + 'Remember my choice' in context menu of explorer?
| 10,679
|
39,654,224
|
I am trying to come up with a neat way of doing this in python.
I have a list of pairs of alphabets and numbers that look like this :
```
[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
```
What I want to do is to create a new list for each alphabet and append all the numerical values to it.
So, output should look like:
```
alist = [1,2,3]
blist = [10,100]
clist = [99]
dlist = [-1,-2]
```
Is there a neat way of doing this in Python?
|
2016/09/23
|
[
"https://Stackoverflow.com/questions/39654224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2272156/"
] |
```
from collections import defaultdict
data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
if __name__ == '__main__':
result = defaultdict(list)
for alphabet, number in data:
result[alphabet].append(number)
```
or without collections module:
```
if __name__ == '__main__':
result = {}
for alphabet, number in data:
if alphabet not in result:
result[alphabet] = [number, ]
continue
result[alphabet].append(number)
```
But i think, that first solution more effective and clear.
|
You can use `defaultdict` from the `collections` module for this:
```
from collections import defaultdict
l = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
d = defaultdict(list)
for k,v in l:
d[k].append(v)
for k,v in d.items():
exec(k + "list=" + str(v))
```
| 10,686
|
65,676,114
|
From one file, I'm trying to import and initialize a class from another file, where that class is initialized with a global variable defined in the calling file.
My file setup looks like this.
```
folder
├──subfolder
│ └── __init__.py
│ └── sub.py
├──__init__.py
├──orig.py
```
My `orig.py` file looks like this:
```
from folder.subfolder.sub import Test
def varinit():
global var
var = 8
def runn():
varinit()
testInstance = Test()
testInstance.print_modvar()
if __name__ == "__main__":
runn()
```
My `sub.py` file looks like this:
```
from folder.orig import var
class Test():
def __init__(self):
self.mod_var=var+8
def print_modvar(self):
print(self.mod_var)
```
In my terminal, I set:
```
export PYTHONPATH=/path/to/rootfolder
```
Where `rootfolder` contains folder.
When I run `python3 folder.orig.py` I get this error:
```
Traceback (most recent call last):
File "folder/orig.py", line 1, in <module>
from folder.subfolder.sub import Test
File "/content/folder/subfolder/sub.py", line 1, in <module>
from folder.orig import var
File "/content/folder/orig.py", line 1, in <module>
from folder.subfolder.sub import Test
ImportError: cannot import name 'Test'
```
The issue is that it is not able to locate `sub.py`? Or is it able to locate `sub.py`, but just not the class defined in `sub.py`?
How can I modify this to be able to correctly `import` the class, with it correctly using the global variable at initialization?
The result is that it should print the number `16`.
For convenience I have a colab notebook with the code that is interactive. The files likely won't persist though
<https://colab.research.google.com/drive/1mYk-XTpQh5d8IoTzXg9phGc2WupYKlRU?usp=sharing>
|
2021/01/11
|
[
"https://Stackoverflow.com/questions/65676114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259896/"
] |
You have got your program almost right. The only challenge I see is with resetting the variable `digit_total = 0` after each iteration.
```
def digital_root(n):
n_str = str(n)
while len(n_str) != 1:
digit_total = 0 #move this inside the while loop
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
print (digital_root(23485))
```
The output for `print (digital_root(23485))` is `4`
```
2 + 3 + 4 + 8 + 5 = 22
2 + 2 = 4
```
If the `digit_total = 0` is not inside the while loop, then it keeps getting added and you get a never ending loop.
While you have a lot of code, you can do this in a single line.
```
def sum_digits(n):
while len(str(n)) > 1: n = sum(int(i) for i in str(n))
return n
print (sum_digits(23485))
```
You don't need to create too many variables and get lost in keeping track of them.
|
Alex,
running a recursive function would always be better than a while loop in such scenarios.
Try this :
```
def digital_root(n):
n=sum([int(i) for i in str(n)])
if len(str(n))==1:
print(n)
else:
digital_root(n)
```
| 10,692
|
70,995,571
|
Im still VERY NEW to programming and python...Any help would be GREATLY appreciated..
I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult.
My original code that actually worked as the intructor wanted is this:
```
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
height = float(height)
weight = int(weight)
result = (height ** 2)
print(int(weight / result))
```
Now when it runs it prints out Enter your height in m:
Then you enter the height then it prints
enter your weight in kg:
then you enter your weight then it just calculates it and returns just the resulting number.. In this case 35.
I wanted to be a little ambitious and I wanted to make it print out like this:
I wanted it to print
Your BMI is 35 instead of just 35..
I wouldnt have thought it would be that hard but WOW..
I have tried SO MANY different ways..
Here is the last I tried.. And it actually prints the way I want it to but then it shows this big LONG error.. It even calculates it correctly.. So I dont know why its giving the error when its performing what I want it to do???
Here is the code I have in it now...
```
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
height = float(height)
weight = int(weight)
result= (height ** 2)
BMI = int(weight / result)
print("Your BMI is: ")
print(BMI)
```
Now it finishes calculating.. And it prints out Your BMI is 35 I am putting in 1.6 for height and 90 for kg
But then after it prints it out as I want it to I see this..
```
enter your height in m: 1.6
enter your weight in kg: 90
Your BMI is
35
.
.
.
Checking if you are printing a single number:
The BMI as an integer (using meters and kilograms)...
Running some tests on your code:
.
.
.
FFF
======================================================================
FAIL: test_1 (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "main.py", line 70, in test_1
self.run_test(given_answer=['2', '8'], expected_print='2\n')
File "main.py", line 67, in run_test
self.assertEqual(fake_out.getvalue(), expected_print)
AssertionError: 'Your BMI is \n2\n' != '2\n'
- Your BMI is
2
======================================================================
FAIL: test_2 (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "main.py", line 73, in test_2
self.run_test(given_answer=['1.8', '85'], expected_print='26\n')
File "main.py", line 67, in run_test
self.assertEqual(fake_out.getvalue(), expected_print)
AssertionError: 'Your BMI is \n26\n' != '26\n'
- Your BMI is
26
======================================================================
FAIL: test_3 (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "main.py", line 76, in test_3
self.run_test(given_answer=['1.6', '90'], expected_print='35\n')
File "main.py", line 67, in run_test
self.assertEqual(fake_out.getvalue(), expected_print)
AssertionError: 'Your BMI is \n35\n' != '35\n'
- Your BMI is
35
----------------------------------------------------------------------
Ran 3 tests in 0.004s
FAILED (failures=3)
KeyboardInterrupt
```
I have NO IDEA what this means or why its doing it when its calculating it correctly and printing it out correctly????
PLEASE HELP???
|
2022/02/05
|
[
"https://Stackoverflow.com/questions/70995571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17611193/"
] |
Well, it's good that you are providing more information to the user than just printing out the BMI. But in this case, your test wants only a single number as output for validation.
Your code is correct but.
A few improvements which you can make in your code:
```
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
height = float(height)
weight = int(weight)
result= (height ** 2)
BMI = int(weight / result)
print("Your BMI is: ")
print(BMI)
```
to:
```
height = input("enter your height in m: ")
weight = int(input("enter your weight in kg: "))#Ask user input in `int` form only.
height = float(height)
result= (height ** 2)
BMI = int(weight / result)
#print("Your BMI is: ") Your evaluator(which checks the code) want the output i.e. BMI only. Kindly remove this and it will work
print(BMI)
```
|
the testing you are using wants your print to be only the BMI calculated, so the last print should only be
```
print(BMI)
```
or you could try:
```
print("Your BMI is: ", BMI)
```
| 10,693
|
50,669,200
|

I need your help in understanding the distribution plot. I was going through tutorial on [this link](http://devarea.com/python-machine-learning-example-linear-regression/#.WxQmilMvxsN). At the end of the post they have mentioned:
>
> We can see from the graph that most of the times the predictions were correct (difference = 0).
>
>
>
So I am not able to understand how are they analyzing the graph.
|
2018/06/03
|
[
"https://Stackoverflow.com/questions/50669200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8285020/"
] |
Reading through your comments, it is difficult to understand where exactly you are having a problem. I'm going to assume it's because you did not know how to write the other initializer due to your first comment:
```
`my object is simple "stuct" and I could not make "(dictionary: data)" -call.`
```
Here's the initializer you could use:
```
extension User {
init?(dictionary: [String: Any]){
guard let firstName = dictionary["firstName"] as? String else { return nil }
guard let lastName = dictionary["lastName"] as? String else { return nil }
}
self.init(firstName: firstName, lastName: lastName)
}
```
|
I finally found that simply swift firestore sdk still missing that function but it seams like it is in works and you can find discussion about that in [here](https://github.com/firebase/firebase-ios-sdk/issues/627)
>
> ...We've had something like this on our radar for a bit. Essentially we want to provide an equivalent to the Android DocumentSnapshot.toObject.
>
>
>
, hopefully it's done soon...
| 10,700
|
21,611,328
|
I'm trying to unzip a file with `7z.exe` and the password contains special characters on it
EX. `&)kra932(lk0¤23`
By executing the following command:
```
subprocess.call(['7z.exe', 'x', '-y', '-ps^&)kratsaslkd932(lkasdf930¤23', 'file.zip'])
```
`7z.exe` launches fine but it says the password is wrong.
This is a file I created and it is driving me nuts.
If I run the command on the windows command line it runs fine
```
7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip
```
How can I make python escape the `&` character?
---
@Wim the issue occurs & on the password, because when i execute
```
7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip
```
it says invalid command `')kratsaslkd932(lkasdf930¤23'`
im using python 2.76, cant upgrade to 3.x due to company tools that only run on 2.76
|
2014/02/06
|
[
"https://Stackoverflow.com/questions/21611328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2065094/"
] |
There is a big security risk in passing the password on the command line. With administrative rights, it is possible to retrieve that information (startup info object) and extract the password. A better solution is to open 7zip as a process, and feed the password into its standard input.
Here is an example of a command line that compresses "source.txt" into "dest.7z":
```
CMD = ['c:\\Program Files\\7-Zip\\7z.exe', 'a', '-t7z', '-p', 'c:\\source.txt', 'd:\\dest.7z']
PASSWORD = "Nj@8G86Tuj#a"
```
First you need to convert the password into an input string. Please note that 7-zip expects the password to by typed into the terminal. You can use special characters as long as they can be represented in your terminal. The encoding of the terminal matters! For example, on Hungarian Windows, you might want to use "cp1250" encoding. In all cases, the standard input is a binary file, and it expects a binary string ("bytes" in Python 3). If you want to be on the safe side, you can restrict passwords to plain ascii and create your input like this:
```
input = (PASSWORD + "\r\n").encode("ascii")
```
If you know the encoding of your terminal, then you can convert the password to that encoding. You will also be able to detect if the password cannot be used with the system's encoding. (And by the way, it also means that it cannot be used interactively either.)
(Last time I checked, the terminal encoding was different for different regional settings on Windows. Maybe there is a trick to change that to UTF-8, but I'm not sure how.)
This is how you execute a command:
```
import subprocess
import typing
def execute(cmd : typing.List[str], input: typing.Optional[bytes] = None, verbose=False, debug=False, normal_priority=False):
if verbose:
print(cmd)
creationflags = subprocess.CREATE_NO_WINDOW
if normal_priority:
creationflags |= subprocess.NORMAL_PRIORITY_CLASS
else:
creationflags |= subprocess.BELOW_NORMAL_PRIORITY_CLASS
if debug:
process = subprocess.Popen(cmd, shell=False, stdout=sys.stdout, stderr=sys.stderr, stdin=subprocess.PIPE,
creationflags=creationflags)
else:
process = subprocess.Popen(cmd, shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
stdin=subprocess.PIPE, creationflags=creationflags)
if input:
process.stdin.write(input)
process.stdin.flush()
returncode = process.wait()
if returncode:
raise OSError(returncode)
CMD = ['c:\\Program Files\\7-Zip\\7z.exe', 'a', '-t7z', '-p', 'c:\\source.txt', 'd:\\dest.7z']
PASSWORD = "Nj@8G86Tuj#a"
input = (PASSWORD + "\r\n").encode("ascii")
execute(CMD, input)
```
This also shows how to lower process priority (which is usually a good idea when compressing large amounts of data), and it also shows how to forward standard output and standard error to the console.
The absolute correct solution would be to load 7-zip DLL and use its API. (I did not check but that can probably use 8 bit binary strings for passwords.)
Note: this example is for Python 3 but the same can be done with Python 2.
|
I'd suggest using a raw string and the shlex module (esp. on Windows) and NOT supporting any encoding other than ASCII.
```
import shlex
import subprocess
cmd = r'7z.exe x -y -p^&moreASCIIpasswordchars file.zip'
subprocess.call(shlex.split(cmd))
```
Back to the non-ASCII character issue...
I'm pretty sure in Python versions < 3 you simply can't use non-ASCII characters. I'm no C expert, but notice the difference between [2.7](http://hg.python.org/cpython/file/712b4665955d/PC/_subprocess.c#l420) and [3.3](http://hg.python.org/cpython/file/b5ad525076eb/Modules/_winapi.c#l579). The former uses a "standard" char while the later uses a wide char.
| 10,701
|
74,611,463
|
I have this code
```
import numpy
a=numpy.pad(numpy.empty([8,8]), 1, constant_values=1)
print(a)
```
50% of the times I execute it it prints a normal array, 50% of times it prints this
```
[[ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000
1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000
1.00000000e+000 1.00000000e+000]
[ 1.00000000e+000 3.25639960e-265 2.03709399e-231 -7.49281680e-111
9.57832017e-299 8.17611616e-093 9.57832017e-299 1.31887592e+066
-2.29724802e+236 1.00000000e+000]
[ 1.00000000e+000 5.11889256e-014 -2.29724802e+236 2.19853714e-004
-2.29724802e+236 -9.20964279e+232 2.37057719e+043 1.48921177e+048
5.29583156e-235 1.00000000e+000]
[ 1.00000000e+000 6.37391724e+057 5.68896808e-235 2.73626021e+067
6.08210460e-235 1.17578020e+077 6.66029790e-235 7.05235822e-235
2.13106310e-308 1.00000000e+000]
[ 1.00000000e+000 7.83852638e-235 2.13214956e-308 8.62479942e-235
2.13323602e-308 9.41107246e-235 2.13432248e-308 1.61214828e+063
1.35001671e-284 1.00000000e+000]
[ 1.00000000e+000 7.20990215e-264 9.57831969e-299 5.06352214e+139
3.18093720e+144 1.21642092e-234 1.25562635e-234 2.13866833e-308
1.41045067e-234 1.00000000e+000]
[ 1.00000000e+000 2.13975479e-308 1.56770528e-234 2.14084125e-308
1.72495988e-234 2.14192771e-308 1.88221449e-234 2.14301418e-308
2.03946910e-234 1.00000000e+000]
[ 1.00000000e+000 2.14410064e-308 2.19672371e-234 2.14518710e-308
2.35397832e-234 2.14627356e-308 1.61656736e+063 1.35004493e-284
7.20998544e-264 1.00000000e+000]
[ 1.00000000e+000 3.93674833e-241 7.20999301e-264 6.00700127e-246
2.03709519e-231 -5.20176578e-111 9.57832021e-299 5.66452894e+075
-2.29724802e+236 1.00000000e+000]
[ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000
1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000
1.00000000e+000 1.00000000e+000]]
```
what is worse, when i do .astype(int) it keeps doing this
```
[[ 1 1 1 1 1 1
1 1 1 1]
[ 1 0 0 0 -2147483648 0
-2147483648 0 0 1]
[ 1 0 0 -2147483648 0 0
0 0 -2147483648 1]
[ 1 0 0 0 0 -2147483648
0 0 0 1]
[ 1 0 0 0 0 0
-2147483648 0 0 1]
[ 1 0 0 -2147483648 0 0
0 0 0 1]
[ 1 0 -2147483648 0 0 0
-2147483648 0 -2147483648 1]
[ 1 0 -2147483648 -2147483648 0 -2147483648
0 0 -2147483648 1]
[ 1 0 0 0 0 0
0 0 0 1]
[ 1 1 1 1 1 1
1 1 1 1]]
```
tried on normal python 3.11 and anaconda 3.9.
I googled but I couldn't find a way to fix this, so any help would be much appreciated. The post needs to have more text so that it isn't "mostly code" and it lets me post it. I would like to know if there are any good ways to solve the issue I've described. As I wrote, I tested it on two different versions of python. Unfortunately, both lead to the same issue.
|
2022/11/29
|
[
"https://Stackoverflow.com/questions/74611463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15673832/"
] |
You can use [apache\_beam.io.jdbc](https://beam.apache.org/releases/pydoc/current/apache_beam.io.jdbc.html) to read from your MySQL database, and the [BigQuery I/O](https://beam.apache.org/documentation/io/built-in/google-bigquery/) to write on BigQuery.
Beam knowledge is expected, so I recommend looking at [Apache Beam Programming Guide](https://beam.apache.org/documentation/programming-guide/) first.
If you are looking for something pre-built, we have the [JDBC to BigQuery Google-provided template](https://cloud.google.com/dataflow/docs/guides/templates/provided-batch#java-database-connectivity-jdbc-to-bigquery), which is open-source ([here](https://github.com/GoogleCloudPlatform/DataflowTemplates/blob/main/v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/templates/JdbcToBigQuery.java)), but it is written in Java.
|
If you only want to copy data from `MySQL` to `BigQuery`, you can firstly export your `MySql` data to `Cloud Storage`, then load this file to a `BigQuery` table.
I think no need using `Dataflow` in this case because you don't have complex transformations and business logics. It only corresponds to a copy.
[Export](https://cloud.google.com/sql/docs/mysql/import-export/import-export-csv#customize-csv-format) the `MySQL` data to `Cloud Storage` via a `sql` query and `gcloud` cli :
```bash
gcloud sql export csv INSTANCE_NAME gs://BUCKET_NAME/FILE_NAME \
--database=DATABASE_NAME \
--offload \
--query=SELECT_QUERY \
--quote="22" \
--escape="5C" \
--fields-terminated-by="2C" \
--lines-terminated-by="0A"
```
[Load](https://cloud.google.com/bigquery/docs/loading-data-cloud-storage-csv#loading_csv_data_into_a_table) the `csv` file to a `BigQuery` table via `gcloud` cli and `bq` :
```bash
bq load \
--source_format=CSV \
mydataset.mytable \
gs://mybucket/mydata.csv \
./myschema.json
```
`./myschema.json` is the `BigQuery` table schema.
| 10,703
|
62,482,387
|
I have done everything the documentation says to.
* I added pip path and it is working but the python command is not working. [Image of path to my python38 DLL](https://i.stack.imgur.com/HSGzo.png)
* The pip path which I added: `C:\Users\Harshal\AppData\Local\Programs\Python\Python38\Scripts
python path : C:\Users\Harshal\AppData\Local\Programs\Python\Python38`
* python command is not working .pip works
|
2020/06/20
|
[
"https://Stackoverflow.com/questions/62482387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10537108/"
] |
In some cases, `py` command works as well as `python` command, so you can try `py`:
```
py -V
py -m pip # this is for pip, exactly for this python version
```
|
Add your python to system environment variables like your path.
or Reinstall python and check the Add to path Checkbox while installing
```
Add to path
```
| 10,704
|
64,652,322
|
I'm currently struggling with python's bit operations as in python3 there is no difference anymore between 32bit integers (int) and 64bit integers (long).
What I want is an **efficient** function that takes any integer and cuts the most significant 32 bits and then converts these 32 bits back to an integer with the correct sign.
Example 1:
```
>>> bin_string = bin(3293670138 & 0b11111111111111111111111111111111)
>>> print(bin_string)
0b11000100010100010110101011111010
>>> print(int(bin_string,2))
3293670138
```
But the result should have been -1001297158 since converting '11000100010100010110101011111010' in a 32 bits integer is a negative number.
I already have my own solution:
```
def int32(val):
if val >= -2**31 and val <= 2**31-1:
return val
bin_string = bin(val & 0b11111111111111111111111111111111)
int_val = int(bin_string,2)
if int_val > 2147483647:
return -(~(int_val-1)%2**32)
return int_val
```
However, I would like to know if someone has a more elegant and performant idea.
Thank you in advance!
|
2020/11/02
|
[
"https://Stackoverflow.com/questions/64652322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10684977/"
] |
Significantly simpler solution: Let [`ctypes`](https://docs.python.org/3/library/ctypes.html) do the work for you.
```
from ctypes import c_int32
def int32(val):
return c_int32(val).value
```
That just constructs a `c_int32` type from the provided Python `int`, which truncates as you desire, then extracts the value back out as a normal Python `int` type. The time taken is less than that of your existing function for values that actually require trimming. On my machine, it takes about 155-175 ns reliably, where your function is more variable, taking around 310-320 ns for positive values, and 405-415 ns for negative values.
It *is* slower for values that don't require trimming though; your code excludes them relatively cheaply (I improved it slightly by changing the test to `if -2 ** 31 <= val < 2 ** 31:`), taking ~75 ns, but this code does the conversion no matter what, taking the same roughly fixed amount of time. If numbers usually fit, and performance is critical, you can short cut out the way your original code (with slightly modification from me) did:
```
def int32(val):
if -2 ** 31 <= val < 2 ** 31:
return val
return c_int32(val).value
```
That makes the "must truncate" case slightly slower (just under 200 ns) in exchange for making the "no truncation needed" case faster (below 80 ns).
Importantly, either way, it's fairly simple. It doesn't involve maintaining complicated code, and it's largely self-documenting; you tell it to make a signed 32 bit int, and it does so.
|
use bitstring library which is excellent.
```
from bitstring import BitArray
x = BitArray(bin='11000100010100010110101011111010')
print(x.int)
```
| 10,705
|
20,534,999
|
Here is an example of failure from a shell.
```
>>> from traits.api import Dict
>>> d=Dict()
>>> d['Foo']='BAR'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Dict' object does not support item assignment
```
I have been searching all over the web, and there is no indication of how to use Dict.
I am trying to write a simple app that displays the contents of a python dictionary. This link ([Defining view elements from dictionary elements in TraitsUI](https://stackoverflow.com/questions/19228631/defining-view-elements-from-dictionary-elements-in-traitsui)) was moderately helpful except for the fact that the dictionary gets updated on some poll\_interval and if I use the solution there (wrapping a normal python dict in a class derived from HasTraits) the display does not update when the underlying dictionary gets updated.
Here are the relevant parts of what I have right now. The last class can pretty much be ignored, the only reason I included it is to help understand how I intend to use the Dict.
pyNetObjDisplay.run\_ext() gets called once per loop from the base classes run() method
```
class DictContainer(HasTraits):
_dict = {}
def __getattr__(self, key):
return self._dict[key]
def __getitem__(self, key):
return self._dict[key]
def __setitem__(self, key, value):
self._dict[key] = value
def __delitem__(self, key, value):
del self._dict[key]
def __str__(self):
return self._dict.__str__()
def __repr__(self):
return self._dict.__repr__()
def has_key(self, key):
return self._dict.has_key(key)
class displayWindow(HasTraits):
_remote_data = Instance(DictContainer)
_messages = Str('', desc='Field to display messages to the user.', label='Messages', multi_line=True)
def __remote_data_default(self):
tempDict = DictContainer()
tempDict._dict = Dict
#tempDict['FOO'] = 'BAR'
sys.stderr.write('SETTING DEFAULT DICTIONARY:\t%s\n' % tempDict)
return tempDict
def __messages_default(self):
tempStr = Str()
tempStr = ''
return tempStr
def traits_view(self):
return View(
Item('object._remote_data', editor=ValueEditor()),
Item('object._messages'),
resizable=True
)
class pyNetObjDisplay(pyNetObject.pyNetObjPubClient):
'''A derived pyNetObjPubClient that stores remote data in a dictionary and displays it using traitsui.'''
def __init__(self, hostname='localhost', port=54322, service='pyNetObject', poll_int=10.0):
self._display = displayWindow()
self.poll_int = poll_int
super(pyNetObjDisplay, self).__init__(hostname, port, service)
self._ui_running = False
self._ui_pid = 0
### For Testing Only, REMOVE THESE LINES ###
self.connect()
self.ns_subscribe(service, 'FOO', poll_int)
self.ns_subscribe(service, 'BAR', poll_int)
self.ns_subscribe(service, 'BAZ', poll_int)
############################################
def run_ext(self):
if not self._ui_running:
self._ui_running = True
self._ui_pid = os.fork()
if not self._ui_pid:
time.sleep(1.25*self.poll_int)
self._display.configure_traits()
for ((service, namespace, key), value) in self._object_buffer:
sys.stderr.write('TEST:\t' + str(self._display._remote_data) + '\n')
if not self._display._remote_data.has_key(service):
self._display._remote_data[service] = {}
if not self._display._remote_data[service].has_key(namespace):
#self._remote_data[service][namespace] = {}
self._display._remote_data[service][namespace] = {}
self._display._remote_data[service][namespace][key] = value
msg = 'Got Published ((service, namespace, key), value) pair:\t((%s, %s, %s), %s)\n' % (service, namespace, key, value)
sys.stderr.write(msg)
self._display._messages += msg
sys.stderr.write('REMOTE DATA:\n' + str(self._display._remote_data)
self._object_buffer = []
```
|
2013/12/12
|
[
"https://Stackoverflow.com/questions/20534999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2121874/"
] |
I think your basic problem has to do with notification issues for traits that live outside the model object, and not with "how to access those objects" per se [edit: actually no this is not your problem at all! But it is what I thought you were trying to do when I read your question with my biased mentality towards problems I have seen before and in any case my suggested solution will still work]. I have run into this sort of problem recently because of how I decided to design my program (with code describing a GUI separated modularly from the very complex sets of data that it can contain). You may have found my other questions, as you found the first one.
Having lots of data live in a complex data hierarchy away from the GUI is not the design that traitsui has in mind for your application and it causes all kinds of problems with notifications. Having a flatter design where GUI information is integrated into the different parts of your program more directly is the design solution.
I think that various workarounds might be possible for this in general (I have used some for instance in [enabled\_when listening outside model object](https://stackoverflow.com/questions/20409629/enabled-when-listening-outside-model-object)) that don't involve dictionaries. I'm not sure what the most design friendly solution to your problem with dictionaries is, but one thing that works and doesn't interfere a lot with your design (but it is still a "somewhat annoying" solution) is to make everything in a dictionary be a HasTraits and thus tag it as listenable. Like so:
```
from traits.api import *
from traitsui.api import *
from traitsui.ui_editors.array_view_editor import ArrayViewEditor
import numpy as np
class DContainer(HasTraits):
_dict=Dict
def __getattr__(self, k):
if k in self._dict:
return self._dict[k]
class DItem(HasTraits):
_item=Any
def __init__(self,item):
super(DItem,self).__init__()
self._item=item
def setitem(self,val):
self._item=val
def getitem(self):
return self._item
def traits_view(self):
return View(Item('_item',editor=ArrayViewEditor()))
class LargeApplication(HasTraits):
d=Instance(DContainer)
stupid_listener=Any
bn=Button('CLICKME')
def _d_default(self):
d=DContainer()
d._dict={'a_stat':DItem(np.random.random((10,1))),
'b_stat':DItem(np.random.random((10,10)))}
return d
def traits_view(self):
v=View(
Item('object.d.a_stat',editor=InstanceEditor(),style='custom'),
Item('bn'),
height=500,width=500)
return v
def _bn_fired(self):
self.d.a_stat.setitem(np.random.random((10,1)))
LargeApplication().configure_traits()
```
|
Okay, I found the answer (kindof) in this question: [Traits List not reporting items added or removed](https://stackoverflow.com/questions/19041426/traits-list-not-reporting-items-added-or-removed)
when including Dict or List objects as attributes in a class one should NOT do it this way:
```
class Foo(HasTraits):
def __init__(self):
### This will not work as expected!
self.bar = Dict(desc='Description.', label='Name', value={})
```
Instead do this:
```
class Foo(HasTraits):
def __init__(self):
self.add_trait('bar', Dict(desc='Description.', label='Name', value={}) )
```
Now the following will work:
```
>>> f = Foo()
>>> f.bar['baz']='boo'
>>> f.bar['baz']
'boo'
```
Unfortunately for some reason the GUI generated with configure\_traits() does not update it's view when the underlying data changes. Here is some test code that demonstrates the problem:
```
import os
import time
import sys
from traits.api import HasTraits, Str, Dict
from traitsui.api import View, Item, ValueEditor
class displayWindow(HasTraits):
def __init__(self, **traits):
super(displayWindow, self).__init__(**traits)
self.add_trait('_remote_data', Dict(desc='Dictionary to store remote data in.', label='Data', value={}) )
self.add_trait('_messages', Str(desc='Field to display messages to the user.', label='Messages', multi_line=True, value='') )
def traits_view(self):
return View(
Item('object._remote_data', editor=ValueEditor()),
Item('object._messages'),
resizable=True
)
class testObj(object):
def __init__(self):
super(testObj, self).__init__()
self._display = displayWindow()
self._ui_pid = 0
def run(self):
### Run the GUI in the background
self._ui_pid = os.fork()
if not self._ui_pid:
self._display.configure_traits()
i = 0
while True:
self._display._remote_data[str(i)] = i
msg = 'Added (key,value):\t("%s", %s)\n' % (str(i), i, )
self._display._messages += msg
sys.stderr.write(msg)
time.sleep(5.0)
i+=1
if __name__ == '__main__':
f = testObj()
f.run()
```
| 10,706
|
66,047,199
|
So what i am basically trying to do is groups a set of mongo docs having the same `key:value` pair and return them in the form of a list of list.
EX:
```
{"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"}
```
Output:
```
{"result": [ [{"client":"abp","product":"a"},{"client":"abp","product":"c"}], [{"client":"aaj","product":"b"}] ] }
```
Mongo query or any other logic in python would help. Thanks in advance.
|
2021/02/04
|
[
"https://Stackoverflow.com/questions/66047199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12408855/"
] |
I would group by client and then create and array of product using $push. $push allows you to insert each grouped object in an array.
```
db.yourcollection.aggregate([
{
$group: {
_id: '$client',
products: {$push: {client: '$client', product: '$product'}}
}
}])
```
|
```
from operator import itemgetter
from itertools import groupby
x=[{"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"}]
x.sort(key=itemgetter('client'),reverse=True)
d=[list(g) for (k,g) in groupby(x,itemgetter('client'))]
final = {}
final['result']=d
Output:
{'result': [[{'client': 'abp', 'product': 'a'},
{'client': 'abp', 'product': 'c'}],
[{'client': 'aaj', 'product': 'b'}]]
```
| 10,707
|
34,651,824
|
Currently `--resize` flag that I created is boolean, and means that all my objects will be resized:
```
parser.add_argument("--resize", action="store_true", help="Do dictionary resize")
# ...
# if resize flag is true I'm re-sizing all objects
if args.resize:
for object in my_obects:
object.do_resize()
```
Is there a way implement argparse argument that if passed as boolean flag (`--resize`) will return true, but if passed with value (`--resize 10`), will contain value.
Example:
1. `python ./my_script.py --resize # Will contain True that means, resize all the objects`
2. `python ./my_script.py --resize <index> # Will contain index, that means resize only specific object`
|
2016/01/07
|
[
"https://Stackoverflow.com/questions/34651824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/524743/"
] |
In order to optionally accept a value, you need to set [`nargs`](https://docs.python.org/2/library/argparse.html#nargs) to `'?'`. This will make the argument consume one value if it is specified. If the argument is specified but without value, then the argument will be assigned the argument’s [`const`](https://docs.python.org/3/library/argparse.html#const) value, so that’s what you need to specify too:
```
parser = argparse.ArgumentParser()
parser.add_argument('--resize', nargs='?', const=True)
```
There are now three cases for this argument:
1. Not specified: The argument will get its [default value](https://docs.python.org/3/library/argparse.html#default) (`None` by default):
```
>>> parser.parse_args(''.split())
Namespace(resize=None)
```
2. Specified without a value: The argument will get its const value:
```
>>> parser.parse_args('--resize'.split())
Namespace(resize=True)
```
3. Specified with a value: The argument will get the specified value:
```
>>> parser.parse_args('--resize 123'.split())
Namespace(resize='123')
```
Since you are looking for an index, you can also specify `type=int` so that the argument value will be automatically parsed as an integer. This will not affect the default or const case, so you still get `None` or `True` in those cases:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--resize', nargs='?', type=int, const=True)
>>> parser.parse_args('--resize 123'.split())
Namespace(resize=123)
```
---
Your usage would then look something like this:
```
if args.resize is True:
for object in my_objects:
object.do_resize()
elif args.resize:
my_objects[args.resize].do_resize()
```
|
You can add `default=False`, `const=True` and `nargs='?'` to the argument definition and remove `action`. This way if you don't pass `--resize` it will store False, if you pass `--resize` with no argument will store `True` and otherwise the passed argument. Still you will have to refactor the code a bit to know if you have index to delete or delete all objects.
| 10,708
|
24,818,096
|
I am new to python app development. When I tried a code I'm not able to see its output. My sample code is:
```
class name:
def __init__(self):
x = ''
y = ''
print x,y
```
When i called the above function like
```
some = name()
some.x = 'yeah'
some.x.y = 'hell'
```
When i called `some.x` it works fine but when i called `some.x.y = 'hell'` it shows error like
```
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
some.x.y = 'hell'
AttributeError: 'str' object has no attribute 'y'
```
Hope you guys can help me out.
|
2014/07/18
|
[
"https://Stackoverflow.com/questions/24818096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843420/"
] |
First of all, you are defining the class with the wrong way, you should;
```
class name:
def __init__(self):
self.x = ''
self.y = ''
print x,y
```
Then, you are calling the wrong way, you should;
```
some = name()
some.x = 'yeah'
some.y = 'hell'
```
The problem is, `x` and `y` are `strings`. If you want to `some.x.y` for some reason, you should define `x` on your own.In other words, you can't use `some.x.y` for now.
Ok, you still need for `some.x.y`;
```
class name:
def __init__(self):
pass
some = name()
some.x = name()
some.x.y = "foo"
print some.x.y
>>> foo
```
|
`x` and `y` are two different variables on your instance `some`.
When you call `some.x`, you are returning the string `'yeah'`. And then you call `.y`, you are actually trying to do `'yeah'.y`, which is why it says string object has no attribute `y`.
So what you want to do is:
```
some = name()
some.x = 'hell'
some.y = 'yeah'
print some.x, some.y
```
| 10,710
|
72,462,419
|
Given a website (for example stackoverflow.com) I want to download all the files under:
```
(Right Click) -> Inspect -> Sources -> Page
```
Please Try it yourself and see the files you get.
**How can I do that in python?**
I know how to retrive page source but not the source files.
I tried searching this multiple times with no success and there is a confusion between sources (files) and page source.
Please Note, I'm looking for a an approach or example rather than ready-to-use code.
For example, I want to gather all of these files under `top`:

|
2022/06/01
|
[
"https://Stackoverflow.com/questions/72462419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19248696/"
] |
To download website source files (mirroring websites / copy source files from websites) you may try [`PyWebCopy`](https://github.com/rajatomar788/pywebcopy/) library.
To save any single page -
```
from pywebcopy import save_webpage
save_webpage(
url="https://httpbin.org/",
project_folder="E://savedpages//",
project_name="my_site",
bypass_robots=True,
debug=True,
open_in_browser=True,
delay=None,
threaded=False,
)
```
To save full website -
```
from pywebcopy import save_website
save_website(
url="https://httpbin.org/",
project_folder="E://savedpages//",
project_name="my_site",
bypass_robots=True,
debug=True,
open_in_browser=True,
delay=None,
threaded=False,
)
```
You can also check tools like [httrack](https://www.httrack.com/) which comes with a GUI to download website files (mirror).
On the other hand to download web-page source code (HTML pages) -
```
import requests
url = 'https://stackoverflow.com/questions/72462419/how-to-download-website-source-files-in-python'
html_output_name = 'test2.html'
req = requests.get(url, 'html.parser', headers={
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'})
with open(html_output_name, 'w') as f:
f.write(req.text)
f.close()
```
|
The easiest way to do this is definitely not with Python.
As you seem to know, you can download code to a single site w/ Command click > View Page Source or the sources tab of inspect element. To download all the files in a website's structure, you should use a web-scraper.
For Mac, SiteSucker is your best option if you don’t care about having all of the site assets (videos, images, etc. hosted on the website) downloaded locally on your computer. Videos especially could take up a lot of space, so this sometimes helpful. (Site Sucker is not free, but pretty cheap). The GUI in SiteSucker is self-explanatory, so there's no learning curve.
If you do want all assets to be downloaded locally on your computer (you may want to do this if you want to access a site’s content offline, for example), HTTrack is the best option, in my opinion, for Mac and Windows. (Free). HTTrack is harder to use than SiteSucker, but allows more options about which files to grab, and again will download things locally. There are many good tutorials/pages about how to use the GUI for HTTrack, like this one: <http://www.httrack.com/html/shelldoc.html>
You could also use wget (Free) to download content, but wget does not have a GUI and has less flexibility, so I prefer HTTrack.
| 10,715
|
63,158,692
|
**Summarize the problem:**
The Python package basically opens PDFs in batch folder, reads the first page of each PDF, matches keywords, and dumps compatible PDFs in source folder for OCR scripts to kick in. The first script to take all PDFs are **MainBankClass.py**. I am trying to use a docker-compose file to include all these python scripts under the same *network* and *volume* so that each OCR script starts to scan bank statements when the pre-processing is done. [This link](https://stackoverflow.com/questions/53920742/how-to-run-multiple-python-scripts-and-an-executable-files-using-docker/53921177) is the closest so far to accomplish the goal but it seems that I missed some parts of it. The process to call different OCR scripts is achieved by `runpy.run_path(path_name='ChaseOCR.py')`, thus these scripts are in the same directory of `__init__.py`. Here is the filesystem structure:
```
BankStatements
┣ BankofAmericaOCR
┃ ┣ BancAmericaOCR.py
┃ ┗ Dockerfile.bankofamerica
┣ ChaseBankStatementOCR
┃ ┣ ChaseOCR.py
┃ ┗ Dockerfile.chase
┣ WellsFargoStatementOCR
┃ ┣ Dockerfile.wellsfargo
┃ ┗ WellsFargoOCR.py
┣ BancAmericaOCR.py
┣ ChaseOCR.py
┣ Dockerfile
┣ WellsFargoOCR.py
┣ __init__.py
┗ docker-compose.yml
```
**What I've tried so far:**
In docker-compose.yml:
```
version: '3'
services:
mainbankclass_container:
build:
context: '.'
dockerfile: Dockerfile
volumes:
- /Users:/Users
#links:
# - "chase_container"
# - "wellsfargo_container"
# - "bankofamerica_container"
chase_container:
build: .
working_dir: /app/ChaseBankStatementOCR
command: ./ChaseOCR.py
volumes:
- /Users:/Users
bankofamerica_container:
build: .
working_dir: /app/BankofAmericaOCR
command: ./BancAmericaOCR.py
volumes:
- /Users:/Users
wellsfargo_container:
build: .
working_dir: /app/WellsFargoStatementOCR
command: ./WellsFargoOCR.py
volumes:
- /Users:/Users
```
And each dockerfile under each bank folder is similar except `CMD` would be changed accordingly. For example, in ChaseBankStatementOCR folder:
```
FROM python:3.7-stretch
WORKDIR /app
COPY . /app
CMD ["python3", "ChaseOCR.py"] <---- changes are made here for the other two bank scripts
```
The last element is for Dockerfile outside of each folder:
```
FROM python:3.7-stretch
WORKDIR /app
COPY ./requirements.txt ./
RUN pip3 install --upgrade pip
RUN pip3 install -r requirements.txt
RUN pip3 install --upgrade PyMuPDF
COPY . /app
COPY ./ChaseOCR.py /app
COPY ./BancAmericaOCR.py /app
COPY ./WellsFargoOCR.py /app
EXPOSE 8080
CMD ["python3", "MainBankClass.py"]
```
After running `docker-compose build`, containers and network are successfully built. Error occurs when I run `docker run -v /Users:/Users: python3 python3 ~/BankStatementsDemoOCR/BankStatements/MainBankClass.py` and the error message is *FileNotFoundError: [Errno 2] No such file or directory: 'BancAmericaOCR.py'*
I am assuming that the container doesn't have BancAmericaOCR.py but I have composed each .py file under the same network and I don't think `links` is a good practice since docker recommended to use `networks` [here](https://docs.docker.com/compose/networking/). What am I missing here? Any help is much appreciated. Thanks in advance.
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63158692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12961386/"
] |
>
> single application in a single container ... need networks for different py files to communicate
>
>
>
You only have one container. Docker networks are for multiple containers to talk to one another. And Docker Compose has a default bridge network defined for all services, so you shouldn't need that if you were still using docker-compose
Here's a cleaned up Dockerfile with all the scripts copied in, with the addition of an entrypoint file
```
FROM python:3.7-stretch
WORKDIR /app
COPY ./requirements.txt ./
RUN pip3 install --upgrade pip PyMuPDF && pip3 install -r requirements.txt
COPY . /app
COPY ./docker-entrypoint.sh /
ENTRYPOINT /docker-entrypoint.sh
```
In your entrypoint, you can loop over every file
```
#!/bin/bash
for b in Chase WellsFargo BofA ; do
python3 /app/$b.py
done
exec python3 /app/MainBankClass.py
```
|
So after days of searching regarding my case, I am closing this thread with an implementation of **single application in a single container** suggested on [this link](https://forums.docker.com/t/is-it-possible-to-run-python-package-with-multiple-py-scripts-in-docker-compose-yml/97094/8) from docker forum. Instead of going with docker-compose, the suggested approach is to use 1 container with dockerfile for this application and it's working as expected.
On top of the dockerfile, we also need *networks* for different py files to communicate. For example:
```
docker network create my_net
docker run -it --network my_net -v /Users:/Users --rm my_awesome_app
```
**EDIT:**
No network is needed since we are only running one container.
**EDIT 2:**
Please see the accepted answer for future reference
Any answers are welcomed if anyone has better ideas on the case.
| 10,716
|
378,811
|
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error:
```
500 Internal Server Error
```
When I check my error logs I see the message
```
Premature end of script headers
```
The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine.
"
So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.
Thanks!
---
Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:
```
#!/usr/local/bin/python
print "Content-type: text/html\n"
print "\n\n"
print "<HTML>"
print "<HEAD>"
print "<TITLE>Test</TITLE>"
print "</HEAD>"
print "<BODY>"
print "<H2>Hi there.</h2>"
print "</BODY>"
print "</HTML>"
```
Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder.
---
An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error.
I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
|
2008/12/18
|
[
"https://Stackoverflow.com/questions/378811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47514/"
] |
One common error is the wrong path. I my case it was usr/bin/python. The other common error is not transferring the file in ASCII mode. I am using WinSCP where you can set it easily: Go to Options->Preferences->Transfers->click Edit and change the mode to Text.
This code should work:
```
#!/usr/bin/python
print "Content-type: text/html\n\n";
print "<html><head>";
print "<title>CGI Test</title>";
print "</head><body>";
print "<p>Test page using Python</p>";
print "</body></html>";
```
|
Sounds to me like you're using a script written in Windows on a Unix machine, without first converting the line-endings from 0d0a to 0a. It should be easy to convert it. One way is with your ftp program; transfer the file in ASCII mode. The way I use with Metapad is to use File->FileFormat before saving.
| 10,717
|
58,604,645
|
I want to get all the installed patches on an `AWS EC2 instance`, So I run this code in `boto3`:
```
response = client.describe_instance_patches(InstanceId=instance_id, Filters=[{'Key': 'State','Values': ['Installed',]} ])
```
My instance has a patch with a negative timestamp :
```
{
"Patches": [
{
"KBId": "KB3178539",
"Severity": "Important",
"Classification": "SecurityUpdates",
"Title": "Security Update for Windows 8.1 (KB3178539)",
"State": "Installed",
"InstalledTime": 1483574400.0
},
{
"KBId": "KB4493446",
"Severity": "Critical",
"Classification": "SecurityUpdates",
"Title": "2019-04 Security Monthly Quality Rollup for Windows 8.1 for x64-based Systems (KB4493446)",
"State": "Installed",
"InstalledTime": 1555804800.0
},
{
"KBId": "KB4487080",
"Severity": "Important",
"Classification": "SecurityUpdates",
"Title": "2019-02 Security and Quality Rollup for .NET Framework 3.5, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2 for Windows 8.1 (KB4487080)",
"State": "Installed",
"InstalledTime": -62135596800.0
}
]
}
```
So my boto3 snippet gives me this error:
```
response = client.describe_instance_patches(InstanceId=instance_id, Filters=[{'Key': 'State','Values': ['Installed',]}, ])
File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 648, in _make_api_call
operation_model, request_dict, request_context)
File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 667, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 102, in make_request
return self._send_request(request_dict, operation_model)
File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 135, in _send_request
request, operation_model, context)
File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 167, in _get_response
request, operation_model)
File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 218, in _do_get_response
response_dict, operation_model.output_shape)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 242, in parse
parsed = self._do_parse(response, shape)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 740, in _do_parse
parsed = self._handle_json_body(response['body'], shape)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 761, in _handle_json_body
return self._parse_shape(shape, parsed_json)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 302, in _parse_shape
return handler(shape, node)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 572, in _handle_structure
raw_value)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 302, in _parse_shape
return handler(shape, node)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 310, in _handle_list
parsed.append(self._parse_shape(member_shape, item))
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 302, in _parse_shape
return handler(shape, node)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 572, in _handle_structure
raw_value)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 302, in _parse_shape
return handler(shape, node)
File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 589, in _handle_timestamp
return self._timestamp_parser(value)
File "/usr/local/lib/python2.7/dist-packages/botocore/utils.py", line 558, in parse_timestamp
return datetime.datetime.fromtimestamp(value, tzlocal())
File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/_common.py", line 144, in fromutc
return f(self, dt)
File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/_common.py", line 258, in fromutc
dt_wall = self._fromutc(dt)
File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/_common.py", line 222, in _fromutc
dtoff = dt.utcoffset()
File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/tz.py", line 216, in utcoffset
if self._isdst(dt):
File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/tz.py", line 288, in _isdst
if self.is_ambiguous(dt):
File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/tz.py", line 250, in is_ambiguous
(naive_dst != self._naive_is_dst(dt - self._dst_saved)))
OverflowError: date value out of range
```
I need to get the installed patches of several instances and I don't want the script to break when it finds a negative timestamp. How can workaround this ? How can I use the filters to get only valid timestamps ?
|
2019/10/29
|
[
"https://Stackoverflow.com/questions/58604645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2337243/"
] |
Assuming this is nothing to with service worker/PWA, the solution could be implemented by returning the front end version by letting the server return the current version of the Vue App everytime.
`axiosConfig.js`
```
axios.interceptors.response.use(
(resp) => {
let fe_version = resp.headers['fe-version'] || 'default'
if(fe_version !== localStorage.getItem('fe-version') && resp.config.method == 'get'){
localStorage.setItem('fe-version', fe_version)
window.location.reload() // For new version, simply reload on any get
}
return Promise.resolve(resp)
},
)
```
Full Article here: <https://blog.francium.tech/vue-js-cache-not-getting-cleared-in-production-on-deploy-656fcc5a85fe>
|
A possible problem could be that the browser is caching the `index.html` file.
Try to disable cache for `index.html` like this:
```
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
```
Or if you are using a .htaccess file, add this code to the bottom of the file:
```
<Files index.html>
FileETag None
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</Files>
```
| 10,727
|
49,604,025
|
I'm trying to translate code that generates a Voronoi Diagram from Javascript into Python. This is a struggle because I don't know Javascript. I think I can sort-of make it out, but I'm still running into issues with things I don't understand. Please help me figure out what is wrong with my code.
The code I've written simply give a blank window. Please help me generate a Voronoi Diagram.
In order, I have my code, then the original code.
Here's a link to the website I found it at:
[Procedural Generation Wiki](http://pcg.wikidot.com/pcg-algorithm:voronoi-diagram)
My Code:
```
"""
Translated from javascript example at
http://pcg.wikidot.com/pcg-algorithm:voronoi-diagram
I have included the original comments.
My own comments are preceded by two hash-tags/pound-signs.
IE
# Original Javascript comments here
## My comments here
"""
import random
import pygame
from pygame import gfxdraw
# specify an empty points array
## I will use a list.
points = []
lines = []
# get a random number in range min, max -1
## No need for our own random number function.
## Just, import random, instead.
def definePoints(numPoints, mapSize):
# we want to take a group of points that will fit on our map at random
for typ in range(numPoints):
# here's the random points
x = random.randrange(0, mapSize)
y = random.randrange(0, mapSize)
# "type:" decides what point it is
# x, y: location
# citizens: the cells in our grid that belong to this point
## Can't use "type:" (without quotes) in python comments
## Since I don't know Javascript, I dunno what he's doing here.
## I'm just going to append lists inside points.
## order is: type, x, y, citizens
points.append([typ, x, y, []])
# brute force-y but it works
# for each cell in the grid
for x in range(mapSize):
for y in range(mapSize):
# find the nearest point
lowestDelta = (0, mapSize * mapSize)
for p in range(len(points)):
# for each point get the difference in distance
# between our point and the current cell
## I split the above comment into two so
## it would be less than 80 characters.
delta = abs(points[p][1] - x) + abs(points[p][2] - y)
# store the point nearest if it's closer than the last one
if delta < lowestDelta[1]:
lowestDelta = (p, delta)
# push the cell to the nearest point
## Okay, here's where I start getting confused.
## I dunno how to do whatever he's doing in Python.
for point in points:
if lowestDelta[0] == point[0]:
activePoint = point
dx = x - activePoint[1]
dy = y - activePoint[2]
# log delta in cell for drawing
## Again, not sure what he's doing here.
for point in points:
if activePoint == point:
point[3].append(dx)
point[3].append(dy)
return points
## all comments and code from here on are mine.
def main():
# Get points
points = definePoints(20, 400)
print("lines: ", lines)
# Setup pygame screens.
pygame.init()
size = (400, 400)
screen = pygame.display.set_mode(size)
white = (255, 255, 255)
done = False
# Control fps of window.
clock = pygame.time.Clock()
fps = 40
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
for point in points:
for p in point[3]:
# draw white wherever there's a point.
# pygame windows are black by default
gfxdraw.pixel(screen, point[1], point[2], white)
# controls FPS
clock.tick(fps)
if __name__ == "__main__":
main()
```
Original Example Code:
```
//specify an empty points array
var points = [];
//get a random number in range min, max - 1
function randRange(min, max) {
return Math.floor(Math.random() * ((max) - min) + min);
}
function definePoints(numPoints, mapSize) {
//we want to take a group of points that will fit on our map at random
for(var i = 0; i < numPoints; i++) {
//here's the random points
var x = randRange(0, mapSize);
var y = randRange(0, mapSize);
//type: decides which point it is
//x, y: location
//citizens: the cells in our grid that belong to this point
points.push({type: i, x: x, y: y, citizens: []});
}
//brute force-y but it works
//for each cell in the grid
for(var x = 0; x < mapSize; x++) {
for(var y = 0; y < mapSize; y++) {
//find the nearest point
var lowestDelta = {pointId: 0, delta: mapSize * mapSize};
for(var p = 0; p < points.length; p++) {
//for each point get the difference in distance between our point and the current cell
var delta = Math.abs(points[p].x - x) + Math.abs(points[p].y - y);
//store the point as nearest if it's closer than the last one
if(delta < lowestDelta.delta) {
lowestDelta = {pointId: p, delta: delta};
}
}
//push the cell to the nearest point
var activePoint = points[lowestDelta.pointId];
var dx = x - activePoint.x;
var dy = y - activePoint.y;
//log delta in cell for drawing
activePoint.citizens.push({
dx: dx,
dy: dy
});
}
}
}
definePoints(20, 40);
for(var point of points) {
for(var citizen of point.citizens) {
//set color of cell based on point
//draw cell at (point.x + citizen.dx) * cellSize, (point.y + citizen.dy) * cellSize
}
}
```
|
2018/04/02
|
[
"https://Stackoverflow.com/questions/49604025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7944978/"
] |
This seems a little bit like homework, so lets try to get you on the right track over outright providing the code to accomplish this.
You're going to want to create a loop that performs your code a certain number of times. Let's say we just want to output a certain string 5 times. As an example, here's some really simple code:
```
def testPrint():
print('I am text!')
for i in range(5):
testPrint()
```
This will create a function called testPrint() that prints text "I am Text!", then run that function 5 times in a loop. If you can apply this to the section of code you need to run 5 times, it should solve the problem you are facing.
|
This worked for me. It creates a table using the .messagebox module. You can enter your name into the entry label. Then, when you click the button it returns "Hello (name)".
```
from tkinter import *
from tkinter.messagebox import *
master = Tk()
label1 = Label(master, text = 'Name:', relief = 'groove', width = 19)
entry1 = Entry(master, relief = 'groove', width = 20)
blank1 = Entry(master, relief = 'groove', width = 20)
def show_answer():
a = entry1.get()
b = "Hello",a
blank1.insert(0, b)
button1 = Button(master, text = 'Output Name', relief = 'groove', width = 20, command =show_answer)
#Geometry
label1.grid( row = 1, column = 1, padx = 10 )
entry1.grid( row = 1, column = 2, padx = 10 )
blank1.grid( row = 1, column = 3, padx = 10 )
button1.grid( row = 2, column = 2, columnspan = 2)
#Static Properties
master.title('Hello')
```
| 10,728
|
55,927,009
|
I'm trying to write a script that creates a playlist on my spotify account in python, from scratch and not using a module like *spotipy*.
My question is how do I authenticate with my client id and client secret key using the *requests* module or grab an access token using those credentials?
|
2019/04/30
|
[
"https://Stackoverflow.com/questions/55927009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9128668/"
] |
Try this full Client Credentials Authorization flow.
First step – get an authorization token with your credentials:
```
CLIENT_ID = " < your client id here... > "
CLIENT_SECRET = " < your client secret here... > "
grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}
url='https://accounts.spotify.com/api/token'
response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET))
token_raw = json.loads(response.text)
token = token_raw["access_token"]
```
Second step – make a request to any of the playlists endpoint. Make sure to set a valid value for `<spotify_user>`.
```
headers = {"Authorization": "Bearer {}".format(token)}
r = requests.get(url="https://api.spotify.com/v1/users/<spotify_user>/playlists", headers=headers)
print(r.text)
```
|
As it is referenced [here](https://developer.spotify.com/documentation/web-api/reference/playlists/create-playlist/), you have to give the Bearer token to the Authorization header, and using requests it is done by declaring the "headers" optional:
```py
r = requests.post(url="https://api.spotify.com/v1/users/{your-user}/playlists",
headers={"Authorization": <token>, ...})
```
The details of how can you get the Bearer token of your users can be found [here](https://developer.spotify.com/documentation/general/guides/authorization-guide/)
| 10,729
|
72,230,877
|
So I had created a python web scraper for my college capstone project that scraped around the web and followed links based on a random selection from the page. I utilized Python's request module to return links from a get request. I had it working flawlessly along with a graphing program that showed the program working in real time. I fired it up to show my professor and now the `.links` returns an empty dictionary for every single website.
Originally I had added a skip for any site that returned no links, but now all of them are returning empty. I've reinstalled Python, reinstalled the requests module, and tried feeding the program websites manually and I cannot seem to find a reason for the change.
For reference, I have been using *Portswigger.net* as a baseline to test the `.links` to see if I get them returned. It worked before, and now it does not.
Here is the get request sample:
```
import requests
Url = "https://portswigger.net"
def GetRequest(url):
with requests.get(url=Url) as response:
try:
links = response.links
if links:
return links
else:
return False
except Exception as error:
return error
print(GetRequest(Url))
```
**UPDATE**
So out of the 200 sites I tested this morning, the only one to return links was *kite.com*. It returned the links no problem and my program was able to follow them and collect the data. Literally a week ago the whole program would run fine and return page links from almost every single website.
|
2022/05/13
|
[
"https://Stackoverflow.com/questions/72230877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13450139/"
] |
`Requests.Response.links` doesn't work like that [1]. It looks for [Links in the Header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link), not link elements in the Response body.
What you want is to extract link *elements* from the Response body, so I would recommend something like `lxml` or `beautifulsoup`.
Seeing as this is fairly common and straight forward and this is a school project, I'll leave that task up to the reader.
[1] - <https://docs.python-requests.org/en/latest/api/#requests.Response.links>
|
Parsing links with `beautifulsoup4` is a possible solution:
```py
import requests
from bs4 import BeautifulSoup
def get_links(url: str) -> list[str]:
with requests.get(url) as response:
soup = BeautifulSoup(response.text, features='html.parser')
links = []
for link in soup.find_all('a'):
target = link.get('href')
if target.startswith('http'):
links.append(target)
return links
links = get_links('https://portswigger.com')
print(*links, sep='\n')
# https://forum.portswigger.net/
# https://portswigger.net/web-security
# https://portswigger.net/research
# https://portswigger.net/daily-swig
# ...
```
| 10,730
|
62,556,358
|
Sometimes when I run the code it gives me the correct output, other times it says "List index out of range" and other times it just continues following code. I found the code on: <https://www.codeproject.com/articles/873060/python-search-youtube-for-video>
How can I fix this?
```
searchM = input("Enter the movie you would like to search: ")
def watch_trailer():
query_string = urllib.parse.urlencode({"search_query" : searchM})
html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
print("Click on the link to watch the trailer: ","http://www.youtube.com/watch?v="+search_results[0])
watch_trailer()
```
|
2020/06/24
|
[
"https://Stackoverflow.com/questions/62556358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13757098/"
] |
The error occurs when no 'search results' have been obtained, such that search\_results[0] cannot be found.
I would suggest you use an 'if/else' statement, something like:
```
if len(search_results) == 0:
print("No search results obtained. Please try again.")
else:
print("Click on the link to watch the trailer: ","http://www.youtube.com/watch?v="+search_results[0])
```
|
search[0] will return the first element of the list. However, if there are no elements in the list, there will not be a first element in the list, and "List index out of range". I recommend adding an if statement to check if the length of search\_results is greater than 0 and then printing search[0]. Hope this helps!
```
if len(search_results) > 0:
print(search_results[0])
else:
print("There are no results for this search")
```
| 10,731
|
51,140,417
|
For the past 4 days I have been working to get taskwarrior and taskwarrior server running on windows 10. It has proven quite a challenge for me.
I followed the steps written below: "Building the Stable Version" on <https://taskwarrior.org/docs/build.html> and created a folder:
```
C:\taskwarrior
```
Opened Developer Command Prompt for VC 2017
```
cd /d C:/taskwarrior
git clone https://github.com/GothenburgBitFactory/taskwarrior.git taskwarrior.git
cd taskwarrior.git
git checkout master
```
And then depending on whether I try to build taskwarrior with Sync enabled (automatically unless manually disabled):
```
cmake -DCMAKE_BUILD_TYPE=release .
```
>
> GNUTLS\_library is missing
>
>
>
or:
```
cmake -DCMAKE_BUILD_TYPE=release . -DENABLE_SYNC=OFF
```
>
> -- libuuid not found.
>
>
>
**A short summary of steps followed and attempts so far:**
1. Downloaded and installed Microsoft Visual C++ 2017 Redistributable (x64 and x86) from: <https://visualstudio.microsoft.com/vs/features/cplusplus/>
2. Ensured cl was available as suggested in the documentation of microsoft: <https://msdn.microsoft.com/en-us/library/cyz1h6zd.aspx>
3. Downloaded MinGW installation Manager and installed the base package as was suggested on <http://www.mingw.org/wiki/Getting_Started>:
>
> If you do wish to install mingw-get-inst.exe's obligatory set,
> (including the GNU C Compiler, the GNU Debugger (GDB), and the GNU
> make tool), you should select the mingw-base package for installation.
>
>
>
4. Installing Cmake from <https://cmake.org/download/>
5. Running the commands described above from cmd in administrator mode
6. Opening Cmake selecting the source folder:
`C:/taskwarrior/taskwarrior.git`
With build folder:
```
C:/taskwarrior
```
This gave the exact same errors as when I tried the it through the Developer Command Prompt for VC 2017 described above, from which I conclude that I do not have a typo in my commands described above.
7. Even though it should be installed with Mingw already, GNU is still not found (even after reboot). So I tried downloading it manually from:
8. <http://gnuwin32.sourceforge.net/packages/make.htm>
9. <https://sourceforge.net/projects/gnuwin32/>
10. And I tried the following commands from Command prompt:
`install libgnutlsxx28 gnutls-dev`
`install gnutls-dev`
11. As suggested in the install file in taskwarrior for Debian based distributions, I tried:
`libgnutls-dev`
Which opens the IncrediBuild Version 9.2.1 Setup, I currently do not know what that does.
12. I tried downloading the libuuid library from: <https://sourceforge.net/projects/libuuid/> but I currently do not know how to build and install it.
13. I tried installing it through python in cmd with:
`easy_install python-libuuid`
14. Learning building programs from source code from: <https://msdn.microsoft.com/en-us/library/cyz1h6zd.aspx>
15. Learning and practicing from <https://github.com/codebox/bitmeteros/wiki/How-to-build-on-Windows>.
16. At the end I learned I had [Cygwin](https://cygwin.com/install.html) installed already and that I could simply install an old version of taskwarrior by reinstalling cygwin and checking/marking the task package. So I have the taskwarrior running, but not the taskwarrior server. And moreover I am trying to learn how to build code/projects from source, so I am trying to make a succesfull build to increase my skillset and hence toolset.
17. The explenation to install GNU TLS 3.6.2 on <https://www.gnutls.org/manual/gnutls.html#Downloading-and-installing> is limited to:
>
> The package is then extracted, configured and built like many other packages that use Autoconf. For detailed information on configuring and building it, refer to the INSTALL file that is part of the distribution archive. Typically you invoke ./configure and then make check install.
>
>
>
However, the latest GNUTLS for Windows x64 download file: Latest w64 version on gitlab on: <https://www.gnutls.org/download.html> named artifacts.zip contains no file named `INSTALL`.
So I am currently working on understanding how to configure and built using autoconf.
**Question:**
*Do you know how I could install the GNU library and/or libuuid library on windows 10?*
|
2018/07/02
|
[
"https://Stackoverflow.com/questions/51140417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7437143/"
] |
I'm not sure that it is still relevant to your problem, but I was able to build taskwarrior v2.5.1 under 64-bit cygwin (on Win7), using the `cmake` line from here: [TW-1845 Cygwin build fails, missing get\_current\_dir\_name](https://github.com/GothenburgBitFactory/taskwarrior/issues/1861)
Namely, this `cmake` line followed by `make`:
```
cmake -DHAVE_GET_CURRENT_DIR_NAME=0
```
|
I am likely to have misunderstood the context. GnuTLS Appears to be a program that works/is made for a linux/debian operating system.
Nevertheless, the following two solutions were effective in:
1. Finding and using the UUID library in Windows.
2. Solving the XY-problem and using GnuTLS on a "windows pc" (with Linux on it).:
For the missing UUID missing library error:
1. Open explorer>go to C: (or other system disc)>search for: `uuid.lib`>Memorize the path to the/any `uuid.lib` file. (For me `C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib worked`)
2. Open Cmake and in UUID\_LIBRARY\_DIR enter:
3. `C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib`
4. Then in UUID\_LIBRARY enter:
`C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib/Uuid.Lib`
Where you substitute `C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib` with the path you found yourself for your own UUID.lib at step 1.
That made CMake overcome the UUID error in windows.
Now for the GnuTLS I could not find a solution in windows itself.
But when I read the taskserver installation guide on: <https://gitpitch.com/GothenburgBitFactory/taskserver-setup#/4/4>
I learned that Taskwarrior is not intended to run on Windows itself/natively, but in a linux environment (To be specific, the linux distribution Ubuntu is recommended to be installed on windows as is specified here: <https://taskwarrior.org/download/>) it takes 1 click to completely download and install the linux distribution (which currently looks like an emulator to me).
In the windows store one can download Ubuntu and other Linux distributions as Debian GNU/Linux: <https://learn.microsoft.com/en-us/windows/wsl/install-win10>. Since I had quite a bit of difficulties installing GnuTLS I tried the debian GNU/Linux distribution, hoping it would be pre-installed in the distribution. The following commands successfully installed taskwarrior and GnuTLS and Taskserver on the debian GNU/Linux:
1. `sudo apt-get update`
2. `sudo apt-get install taskwarrior`
3. `cd /home/a/`
4. then create new directory 'taskwarrior'
5. `mkdir taskwarrior`
6. `cd /home/a/taskwarrior`
Task Server installation in Debian:
7. `sudo apt install g++`
8. `sudo apt install libgnutls28-dev`
9. `sudo apt install uuid-dev`
10. `sudo apt install cmake`
11. `**sudo apt install gnutls-utils**`
gnutls failed so:
12. `**sudo apt-get update**`
13. `**sudo apt install gnutls-utils**`
14. `sudo apt-get update`
15. `sudo apt-get install git-core`
Source: <https://gitpitch.com/GothenburgBitFactory/taskserver-setup#/6/1> suggests you enter:
`git clone --recurse-submodules=yes https://github.com/GothenburgBitFactory/taskserver.git taskserver.git` that gave the following error: `option`recurse-submodules`takes no value`, so rewrite it to:
16. `git clone https://github.com/GothenburgBitFactory/taskserver.git taskserver.git`
17. `cd taskserver.git/`
18. `git checkout master`
19. `cmake -DCMAKE_BUILD_TYPE=release .`
20. `make`
Now you can test the build as described in: <https://gitpitch.com/GothenburgBitFactory/taskserver-setup#/6/8>
Note: the SOURCEDIR now is home/a/taskwarrior/taskserver.git (/test I currently do not know whether /test is a subfolder of the source or the actual source directory)
21. `sudo make install`
Note: You can Verify GnuTLS installation with:
22. `task diagnostics | grep libgnutls`
23. `sudo apt install taskd`
**Remaining unanswered**
The above only answers half of my question (and solves the [XY-problem](https://en.wikipedia.org/wiki/XY_problem)). The installation of GnuTLS on windows itself is still not solved. I currently am unsure about the download
>
> GNU for windows
>
>
> Latest w64 version on gitlab gnutls\_3\_6\_0\_1:mingw64
>
>
>
on <https://gnutls.org/download.html>.
1. It contains a lib and a bin folder, which seems to indicate that even the files listed under "windows" are intended for a Linux Operating System(OS) (since I think those type of folders are not used conventionally used in windows/I do not know what to do with them/how to install them).
2. That would imply that GnuTLS assumes that the only application of
GnuTLS, even on a Windows operating system happens in a Linux
system. It could also just be my lack of
knowledge/work/understanding in how to use/install those files in
windows.
So if anyone can still answer how GnuTLS on windows is intended to be applied, I would greatly appreciate the insight!
| 10,732
|
33,355,299
|
I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists.
I have:
```
my_list = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ]
```
I want:
```
my_list = [ [1,2,3,4,5], [9,8,9,10,3,4,6], [1] ]
```
The solution should work for a list of floats as well. Any suggestions?
|
2015/10/26
|
[
"https://Stackoverflow.com/questions/33355299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2483176/"
] |
If we apply the logic from [this answer](https://stackoverflow.com/a/952952/771848), should not it be just:
```
In [2]: [[item for subsublist in sublist for item in subsublist] for sublist in my_list]
Out[2]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
```
And, similarly via [`itertools.chain()`](https://stackoverflow.com/a/953097/771848):
```
In [3]: [list(itertools.chain(*sublist)) for sublist in my_list]
Out[3]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
```
|
You could use this recursive subroutine
```
def flatten(lst, n):
if n == 0:
return lst
return flatten([j for i in lst for j in i], n - 1)
mylist = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ]
flatten(mylist, 1)
#=> [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]]
flatten(mylist, 2)
#=> [1, 2, 3, 4, 5, 9, 8, 9, 10, 3, 4, 6, 1]
```
| 10,733
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.