qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
53,480,409
I have installed the bloomberg Python API and set the `BLPAPI_ROOT` to the VC++ folder. However, when I import `blpapi`, I got the following error. How to get rid of these errors? Thank you very much. ``` import blpapi Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\internals.py", line 39, in swig_import_helper return importlib.import_module(mname) File "C:\Program Files\WinPython-64bit-3.6.2.0Qt5\python-3.6.2.amd64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 648, in _load_unlocked File "<frozen importlib._bootstrap>", line 560, in module_from_spec File "<frozen importlib._bootstrap_external>", line 922, in create_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed ImportError: DLL load failed: The specified procedure could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\__init__.py", line 4, in <module> from .internals import CorrelationId File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\internals.py", line 42, in <module> _internals = swig_import_helper() File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\internals.py", line 41, in swig_import_helper return importlib.import_module('_internals') File "C:\Program Files\WinPython-64bit-3.6.2.0Qt5\python-3.6.2.amd64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named '_internals' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\__init__.py", line 9, in <module> raise debug_load_error(error) ImportError: No module named '_versionhelper' Could not open the C++ SDK library. Download and install the latest C++ SDK from: http://www.bloomberg.com/professional/api-library If the C++ SDK is already installed, please ensure that the path to the library was added to PATH before entering the interpreter. ```
2018/11/26
[ "https://Stackoverflow.com/questions/53480409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9087866/" ]
I did 2 things to solve an issue similar to that: 1- I installed Microsoft Visual Studio with the following components * C++/CLI Support * VC++ 2015.3 v14.00 (v140) toolset for desktop * Visual C++ MFC for x86 and x64 * Visual C++ ATL for x86 and x64 2- I manually copied the .dll files in C++API\lib (blpapi3\_32.dll and blpapi3\_64.dll in my case) into C:\windows\system32 where all the dll files that system uses. Also, I copied the dll files in in C++API\lib into C:\blp\DAPI, replacing the new ones with the old ones.
Please set BLPAPI\_ROOT environment variable to the location where the blpapi C++ SDK is located.
53,480,409
I have installed the bloomberg Python API and set the `BLPAPI_ROOT` to the VC++ folder. However, when I import `blpapi`, I got the following error. How to get rid of these errors? Thank you very much. ``` import blpapi Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\internals.py", line 39, in swig_import_helper return importlib.import_module(mname) File "C:\Program Files\WinPython-64bit-3.6.2.0Qt5\python-3.6.2.amd64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 648, in _load_unlocked File "<frozen importlib._bootstrap>", line 560, in module_from_spec File "<frozen importlib._bootstrap_external>", line 922, in create_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed ImportError: DLL load failed: The specified procedure could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\__init__.py", line 4, in <module> from .internals import CorrelationId File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\internals.py", line 42, in <module> _internals = swig_import_helper() File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\internals.py", line 41, in swig_import_helper return importlib.import_module('_internals') File "C:\Program Files\WinPython-64bit-3.6.2.0Qt5\python-3.6.2.amd64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named '_internals' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\user\AppData\Roaming\Python\Python36\site-packages\blpapi\__init__.py", line 9, in <module> raise debug_load_error(error) ImportError: No module named '_versionhelper' Could not open the C++ SDK library. Download and install the latest C++ SDK from: http://www.bloomberg.com/professional/api-library If the C++ SDK is already installed, please ensure that the path to the library was added to PATH before entering the interpreter. ```
2018/11/26
[ "https://Stackoverflow.com/questions/53480409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9087866/" ]
I did 2 things to solve an issue similar to that: 1- I installed Microsoft Visual Studio with the following components * C++/CLI Support * VC++ 2015.3 v14.00 (v140) toolset for desktop * Visual C++ MFC for x86 and x64 * Visual C++ ATL for x86 and x64 2- I manually copied the .dll files in C++API\lib (blpapi3\_32.dll and blpapi3\_64.dll in my case) into C:\windows\system32 where all the dll files that system uses. Also, I copied the dll files in in C++API\lib into C:\blp\DAPI, replacing the new ones with the old ones.
An alternative option is to use `conda`, as discussed [here](https://stackoverflow.com/questions/43322486/conda-install-blpapi) and [here](https://stackoverflow.com/questions/41725483/anaconda-install-blpapi-in-environment). If you use `conda` you don't need to worry about downloading the C++ SDK and properly configuring the `BLPAPI_ROOT`. From the `conda-forge` channel this can be done using `conda install -c conda-forge blpapi`
1,440,233
I want to intercept and transform some automated emails into a more readable format. I believe this is possible using VBA, but I would prefer to manipulate the text with Python. Can I create an ironpython client-side script to pre-process certain emails? EDIT: I believe this can be done with outlook rules. In Outlook 2007, you can do: Tools->Rules -> New Rule "check messages when they arrive" next [filter which emails to process] next "run a script" In the "run a script" it allows you to use a VBA script.
2009/09/17
[ "https://Stackoverflow.com/questions/1440233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20712/" ]
I can only offer you a pointer. Years ago, I used a Bayesian spam filter with Outlook. It was written in Python, and provided an Outlook plug-in that would filter incoming mail. The name of the software was [*SpamBayes*](http://spambayes.sourceforge.net/), and the project is still online. As it is open source, you will probably find all necessary information how to plug a mail filter into Outlook. This should give you enough background to add code that will actually be able to transform mail content. My understanding was it was written in vanilla Python (CPython), but if you are more comfortable with IronPython, it shouldn't be hard to translate. Give it a go.
There is an answer here: [how to trigger a python script in outlook using rules?](https://stackoverflow.com/questions/13265861/how-to-trigger-a-python-script-in-outlook-using-rules) that may help you. You can make a simple VBA script to trigger the python script.
1,440,233
I want to intercept and transform some automated emails into a more readable format. I believe this is possible using VBA, but I would prefer to manipulate the text with Python. Can I create an ironpython client-side script to pre-process certain emails? EDIT: I believe this can be done with outlook rules. In Outlook 2007, you can do: Tools->Rules -> New Rule "check messages when they arrive" next [filter which emails to process] next "run a script" In the "run a script" it allows you to use a VBA script.
2009/09/17
[ "https://Stackoverflow.com/questions/1440233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20712/" ]
You can reference the outlook object model here: <http://msdn.microsoft.com/en-us/library/ms268893.aspx> Connect to outlook through COM, you'll need [pywin32](http://sourceforge.net/projects/pywin32/). There's no python reference that I know of, but you can reference the sample scripts and 'translate' to python. It's difficult at first, but once you understand the objects and their usage in python it's not hard. Looks like you want to look at: [How to: Perform Actions When an E-Mail Message Is Received](http://msdn.microsoft.com/en-us/library/ms268998.aspx)
There is an answer here: [how to trigger a python script in outlook using rules?](https://stackoverflow.com/questions/13265861/how-to-trigger-a-python-script-in-outlook-using-rules) that may help you. You can make a simple VBA script to trigger the python script.
1,440,233
I want to intercept and transform some automated emails into a more readable format. I believe this is possible using VBA, but I would prefer to manipulate the text with Python. Can I create an ironpython client-side script to pre-process certain emails? EDIT: I believe this can be done with outlook rules. In Outlook 2007, you can do: Tools->Rules -> New Rule "check messages when they arrive" next [filter which emails to process] next "run a script" In the "run a script" it allows you to use a VBA script.
2009/09/17
[ "https://Stackoverflow.com/questions/1440233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20712/" ]
This is a work in progress, but I've figured out part of the answer with the help of the other posts. Here are the instructions for re-writing specified emails by running a script. I'm using Outlook 2007. 1. Download and install [pywin32](http://sourceforge.net/projects/pywin32/) 2. Download and install [ExchangeCdo.exe](http://support.microsoft.com/kb/945835) 3. Put this code in a file and run it from `cmd`: ``` import os, sys, re import win32com.client session = win32com.client.gencache.EnsureDispatch("MAPI.session") win32com.client.gencache.EnsureDispatch("Outlook.Application") outlook = win32com.client.Dispatch("Outlook.Application") #print '\n'.join(dir(outlook)) mapi = outlook.GetNamespace('MAPI') inbox = mapi.GetDefaultFolder(win32com.client.constants.olFolderInbox) items = inbox.Items #items.Restrict("[Unread] = true") #print '\n'.join(dir(items)) while True: item = items.GetNext() if item == None: break #print '\n'.join(dir(item)) if re.compile(r'crazy email').search(item.Subject): print item.Subject print item.Body # works VVVV item.Body = 'whoya!' item.Save() break ```
There is an answer here: [how to trigger a python script in outlook using rules?](https://stackoverflow.com/questions/13265861/how-to-trigger-a-python-script-in-outlook-using-rules) that may help you. You can make a simple VBA script to trigger the python script.
63,896,043
I am creating my first django app in django 3.1.1. There are video tutorials for old django versions and they don't always work... I want to create HTML pages for both home and about sections. I have already written some HTML files, but the ``` def home(request): return render(request, 'home.html') ``` doesn't want to work. I add my file tree for you to see the structure of files. ``` RemoveBigFile β”œβ”€β”€ RBF1module β”‚Β Β  β”œβ”€β”€ __init__.py β”‚Β Β  β”œβ”€β”€ admin.py β”‚Β Β  β”œβ”€β”€ apps.py β”‚Β Β  β”œβ”€β”€ migrations β”‚Β Β  β”‚Β Β  └── __init__.py β”‚Β Β  β”œβ”€β”€ models.py β”‚Β Β  β”œβ”€β”€ tests.py β”‚Β Β  └── views.py β”œβ”€β”€ RemoveBigFile β”‚Β Β  β”œβ”€β”€ __init__.py β”‚Β Β  β”œβ”€β”€ __pycache__ β”‚Β Β  β”‚Β Β  β”œβ”€β”€ __init__.cpython-38.pyc β”‚Β Β  β”‚Β Β  β”œβ”€β”€ settings.cpython-38.pyc β”‚Β Β  β”‚Β Β  β”œβ”€β”€ urls.cpython-38.pyc β”‚Β Β  β”‚Β Β  β”œβ”€β”€ views.cpython-38.pyc β”‚Β Β  β”‚Β Β  └── wsgi.cpython-38.pyc β”‚Β Β  β”œβ”€β”€ asgi.py β”‚Β Β  β”œβ”€β”€ settings.py β”‚Β Β  β”œβ”€β”€ urls.py β”‚Β Β  β”œβ”€β”€ views.py β”‚Β Β  └── wsgi.py β”œβ”€β”€ RemoveBigFile.sublime-project β”œβ”€β”€ RemoveBigFile.sublime-workspace β”œβ”€β”€ db.sqlite3 β”œβ”€β”€ manage.py └── templates β”œβ”€β”€ about.html └── home.html ``` And that is the error message I get: ``` TemplateDoesNotExist at / home.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.1 Exception Type: TemplateDoesNotExist Exception Value: home.html ``` Django also asks me to put my templates in one of main django installation directories called templates and as far as I know, if I do so, I won't be able to send my app to other people (and that's what I intend to do with it after I am finished). I use my RemoveBigFile/RemoveBigFile views.py to point django to HTML templates. EDIT: as requested, I add my templates definition from settings.py ``` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` As I see, there is nothing in DIRS. Should I put the path to my templates in DIRS parentheses? I also have one more question - is it better to have templates in the folder where manage.py is or where settings.py is?
2020/09/15
[ "https://Stackoverflow.com/questions/63896043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14224948/" ]
Alright, found it myself with your inspiration :) Thank you, @Selcuk and @m.arthur. Thanks for contributing @Mahmoud Ishag too :) The answer lies in there I mustn't have created this app as a project and there was a short string missing in templates: ``` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` namely this one: ``` 'DIRS': [BASE_DIR / 'templates'] ``` Please compare my code from main post to this one.
Django look for the template in folder called `templates` you need to create that folder inside your app folder and put `home.html` inside it.
43,413,914
I recently found out that scrapy is a great library for scraping so i tried to install scrapy on my machine, but when i tried to do `pip install scrapy` it installed for a while and threw me this error.. ``` error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools ``` and ``` error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools ---------------------------------------- Command "d:\pycharmprojects\environments\scrapyenv\scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\User\\AppData\\Local\\Temp\\pip-build-arbeqlly\\Twisted\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\User\AppData\Local\Temp\pip-jdj93131-record\install-record.txt --single-version-externally-managed --compile --install-headers d:\pycharmprojects\environments\scrapyenv\include\site\python3.5\Twisted" failed with error code 1 in C:\Users\User\AppData\Local\Temp\pip-build-arbeqlly\Twisted\ ``` So after that I went to [this](https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2017) website and installed the tools for python.. but getting this at the end of installing: ``` warning: no previously-included files matching '*.misc' found under directory 'src\twisted' warning: no previously-included files matching '*.bugfix' found under directory 'src\twisted' warning: no previously-included files matching '*.doc' found under directory 'src\twisted' warning: no previously-included files matching '*.feature' found under directory 'src\twisted' warning: no previously-included files matching '*.removal' found under directory 'src\twisted' warning: no previously-included files matching 'NEWS' found under directory 'src\twisted' warning: no previously-included files matching 'README' found under directory 'src\twisted' warning: no previously-included files matching 'topfiles' found under directory 'src\twisted' warning: no previously-included files found matching 'src\twisted\topfiles\CREDITS' warning: no previously-included files found matching 'src\twisted\topfiles\ChangeLog.Old' warning: no previously-included files found matching 'codecov.yml' warning: no previously-included files found matching 'appveyor.yml' no previously-included directories found matching 'bin' no previously-included directories found matching 'admin' no previously-included directories found matching '.travis' warning: no previously-included files found matching 'docs\historic\2003' warning: no previously-included files matching '*' found under directory 'docs\historic\2003' error: Setup script exited with error: [WinError 3] The system cannot find the path specified: 'C:\\Program Files\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.10.25017\\PlatformSDK\\lib' ``` any help?
2017/04/14
[ "https://Stackoverflow.com/questions/43413914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
Scrapy docs now recommend using [Conda](https://conda.io/miniconda) for Windows installation: <https://doc.scrapy.org/en/latest/intro/install.html#windows>
This error comes up when you don't have Windows SDK installed. When you used Build Tools or Visual Studio to compile, often you need both the C++ compiler and Windows SDK. In the Build Tools, there is a "Custom" installation option which enables you to select to install both C++ and Windows SDK. In Visual Studio, you have to modify your installation to install Windows SDK. I *believe* you need the SDK corresponding to the the platform you are using (Windows 10 SDK for Windows 10, etc).
43,989,929
I'm trying to use `pytesseract` for the first time. I'm also not so confortable with python. I've created a new folder called `python_test` on my desktop. I'm on Mac. In this folder I have a `test.png` file and a py script : ``` from pytesseract import image_to_string from PIL import Image print image_to_string(Image.open('test.png')) print image_to_string(Image.open('test-english.jpg'), lang='eng') ``` So from my terminal, I'm going into the python\_test folder then I'm running `python read.py` then I have the following error : ``` Traceback (most recent call last): File "read.py", line 4, in <module> print image_to_string(Image.open('test.png')) File "/anaconda/anaconda/lib/python2.7/site-packages/pytesseract/pytesseract.py", line 161, in image_to_string config=config) File "/anaconda/anaconda/lib/python2.7/site-packages/pytesseract/pytesseract.py", line 94, in run_tesseract stderr=subprocess.PIPE) File "/anaconda/anaconda/lib/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/anaconda/anaconda/lib/python2.7/subprocess.py", line 1343, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory ``` What I'am doing wrong ?
2017/05/15
[ "https://Stackoverflow.com/questions/43989929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6273496/" ]
I got the same error as you, installing the `tesseract` package fixed it (or `tesseract-ocr` on debian/ubuntu). It contains the native code library used under the hood by `pytesseract`. An image load error seems like an odd way for the library to fail if the underlying native library is not installed, but there you go. To install use commands (insert sudo as appropriate) macos ``` brew install tesseract ``` ubuntu ``` apt install tesseract-ocr ```
I also had the error when I used first time `image_to_string`. You have to change the the following line in the `pytesseract.py` file. ``` tesseract_cmd = 'C:\\Tesseract-OCR\\tesseract' ``` *Note: I'm using windows.*
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
Michael Kaplan has series of blog posts about the `cmd` console and Unicode that may be informative (while not really answering your question): * [Conventional wisdom is retarded, aka What the @#%&\* is \_O\_U16TEXT?](https://web.archive.org/web/20130101094000/http://www.siao2.com/2008/03/18/8306597.aspx) * [Anyone who says the console can't do Unicode isn't as smart as they think they are](https://web.archive.org/web/20130519074717/http://www.siao2.com/2010/04/07/9989346.aspx) * [A confluence of circumstances leaves a stone unturned...](https://web.archive.org/web/20130620152913/http://www.siao2.com/2010/09/23/10066660.aspx) PS: Thanks [@Jeff](https://stackoverflow.com/users/604049/jeff) for finding the archive.org links.
Are you sure your script would output Unicode on some other platform correctly? "wide character in print" warning makes me very suspicious. I recommend to look over this [overview](http://en.wikibooks.org/wiki/Perl_Programming/Unicode_UTF-8)
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
I have to unask many of your questions. Did you know that * Windows uses UTF-16 for its APIs, but still defaults to the various "fun" legacy encodings (e.g. Windows-1252, Windows-1251) in userspace, including file names, differently for the many localisations of Windows? * you need to encode output, and picking the appropriate encoding for the system is achieved by the [locale pragma](http://p3rl.org/locale), and that there is the a POSIX standard called [locale](http://en.wikipedia.org/wiki/Locale) on which this is built, and Windows is incompatible with it? * [Perl already supported](https://stackoverflow.com/q/2796127) the so-called "wide" APIs once? * Microsoft managed to adapt UTF-8 into their codepage system of character encoding, and you can switch your terminal by issuing the appropriate `chcp 65001` command?
[Unicode issues in Perl](http://www.i-programmer.info/programming/other-languages/1973-unicode-issues-in-perl.html) covers how the Win32 console works with Perl and the transcoding that happens behind the scene from ANSI to Unicode;albeit not just a Perl issue but affects other languages
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
Michael Kaplan has series of blog posts about the `cmd` console and Unicode that may be informative (while not really answering your question): * [Conventional wisdom is retarded, aka What the @#%&\* is \_O\_U16TEXT?](https://web.archive.org/web/20130101094000/http://www.siao2.com/2008/03/18/8306597.aspx) * [Anyone who says the console can't do Unicode isn't as smart as they think they are](https://web.archive.org/web/20130519074717/http://www.siao2.com/2010/04/07/9989346.aspx) * [A confluence of circumstances leaves a stone unturned...](https://web.archive.org/web/20130620152913/http://www.siao2.com/2010/09/23/10066660.aspx) PS: Thanks [@Jeff](https://stackoverflow.com/users/604049/jeff) for finding the archive.org links.
For Perl to fully support Windows in this way, every call to `print` `printf` `say` `warn` and `die` has to be modified. * Is this Windows? * Which version of Windows? Perl still mostly works on Windows 95 * Is this going to the console, or somewhere else. Once you have that determined, you then have to use a completely different set of API functions. If you really want to see everything involved in doing this properly, have a look at the [source](http://cpansearch.perl.org/src/XAICRON/Win32-Unicode-0.25/lib/Win32/Unicode/Console.pm) of [Win32::Unicode::Console](http://search.cpan.org/perldoc/Win32%3a%3aUnicode%3a%3aConsole). --- On Linux, OpenBSD, FreeBSD and similar OS's you can usually just call [`binmode`](http://perldoc.perl.org/functions/binmode.html) on the `STDOUT` and `STDERR` file handles. ``` binmode STDOUT, ':utf8'; binmode STDERR, ':utf8'; ``` This assumes that the terminal is using the UTF-8 encoding.
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
Michael Kaplan has series of blog posts about the `cmd` console and Unicode that may be informative (while not really answering your question): * [Conventional wisdom is retarded, aka What the @#%&\* is \_O\_U16TEXT?](https://web.archive.org/web/20130101094000/http://www.siao2.com/2008/03/18/8306597.aspx) * [Anyone who says the console can't do Unicode isn't as smart as they think they are](https://web.archive.org/web/20130519074717/http://www.siao2.com/2010/04/07/9989346.aspx) * [A confluence of circumstances leaves a stone unturned...](https://web.archive.org/web/20130620152913/http://www.siao2.com/2010/09/23/10066660.aspx) PS: Thanks [@Jeff](https://stackoverflow.com/users/604049/jeff) for finding the archive.org links.
> > Why on earth after all these years do > they not just simply call the Win32 -W > APIs that output UTF-16 Unicode > instead of forcing everything through > the ANSI/codepage bottleneck? > > > Because Perl and Python aren't Windows programs. They're Unix programs that happen to have been mostly ported to Windows. As such, they don't like to call Win32 functions unless necessary. For byte-based I/O, it's not necessary; this can be done with the Standard C Libary. UTF-16-based I/O is a special case. > > Or are the -W APIs inherently broken > to such a degree that they can't be > used as-is? > > > I wouldn't say that the -W APIs are inherently broken as much as I'd say that Microsoft's approach to Unicode in C(++) is inherently broken. No matter how much certain Windows developers insist that programs should use `wchar_t` instead of `char`, there are just too many barriers to switching: * Platform dependence: + The use of UTF-16 `wchar_t` on Windows and UTF-32 `wchar_t` elsewhere. (The new `char16_t` and `char32_t` types may help.) + The non-standardness of UTF-16 filename functions like `_wfopen`, `_wstat`, etc. limits the ability to use `wchar_t` in cross-platform code. * Education. Everbody learns C with `printf("Hello, world!\n");`, not `wprintf(L"Hello, world!\n");`. The C textbook I used in college never even mentioned wide characters until Appendix A.13. * The existing zillions of lines of code that use `char*` strings.
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
The main problem seems to be that it is not possible to use Unicode on Windows using only the standard C library and no platform-dependent or third-party extensions. The languages you mentioned originate from Unix platforms, whose method of implementing Unicode blends well with C (they use normal `char*` strings, the C locale functions, and UTF-8). If you want to do Unicode in C, you more or less have to write everything twice: once using nonstandard Microsoft extensions, and once using the standard C API functions for all other operating systems. While this can be done, it usually doesn't have high priority because it's cumbersome and most scripting language developers either hate or ignore Windows anyway. At a more technical level, I think the basic assumption that most standard library designers make is that all I/O streams are inherently byte-based on the OS level, which is true for files on all operating systems, and for all streams on Unix-like systems, with the Windows console being the only exception. Thus the architecture many class libraries and programming language standard have to be modified to a great extent if one wants to incorporate Windows console I/O. Another more subjective point is that Microsoft just did not enough to promote the use of Unicode. The first Windows OS with decent (for its time) Unicode support was Windows NT 3.1, released in 1993, long before Linux and OS X grew Unicode support. Still, the transition to Unicode in those OSes has been much more seamless and unproblematic. Microsoft once again listened to the sales people instead of the engineers, and kept the technically obsolete Windows 9x around until 2001; instead of forcing developers to use a clean Unicode interface, they still ship the broken and now-unnecessary 8-bit API interface, and invite programmers to use it (look at a few of the recent Windows API questions on Stack Overflow, most newbies *still* use the horrible legacy API!). When Unicode came out, many people realized it was useful. Unicode started as a pure 16-bit encoding, so it was natural to use 16-bit code units. Microsoft then apparently said "OK, we have this 16-bit encoding, so we have to create a 16-bit API", not realizing that nobody would use it. The Unix luminaries, however, thought "how can we integrate this into the current system in an efficient and backward-compatible way so that people will actually use it?" and subsequently invented UTF-8, which is a brilliant piece of engineering. Just as when Unix was created, the Unix people thought a bit more, needed a bit longer, has less financially success, but did it eventually right. I cannot comment on Perl (but I think that there are more Windows haters in the Perl community than in the Python community), but regarding Python I know that the BDFL (who doesn't like Windows as well) has stated that adequate Unicode support on all platforms is a major goal.
Small contribution to the discussion - I am running Czech localized Windows XP, which almost everywhere uses CP1250 code page. Funny thing with console is though that it still uses legacy DOS 852 code page. I was able to make very simple perl script that prints utf8 encoded data to console using: ``` binmode STDOUT, ":utf8:encoding(cp852)"; ``` Tried various options (including utf16le), but only above settings printed accented Czech characters correctly. **Edit:** I played a little more with the problem and found [Win32::Unicode](http://search.cpan.org/perldoc?Win32%3a%3aUnicode). The module exports function `printW` that works properly both in output and redirected: ``` use utf8; use Win32::Unicode; binmode STDOUT, ":utf8"; printW "PΕ™Γ­liΕ‘ ΕΎluΕ₯oučkΓ½ kůň ΓΊpΔ›l ďÑbelskΓ© Γ³dy"; ```
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
Are you sure your script would output Unicode on some other platform correctly? "wide character in print" warning makes me very suspicious. I recommend to look over this [overview](http://en.wikibooks.org/wiki/Perl_Programming/Unicode_UTF-8)
[Unicode issues in Perl](http://www.i-programmer.info/programming/other-languages/1973-unicode-issues-in-perl.html) covers how the Win32 console works with Perl and the transcoding that happens behind the scene from ANSI to Unicode;albeit not just a Perl issue but affects other languages
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
> > Why on earth after all these years do > they not just simply call the Win32 -W > APIs that output UTF-16 Unicode > instead of forcing everything through > the ANSI/codepage bottleneck? > > > Because Perl and Python aren't Windows programs. They're Unix programs that happen to have been mostly ported to Windows. As such, they don't like to call Win32 functions unless necessary. For byte-based I/O, it's not necessary; this can be done with the Standard C Libary. UTF-16-based I/O is a special case. > > Or are the -W APIs inherently broken > to such a degree that they can't be > used as-is? > > > I wouldn't say that the -W APIs are inherently broken as much as I'd say that Microsoft's approach to Unicode in C(++) is inherently broken. No matter how much certain Windows developers insist that programs should use `wchar_t` instead of `char`, there are just too many barriers to switching: * Platform dependence: + The use of UTF-16 `wchar_t` on Windows and UTF-32 `wchar_t` elsewhere. (The new `char16_t` and `char32_t` types may help.) + The non-standardness of UTF-16 filename functions like `_wfopen`, `_wstat`, etc. limits the ability to use `wchar_t` in cross-platform code. * Education. Everbody learns C with `printf("Hello, world!\n");`, not `wprintf(L"Hello, world!\n");`. The C textbook I used in college never even mentioned wide characters until Appendix A.13. * The existing zillions of lines of code that use `char*` strings.
[Unicode issues in Perl](http://www.i-programmer.info/programming/other-languages/1973-unicode-issues-in-perl.html) covers how the Win32 console works with Perl and the transcoding that happens behind the scene from ANSI to Unicode;albeit not just a Perl issue but affects other languages
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
The main problem seems to be that it is not possible to use Unicode on Windows using only the standard C library and no platform-dependent or third-party extensions. The languages you mentioned originate from Unix platforms, whose method of implementing Unicode blends well with C (they use normal `char*` strings, the C locale functions, and UTF-8). If you want to do Unicode in C, you more or less have to write everything twice: once using nonstandard Microsoft extensions, and once using the standard C API functions for all other operating systems. While this can be done, it usually doesn't have high priority because it's cumbersome and most scripting language developers either hate or ignore Windows anyway. At a more technical level, I think the basic assumption that most standard library designers make is that all I/O streams are inherently byte-based on the OS level, which is true for files on all operating systems, and for all streams on Unix-like systems, with the Windows console being the only exception. Thus the architecture many class libraries and programming language standard have to be modified to a great extent if one wants to incorporate Windows console I/O. Another more subjective point is that Microsoft just did not enough to promote the use of Unicode. The first Windows OS with decent (for its time) Unicode support was Windows NT 3.1, released in 1993, long before Linux and OS X grew Unicode support. Still, the transition to Unicode in those OSes has been much more seamless and unproblematic. Microsoft once again listened to the sales people instead of the engineers, and kept the technically obsolete Windows 9x around until 2001; instead of forcing developers to use a clean Unicode interface, they still ship the broken and now-unnecessary 8-bit API interface, and invite programmers to use it (look at a few of the recent Windows API questions on Stack Overflow, most newbies *still* use the horrible legacy API!). When Unicode came out, many people realized it was useful. Unicode started as a pure 16-bit encoding, so it was natural to use 16-bit code units. Microsoft then apparently said "OK, we have this 16-bit encoding, so we have to create a 16-bit API", not realizing that nobody would use it. The Unix luminaries, however, thought "how can we integrate this into the current system in an efficient and backward-compatible way so that people will actually use it?" and subsequently invented UTF-8, which is a brilliant piece of engineering. Just as when Unix was created, the Unix people thought a bit more, needed a bit longer, has less financially success, but did it eventually right. I cannot comment on Perl (but I think that there are more Windows haters in the Perl community than in the Python community), but regarding Python I know that the BDFL (who doesn't like Windows as well) has stated that adequate Unicode support on all platforms is a major goal.
For Python, the relevant issue in tracker is <http://bugs.python.org/issue1602> (as said in comments). Note that it is open for 7 years. I tried to publish a working solution (based on information in the issue) as a Python package: <https://github.com/Drekin/win-unicode-console>, <https://pypi.python.org/pypi/win_unicode_console>.
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
The main problem seems to be that it is not possible to use Unicode on Windows using only the standard C library and no platform-dependent or third-party extensions. The languages you mentioned originate from Unix platforms, whose method of implementing Unicode blends well with C (they use normal `char*` strings, the C locale functions, and UTF-8). If you want to do Unicode in C, you more or less have to write everything twice: once using nonstandard Microsoft extensions, and once using the standard C API functions for all other operating systems. While this can be done, it usually doesn't have high priority because it's cumbersome and most scripting language developers either hate or ignore Windows anyway. At a more technical level, I think the basic assumption that most standard library designers make is that all I/O streams are inherently byte-based on the OS level, which is true for files on all operating systems, and for all streams on Unix-like systems, with the Windows console being the only exception. Thus the architecture many class libraries and programming language standard have to be modified to a great extent if one wants to incorporate Windows console I/O. Another more subjective point is that Microsoft just did not enough to promote the use of Unicode. The first Windows OS with decent (for its time) Unicode support was Windows NT 3.1, released in 1993, long before Linux and OS X grew Unicode support. Still, the transition to Unicode in those OSes has been much more seamless and unproblematic. Microsoft once again listened to the sales people instead of the engineers, and kept the technically obsolete Windows 9x around until 2001; instead of forcing developers to use a clean Unicode interface, they still ship the broken and now-unnecessary 8-bit API interface, and invite programmers to use it (look at a few of the recent Windows API questions on Stack Overflow, most newbies *still* use the horrible legacy API!). When Unicode came out, many people realized it was useful. Unicode started as a pure 16-bit encoding, so it was natural to use 16-bit code units. Microsoft then apparently said "OK, we have this 16-bit encoding, so we have to create a 16-bit API", not realizing that nobody would use it. The Unix luminaries, however, thought "how can we integrate this into the current system in an efficient and backward-compatible way so that people will actually use it?" and subsequently invented UTF-8, which is a brilliant piece of engineering. Just as when Unix was created, the Unix people thought a bit more, needed a bit longer, has less financially success, but did it eventually right. I cannot comment on Perl (but I think that there are more Windows haters in the Perl community than in the Python community), but regarding Python I know that the BDFL (who doesn't like Windows as well) has stated that adequate Unicode support on all platforms is a major goal.
> > Why on earth after all these years do > they not just simply call the Win32 -W > APIs that output UTF-16 Unicode > instead of forcing everything through > the ANSI/codepage bottleneck? > > > Because Perl and Python aren't Windows programs. They're Unix programs that happen to have been mostly ported to Windows. As such, they don't like to call Win32 functions unless necessary. For byte-based I/O, it's not necessary; this can be done with the Standard C Libary. UTF-16-based I/O is a special case. > > Or are the -W APIs inherently broken > to such a degree that they can't be > used as-is? > > > I wouldn't say that the -W APIs are inherently broken as much as I'd say that Microsoft's approach to Unicode in C(++) is inherently broken. No matter how much certain Windows developers insist that programs should use `wchar_t` instead of `char`, there are just too many barriers to switching: * Platform dependence: + The use of UTF-16 `wchar_t` on Windows and UTF-32 `wchar_t` elsewhere. (The new `char16_t` and `char32_t` types may help.) + The non-standardness of UTF-16 filename functions like `_wfopen`, `_wstat`, etc. limits the ability to use `wchar_t` in cross-platform code. * Education. Everbody learns C with `printf("Hello, world!\n");`, not `wprintf(L"Hello, world!\n");`. The C textbook I used in college never even mentioned wide characters until Appendix A.13. * The existing zillions of lines of code that use `char*` strings.
4,942,305
The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" warning, Python gives a charmap error and quits. Why on earth after all these years do they not just simply call the Win32 -W APIs that output UTF-16 Unicode instead of forcing everything through the ANSI/codepage bottleneck? Is it just that cross-platform performance is low priority? Is it that the languages use UTF-8 internally and find it too much bother to output UTF-16? Or are the -W APIs inherently broken to such a degree that they can't be used as-is? **UPDATE** It seems that the blame may need to be shared by all parties. I imagined that the scripting languages could just call `wprintf` on Windows and let the OS/runtime worry about things such as redirection. But it turns out that [even wprintf on Windows converts wide characters to ANSI and back before printing to the console](http://blog.kalmbachnet.de/?postid=23)! Please let me know if this has been fixed since the bug report link seems broken but my Visual C test code still fails for wprintf and succeeds for WriteConsoleW. **UPDATE 2** Actually you can print UTF-16 to the console from C using `wprintf` but only if you first do `_setmode(_fileno(stdout), _O_U16TEXT)`. From C you can print UTF-8 to a console whose codepage is set to codepage 65001, however Perl, Python, PHP and Ruby all have bugs which prevent this. Perl and PHP corrupt the output by adding additional blank lines following lines which contain at least one wide character. Ruby has slightly different corrupt output. Python crashes. **UPDATE 3** Node.js is the first scripting language that shipped without this problem straight out of the box. The Python dev team slowly came to realize this was a real problem since [it was first reported back at the end of 2007](http://bugs.python.org/issue1602) and has seen a huge flurry of activity to fully understand and fully fix the bug in 2016.
2011/02/09
[ "https://Stackoverflow.com/questions/4942305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527702/" ]
The main problem seems to be that it is not possible to use Unicode on Windows using only the standard C library and no platform-dependent or third-party extensions. The languages you mentioned originate from Unix platforms, whose method of implementing Unicode blends well with C (they use normal `char*` strings, the C locale functions, and UTF-8). If you want to do Unicode in C, you more or less have to write everything twice: once using nonstandard Microsoft extensions, and once using the standard C API functions for all other operating systems. While this can be done, it usually doesn't have high priority because it's cumbersome and most scripting language developers either hate or ignore Windows anyway. At a more technical level, I think the basic assumption that most standard library designers make is that all I/O streams are inherently byte-based on the OS level, which is true for files on all operating systems, and for all streams on Unix-like systems, with the Windows console being the only exception. Thus the architecture many class libraries and programming language standard have to be modified to a great extent if one wants to incorporate Windows console I/O. Another more subjective point is that Microsoft just did not enough to promote the use of Unicode. The first Windows OS with decent (for its time) Unicode support was Windows NT 3.1, released in 1993, long before Linux and OS X grew Unicode support. Still, the transition to Unicode in those OSes has been much more seamless and unproblematic. Microsoft once again listened to the sales people instead of the engineers, and kept the technically obsolete Windows 9x around until 2001; instead of forcing developers to use a clean Unicode interface, they still ship the broken and now-unnecessary 8-bit API interface, and invite programmers to use it (look at a few of the recent Windows API questions on Stack Overflow, most newbies *still* use the horrible legacy API!). When Unicode came out, many people realized it was useful. Unicode started as a pure 16-bit encoding, so it was natural to use 16-bit code units. Microsoft then apparently said "OK, we have this 16-bit encoding, so we have to create a 16-bit API", not realizing that nobody would use it. The Unix luminaries, however, thought "how can we integrate this into the current system in an efficient and backward-compatible way so that people will actually use it?" and subsequently invented UTF-8, which is a brilliant piece of engineering. Just as when Unix was created, the Unix people thought a bit more, needed a bit longer, has less financially success, but did it eventually right. I cannot comment on Perl (but I think that there are more Windows haters in the Perl community than in the Python community), but regarding Python I know that the BDFL (who doesn't like Windows as well) has stated that adequate Unicode support on all platforms is a major goal.
Michael Kaplan has series of blog posts about the `cmd` console and Unicode that may be informative (while not really answering your question): * [Conventional wisdom is retarded, aka What the @#%&\* is \_O\_U16TEXT?](https://web.archive.org/web/20130101094000/http://www.siao2.com/2008/03/18/8306597.aspx) * [Anyone who says the console can't do Unicode isn't as smart as they think they are](https://web.archive.org/web/20130519074717/http://www.siao2.com/2010/04/07/9989346.aspx) * [A confluence of circumstances leaves a stone unturned...](https://web.archive.org/web/20130620152913/http://www.siao2.com/2010/09/23/10066660.aspx) PS: Thanks [@Jeff](https://stackoverflow.com/users/604049/jeff) for finding the archive.org links.
10,474,942
I try my very best to never use php and as thus i am not well versed in it I am having a issue that I don't understand at all here I have tried a number of things including not including the table reference in /config changing to from localhost as mysql host ect. It will probably be something exceedingly obvious but im just not spotting it! I goes with out saying all the DB credentials are completely correct (And i can connect with it fine from scala and python) anway here's the error (the real username/password not there OFC) > > Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000] [1044] Access denied for user 'username'@'10.1.1.43' to database 'a5555413\_AudioPl.users'' in /home/a5555413/public\_html/drive/auth\_handler.php:153 Stack trace: #0 /home/a5555413/public\_html/drive/auth\_handler.php(153): PDO->\_\_construct('mysql:host=mysq...', 'username...', 'passwd') #1 /home/a5555413/public\_html/drive/auth\_handler.php(74): AuthHandler->GetDbConnection() #2 /home/a5555413/public\_html/drive/index.php(47): AuthHandler->AuthHandler('webui') #3 {main} thrown in /home/a5555413/public\_html/drive/auth\_handler.php on line 153 > > > Connect code the const's are defined in a separate config file ``` function GetDbConnection() { $dbh = new PDO(Config::DB_PDO_CONNECT, Config::DB_PDO_USER, Config::DB_PDO_PASSWORD); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbConnection = $dbh; return $dbConnection; } ```
2012/05/06
[ "https://Stackoverflow.com/questions/10474942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1231175/" ]
Access denied means you're using the wrong username/password, and/or the account you're accessing has not be properly created in MySQL. What does a `show grants for username@10.1.1.43` show? if you created the account as `username@machinename` and MySQL is unable to do a reverse DNS lookup to change your IP back to machinename, you'll also get this error.
Check the following: 1) You entered the right database hostname (this is not always localhost), username and password? 2) The user has permissions on database. Let me know if you don't know how to check.
38,570,698
This is my first time using raw sockets (yes, I need to use them as I must modify a field inside a network header) and all the documentation or tutorials I read describe a solution to sniff packets but that is not exactly what I need. I need to create a script which intercepts the packet, process it and sends it further to the destination, i.e. the packets should not reach the destination unless my script decides to. In order to learn, I created a small prototype which detects pings and just prints "PING". I would expect ping not to work as I intercept the packets and I don't include the logic to send them to its destination. However ping is working (again, it seems as it is just sniffing/mirroring packets). My goal is that the ping packets are "trapped" in my script and I don't know how to do that. This is what I do in my current python script (I avoid writing how I do the decode for simplicity) ``` sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) sock.bind((eth0, 0)) packet = sock.recvfrom(65565) decode_eth(packet) decode_ip(packet) if (ipheader.ip_proto == 1): print("\nPING") ``` Can somebody explain how can I achieve my goal or point me to the right documentation?
2016/07/25
[ "https://Stackoverflow.com/questions/38570698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6104632/" ]
Your description seems to be different from what your title suggest. My understanding is that you want to receive, modify and possibly drop incoming network packets. And this is to be done on Linux. In that case I suggest you use a netfilter prerouting hook, which will make things a lot simpler (and likely more stable). Netfilter is well documented, a nice overview including information related to your requirements can be seen [here](http://www.grep.it/RMD/05-Netfilter.pdf). The important function to use is nf\_register\_hook(), read the answer to [this](https://stackoverflow.com/questions/19342252/how-to-filter-and-intercept-linux-packets-by-using-net-dev-add-api) question to get an idea of how to set things up.
I suppose that your Linux box is configured as a router (not a bridge). The packet will pass through your Linux because you have enabled **IP Forwarding**. So there are two solution: ***Solution 1:*** Disable **IP Forwarding** and then receive the packet from one interface and do the appropriate task (forwarding to another interface or dropping it). ***Solution 2:*** Use `NetFilterQueue`. Install it on your Linux box (Debian/Ubuntu in my example): ``` apt-get install build-essential python-dev libnetfilter-queue-dev ``` Use `iptables` to send packets coming from input interface (eth0 in my example): ``` iptables -I INPUT -i eth0 -j NFQUEUE --queue-num 1 ``` Run this script to handle packets forwarded to the Queue No.1 : ``` from netfilterqueue import NetfilterQueue def print_and_accept(pkt): print pkt pkt.accept() nfqueue = NetfilterQueue() nfqueue.bind(1, print_and_accept) try: nfqueue.run() except KeyboardInterrupt: print ``` Note that `pkt.drop()` cause dropping the packet. Also you should accept/drop every packet.
35,393,672
python 2.7: Count how many numbers are entered by the user. I can't figure out how to count the raw\_input... here's what I have so far: ``` while True: datum = raw_input('enter a number: ') if datum == 'done': break count = 0 for line in datum: if datum == int(datum): count = count + 1 print 'count', count ```
2016/02/14
[ "https://Stackoverflow.com/questions/35393672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5925494/" ]
The reason for the endless loop is dead simple. You are *never* updating the value of `$terms` inside the loop body, which is being used in loop condition. So the loop body is executed either zero times or infinitely. --- The fix seems to replace the `while` with the `if`, because you handle the parent via a recursive call already. However, I may be wrong since your function doesn't return anything and seems to have no side effects...
The misunderstanding lies in the scope of the `$terms` variable. This variable has scope that is local to the function call it exists in. The loop ``` while ($terms > 0) { //do some logic $parent_id = $terms->parent; $this->parent_category_has_fiance($parent_id); } ``` is referencing the `$terms` variable, but when `parent_category_has_fiance` is called, the `$terms` variable inside that function only exists there. That is, it doesn't change `$terms` that the while loop is looking at.
55,758,883
When i tried to install openCV using pip3 install opencv-python i got this error Could not find a version that satisfies the requirement opencv-python (from versions: ) No matching distribution found for opencv-python i have tried upgrading pip using ``` pip install --upgrade pip ``` and ``` curl https://bootstrap.pypa.io/get-pip.py | python ``` none of them helped me and pip is up to date tried to download and compile opencv manually gives me bunch of errors ``` python version -2.7,3.6.2 pip version- up to date raspberry pi 2 ```
2019/04/19
[ "https://Stackoverflow.com/questions/55758883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8923850/" ]
Here is the code corrected, there are. Which are to be deleted I also added `math.round` to get rounded result: ```html <html> <head> <script> function calcAmount() { let userAmount = document.getElementById("amount").value; let level1 = 351; if (userAmount <= level1) { document.getElementById("marginAmount").textContent = Math.round(userAmount * 7) / 100; } else { document.getElementById("marginAmount").textContent = "Amount is > 351"; } } </script> </head> <body> <div class="form"> <label for="points amount">Entrez un montant en points</label> <input type="number" class="amount-enter" id="amount"> <input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter" onclick="calcAmount()"> </div> <p id="marginAmount" class="enter-margin"></p> </body> ```
Three things: * You had `.` in your ID selectors, these shouldn't be there (they should be `#` but only in a `querySelector` method). * You were calculating `calcLevel1` straightaway, which meant it was `0 * 7 / 100` which is `0`. * You needed to calculate `calcLevel1` with `amount.value`, which means you can remove `calcLevel1.value` when you're setting the `textContent` of the paragraph. I also added an `else` statement so the `textContent` is emptied when the statement is false. ```js let amount = document.getElementById("amount"); let marginAmount = document.getElementById("marginAmount") let submit = document.getElementById("submit"); submit.addEventListener('click', calcAmount); function calcAmount() { const calcLevel1 = amount.value * 7 / 100; let userAmount = Number(amount.value); let level1 = 351; if (userAmount <= level1) { marginAmount.textContent = calcLevel1; } else { marginAmount.textConten = ""; } } ``` ```html <div class="form"> <label for="points amount">Entrez un montant en points</label> <input type="number" class="amount-enter" id="amount"> <input type="submit" value="Montant marge additionnelle" id="submit" class="submit-enter"> </div> <p id="marginAmount" class="enter-margin"></p> ```
47,041,267
I'm currently trying to program and learn python, while making a project with the raspberry pi zero w. So far I'm just trying to get it to start recording video using picamera in python, as well as stream that video so I can monitor what the output is on my phone. However as it currently stands it only starts recording video once I connect to it via some sort of streaming program. What I'd like for it to do is start recording the video at the start of the program and be able to connect to it whenever I'd like to monitor it. As it stands I can connect to it no problem, but then I'm unable to reconnect to it. A basic idea of what I'm wanting kinda goes like this. ``` Start Recording Listen on port 8080 if connection is started start streaming video stream 2 (also known as splitter port) else connection ended wait for new connection ``` I realize that sounds horrible. I hope it gives the general idea of what I'm trying to do. Like I said I'm just learning python, and only have some basic knowledge in Basic. Here's my code that I'm currently working with. Like I said, it works, just only when I connect to it. ``` #!/usr/bin/python import socket import picamera import datetime as dt import os.path filename = 'hauntvideo' save_path = '/home/pi' completed_video = os.path.join(save_path, filename) import warnings warnings.filterwarnings('error', category=DeprecationWarning) #Camera Setup with picamera.PiCamera() as camera: camera.resolution = (1920, 1080) camera.framerate = 30 camera.hflip = True camera.vflip = True #Connection Listening server_socket = socket.socket() server_socket.bind(('0.0.0.0', 8080)) server_socket.listen(5) connection = server_socket.accept()[0].makefile('wb') try: camera.start_recording(connection, format='h264', splitter_port=2, resize=(640,360)) camera.start_recording(completed_video + '{}.h264'.format( dt.datetime.now().strftime('%Y%m%d%H%M%S') ), bitrate=4500000) camera.wait_recording(7*60*60) camera.stop_recording() finally: connection.close() server_socket.close() quit() ```
2017/10/31
[ "https://Stackoverflow.com/questions/47041267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8863714/" ]
> > However as it currently stands it only starts recording video once I connect to it via some sort of streaming program. What I'd like for it to do is start recording the video at the start of the program and be able to connect to it whenever I'd like to monitor it. > > > This is due to the following line of code: ``` connection = server_socket.accept()[0].makefile('wb') ``` The accept() function blocks, meaning that it doesn't return until the connection is established. Therefore, the code that starts recording: ``` camera.start_recording(connection, format='h264', ... ) ``` only gets executed after the connection is established (after accept() returns). In order to accomplish what you want, you would need to use threads. In one thread, start recording the video locally, i.e. ``` camera.start_recording(completed_video + '{}.h264'.format( dt.datetime.now().strftime('%Y%m%d%H%M%S') ), bitrate=4500000) ``` In another thread, accept an incoming connection, and upon connection call: ``` camera.start_recording(connection, format='h264', splitter_port=2, resize=(640,360)) ``` > > As it stands I can connect to it no problem, but then I'm unable to reconnect to it. > > > If you want to be able to connect, disconnect, and reconnect indefinitely, then you need to accept the connection in a loop (in its own thread). Perhaps something like this: ``` while(True): connection = server_socket.accept()[0].makefile('wb') camera.start_recording(connection, format='h264', splitter_port=2, resize=(640,360)) camera.wait_recording(7*60*60) #assuming this records for 7 hours? ``` > > I'm currently trying to program and learn python, while making a project with the raspberry pi zero w. > > > I don't know if you are new to programming in general, or just to python. In the former case, dealing with network programming concepts and threads might be a little bit challenging at first. However, they are necessary to use/understand in order to achieve the functionality you desire.
KillerXtreme, This should be the code you were looking for 5 years ago (namely, you can connect and reconnect to this over and over with no hiccups)! Hope this helps somebody! ``` import socket import picamera from threading import Thread def stop_recording(cam): try: cam.stop_recording() except Exception as e: pass # print('Error: {}'.format(e)) def camera_setup(): camera = picamera.PiCamera() camera.resolution = (1024, 768) camera.framerate = 24 return camera def create_socket(): server_socket = socket.socket() server_socket.bind(('0.0.0.0', 9090)) server_socket.listen(0) return server_socket def stream(server_socket, cam): connection = server_socket.accept()[0].makefile('wb') if cam.recording: stop_recording(cam) cam.start_recording(connection, format='h264', resize=(1024, 768), inline_headers=True) def stream_video_to_network(cam): server_socket = create_socket() while True: stream(server_socket, cam) def main(camera): Thread(target=stream_video_to_network, args=(camera,)).start() if __name__ == "__main__": main(camera_setup()) ```
42,630,281
I have a python script which is supposed to loop through all files in a directory and set the date of each file to the current time. It seems to have no effect, i.e. the Date column in the file explorer shows no change. I see the code looping through all files, it just appears that the call to `utime` has no effect. The problem is [not this](https://mail.python.org/pipermail/python-bugs-list/2004-November/025966.html) because most of the dates are months old. ``` # set file access time to current time #!/usr/bin/python import os import math import datetime def convertSize(size): if (size == 0): return '0B' size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size,1024))) p = math.pow(1024,i) s = round(size/p,2) return '%s %s' % (s,size_name[i]) # see www.tutorialspoint.com/python/os_utime.htm def touch(fname, times=None): fhandle = open(fname, 'a') try: os.utime(fname, times) finally: fhandle.close() def main(): print ("*** Touch Files ***"); aml_root_directory_string = "C:\\Documents" file_count = 0 file_size = 0 # traverse root directory, and list directories as dirs and files as files for root, dirs, files in os.walk(aml_root_directory_string): path = root.split('/') #print((len(path) - 1) * '---', os.path.basename(root)) for file in files: filename, file_extension = os.path.splitext(file) print(len(path) * '---', file) touch(filename, ) # print ("\n*** Total files: " + str(file_count) + " Total file size: " + convertSize(file_size) + " ***"); print ("*** Done: Time: " + str(datetime.datetime.now()) + " - Touch Files ***"); # main ############################################################################### if __name__ == "__main__": # stuff only to run when not called via 'import' here main() ``` Edit: In case anyone reads this in the future, it is also important to note the the file explorer can [display more than 1 kind of date](https://superuser.com/questions/212542/how-can-i-make-windows-explorer-show-file-modified-date-instead-of-created-date)
2017/03/06
[ "https://Stackoverflow.com/questions/42630281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1978617/" ]
You've got three issues: 1. You're using the file name, not the full path, when `touch`ing, so all the `touch`ing occurs in the working directory 2. You're stripping the file extension too, so the touched files lack extensions 3. You're touching files to which you have an open file handle, and on Windows, on Python 2.7, this is a problem, because [`os.utime` opens the files with no sharing allowed](https://hg.python.org/cpython/file/2.7/Modules/posixmodule.c#l2970), which is incompatible with existing open file handles To fix #3, change your `touch` method to: ``` def touch(fname, times=None): # Open and immediately close file to force existence with open(fname, 'ab') as f: pass # Only alter times when file is closed os.utime(fname, times) ``` To fix #1 and #2, change your main method to call `touch` like so: ``` touch(os.path.join(root, file)) ``` which uses the original name and joins it with the root directory being traversed, where `touch(filename)` was touching a file without the extension, in the program's working directory (because you used an unqualified name). If you find your program's working directory (`print os.getcmd()` will tell you where to look), you'll find a bunch of random empty files there corresponding to the files found in the tree you were traversing, stripped of paths and file extensions. Side-note: If you can move to Python 3 (it's been a while, and there are a lot of improvements), you can make a slightly safer (race-free) and faster `touch` thanks to file descriptor support in `os.utime`: ``` def touch(fname, times=None): with open(fname, 'ab') as f: os.utime(f.fileno(), times) ``` Not all systems will support file descriptors, so if you need to handle such systems, define `touch` based on testing for [file descriptor support via `os.supports_fd`](https://docs.python.org/3/library/os.html#os.supports_fd).
os.utime does work on Windows but probably you are looking at the wrong date in explorer. os.utime does not modify the creation date (which it looks like is what is used in the date field in explorer). It does update the "Date modified" field. You can see this if you right click on the category bar and check the "date modified" box. Alternatively start a command line and type "dir". The date shown there should reflect the change. I tested os.utime on python 2.7 where you have to give two arguments: ``` os.utime("file.txt", None) ``` and on Python 3 where the second argument defaults to None: ``` os.utime("file.txt") ```
46,742,947
I have a folder full of files that need to be modified in order to extract the true file in it's real format. I need to remove a certain number of bytes from BOTH the beginning and end of the file in order to extract the data I am looking for. How can I do this in python? * I need this to work recursively on an entire folder only * I also need this to output (or modify the exisiting) file with the bytes removed. I would greatly appreciate any help or guidance you can provide.
2017/10/14
[ "https://Stackoverflow.com/questions/46742947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7838844/" ]
1. Recursive iteration over files [os.walk](https://docs.python.org/3/library/os.html#os.walk) 2. Change position in file: [f.seek](https://docs.python.org/3/tutorial/inputoutput.html?highlight=seek) 3. Get file size: [os.stat](https://docs.python.org/3/library/os.html#os.stat) 4. Remove data from current position to end of file: [f.truncate](https://docs.python.org/3/tutorial/inputoutput.html?highlight=truncate) So, base logic: 1. Iterate over files 2. Get file size. 3. Open file ('rb+' i suppouse ) 4. Seek to position from wich you want read file 5. Read until bytes you want to drop ( f.read(file\_size - top\_dropped - bottom\_dropped ) ) 6. Seek(0) 7. Write read text to file 8. Truncate file
Your question is pretty badly constructed, but as this is somewhat advanced stuff I'll provide you with a code. You can now use os.walk() to recursively traverse directory you want and apply my slicefile() function. This code does the following: 1. After checking validity of start and end arguments it creates a memory map on top of an opened file. mmap() creates a memory map object that mapps, in this case, portion of a file system over which the file is written. The object exposes both a string-like and file-like interface with some additional methods like move(). So you can treat memory map either as a string or as a file or use size(), move(), resize() or whatever additional methods you need. 2. We calculate what is a distance between our start and end, i.e. this is how much bytes we will have in the end. 3. We move stream of bytes, end-start long, starting from our start position to the 0 position i.e. we move them backwards for number of bytes indicated by starting point. 4. We discard the rest of file. I.e. we resize it to end-start bytes. So, what is left is our new string. The operation will be longer as the file is bigger. Unfortunately there is nothing much you can do about it. If a file is big, this is your best bet. The procedure is the same as when removing items from a start/middle of an in-memory array, except this has to be buffered (in chunks) not to fill RAM too much. If your file is smaller than a third of your free RAM space, you can load it whole into a string with f.read(), then perform string slicing on the loaded content ( s = s[start:end] ) and then write it back into file by opening it again and just doing f.write(s). If you have enough disk space, you can open another file, seek to the starting point you want in the original file and then read it in chunks and write these into the new file. Perhaps even using shutil.copyfileobj(). After that, you remove the original file and use os.rename() to put the new one in its place. These are your only 3 options. Whole file into RAM; move by buffering backward and then resizing; and, copying into another file, then renaming it. The second option is most universal and won't fail you for small or big files. Therefore I used it. OK, Not only 3 options. There is a fourth option. It could be possible to cut off N number of bytes from beginning of the file by manipulating the file system itself using low-level operations. To write a kind of truncate() function that truncates the beginning instead of the end. But this would be pretty suicidal. In the end memory fragmentation would occur and whole mess will arise. You don't need such speed anyway. You will be patient until your script finishes. :D Why did i use mmap()? Because it uses memory maps implemented in OS rather than completely new code. This reduces number of system calls needed to deal with the opened file. Half of the work is thrust upon operating system, leaving Python to breathe easily. Because it is mostly written in C which makes it a touch faster than its pure Python implementation would be. Because it implements move() which wee need. The buffering and everything is already written, so no needs for bulky while loop which would be the alternative (manual) solution. And so on... ``` from mmap import mmap def slicefile (path, start=0, end=None): f = open(path, "r+b") # Read and write binary f.seek(0, 2) size = f.tell() start = 0 if start==None else start end = size if end==None else end start = size+start if start<0 else start end = size+end if end<0 else end end = size if end>size else end if (end==size and start==0) or (end<=start): f.close() return # If start is 0, no need to move anything, just cut off the rest after end if start==0: f.seek(end) f.truncate() f.close() return # Modify in place using mapped memory: newsize = end-start m = mmap(f.fileno(), 0) m.move(0, start, newsize) m.flush() m.resize(newsize) m.close() f.close() ```
14,416,914
I am new to bash and shell but I am running a debian install and I am trying to make a script which can find a date in the past without having to install any additional packages. From tutorials I have got to this stage: ``` #!/bin/sh # # BACKUP DB TO S3 # # VARIABLES TYPE="DATABASE" DAYS="30" # GET CURRENT DATETIME CURRENTDATE="$(date +%Y%m%d%H%M%S)" # GENERATE PAST DATE FROM DAYS CONTSTANT OLDERDATE=`expr $CURRENTDATE - $DAYS' # CALL PYTHON SCRIPT WITH OLDERDATE ARGUMENT python script.py $OLDERDATE ``` Where I am getting stuck is the fact that my "days" is just the number 30 and isnt datetime formattted, so when I come to minus it from the currentdate variable it obviously isnt compatible. Would anyone be kind enough to help me find a way to get this working as it should?
2013/01/19
[ "https://Stackoverflow.com/questions/14416914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738522/" ]
Try ``` date -d '30 days ago' ``` should do on debian.
You could modify the python script instead -- that way you would not depend on particular implementation of `date`
14,416,914
I am new to bash and shell but I am running a debian install and I am trying to make a script which can find a date in the past without having to install any additional packages. From tutorials I have got to this stage: ``` #!/bin/sh # # BACKUP DB TO S3 # # VARIABLES TYPE="DATABASE" DAYS="30" # GET CURRENT DATETIME CURRENTDATE="$(date +%Y%m%d%H%M%S)" # GENERATE PAST DATE FROM DAYS CONTSTANT OLDERDATE=`expr $CURRENTDATE - $DAYS' # CALL PYTHON SCRIPT WITH OLDERDATE ARGUMENT python script.py $OLDERDATE ``` Where I am getting stuck is the fact that my "days" is just the number 30 and isnt datetime formattted, so when I come to minus it from the currentdate variable it obviously isnt compatible. Would anyone be kind enough to help me find a way to get this working as it should?
2013/01/19
[ "https://Stackoverflow.com/questions/14416914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738522/" ]
Try ``` date -d '30 days ago' ``` should do on debian.
You can use the following script: ``` #!/bin/bash days=73 while [ ${days} -ge 0 ]; do date -d "${days} days ago" +'%F' days=$((days-1)) done ```
14,416,914
I am new to bash and shell but I am running a debian install and I am trying to make a script which can find a date in the past without having to install any additional packages. From tutorials I have got to this stage: ``` #!/bin/sh # # BACKUP DB TO S3 # # VARIABLES TYPE="DATABASE" DAYS="30" # GET CURRENT DATETIME CURRENTDATE="$(date +%Y%m%d%H%M%S)" # GENERATE PAST DATE FROM DAYS CONTSTANT OLDERDATE=`expr $CURRENTDATE - $DAYS' # CALL PYTHON SCRIPT WITH OLDERDATE ARGUMENT python script.py $OLDERDATE ``` Where I am getting stuck is the fact that my "days" is just the number 30 and isnt datetime formattted, so when I come to minus it from the currentdate variable it obviously isnt compatible. Would anyone be kind enough to help me find a way to get this working as it should?
2013/01/19
[ "https://Stackoverflow.com/questions/14416914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738522/" ]
Try doing this : ``` #!/bin/sh # # BACKUP DB TO S3 # # VARIABLES TYPE="DATABASE" DAYS="30" # GET CURRENT DATETIME CURRENTDATE="$(date +%Y%m%d%H%M%S)" # GENERATE PAST DATE FROM DAYS CONSTANT OLDERDATE="$(date "+%Y%m%d%H%M%S" -d "$DAYS days ago")" # CALL PYTHON SCRIPT WITH OLDERDATE ARGUMENT python script.py "$OLDERDATE" ``` See `info coreutils 'date invocation' | less +/28.7\ Relative\ items\ in\ date\ strings`
You could modify the python script instead -- that way you would not depend on particular implementation of `date`
14,416,914
I am new to bash and shell but I am running a debian install and I am trying to make a script which can find a date in the past without having to install any additional packages. From tutorials I have got to this stage: ``` #!/bin/sh # # BACKUP DB TO S3 # # VARIABLES TYPE="DATABASE" DAYS="30" # GET CURRENT DATETIME CURRENTDATE="$(date +%Y%m%d%H%M%S)" # GENERATE PAST DATE FROM DAYS CONTSTANT OLDERDATE=`expr $CURRENTDATE - $DAYS' # CALL PYTHON SCRIPT WITH OLDERDATE ARGUMENT python script.py $OLDERDATE ``` Where I am getting stuck is the fact that my "days" is just the number 30 and isnt datetime formattted, so when I come to minus it from the currentdate variable it obviously isnt compatible. Would anyone be kind enough to help me find a way to get this working as it should?
2013/01/19
[ "https://Stackoverflow.com/questions/14416914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738522/" ]
Try doing this : ``` #!/bin/sh # # BACKUP DB TO S3 # # VARIABLES TYPE="DATABASE" DAYS="30" # GET CURRENT DATETIME CURRENTDATE="$(date +%Y%m%d%H%M%S)" # GENERATE PAST DATE FROM DAYS CONSTANT OLDERDATE="$(date "+%Y%m%d%H%M%S" -d "$DAYS days ago")" # CALL PYTHON SCRIPT WITH OLDERDATE ARGUMENT python script.py "$OLDERDATE" ``` See `info coreutils 'date invocation' | less +/28.7\ Relative\ items\ in\ date\ strings`
You can use the following script: ``` #!/bin/bash days=73 while [ ${days} -ge 0 ]; do date -d "${days} days ago" +'%F' days=$((days-1)) done ```
14,416,914
I am new to bash and shell but I am running a debian install and I am trying to make a script which can find a date in the past without having to install any additional packages. From tutorials I have got to this stage: ``` #!/bin/sh # # BACKUP DB TO S3 # # VARIABLES TYPE="DATABASE" DAYS="30" # GET CURRENT DATETIME CURRENTDATE="$(date +%Y%m%d%H%M%S)" # GENERATE PAST DATE FROM DAYS CONTSTANT OLDERDATE=`expr $CURRENTDATE - $DAYS' # CALL PYTHON SCRIPT WITH OLDERDATE ARGUMENT python script.py $OLDERDATE ``` Where I am getting stuck is the fact that my "days" is just the number 30 and isnt datetime formattted, so when I come to minus it from the currentdate variable it obviously isnt compatible. Would anyone be kind enough to help me find a way to get this working as it should?
2013/01/19
[ "https://Stackoverflow.com/questions/14416914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738522/" ]
You can use the following script: ``` #!/bin/bash days=73 while [ ${days} -ge 0 ]; do date -d "${days} days ago" +'%F' days=$((days-1)) done ```
You could modify the python script instead -- that way you would not depend on particular implementation of `date`
35,642,131
I am training a problem such that my output (y) could be more than one class. For example, the SVM could say, this input vector is class 1, but it could also say, this input vector is classes 1 AND 5. This is not the same as a multiclass SVM problem, where the output could be ONE of multiple classes. My output could be ONE or SEVERAL of multiple classes. Example: My training data looks like (for each training vector X) ``` X_1 [1 0 0 0] X_2 [0 1 1 0] X_3 [0 0 0 1] X_4 [1 1 0 1] ``` Where the right side is the Y to be predicted (here I am showing an example with 4 classes, where a 1 indicates class membership). I understand that I need to probably use a structural SVM such as discussed here: <http://www.robots.ox.ac.uk/~vedaldi/svmstruct.html> However, this is all very confusing to me. I do NOT want to simply do one-vs-all classifiers for each of the possible output classes, however. I need to somehow take into account class relationships, so I guess what I need is a structural SVM. My training data will have some instances tagged with single classes and other instances tagged with multiple classes. I guess I'm asking how to tackle this problem and if you know any packages to do so in MATLAB or python.
2016/02/26
[ "https://Stackoverflow.com/questions/35642131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5983697/" ]
Yes, use a for loop using the `length` method. You can get the letter at a given position using [CharSequence#charAt](https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#charAt-int-). `String` implements `CharSequence` so you can do `a.charAt(i);`
I like the `charAtSequence()` suggested by pyb, my own first instinct however would be char array. I think they both will work the same though. I didint want to write the whole code for you, but I hope this helps... ``` char [] _a = a.toCharArray(); // note 1 //do the same for the b string here... else if (a.length() == b.length()); for(int i = 0; i < a.length; i++){ // note 2 //compare each character here.. } System.out.printf("Bye"); } ``` Here are some good resources on `toCharArray()` if you need more help or understanding [java documentation on `tocharArray()`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray%28%29) [beginner's guide to `toCharArray()`](http://beginnersbook.com/2013/12/java-string-tochararray-method-example/) note 1: this line sets aside a char[] variable ( an array of characters) : `char[]_a` the second par `= a.toCharArray` uses a method of the String class that will instantiate a char array of the length of string `a` then take every letter of the String `a` and place them into the char[] array.. so.... ``` String a = cat char[] _a = a.toCharArray(); ``` results in an array characters [c] [a] [t] now we preform the same manipulation with string `b`.... ``` String b = cat char[] _b = b.toCharArray(); ``` this (since the strings are equivalent) will result in equivalent arrays.. however you must test this to be sure. to test the equivalency of these arrays we must test each index against the corresponding index... we will do so with a `for` loop This for loop, as shown above [note 2] is set to run through the same number of rotations as the array is long. (I'm not sure how to phrase this right now I'm not using my words well tonight, so if you can phrase that better please do...) then we will compare each index to the cooresponding one here... ``` boolean flag = true; for(int i = 0; i < a.length; i++){ // ( or > or < or >= or <= ) however it is you wish to compare these if( _a[i] != _b[i]){ flag = false; } } ``` And then if flag == true, print out your corresponding message else.. print other message... for this answer.. ``` if( _a[i] != _b[i]){ flag = false; System.out.printf("Bye\n"); } ``` Take your System.out.print, and move it outside your loop.. everytime your loop passes through it prints bye... try a statment that prints Flag and bye...
35,642,131
I am training a problem such that my output (y) could be more than one class. For example, the SVM could say, this input vector is class 1, but it could also say, this input vector is classes 1 AND 5. This is not the same as a multiclass SVM problem, where the output could be ONE of multiple classes. My output could be ONE or SEVERAL of multiple classes. Example: My training data looks like (for each training vector X) ``` X_1 [1 0 0 0] X_2 [0 1 1 0] X_3 [0 0 0 1] X_4 [1 1 0 1] ``` Where the right side is the Y to be predicted (here I am showing an example with 4 classes, where a 1 indicates class membership). I understand that I need to probably use a structural SVM such as discussed here: <http://www.robots.ox.ac.uk/~vedaldi/svmstruct.html> However, this is all very confusing to me. I do NOT want to simply do one-vs-all classifiers for each of the possible output classes, however. I need to somehow take into account class relationships, so I guess what I need is a structural SVM. My training data will have some instances tagged with single classes and other instances tagged with multiple classes. I guess I'm asking how to tackle this problem and if you know any packages to do so in MATLAB or python.
2016/02/26
[ "https://Stackoverflow.com/questions/35642131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5983697/" ]
Can't you simply use the [String compareTo()](http://www.tutorialspoint.com/java/java_string_compareto.htm) function? It seems to do exactly what you need: ``` String a = "cats"; String b = "cuts"; String result = ""; if(a.length() != b.length()){ result = "BYE"; } else if (a.compareTo(b) <= 0){ result = "TRUE"; } else{ result = "FALSE"; } System.out.println(result); ```
Yes, use a for loop using the `length` method. You can get the letter at a given position using [CharSequence#charAt](https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#charAt-int-). `String` implements `CharSequence` so you can do `a.charAt(i);`
35,642,131
I am training a problem such that my output (y) could be more than one class. For example, the SVM could say, this input vector is class 1, but it could also say, this input vector is classes 1 AND 5. This is not the same as a multiclass SVM problem, where the output could be ONE of multiple classes. My output could be ONE or SEVERAL of multiple classes. Example: My training data looks like (for each training vector X) ``` X_1 [1 0 0 0] X_2 [0 1 1 0] X_3 [0 0 0 1] X_4 [1 1 0 1] ``` Where the right side is the Y to be predicted (here I am showing an example with 4 classes, where a 1 indicates class membership). I understand that I need to probably use a structural SVM such as discussed here: <http://www.robots.ox.ac.uk/~vedaldi/svmstruct.html> However, this is all very confusing to me. I do NOT want to simply do one-vs-all classifiers for each of the possible output classes, however. I need to somehow take into account class relationships, so I guess what I need is a structural SVM. My training data will have some instances tagged with single classes and other instances tagged with multiple classes. I guess I'm asking how to tackle this problem and if you know any packages to do so in MATLAB or python.
2016/02/26
[ "https://Stackoverflow.com/questions/35642131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5983697/" ]
You have to loop the individual chars in your strings ``` for (int x = 0; x < a.length(); x++) { if (a.charAt (x) > b.charAt (x)) { System.out.println ("First String is BIGGER"); // maybe break now ? } } ```
I like the `charAtSequence()` suggested by pyb, my own first instinct however would be char array. I think they both will work the same though. I didint want to write the whole code for you, but I hope this helps... ``` char [] _a = a.toCharArray(); // note 1 //do the same for the b string here... else if (a.length() == b.length()); for(int i = 0; i < a.length; i++){ // note 2 //compare each character here.. } System.out.printf("Bye"); } ``` Here are some good resources on `toCharArray()` if you need more help or understanding [java documentation on `tocharArray()`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray%28%29) [beginner's guide to `toCharArray()`](http://beginnersbook.com/2013/12/java-string-tochararray-method-example/) note 1: this line sets aside a char[] variable ( an array of characters) : `char[]_a` the second par `= a.toCharArray` uses a method of the String class that will instantiate a char array of the length of string `a` then take every letter of the String `a` and place them into the char[] array.. so.... ``` String a = cat char[] _a = a.toCharArray(); ``` results in an array characters [c] [a] [t] now we preform the same manipulation with string `b`.... ``` String b = cat char[] _b = b.toCharArray(); ``` this (since the strings are equivalent) will result in equivalent arrays.. however you must test this to be sure. to test the equivalency of these arrays we must test each index against the corresponding index... we will do so with a `for` loop This for loop, as shown above [note 2] is set to run through the same number of rotations as the array is long. (I'm not sure how to phrase this right now I'm not using my words well tonight, so if you can phrase that better please do...) then we will compare each index to the cooresponding one here... ``` boolean flag = true; for(int i = 0; i < a.length; i++){ // ( or > or < or >= or <= ) however it is you wish to compare these if( _a[i] != _b[i]){ flag = false; } } ``` And then if flag == true, print out your corresponding message else.. print other message... for this answer.. ``` if( _a[i] != _b[i]){ flag = false; System.out.printf("Bye\n"); } ``` Take your System.out.print, and move it outside your loop.. everytime your loop passes through it prints bye... try a statment that prints Flag and bye...
35,642,131
I am training a problem such that my output (y) could be more than one class. For example, the SVM could say, this input vector is class 1, but it could also say, this input vector is classes 1 AND 5. This is not the same as a multiclass SVM problem, where the output could be ONE of multiple classes. My output could be ONE or SEVERAL of multiple classes. Example: My training data looks like (for each training vector X) ``` X_1 [1 0 0 0] X_2 [0 1 1 0] X_3 [0 0 0 1] X_4 [1 1 0 1] ``` Where the right side is the Y to be predicted (here I am showing an example with 4 classes, where a 1 indicates class membership). I understand that I need to probably use a structural SVM such as discussed here: <http://www.robots.ox.ac.uk/~vedaldi/svmstruct.html> However, this is all very confusing to me. I do NOT want to simply do one-vs-all classifiers for each of the possible output classes, however. I need to somehow take into account class relationships, so I guess what I need is a structural SVM. My training data will have some instances tagged with single classes and other instances tagged with multiple classes. I guess I'm asking how to tackle this problem and if you know any packages to do so in MATLAB or python.
2016/02/26
[ "https://Stackoverflow.com/questions/35642131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5983697/" ]
Can't you simply use the [String compareTo()](http://www.tutorialspoint.com/java/java_string_compareto.htm) function? It seems to do exactly what you need: ``` String a = "cats"; String b = "cuts"; String result = ""; if(a.length() != b.length()){ result = "BYE"; } else if (a.compareTo(b) <= 0){ result = "TRUE"; } else{ result = "FALSE"; } System.out.println(result); ```
I like the `charAtSequence()` suggested by pyb, my own first instinct however would be char array. I think they both will work the same though. I didint want to write the whole code for you, but I hope this helps... ``` char [] _a = a.toCharArray(); // note 1 //do the same for the b string here... else if (a.length() == b.length()); for(int i = 0; i < a.length; i++){ // note 2 //compare each character here.. } System.out.printf("Bye"); } ``` Here are some good resources on `toCharArray()` if you need more help or understanding [java documentation on `tocharArray()`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray%28%29) [beginner's guide to `toCharArray()`](http://beginnersbook.com/2013/12/java-string-tochararray-method-example/) note 1: this line sets aside a char[] variable ( an array of characters) : `char[]_a` the second par `= a.toCharArray` uses a method of the String class that will instantiate a char array of the length of string `a` then take every letter of the String `a` and place them into the char[] array.. so.... ``` String a = cat char[] _a = a.toCharArray(); ``` results in an array characters [c] [a] [t] now we preform the same manipulation with string `b`.... ``` String b = cat char[] _b = b.toCharArray(); ``` this (since the strings are equivalent) will result in equivalent arrays.. however you must test this to be sure. to test the equivalency of these arrays we must test each index against the corresponding index... we will do so with a `for` loop This for loop, as shown above [note 2] is set to run through the same number of rotations as the array is long. (I'm not sure how to phrase this right now I'm not using my words well tonight, so if you can phrase that better please do...) then we will compare each index to the cooresponding one here... ``` boolean flag = true; for(int i = 0; i < a.length; i++){ // ( or > or < or >= or <= ) however it is you wish to compare these if( _a[i] != _b[i]){ flag = false; } } ``` And then if flag == true, print out your corresponding message else.. print other message... for this answer.. ``` if( _a[i] != _b[i]){ flag = false; System.out.printf("Bye\n"); } ``` Take your System.out.print, and move it outside your loop.. everytime your loop passes through it prints bye... try a statment that prints Flag and bye...
35,642,131
I am training a problem such that my output (y) could be more than one class. For example, the SVM could say, this input vector is class 1, but it could also say, this input vector is classes 1 AND 5. This is not the same as a multiclass SVM problem, where the output could be ONE of multiple classes. My output could be ONE or SEVERAL of multiple classes. Example: My training data looks like (for each training vector X) ``` X_1 [1 0 0 0] X_2 [0 1 1 0] X_3 [0 0 0 1] X_4 [1 1 0 1] ``` Where the right side is the Y to be predicted (here I am showing an example with 4 classes, where a 1 indicates class membership). I understand that I need to probably use a structural SVM such as discussed here: <http://www.robots.ox.ac.uk/~vedaldi/svmstruct.html> However, this is all very confusing to me. I do NOT want to simply do one-vs-all classifiers for each of the possible output classes, however. I need to somehow take into account class relationships, so I guess what I need is a structural SVM. My training data will have some instances tagged with single classes and other instances tagged with multiple classes. I guess I'm asking how to tackle this problem and if you know any packages to do so in MATLAB or python.
2016/02/26
[ "https://Stackoverflow.com/questions/35642131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5983697/" ]
Can't you simply use the [String compareTo()](http://www.tutorialspoint.com/java/java_string_compareto.htm) function? It seems to do exactly what you need: ``` String a = "cats"; String b = "cuts"; String result = ""; if(a.length() != b.length()){ result = "BYE"; } else if (a.compareTo(b) <= 0){ result = "TRUE"; } else{ result = "FALSE"; } System.out.println(result); ```
You have to loop the individual chars in your strings ``` for (int x = 0; x < a.length(); x++) { if (a.charAt (x) > b.charAt (x)) { System.out.println ("First String is BIGGER"); // maybe break now ? } } ```
73,739,734
I am currently able to use quick fix to auto import python functions from external typings such as `from typing import List`. [Python module quick fix import](https://i.stack.imgur.com/q3m7F.png) However, I am unable to detect local functions/classes for import. For example: If I have the data class `SampleDataClass` in `dataclasses.py`, and I reference it in a function in `test_file.py`, VSCode is unable to detect it and I have to manually type out the import path for the dataclass. [Definition of dataclass](https://i.stack.imgur.com/KlXuJ.png) [Reference to dataclass](https://i.stack.imgur.com/dRY6H.png) I have the following extensions enabled: * Python * Pylance * Intellicode My settings.json includes: ``` { "python.envFile": "${workspaceFolder}/.env", "python.languageServer": "Pylance", "python.analysis.indexing": true, "python.formatting.provider": "black", "python.analysis.autoImportCompletions": true, "python.analysis.autoSearchPaths": true, "python.autoComplete.extraPaths": ["~/Development/<django repo name>/server"], "python.analysis.extraPaths": ["~/Development/<django repo name>/server"], "vsintellicode.features.python.deepLearning": "enabled", } ``` I am using poetry for my virtual environment which is located at `~/Development/<django repo name>/.venv` Is there something that I'm missing?
2022/09/16
[ "https://Stackoverflow.com/questions/73739734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20008915/" ]
Turns out the latest versions for Pylance broke quick-fix imports and any extra path settings for VSCode. When I rolled back the version to `v2022.8.50` it now works again. I filed an issue here: <https://github.com/microsoft/pylance-release/issues/3353>.
According to an [issue](https://github.com/microsoft/pylance-release/issues/3324) I raised in github earlier, the developer gave a reply. Custom code will **not** be added to the autocomplete list at this time (unless it has already been imported). This is done to prevent users from having too many custom modules, which may lead to too long loading time. If necessary, you can start a discussion in github and vote for it. **Add:** [![enter image description here](https://i.stack.imgur.com/1sO0x.png)](https://i.stack.imgur.com/1sO0x.png)
72,631,459
I am trying to test an API that sends long-running jobs to a queue processed by Celery workers.. I am using RabbitMQ running in a Docker container as the message queue. However, when sending a message to the queue I get the following error: `Error: [Errno 111] Connection refused` Steps to reproduce: * Start RabbitMQ container: `docker run -d -p 5672:5672 rabbitmq` * Start Celery server: `celery -A celery worker --loglevel=INFO` * Build docker image: `docker build -t fastapi .` * Run container `docker run -it -p 8000:8000 fastapi` Dockerfile: ``` FROM python:3.9 WORKDIR / COPY . . RUN pip install --no-cache-dir --upgrade -r ./requirements.txt EXPOSE 8000 CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"] ``` requirements.txt: ``` anyio==3.6.1 asgiref==3.5.2 celery==5.2.7 click==8.1.3 colorama==0.4.4 fastapi==0.78.0 h11==0.13.0 httptools==0.4.0 idna==3.3 pydantic==1.9.1 python-dotenv==0.20.0 PyYAML==6.0 sniffio==1.2.0 starlette==0.19.1 typing_extensions==4.2.0 uvicorn==0.17.6 watchgod==0.8.2 websockets==10.3 ``` app.py: ``` from fastapi import FastAPI import tasks @app.get("/{num}") async def root(num): tasks.update_db.delay(num) return {"success": True} ``` tasks.py: ``` from celery import Celery import time celery = Celery('tasks', broker='amqp://') @celery.task(name='update_db') def update_db(num: int) -> None: time.sleep(30) return ```
2022/06/15
[ "https://Stackoverflow.com/questions/72631459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6131554/" ]
You can't connect to rabbitmq on `localhost`; it's not running in the same container as your Python app. Since you've exposed rabbit on your host, you can connect to it using the address of your host. One way of doing that is starting the app container like this: ``` docker run -it -p 8000:8000 --add-host host.docker.internal:host-gateway fastapi ``` And then modify your code like this: ``` celery = Celery('tasks', broker='amqp://host.docker.internal') ``` With that code in place, let's re-run your example: ``` $ docker run -d -p 5672:5672 rabbitmq $ docker run -d -p 8000:8000 --add-host host.docker.internal:host-gateway fastapi $ curl http://localhost:8000/1 {"success":true} ``` --- There's no reason to publish the rabbitmq ports on your host if you only need to access it from within a container. When building an application with multiple containers, using something like docker-compose can make your life easier. If you used the following `docker-compose.yaml`: ``` version: "3" services: rabbitmq: image: rabbitmq app: build: context: . ports: - "8000:8000" ``` And modified your code to connect to `rabbitmq`: ``` celery = Celery('tasks', broker='amqp://rabbitmq') ``` You could then run `docker-compose up` to bring up both containers. Your app would be exposed on host port `8000`, but rabbitmq would only be available to your app container. Incidentally, rather than hardcoding the broker uri in your code, you might want to get that from an environment variable instead: ``` celery = Celery('tasks', broker=os.getenv('APP_BROKER_URI')) ``` That allows you to use different connection strings without needing to rebuild your image every time. We'd need to modify the `docker-compose.yaml` to include the appropriate variable: ``` version: "3" services: rabbitmq: image: rabbitmq app: build: context: . environment: APP_BROKER_URI: "amqp://rabbitmq" ports: - "8000:8000" ```
Update **tasks.py** ``` import time celery = Celery('tasks', broker='amqp://user:pass@host:port//') @celery.task(name='update_db') def update_db(num: int) -> None: time.sleep(30) return ```
6,999,522
I'm looking to generate, from a large Python codebase, a summary of heap usage or memory allocations over the course of a function's run. I'm familiar with [heapy](http://guppy-pe.sourceforge.net/), and it's served me well for taking "snapshots" of the heap at particular points in my code, but I've found it difficult to generate a "memory-over-time" summary with it. I've also played with [line\_profiler](http://packages.python.org/line_profiler/), but that works with run time, not memory. My fallback right now is Valgrind with [massif](http://valgrind.org/docs/manual/ms-manual.html), but that lacks a lot of the contextual Python information that both Heapy and line\_profiler give. Is there some sort of combination of the latter two that give a sense of memory usage or heap growth over the execution span of a Python program?
2011/08/09
[ "https://Stackoverflow.com/questions/6999522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/104200/" ]
I would use [`sys.settrace`](http://docs.python.org/library/sys.html#sys.settrace) at program startup to register a custom tracer function. The custom\_trace\_function will be called for each line of code. Then you can use that function to store information gathered by heapy or [meliae](https://launchpad.net/meliae) in a file for later processing. Here is a very simple example which logs the output of hpy.heap() each second to a plain text file: ``` import sys import time import atexit from guppy import hpy _last_log_time = time.time() _logfile = open('logfile.txt', 'w') def heapy_profile(frame, event, arg): currtime = time.time() if currtime - _last_log_time < 1: return _last_log_time = currtime code = frame.f_code filename = code.co_filename lineno = code.co_firstlineno idset = hpy().heap() logfile.write('%s %s:%s\n%s\n\n' % (currtime, filename, lineno, idset)) logfile.flush() atexit.register(_logfile.close) sys.settrace(heapy_profile) ```
You might be interested by [memory\_profiler](https://pypi.org/project/memory-profiler/).
35,667,105
I am an amateur python programer with 2 months of experience. I am trying to write a GUI to-do list through tkinter. The actual placement of the buttons are not important. I can play around with those after. I need some help with displaying the appended item to the list. In the program, it updates well on the digit, but it won't print onto the list. I double checked it on the console and it says "tkinter.StringVar object at 0x102fa4048" but didn't update the actual list. What I need help is how can I update the list Main\_Q on my the label column? Much appreciate some direction and coding help. Thanks. ``` Main_Q =["read","clean dishes", "wash car"] from tkinter import* root=Tk(className="total tasks in the Q") #formula def update(): global Main_Q a=len(Main_Q) num.set(a) def add2list(): Main_Q.append(name) a=len(Main_Q) num.set(a) print (Main_Q) #output num=StringVar() y=Label(root, textvariable=num).grid(row=0, column=1) #input name=StringVar() b=Entry(root, textvariable=name).grid(row=7,column=0) #buttons z=Button(root, text="update", command=update).grid(row=7, column=2) add2list=Button(root,text="add", command=add2list).grid(row=7, column=1) r = 0 for c in Main_Q: Label(text=c, relief=RIDGE,width=15).grid(row=r,column=0) r = r + 1 root.mainloop() ```
2016/02/27
[ "https://Stackoverflow.com/questions/35667105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5989438/" ]
Just replace the package name with your package name / applicationId You do not need to publish the app first, just keep the same applicationId when you eventually upload the app. For example <https://play.google.com/store/apps/details?id=com.instagram.android> market://details?id=com.instagram.android app/build.gradle: ``` android { compileSdkVersion 19 buildToolsVersion "19.1" defaultConfig { applicationId "com.instagram.android" minSdkVersion 15 targetSdkVersion 19 versionCode 1 versionName "1.0" } ```
No need to update the app. First you can do it with a temp link with dynamic process. After your app publish, you can replace that link with playstore link.
35,667,105
I am an amateur python programer with 2 months of experience. I am trying to write a GUI to-do list through tkinter. The actual placement of the buttons are not important. I can play around with those after. I need some help with displaying the appended item to the list. In the program, it updates well on the digit, but it won't print onto the list. I double checked it on the console and it says "tkinter.StringVar object at 0x102fa4048" but didn't update the actual list. What I need help is how can I update the list Main\_Q on my the label column? Much appreciate some direction and coding help. Thanks. ``` Main_Q =["read","clean dishes", "wash car"] from tkinter import* root=Tk(className="total tasks in the Q") #formula def update(): global Main_Q a=len(Main_Q) num.set(a) def add2list(): Main_Q.append(name) a=len(Main_Q) num.set(a) print (Main_Q) #output num=StringVar() y=Label(root, textvariable=num).grid(row=0, column=1) #input name=StringVar() b=Entry(root, textvariable=name).grid(row=7,column=0) #buttons z=Button(root, text="update", command=update).grid(row=7, column=2) add2list=Button(root,text="add", command=add2list).grid(row=7, column=1) r = 0 for c in Main_Q: Label(text=c, relief=RIDGE,width=15).grid(row=r,column=0) r = r + 1 root.mainloop() ```
2016/02/27
[ "https://Stackoverflow.com/questions/35667105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5989438/" ]
**You can use this code** ``` "https://play.google.com/store/apps/details?id="+getApplicationContext().getPackageName() ``` work for me fine I hope help this
No need to update the app. First you can do it with a temp link with dynamic process. After your app publish, you can replace that link with playstore link.
35,667,105
I am an amateur python programer with 2 months of experience. I am trying to write a GUI to-do list through tkinter. The actual placement of the buttons are not important. I can play around with those after. I need some help with displaying the appended item to the list. In the program, it updates well on the digit, but it won't print onto the list. I double checked it on the console and it says "tkinter.StringVar object at 0x102fa4048" but didn't update the actual list. What I need help is how can I update the list Main\_Q on my the label column? Much appreciate some direction and coding help. Thanks. ``` Main_Q =["read","clean dishes", "wash car"] from tkinter import* root=Tk(className="total tasks in the Q") #formula def update(): global Main_Q a=len(Main_Q) num.set(a) def add2list(): Main_Q.append(name) a=len(Main_Q) num.set(a) print (Main_Q) #output num=StringVar() y=Label(root, textvariable=num).grid(row=0, column=1) #input name=StringVar() b=Entry(root, textvariable=name).grid(row=7,column=0) #buttons z=Button(root, text="update", command=update).grid(row=7, column=2) add2list=Button(root,text="add", command=add2list).grid(row=7, column=1) r = 0 for c in Main_Q: Label(text=c, relief=RIDGE,width=15).grid(row=r,column=0) r = r + 1 root.mainloop() ```
2016/02/27
[ "https://Stackoverflow.com/questions/35667105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5989438/" ]
**You can use this code** ``` "https://play.google.com/store/apps/details?id="+getApplicationContext().getPackageName() ``` work for me fine I hope help this
Just replace the package name with your package name / applicationId You do not need to publish the app first, just keep the same applicationId when you eventually upload the app. For example <https://play.google.com/store/apps/details?id=com.instagram.android> market://details?id=com.instagram.android app/build.gradle: ``` android { compileSdkVersion 19 buildToolsVersion "19.1" defaultConfig { applicationId "com.instagram.android" minSdkVersion 15 targetSdkVersion 19 versionCode 1 versionName "1.0" } ```
67,883,300
I want to print all Thursdays between these date ranges ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date ``` What is the best pythonic way to do that?
2021/06/08
[ "https://Stackoverflow.com/questions/67883300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
using your `sdate.weekday() # returns int between 0 (mon) and 6 (sun)`: ``` sdate = ... while sdate < edate: if sdate.weekday() != 3: # not thursday sdate += timedelta(days=1) continue # It is thursday print(sdate) sdate += timedelta(days=7) # next week ```
```py import datetime import calendar def weekday_count(start, end, day): start_date = datetime.datetime.strptime(start, '%d/%m/%Y') end_date = datetime.datetime.strptime(end, '%d/%m/%Y') day_count = [] for i in range((end_date - start_date).days): if calendar.day_name[(start_date + datetime.timedelta(days=i+1)).weekday()] == day: print(str(start_date + datetime.timedelta(days=i+1)).split()[0]) weekday_count("01/01/2017", "31/01/2017", "Thursday") # prints result # 2017-01-05 # 2017-01-12 # 2017-01-19 # 2017-01-26 ```
67,883,300
I want to print all Thursdays between these date ranges ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date ``` What is the best pythonic way to do that?
2021/06/08
[ "https://Stackoverflow.com/questions/67883300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
Compute the number of days till thursday from the start date : ``` days_to_thursday = (3 - sdate.weekday()) % 7 ``` Compute the number of thursdays inbetween both dates: ``` week_diff = ((edate - sdate).days - days_to_thursday ) // 7 ``` Get all thursdays in the date range: ``` thursdays = [sdate + timedelta(days=days_to_thursday + 7 * more_weeks) \ for more_weeks in range(week_diff + 1) ] ``` Print them if you need: ``` for t in thursdays: print(t) ```
```py import datetime import calendar def weekday_count(start, end, day): start_date = datetime.datetime.strptime(start, '%d/%m/%Y') end_date = datetime.datetime.strptime(end, '%d/%m/%Y') day_count = [] for i in range((end_date - start_date).days): if calendar.day_name[(start_date + datetime.timedelta(days=i+1)).weekday()] == day: print(str(start_date + datetime.timedelta(days=i+1)).split()[0]) weekday_count("01/01/2017", "31/01/2017", "Thursday") # prints result # 2017-01-05 # 2017-01-12 # 2017-01-19 # 2017-01-26 ```
67,883,300
I want to print all Thursdays between these date ranges ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date ``` What is the best pythonic way to do that?
2021/06/08
[ "https://Stackoverflow.com/questions/67883300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
Most people are iterating through every day which is a waste. Also might be helpful to delay calculating the thursdays until you actually need them. For this you could use a generator. ```py def get_days(start, day_index, end=None): # set the start as the next valid day start += timedelta(days=(day_index - start.weekday()) % 7) week = timedelta(days=7) while end and start < end or not end: yield start start += week ``` This delays getting the next day until you need it, and allows infinite days if you don't specify and end date. ``` thursday_generator = get_days(date(2015, 1, 7), 3, date(2015, 12, 31)) print(list(thursday_generator)) """ [datetime.date(2015, 1, 8), datetime.date(2015, 1, 15), datetime.date(2015, 1, 22), ...] """ ``` You can easily dump as strings: ``` print("\n".join(map(str, thursday_generator))) """ 2015-01-08 2015-01-15 2015-01-22 ... """ ``` You can also use f-strings for custom string formatting: ``` print("\n".join(f"{day:%A %x}" for day in thursday_generator)) """ Thursday 01/08/15 Thursday 01/15/15 Thursday 01/22/15 ... """ ``` If you don't specify an end date, it goes on forever. ``` In [28]: thursday_generator = get_days(date(2015, 1, 7), 3) ...: print(len(list(thursday_generator))) --------------------------------------------------------------------------- OverflowError Traceback (most recent call last) <ipython-input-28-b161cdcccc75> in <module> 1 thursday_generator = get_days(date(2015, 1, 7), 3) ----> 2 print(len(list(thursday_generator))) <ipython-input-16-0691db329606> in get_days(start, day_index, end) 5 while end and start < end or not end: 6 yield start ----> 7 start += week 8 OverflowError: date value out of range ```
```py import datetime import calendar def weekday_count(start, end, day): start_date = datetime.datetime.strptime(start, '%d/%m/%Y') end_date = datetime.datetime.strptime(end, '%d/%m/%Y') day_count = [] for i in range((end_date - start_date).days): if calendar.day_name[(start_date + datetime.timedelta(days=i+1)).weekday()] == day: print(str(start_date + datetime.timedelta(days=i+1)).split()[0]) weekday_count("01/01/2017", "31/01/2017", "Thursday") # prints result # 2017-01-05 # 2017-01-12 # 2017-01-19 # 2017-01-26 ```
67,883,300
I want to print all Thursdays between these date ranges ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date ``` What is the best pythonic way to do that?
2021/06/08
[ "https://Stackoverflow.com/questions/67883300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
using your `sdate.weekday() # returns int between 0 (mon) and 6 (sun)`: ``` sdate = ... while sdate < edate: if sdate.weekday() != 3: # not thursday sdate += timedelta(days=1) continue # It is thursday print(sdate) sdate += timedelta(days=7) # next week ```
Simple solution: ```py from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date delta = edate - sdate for day in range(delta.days + 1): day_obj = sdate + timedelta(days=day) if day_obj.weekday() == 3: # Thursday print(day_obj) # 2015-01-08 # 2015-01-15 # ... # 2015-12-24 # 2015-12-31 ``` The most efficient solution: ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date day_index = 3 # Thursday delta = (day_index - sdate.weekday()) % 7 match = sdate + timedelta(days=delta) while match <= edate: # Change this to `<` to ignore the last one print(match) # Can be easily converted to a generator with `yield` match += timedelta(days=7) # 2015-01-08 # 2015-01-15 # ... # 2015-12-24 # 2015-12-31 ``` Docs: * `.weekday()`: <https://docs.python.org/3/library/datetime.html#datetime.date.weekday> * `.timedelta()`: <https://docs.python.org/3/library/datetime.html#timedelta-objects> * `%` operator on negative numbers: [The modulo operation on negative numbers in Python](https://stackoverflow.com/questions/3883004/the-modulo-operation-on-negative-numbers-in-python)
67,883,300
I want to print all Thursdays between these date ranges ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date ``` What is the best pythonic way to do that?
2021/06/08
[ "https://Stackoverflow.com/questions/67883300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
using your `sdate.weekday() # returns int between 0 (mon) and 6 (sun)`: ``` sdate = ... while sdate < edate: if sdate.weekday() != 3: # not thursday sdate += timedelta(days=1) continue # It is thursday print(sdate) sdate += timedelta(days=7) # next week ```
You could try a list comprehension to get the Thursdays between the 2 dates. This code actually outputs the dates as formatted strings but you can get actual dates by dropping the `strftime`. ```py from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date thursdays = [(sdate+timedelta(days=d)).strftime('%A %Y-%m-%d') for d in range(0, (edate-sdate).days+1) if (sdate+timedelta(days=d)).weekday() ==3] print('\n'.join(thursdays)) """ Example output Thursday 2015-01-08 Thursday 2015-01-15 Thursday 2015-01-22 Thursday 2015-01-29 Thursday 2015-02-05 Thursday 2015-02-12 """" ```
67,883,300
I want to print all Thursdays between these date ranges ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date ``` What is the best pythonic way to do that?
2021/06/08
[ "https://Stackoverflow.com/questions/67883300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
Compute the number of days till thursday from the start date : ``` days_to_thursday = (3 - sdate.weekday()) % 7 ``` Compute the number of thursdays inbetween both dates: ``` week_diff = ((edate - sdate).days - days_to_thursday ) // 7 ``` Get all thursdays in the date range: ``` thursdays = [sdate + timedelta(days=days_to_thursday + 7 * more_weeks) \ for more_weeks in range(week_diff + 1) ] ``` Print them if you need: ``` for t in thursdays: print(t) ```
Simple solution: ```py from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date delta = edate - sdate for day in range(delta.days + 1): day_obj = sdate + timedelta(days=day) if day_obj.weekday() == 3: # Thursday print(day_obj) # 2015-01-08 # 2015-01-15 # ... # 2015-12-24 # 2015-12-31 ``` The most efficient solution: ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date day_index = 3 # Thursday delta = (day_index - sdate.weekday()) % 7 match = sdate + timedelta(days=delta) while match <= edate: # Change this to `<` to ignore the last one print(match) # Can be easily converted to a generator with `yield` match += timedelta(days=7) # 2015-01-08 # 2015-01-15 # ... # 2015-12-24 # 2015-12-31 ``` Docs: * `.weekday()`: <https://docs.python.org/3/library/datetime.html#datetime.date.weekday> * `.timedelta()`: <https://docs.python.org/3/library/datetime.html#timedelta-objects> * `%` operator on negative numbers: [The modulo operation on negative numbers in Python](https://stackoverflow.com/questions/3883004/the-modulo-operation-on-negative-numbers-in-python)
67,883,300
I want to print all Thursdays between these date ranges ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date ``` What is the best pythonic way to do that?
2021/06/08
[ "https://Stackoverflow.com/questions/67883300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
Most people are iterating through every day which is a waste. Also might be helpful to delay calculating the thursdays until you actually need them. For this you could use a generator. ```py def get_days(start, day_index, end=None): # set the start as the next valid day start += timedelta(days=(day_index - start.weekday()) % 7) week = timedelta(days=7) while end and start < end or not end: yield start start += week ``` This delays getting the next day until you need it, and allows infinite days if you don't specify and end date. ``` thursday_generator = get_days(date(2015, 1, 7), 3, date(2015, 12, 31)) print(list(thursday_generator)) """ [datetime.date(2015, 1, 8), datetime.date(2015, 1, 15), datetime.date(2015, 1, 22), ...] """ ``` You can easily dump as strings: ``` print("\n".join(map(str, thursday_generator))) """ 2015-01-08 2015-01-15 2015-01-22 ... """ ``` You can also use f-strings for custom string formatting: ``` print("\n".join(f"{day:%A %x}" for day in thursday_generator)) """ Thursday 01/08/15 Thursday 01/15/15 Thursday 01/22/15 ... """ ``` If you don't specify an end date, it goes on forever. ``` In [28]: thursday_generator = get_days(date(2015, 1, 7), 3) ...: print(len(list(thursday_generator))) --------------------------------------------------------------------------- OverflowError Traceback (most recent call last) <ipython-input-28-b161cdcccc75> in <module> 1 thursday_generator = get_days(date(2015, 1, 7), 3) ----> 2 print(len(list(thursday_generator))) <ipython-input-16-0691db329606> in get_days(start, day_index, end) 5 while end and start < end or not end: 6 yield start ----> 7 start += week 8 OverflowError: date value out of range ```
Simple solution: ```py from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date delta = edate - sdate for day in range(delta.days + 1): day_obj = sdate + timedelta(days=day) if day_obj.weekday() == 3: # Thursday print(day_obj) # 2015-01-08 # 2015-01-15 # ... # 2015-12-24 # 2015-12-31 ``` The most efficient solution: ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date day_index = 3 # Thursday delta = (day_index - sdate.weekday()) % 7 match = sdate + timedelta(days=delta) while match <= edate: # Change this to `<` to ignore the last one print(match) # Can be easily converted to a generator with `yield` match += timedelta(days=7) # 2015-01-08 # 2015-01-15 # ... # 2015-12-24 # 2015-12-31 ``` Docs: * `.weekday()`: <https://docs.python.org/3/library/datetime.html#datetime.date.weekday> * `.timedelta()`: <https://docs.python.org/3/library/datetime.html#timedelta-objects> * `%` operator on negative numbers: [The modulo operation on negative numbers in Python](https://stackoverflow.com/questions/3883004/the-modulo-operation-on-negative-numbers-in-python)
67,883,300
I want to print all Thursdays between these date ranges ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date ``` What is the best pythonic way to do that?
2021/06/08
[ "https://Stackoverflow.com/questions/67883300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
Compute the number of days till thursday from the start date : ``` days_to_thursday = (3 - sdate.weekday()) % 7 ``` Compute the number of thursdays inbetween both dates: ``` week_diff = ((edate - sdate).days - days_to_thursday ) // 7 ``` Get all thursdays in the date range: ``` thursdays = [sdate + timedelta(days=days_to_thursday + 7 * more_weeks) \ for more_weeks in range(week_diff + 1) ] ``` Print them if you need: ``` for t in thursdays: print(t) ```
You could try a list comprehension to get the Thursdays between the 2 dates. This code actually outputs the dates as formatted strings but you can get actual dates by dropping the `strftime`. ```py from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date thursdays = [(sdate+timedelta(days=d)).strftime('%A %Y-%m-%d') for d in range(0, (edate-sdate).days+1) if (sdate+timedelta(days=d)).weekday() ==3] print('\n'.join(thursdays)) """ Example output Thursday 2015-01-08 Thursday 2015-01-15 Thursday 2015-01-22 Thursday 2015-01-29 Thursday 2015-02-05 Thursday 2015-02-12 """" ```
67,883,300
I want to print all Thursdays between these date ranges ``` from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date ``` What is the best pythonic way to do that?
2021/06/08
[ "https://Stackoverflow.com/questions/67883300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
Most people are iterating through every day which is a waste. Also might be helpful to delay calculating the thursdays until you actually need them. For this you could use a generator. ```py def get_days(start, day_index, end=None): # set the start as the next valid day start += timedelta(days=(day_index - start.weekday()) % 7) week = timedelta(days=7) while end and start < end or not end: yield start start += week ``` This delays getting the next day until you need it, and allows infinite days if you don't specify and end date. ``` thursday_generator = get_days(date(2015, 1, 7), 3, date(2015, 12, 31)) print(list(thursday_generator)) """ [datetime.date(2015, 1, 8), datetime.date(2015, 1, 15), datetime.date(2015, 1, 22), ...] """ ``` You can easily dump as strings: ``` print("\n".join(map(str, thursday_generator))) """ 2015-01-08 2015-01-15 2015-01-22 ... """ ``` You can also use f-strings for custom string formatting: ``` print("\n".join(f"{day:%A %x}" for day in thursday_generator)) """ Thursday 01/08/15 Thursday 01/15/15 Thursday 01/22/15 ... """ ``` If you don't specify an end date, it goes on forever. ``` In [28]: thursday_generator = get_days(date(2015, 1, 7), 3) ...: print(len(list(thursday_generator))) --------------------------------------------------------------------------- OverflowError Traceback (most recent call last) <ipython-input-28-b161cdcccc75> in <module> 1 thursday_generator = get_days(date(2015, 1, 7), 3) ----> 2 print(len(list(thursday_generator))) <ipython-input-16-0691db329606> in get_days(start, day_index, end) 5 while end and start < end or not end: 6 yield start ----> 7 start += week 8 OverflowError: date value out of range ```
You could try a list comprehension to get the Thursdays between the 2 dates. This code actually outputs the dates as formatted strings but you can get actual dates by dropping the `strftime`. ```py from datetime import date, timedelta sdate = date(2015, 1, 7) # start date edate = date(2015, 12, 31) # end date thursdays = [(sdate+timedelta(days=d)).strftime('%A %Y-%m-%d') for d in range(0, (edate-sdate).days+1) if (sdate+timedelta(days=d)).weekday() ==3] print('\n'.join(thursdays)) """ Example output Thursday 2015-01-08 Thursday 2015-01-15 Thursday 2015-01-22 Thursday 2015-01-29 Thursday 2015-02-05 Thursday 2015-02-12 """" ```
64,867,992
I am using beautiful soup (BS4) with python to scrape data from the yellowpages through the waybackmachine/webarchive. I am able to return the Business name and phone number easily but when I attempt to retrieve the website url for the business, I only return the entire div tag. ``` #Import Dependencies from splinter import Browser from bs4 import BeautifulSoup import requests import pandas as pd # Path to chromedriver !which chromedriver # Set the executable path and initialize the chrome browser in splinter executable_path = {'executable_path': '/usr/local/bin/chromedriver'} browser = Browser('chrome', **executable_path) #visit Webpage url = 'https://web.archive.org/web/20171004082203/https://www.yellowpages.com/houston-tx/air-conditioning-service-repair' browser.visit(url) # Convert the browser html to a soup object and then quit the browser html = browser.html soup = BeautifulSoup(html, "html.parser") ##Scrapers #business name print(soup.find('a', class_='business-name').text) #Telephone print(soup.find('li', class_='phone primary').text) #website print(soup.find('div', class_='links')) ``` How can I return just the website URL of the company? Thanks.
2020/11/17
[ "https://Stackoverflow.com/questions/64867992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10930010/" ]
Simple and very neat solution: *(added my comments so you can understand what I did)* ``` start = int(input('enter the starting range: ')) end = int(input('enter the ending range: ')) #create an empty list numbers = [] for d in range(start,end): if d % 2 != 0: #if number is odd, add it to the list numbers.append(d) #we use end=" " to make sure there is no new line after first print print('The odd numbers between',start,'&',end,'are:',end=" ") #* symbol is used to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively print(*numbers,sep = ",") ```
Print the message before the loop then the numbers during the loop: ```py start = int(input('enter the starting range:')) end = int(input('enter the ending range:')) # use end='' to avoid printing a newline at the end print(f'The odd numbers between {start} & {end} is: ', end='') should_print_comma = False for d in range(start,end): if d%2!=0: # only start printing commas after the first element if should_print_comma: print(',', end='') print(d, end='') should_print_comma = True ```
64,867,992
I am using beautiful soup (BS4) with python to scrape data from the yellowpages through the waybackmachine/webarchive. I am able to return the Business name and phone number easily but when I attempt to retrieve the website url for the business, I only return the entire div tag. ``` #Import Dependencies from splinter import Browser from bs4 import BeautifulSoup import requests import pandas as pd # Path to chromedriver !which chromedriver # Set the executable path and initialize the chrome browser in splinter executable_path = {'executable_path': '/usr/local/bin/chromedriver'} browser = Browser('chrome', **executable_path) #visit Webpage url = 'https://web.archive.org/web/20171004082203/https://www.yellowpages.com/houston-tx/air-conditioning-service-repair' browser.visit(url) # Convert the browser html to a soup object and then quit the browser html = browser.html soup = BeautifulSoup(html, "html.parser") ##Scrapers #business name print(soup.find('a', class_='business-name').text) #Telephone print(soup.find('li', class_='phone primary').text) #website print(soup.find('div', class_='links')) ``` How can I return just the website URL of the company? Thanks.
2020/11/17
[ "https://Stackoverflow.com/questions/64867992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10930010/" ]
Using list comprehension you could make it more shorter ```py start=int(input('enter the starting range:')) end=int(input('enter the ending range:')) # New lines numbers = ", ".join([str(i) for i in range(start, end) if i % 2 != 0]) print(f"The odds numbers between {start} and {end} are:", numbers) ```
Print the message before the loop then the numbers during the loop: ```py start = int(input('enter the starting range:')) end = int(input('enter the ending range:')) # use end='' to avoid printing a newline at the end print(f'The odd numbers between {start} & {end} is: ', end='') should_print_comma = False for d in range(start,end): if d%2!=0: # only start printing commas after the first element if should_print_comma: print(',', end='') print(d, end='') should_print_comma = True ```
64,867,992
I am using beautiful soup (BS4) with python to scrape data from the yellowpages through the waybackmachine/webarchive. I am able to return the Business name and phone number easily but when I attempt to retrieve the website url for the business, I only return the entire div tag. ``` #Import Dependencies from splinter import Browser from bs4 import BeautifulSoup import requests import pandas as pd # Path to chromedriver !which chromedriver # Set the executable path and initialize the chrome browser in splinter executable_path = {'executable_path': '/usr/local/bin/chromedriver'} browser = Browser('chrome', **executable_path) #visit Webpage url = 'https://web.archive.org/web/20171004082203/https://www.yellowpages.com/houston-tx/air-conditioning-service-repair' browser.visit(url) # Convert the browser html to a soup object and then quit the browser html = browser.html soup = BeautifulSoup(html, "html.parser") ##Scrapers #business name print(soup.find('a', class_='business-name').text) #Telephone print(soup.find('li', class_='phone primary').text) #website print(soup.find('div', class_='links')) ``` How can I return just the website URL of the company? Thanks.
2020/11/17
[ "https://Stackoverflow.com/questions/64867992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10930010/" ]
Simple and very neat solution: *(added my comments so you can understand what I did)* ``` start = int(input('enter the starting range: ')) end = int(input('enter the ending range: ')) #create an empty list numbers = [] for d in range(start,end): if d % 2 != 0: #if number is odd, add it to the list numbers.append(d) #we use end=" " to make sure there is no new line after first print print('The odd numbers between',start,'&',end,'are:',end=" ") #* symbol is used to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively print(*numbers,sep = ",") ```
```py start=int(input('enter the starting range:')) end=int(input('enter the ending range:')) s = "" for d in range(start,end): if d%2!=0: s += str(d) + ", "; print('The odd numbers between',start,'&',end,'is:',s) ``` You should probably put it in a function but that's just a preference.
64,867,992
I am using beautiful soup (BS4) with python to scrape data from the yellowpages through the waybackmachine/webarchive. I am able to return the Business name and phone number easily but when I attempt to retrieve the website url for the business, I only return the entire div tag. ``` #Import Dependencies from splinter import Browser from bs4 import BeautifulSoup import requests import pandas as pd # Path to chromedriver !which chromedriver # Set the executable path and initialize the chrome browser in splinter executable_path = {'executable_path': '/usr/local/bin/chromedriver'} browser = Browser('chrome', **executable_path) #visit Webpage url = 'https://web.archive.org/web/20171004082203/https://www.yellowpages.com/houston-tx/air-conditioning-service-repair' browser.visit(url) # Convert the browser html to a soup object and then quit the browser html = browser.html soup = BeautifulSoup(html, "html.parser") ##Scrapers #business name print(soup.find('a', class_='business-name').text) #Telephone print(soup.find('li', class_='phone primary').text) #website print(soup.find('div', class_='links')) ``` How can I return just the website URL of the company? Thanks.
2020/11/17
[ "https://Stackoverflow.com/questions/64867992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10930010/" ]
Using list comprehension you could make it more shorter ```py start=int(input('enter the starting range:')) end=int(input('enter the ending range:')) # New lines numbers = ", ".join([str(i) for i in range(start, end) if i % 2 != 0]) print(f"The odds numbers between {start} and {end} are:", numbers) ```
```py start=int(input('enter the starting range:')) end=int(input('enter the ending range:')) s = "" for d in range(start,end): if d%2!=0: s += str(d) + ", "; print('The odd numbers between',start,'&',end,'is:',s) ``` You should probably put it in a function but that's just a preference.
43,247,031
I have a file named phone.py which give me output as(in terminal): ``` +911234567890 +910123321423 ``` There can be more number of outputs. Another file named email.py which produces(in terminal): ``` and@abc.com bcd@cdc.com ``` or more. And I have a JSON File whose structure is as follows: ``` {"One":"Some data", "two":"Some more data", "three":"Even more data"} ``` There can be a many more sections like this. Now I want the capture the terminal output and also load the existing JSON and finally, have an output as follows (as a JSON file): ``` {Phone:"+911234567890,+910123321423", "Email":"and@abc.com,bcd@cdc.com","Sections":"{"One":"Some data", "two":"Some more data", "three":Even more data"}"} ``` I tried to capture the output using subprocess module in python and now it is stored in a variable ``` subprocess.run(['python','email.py','filename.txt'], stdout= subprocess.PIPE) ``` output: ``` CompletedProcess(args=['python', 'email_txt.py', 'upload/filename.txt'], returncode=0, stdout=b'abc@xyz.com\nbcd@dcd.com\n') ``` I have a string in which data is stored not I want the desired output through these components. What can I do or refer to tackle this problem ?
2017/04/06
[ "https://Stackoverflow.com/questions/43247031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6541394/" ]
You can obtain the stdout from `subprocess.run` simply by `resp.stdout`, where `resp` is the returned object.
As already mentioned by Rishav, you need to assign the output to a variable & then use it to get the related attributes. [Sample usage](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess) - ``` >>> import subprocess >>> out = subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE) >>> out.stdout b'crw-rw-rw- 1 root root 1, 3 Apr 6 2017 /dev/null\n' ```
47,227,445
Im trying to make a while loop in python, but the loop keeps looping infinitely. Here's what I have so far: ``` def pvalue(num): ans = '' while num > 0: if 1 <= num <= 9: ans += 'B' num -= 1 if num >= 10: ans += 'A' num -= 10 return ans ``` I want num to be returned as ans as follows: if num is 5, I want ans to be BBBBB if num is 10, ans is A if num is 22, I want ans to be AABB.
2017/11/10
[ "https://Stackoverflow.com/questions/47227445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5016648/" ]
You may want to learn about the [break statement](https://docs.python.org/3/reference/simple_stmts.html#break). As for your code: ``` def pvalue(num): ans = '' while num > 0: if num >= 10: ans += 'A' num -= 10 else: ans += 'B' num -= 1 return ans ``` Is much better, the case when `num == 9` is now handled properly
Use the break statement to get out of the loop. ``` def pvalue(num): ans = '' while num > 0: if 1 <= num <= 9: ans += 'B' num -= 1 if num >= 10: ans += 'A' num -= 10 if num<=0: break return ans ```
68,262,836
I'm trying to use an array of dictionaries in python as arguement to a custom dash component and use it as array of objects in python : ``` audioList_py = [ { "name": "random", "singer": 'waveGAN\'s music', "cover": 'link_1.jpg', "musicSrc": 'link_1.mp3', }, { "name": "random", "singer": 'waveGAN\'s music', "cover": 'link_2.jpg', "musicSrc": 'link_2.mp3', }, ... etc ] ``` in Javascript: ``` audioList1_js = [ { name: "random", singer: 'waveGAN\'s music', cover:'link_1.jpg', musicSrc: 'link_1.mp3', }, { name: "random", singer: 'waveGAN\'s music', cover: 'link_2.jpg', musicSrc: 'link_2.mp3', }, ... etc ] ``` Here is snippet of javascript code of the dash custom component: ``` export default class MusicComponent extends Component { render() { const {id, audioLists} = this.props; return ( <div> <h1>{id}</h1> <ReactJkMusicPlayer audioLists={audio_list}/>, </div> ); } } MusicComponent.defaultProps = {}; MusicComponent.propTypes = { /** * The ID used to identify this component in Dash callbacks. */ audios: PropTypes.array, id: PropTypes.string, }; ``` And using the generated component in python: ``` app = dash.Dash(__name__) app.layout = html.Div([ music_component.MusicComponent(audios=audioList_py), html.Div(id='output'), ... etc ]) ``` But I got : ``` TypeError: The `music_component.MusicComponent` component (version 0.0.1) received an unexpected keyword argument: `audios`Allowed arguments: id ``` What I am doing wrong ? Any help or advice will be appreciated, Thanks a lot.
2021/07/05
[ "https://Stackoverflow.com/questions/68262836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13652942/" ]
Make sure you run `npm run build` after you make a change to your custom React component. With those proptypes you shouldn't get that error. If I remove the `audios` proptype I can reproduce that error. Besides that you pass a value to the `audios` property: ``` music_component.MusicComponent(audios=audioList_py) ``` but you try to retrieve `audioLists` from props: ``` const {id, audioLists} = this.props; ``` Change this to: ``` const {id, audios} = this.props; ``` Demo ``` export default class MusicComponent extends Component { render() { const {id, audios} = this.props; return ( <div> <h1>{id}</h1> <ReactJkMusicPlayer audioLists={audios} /> </div> ); } } MusicComponent.defaultProps = {}; MusicComponent.propTypes = { /** * The ID used to identify this component in Dash callbacks. */ id: PropTypes.string, audios: PropTypes.array, }; ```
Issue fixed, I should run : `npm run build:backends` to generate the Python, R and Julia class files for the components, but instead I was executing `npm run build:js` and this command just generate the JavaScript bundle (which didn't know about the new props). And set the audios property in the component to be like so: ``` MusicComponent.defaultProps = {audios: audioList1}; MusicComponent.propTypes = { id: PropTypes.string, audios: PropTypes.arrayOf(PropTypes.objectOf(PropTypes.string)).isRequired }; ```
61,976,835
I'm new to python and I've seen two different ways to initialize an empty list: ``` # way 1 empty_list = [] # way 2 other_empty_list = list() ``` Is there a "preferred" way to do it? Maybe one way is better for certain conditions than the other? Thank you
2020/05/23
[ "https://Stackoverflow.com/questions/61976835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8947060/" ]
No there isn't much of a difference, you can neglect the difference and pick anyone of them As most of the times it's a one or limited execution any difference in execution won't have much impact
Using parenthesis will create a tuple, which is immutable. A list uses brackets.
61,976,835
I'm new to python and I've seen two different ways to initialize an empty list: ``` # way 1 empty_list = [] # way 2 other_empty_list = list() ``` Is there a "preferred" way to do it? Maybe one way is better for certain conditions than the other? Thank you
2020/05/23
[ "https://Stackoverflow.com/questions/61976835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8947060/" ]
`[]` is the pythonic way. `[]` way is quite efficient as you can see from below image. [![enter image description here](https://i.stack.imgur.com/UySz6.png)](https://i.stack.imgur.com/UySz6.png)
Using parenthesis will create a tuple, which is immutable. A list uses brackets.
61,976,835
I'm new to python and I've seen two different ways to initialize an empty list: ``` # way 1 empty_list = [] # way 2 other_empty_list = list() ``` Is there a "preferred" way to do it? Maybe one way is better for certain conditions than the other? Thank you
2020/05/23
[ "https://Stackoverflow.com/questions/61976835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8947060/" ]
`[]` is the pythonic way. `[]` way is quite efficient as you can see from below image. [![enter image description here](https://i.stack.imgur.com/UySz6.png)](https://i.stack.imgur.com/UySz6.png)
No there isn't much of a difference, you can neglect the difference and pick anyone of them As most of the times it's a one or limited execution any difference in execution won't have much impact
66,062,702
I am trying to install the jupyterlab plotly extension with this command (according to <https://plotly.com/python/getting-started/>): **jupyter labextension install jupyterlab-plotly@4.14.3** I get this error: ``` An error occured. ValueError: Please install Node.js and npm before continuing installation. You may be able to install Node.js from your package manager, from conda, or directly from the Node.js website (https://nodejs.org). See the log file for details: /tmp/jupyterlab-debug-epx8b4n6.log ``` I didn't install Node.js on system level, but in a virtual environment using pip. Pip list shows both nodejs 0.1.1 and npm 0.1.1 . I am also using ipywidgets in jupyterlab, which requires nodejs and it is working fine. So I have two questions: 1. How to use plotlywidgets with pip nodejs in a virtual environment? 2. What's the difference between pip nodejs and system level Node.js
2021/02/05
[ "https://Stackoverflow.com/questions/66062702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11904988/" ]
No, you have **not** installed node.js. You installed some kind of Python bindings for node ([python-nodejs](https://pypi.org/project/nodejs/), with its [repository](https://github.com/markfinger/python-nodejs) archived by the author) which itself require an actual nodejs. It is dangerous to install stuff from PyPI without checking what you are installing. It could have been a malicious code - you shouldn't just type a name after `pip install` and hope that it installs what you think. It's the same for your `npm` installation (package comes from the same author); both were not updated in the last 6 years and may contain some vulnerabilities so I would uninstall those quickly ;) It can be seen immediately from the version number that something is wrong because the current nodejs versions are generally >10, (with exact version depending on your JupyterLab version, i.e. either 10 or 12; 14 might work too).
First install nodejs latest version `conda install nodejs -c conda-forge --repodata-fn=repodata.json` Then install jupyterlab extension: `jupyter labextension install jupyterlab-plotly@4.14.3` Then **RESTART JUPYTER LAB**
36,227,688
I have a python program that I usually run as a part of a package: ``` python -m mymod.client ``` in order to deal with relative imports inside "mymod/client.py." How do I run this with pdb - the python debugger. The following does not work: ``` python -m pdb mymod.client ``` It yields the error: ``` Error: mymod.client does not exist ``` EDIT #1 (to address possible duplicity of question) --------------------------------------------------- My question isn't really about running two modules simultaneously python, rather it is about how to use pdb on a python script that has relative imports inside it and which one usually deals with by running the script with "python -m." Restated, my question could then be, how do I use pdb on such a script while not having to change the script itself just to have it run with pdb (ie: preserving the relative imports inside the script as much as possible). Shouldn't this be possible, or am I forced to refactor in some way if I want to use pdb? If so what would be the minimal changes to the structure of the script that I'd have to introduce to allow me to leverage pdb. In summary, I don't care *how* I run the script, just so long as I can get it working with pdb without changing it's internal structure (relative imports, etc) too much.
2016/03/25
[ "https://Stackoverflow.com/questions/36227688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3357587/" ]
I *think* I have a solution. Run it like this: ``` python -m pdb path/mymod/client.py arg1 arg2 ``` that will run it as a script, but will not treat it as a package. At the top of client.py, the first line should be: ``` import mymod ``` That will get the package itself loaded. I am still playing with this, but it seems to work so far.
This is not possible. Though unstated in documentation, Python will not parse two modules via the `-m` command line option.
56,798,328
I am just beginning to use python and could use some help! I was working on a rock, paper, scissors game and I wanted to add a restart option once either the human or computer reaches 3 wins. I have looked all over for some answers but from all the other code I looked at seemed way out of my league or extremely different from what I wrote. I haven't tried using def and classes, which I saw a lot of, and made it look very simple. I know I'm probably going about this in a really round about way but I just want to finish this without completely copying someone's code. ``` import random moves = ["Rock", "Paper", "Scissors"] player_score = 0 computer_score = 0 draws = 0 keep_playing = True while keep_playing == True: cmove = random.choice(moves) pmove = input("What is your move: Rock, Paper, or Scissors?") print("The computer chose", cmove) #Logic to game if cmove == pmove: print("It's a DRAW!") elif pmove == "Rock" and cmove == "Scissors": print("--Player Wins!--") elif pmove == "Rock" and cmove == "Paper": print("--Computer Wins!--") elif cmove == "Paper" and cmove == "Rock": print("--Player Wins!--") elif pmove == "Paper" and cmove == "Scissors": print("--Computer Wins!--") elif pmove == "Scissors" and cmove == "Paper": print("--Player Wins!--") elif pmove == "Scissors" and cmove == "Rock": print("--Computer Wins!--") #Scoreboard if pmove == cmove: draws = draws + 1 print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws)) if pmove == "Rock" and cmove == "Scissors": player_score = player_score + 1 print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws)) if pmove == "Rock" and cmove == "Paper": computer_score = computer_score + 1 print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws)) if pmove == "Paper" and cmove == "Rock": player_score = player_score + 1 print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws)) if pmove == "Paper" and cmove == "Scissors": computer_score = computer_score + 1 print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws)) if pmove == "Scissors" and cmove == "Paper": player_score = player_score + 1 print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws)) if pmove == "Scissors" and cmove == "Rock": computer_score = computer_score + 1 print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws)) #Win/lose restart point? if player_score == 3: print("-----You Win!-----") break if computer_score == 3: print("-----You Lose!-----") break ``` I want the code to end saying, "You Win!" or "You Lose!"and then ask for an input to whether or not they want to restart and then it resets the scores and keeps going or if they say no it breaks.
2019/06/27
[ "https://Stackoverflow.com/questions/56798328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11606900/" ]
You already have the loop to do this. So when you want to "restart" your game, you really just need to reset the scores. Starting from your win/lose conditions: ``` #Win/lose restart point? if player_score == 3: print("-----You Win!-----") replay = input("Would you like to play again?") if replay.upper().startswith('Y'): player_score = 0 computer_score = 0 draws = 0 else: keep_playing = False if computer_score == 3: print("-----You Lose!-----") if replay.upper().startswith('Y'): player_score = 0 computer_score = 0 draws = 0 else: keep_playing = False ```
You need to get user input in the `while` loop and set `keep_playing` accordingly. ``` while keep_playing == True: cmove = random.choice(moves) pmove = input("What is your move: Rock, Paper, or Scissors?") print("The computer chose", cmove) #Logic to game if cmove == pmove: print("It's a DRAW!") elif pmove == "Rock" and cmove == "Scissors": print("--Player Wins!--") elif pmove == "Rock" and cmove == "Paper": print("--Computer Wins!--") elif cmove == "Paper" and cmove == "Rock": print("--Player Wins!--") elif pmove == "Paper" and cmove == "Scissors": print("--Computer Wins!--") elif pmove == "Scissors" and cmove == "Paper": print("--Player Wins!--") elif pmove == "Scissors" and cmove == "Rock": print("--Computer Wins!--") # new code play_again = input("Would you like to play again?") keep_playing = play_again.lower().startswith('y') # this will be set to False if the user's input doesn't start with 'y', the loop will exit ```
57,420,171
I am writing a batch file that lies somewhere in a folder structure alongside a .venv folder (python virtual environment) ``` KnownFolderName | +-- 1.0.0 | | | +-- .venv | | | +-- folder | | | +-- folder | | | +-- batch.bat | +-- 1.0.1 | +-- .venv | +-- folder | +-- batch.bat ``` I want to be able to navigate to .venv from wherever the batch file starts. If you do this manually you can just cd .. until you reach x.y.z then cd .venv But I can't work out how to automate that in a batch file. findstr doesn't return a substring match which was going to be my way to get to KnownFolderName/x.y.z directly. Maybe a looping if would work?
2019/08/08
[ "https://Stackoverflow.com/questions/57420171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/869598/" ]
Got it. Of course as soon as I post the question the answer appears! After trying all sorts of ways to extract the string from the cwd I found that just looping backwards is the way: ``` :loop IF EXIST .venv ( cd .venv\Scripts ) ELSE ( cd .. goto loop ) ``` Then you can return to the original location with the standard: ``` %~dp0 ```
What about the following approach which makes use of string manipulation features: ```cmd @echo off set "BATCH=%~f0" echo ABSOLUTE BATCH PATH: "%BATCH%" set "RELATIVE=%BATCH:*\KnownFolderName\=%" echo RELATIVE BATCH PATH: "%RELATIVE%" set "TEST=%BATCH%|" call set "ROOT=%%TEST:\%RELATIVE%|=%%" echo ROOT DIRECTORY PATH: "%ROOT%" set "VERSION=%RELATIVE:\=" & rem "%" echo VERSION NUMBER NAME: "%VERSION%" set "TARGET=%ROOT%\%VERSION%\.venv" echo DESIRED FOLDER PATH: "%TARGET%" if exist "%TARGET%\" (echo ^(WHICH EXISTS^)) else (echo ^(WHICH DOES NOT EXIST^)) pause ```
68,708,540
I want to generate random number between 0 and 1 in **python code** but only get 2 numbers after sign . Example: ``` 0.22 0.25 0.9 ``` I have searched many sources but have not found the solution. Can you help me?
2021/08/09
[ "https://Stackoverflow.com/questions/68708540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16462598/" ]
Want this? ``` import random round(random.random(), 2) ```
Try this `print(round(random.random(), 2))`
68,708,540
I want to generate random number between 0 and 1 in **python code** but only get 2 numbers after sign . Example: ``` 0.22 0.25 0.9 ``` I have searched many sources but have not found the solution. Can you help me?
2021/08/09
[ "https://Stackoverflow.com/questions/68708540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16462598/" ]
You can use the format method in python if you want EXACTLY 2 digits after the decimal point (for example if you want 0.90): ``` import random x = random.random() print("{:.2f}".format(x)) ``` or if you are fine with numbers like 0.9: ``` import random x = random.random() print(round(x,2)) ```
Try this `print(round(random.random(), 2))`
49,544,701
I'm relatively new to python, and I am trying to build a program that can visit a website using a proxy from a list of proxies in a text file, and continue doing so with each proxy in the file until they're all used. I found some code online and tweaked it to my needs, but when I run the program, the proxies are successfully used, but they don't get used in order. For whatever reason, the first proxy gets used twice in a row, then the second proxy gets used, then the first again, then third, blah blah. It doesn't go in order one by one. The proxies in the text file are organized as such: 123.45.67.89:8080 987.65.43.21:8080 And so on. Here's the code I am using: ``` from fake_useragent import UserAgent import pyautogui import webbrowser import time import random import random import requests from selenium import webdriver import os import re proxylisttext = 'proxylistlist.txt' useragent = UserAgent() profile = webdriver.FirefoxProfile() profile.set_preference("network.proxy.type", 1) profile.set_preference("network.proxy_type", 1) def Visiter(proxy1): try: proxy = proxy1.split(":") print ('Visit using proxy :',proxy1) profile.set_preference("network.proxy.http", proxy[0]) profile.set_preference("network.proxy.http_port", int(proxy[1])) profile.set_preference("network.proxy.ssl", proxy[0]) profile.set_preference("network.proxy.ssl_port", int(proxy[1])) profile.set_preference("general.useragent.override", useragent.random) driver = webdriver.Firefox(firefox_profile=profile) driver.get('https://www.iplocation.net/find-ip-address') time.sleep(2) driver.close() except: print('Proxy failed') pass def loadproxy(): try: get_file = open(proxylisttext, "r+") proxylist = get_file.readlines() writeused = get_file.write('used') count = 0 proxy = [] while count < 10: proxy.append(proxylist[count].strip()) count += 1 for i in proxy: Visiter(i) except IOError: print ("\n[-] Error: Check your proxylist path\n") sys.exit(1) def main(): loadproxy() if __name__ == '__main__': main() ``` And so as I said, this code successfully navigates to the ipchecker site using the proxy, but then it doesn't go line by line in order, the same proxy will get used multiple times. So I guess more specifically, how can I ensure the program iterates through the proxies one by one, without repeating? I have searched exhaustively for a solution, but I haven't been able to find one, so any help would be appreciated. Thank you.
2018/03/28
[ "https://Stackoverflow.com/questions/49544701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9566525/" ]
Your problem is with these nested loops, which don't appear to be doing what you want: ``` proxy = [] while count < 10: proxy.append(proxylist[count].strip()) count += 1 for i in proxy: Visiter(i) ``` The outer loop builds up the `proxy` list, adding one value each time until there are ten. After each value has been added, the inner loop iterates over the `proxy` list that has been built so far, visiting each item. I suspect you want to unnest the loops. That way, the `for` loop will only run after the `while` loop has completed, and so it will only visit each proxy once. Try something like this: ``` proxy = [] while count < 10: proxy.append(proxylist[count].strip()) count += 1 for i in proxy: Visiter(i) ``` You could simplify that into a single loop, if you want. For instance, using `itertools.islice` to handle the bounds checking, you could do: ``` for proxy in itertools.islice(proxylist, 10): Visiter(proxy.strip()) ``` You could even run that directly on the file object (since files are iterable) rather than calling `readlines` first, to read it into a list. (You might then need to add a `seek` call on the file before writing `"used"`, but you may need that anyway, some OSs don't allow you to mix reads and writes without seeking in between.)
`while count < 10: proxy.append(proxylist[count].strip()) count += 1 for i in proxy: Visiter(i)` The for loop within the while loop means that every time you hit proxy.append you'll call Visiter for *every* item already in proxy. That might explain why you're getting multiple hits per proxy. As far as the out of order issue, I'm not sure why readlines() isn't maintaining the line order of your file but I'd try something like: `with open('filepath', 'r') as file: for line in file: do_stuff_with_line(line)` With the above you don't need to hold the whole file in memory at once either which ca be nice for big files. Good luck!
4,778,679
i have no way of upgrade to python 2.7 or 3.1 so i am stuck with python 2.6 on my ubuntu 10.04 machine. will i still be able to find host that supports python 2.6? is using python 2.6 still consider outdated or bad practice?
2011/01/24
[ "https://Stackoverflow.com/questions/4778679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62617/" ]
2.6 will be around for a long time. There are many machines that still run even 2.4, so you're fine.
Python3.1 is in the repositories for 10.04 ``` $ apt-cache show python3 Package: python3 Priority: optional Section: python Installed-Size: 76 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Original-Maintainer: Matthias Klose <doko@debian.org> Architecture: all Source: python3-defaults Version: 3.1.2-0ubuntu1 Depends: python3.1 (>= 3.1.2), python3-minimal (= 3.1.2-0ubuntu1) Suggests: python3-doc (>= 3.1.2-0ubuntu1), python3-tk (>= 3.1.2-0ubuntu1), python3-profiler (>= 3.1.2-0ubuntu1) Filename: pool/main/p/python3-defaults/python3_3.1.2-0ubuntu1_all.deb Size: 11096 MD5sum: 81f3f3bf790f5d7756b76c8d92fcea86 SHA1: 32e12dc7f9500456e063f22645c1cfed76b8845c SHA256: 0f541352ace2fcf1929a93320ffbe2f1de4e1d140bbe70a7c5a709403b73341c Description: An interactive high-level object-oriented language (default python3 version) Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python version (currently v3.1). Bugs: https://bugs.launchpad.net/ubuntu/+filebug Origin: Ubuntu Supported: 3y ```
4,778,679
i have no way of upgrade to python 2.7 or 3.1 so i am stuck with python 2.6 on my ubuntu 10.04 machine. will i still be able to find host that supports python 2.6? is using python 2.6 still consider outdated or bad practice?
2011/01/24
[ "https://Stackoverflow.com/questions/4778679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62617/" ]
2.6 will be around for a long time. There are many machines that still run even 2.4, so you're fine.
> > will i still be able to find host that > supports python 2.6? > > > Yes. No problems whatsoever. > > is using python 2.6 still consider > outdated or bad practice? > > > No, it is not. **However:** > > I have no way of upgrade to python 2.7 > > > **Yes you do.** You download the source code from www.python.org and install it. What you should be careful to do in *not* to overwrite the system Python. Install it either with "altinstall" (will not override the system python) or even better, use a custom prefix. For example: ``` $ ./configure --prefix = /opt/python27 $ make $ sudo make install ``` It is often a good idea to use a separate Python install for development, as you can do whatever you want with it including deleting it and reinstalling it without affecting the system Python. You are NOT stuck. :) I'm Using Ubuntu 10.04 as well I have Python 2.3.7, 2.4.6, 2.5.5, 2.6.6, 2.7.1, 3.0.1, 3.1.2 and 3.2b2+ installed. No problems. Yes, I use all of them, even though it's mostly 2.4 and 2.6.
4,778,679
i have no way of upgrade to python 2.7 or 3.1 so i am stuck with python 2.6 on my ubuntu 10.04 machine. will i still be able to find host that supports python 2.6? is using python 2.6 still consider outdated or bad practice?
2011/01/24
[ "https://Stackoverflow.com/questions/4778679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62617/" ]
Python 2.6 will probably still be around for a while, as Python 2.7 was released only a few months ago. You can always use `from __future__ import ...` to make use of some of the newer features from Python 3.x
Python3.1 is in the repositories for 10.04 ``` $ apt-cache show python3 Package: python3 Priority: optional Section: python Installed-Size: 76 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Original-Maintainer: Matthias Klose <doko@debian.org> Architecture: all Source: python3-defaults Version: 3.1.2-0ubuntu1 Depends: python3.1 (>= 3.1.2), python3-minimal (= 3.1.2-0ubuntu1) Suggests: python3-doc (>= 3.1.2-0ubuntu1), python3-tk (>= 3.1.2-0ubuntu1), python3-profiler (>= 3.1.2-0ubuntu1) Filename: pool/main/p/python3-defaults/python3_3.1.2-0ubuntu1_all.deb Size: 11096 MD5sum: 81f3f3bf790f5d7756b76c8d92fcea86 SHA1: 32e12dc7f9500456e063f22645c1cfed76b8845c SHA256: 0f541352ace2fcf1929a93320ffbe2f1de4e1d140bbe70a7c5a709403b73341c Description: An interactive high-level object-oriented language (default python3 version) Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python version (currently v3.1). Bugs: https://bugs.launchpad.net/ubuntu/+filebug Origin: Ubuntu Supported: 3y ```
4,778,679
i have no way of upgrade to python 2.7 or 3.1 so i am stuck with python 2.6 on my ubuntu 10.04 machine. will i still be able to find host that supports python 2.6? is using python 2.6 still consider outdated or bad practice?
2011/01/24
[ "https://Stackoverflow.com/questions/4778679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62617/" ]
Python 2.6 will probably still be around for a while, as Python 2.7 was released only a few months ago. You can always use `from __future__ import ...` to make use of some of the newer features from Python 3.x
> > will i still be able to find host that > supports python 2.6? > > > Yes. No problems whatsoever. > > is using python 2.6 still consider > outdated or bad practice? > > > No, it is not. **However:** > > I have no way of upgrade to python 2.7 > > > **Yes you do.** You download the source code from www.python.org and install it. What you should be careful to do in *not* to overwrite the system Python. Install it either with "altinstall" (will not override the system python) or even better, use a custom prefix. For example: ``` $ ./configure --prefix = /opt/python27 $ make $ sudo make install ``` It is often a good idea to use a separate Python install for development, as you can do whatever you want with it including deleting it and reinstalling it without affecting the system Python. You are NOT stuck. :) I'm Using Ubuntu 10.04 as well I have Python 2.3.7, 2.4.6, 2.5.5, 2.6.6, 2.7.1, 3.0.1, 3.1.2 and 3.2b2+ installed. No problems. Yes, I use all of them, even though it's mostly 2.4 and 2.6.
4,778,679
i have no way of upgrade to python 2.7 or 3.1 so i am stuck with python 2.6 on my ubuntu 10.04 machine. will i still be able to find host that supports python 2.6? is using python 2.6 still consider outdated or bad practice?
2011/01/24
[ "https://Stackoverflow.com/questions/4778679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62617/" ]
> > will i still be able to find host that > supports python 2.6? > > > Yes. No problems whatsoever. > > is using python 2.6 still consider > outdated or bad practice? > > > No, it is not. **However:** > > I have no way of upgrade to python 2.7 > > > **Yes you do.** You download the source code from www.python.org and install it. What you should be careful to do in *not* to overwrite the system Python. Install it either with "altinstall" (will not override the system python) or even better, use a custom prefix. For example: ``` $ ./configure --prefix = /opt/python27 $ make $ sudo make install ``` It is often a good idea to use a separate Python install for development, as you can do whatever you want with it including deleting it and reinstalling it without affecting the system Python. You are NOT stuck. :) I'm Using Ubuntu 10.04 as well I have Python 2.3.7, 2.4.6, 2.5.5, 2.6.6, 2.7.1, 3.0.1, 3.1.2 and 3.2b2+ installed. No problems. Yes, I use all of them, even though it's mostly 2.4 and 2.6.
Python3.1 is in the repositories for 10.04 ``` $ apt-cache show python3 Package: python3 Priority: optional Section: python Installed-Size: 76 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Original-Maintainer: Matthias Klose <doko@debian.org> Architecture: all Source: python3-defaults Version: 3.1.2-0ubuntu1 Depends: python3.1 (>= 3.1.2), python3-minimal (= 3.1.2-0ubuntu1) Suggests: python3-doc (>= 3.1.2-0ubuntu1), python3-tk (>= 3.1.2-0ubuntu1), python3-profiler (>= 3.1.2-0ubuntu1) Filename: pool/main/p/python3-defaults/python3_3.1.2-0ubuntu1_all.deb Size: 11096 MD5sum: 81f3f3bf790f5d7756b76c8d92fcea86 SHA1: 32e12dc7f9500456e063f22645c1cfed76b8845c SHA256: 0f541352ace2fcf1929a93320ffbe2f1de4e1d140bbe70a7c5a709403b73341c Description: An interactive high-level object-oriented language (default python3 version) Python, the high-level, interactive object oriented language, includes an extensive class library with lots of goodies for network programming, system administration, sounds and graphics. . This package is a dependency package, which depends on Debian's default Python version (currently v3.1). Bugs: https://bugs.launchpad.net/ubuntu/+filebug Origin: Ubuntu Supported: 3y ```
61,804,295
I am using python to do some data cleaning and i've used the datetime module to split date time and tried to create another column with just the time. My script works but it just takes the last value of the data frame. Here is the code: ``` import datetime i = 0 for index, row in df.iterrows(): date = datetime.datetime.strptime(df.iloc[i, 0], "%Y-%m-%dT%H:%M:%SZ") df['minutes'] = date.minute i = i + 1 ``` This is the dataframe : [Output](https://i.stack.imgur.com/uVQsA.png)
2020/05/14
[ "https://Stackoverflow.com/questions/61804295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13543531/" ]
`df['minutes'] = date.minute` reassigns the entire `'minutes'` column with the scalar value `date.minute` from the last iteration. You don't need a loop, as 99% of the cases when using pandas. You can use vectorized assignment, just replace `'source_column_name'` with the name of the column with the source data. ``` df['minutes'] = pd.to_datetime(df['source_column_name'], format='%Y-%m-%dT%H:%M:%SZ').dt.minute ``` It is also most likely that you won't need to specify `format` as `pd.to_datetime` is fairly smart. Quick example: ``` df = pd.DataFrame({'a': ['2020.1.13', '2019.1.13']}) df['year'] = pd.to_datetime(df['a']).dt.year print(df) ``` outputs ``` a year 0 2020.1.13 2020 1 2019.1.13 2019 ```
Seems like you're trying to get the time column from the datetime which is in string format. That's what I understood from your post. Could you give this a shot? ``` from datetime import datetime import pandas as pd def get_time(date_cell): dt = datetime.strptime(date_cell, "%Y-%m-%dT%H:%M:%SZ") return datetime.strftime(dt, "%H:%M:%SZ") df['time'] = df['date_time'].apply(get_time) ```
66,402,926
I am new to python and I want to know how to create empty column with a specific number. Let's say I want to create 20 columns. What I tried: ``` import pandas as pd num =20 for i in range(num): df = df + pd.DataFrame(columns=['col'+str(i)]) ``` But I got the unwanted result: ``` Empty DataFrame Columns: [col0, col1, col10, col11, col12, col13, col14, col15, col16, col17, col18, col19, col2, col3, col4, col5, col6, col7, col8, col9] Index: [] ``` Desired result: ``` Empty DataFrame Columns: [col0, col1, col2,...,col19] Index: [] ``` How to rectify it? Any help will be much appreciated!
2021/02/27
[ "https://Stackoverflow.com/questions/66402926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13230133/" ]
Assuming you wish to create an empty dataframe, the solution is to remove the for loop, and use a list comprehension for the column names: ``` import pandas as pd num =20 df = pd.DataFrame(columns=['col'+str(i) for i in range(num)]) ```
Instead of adding dataframes together, let's just create a dictionary with the mappings you'd like, and create one dataframe: ``` data = {"col" + str(i): [] for i in range(20)} df = pd.DataFrame(data) #Empty DataFrame #Columns: [col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14, col15, col16, col17, col18, col19] #Index: [] ```
35,328,941
In python / numpy - is there a way to build an expression containing factorials - but since in my scenario, many factorials will be duplicated or reduced, wait until I instruct the run time to compute it. Let's say `F(x) := x!` And I build an expression like `(F(6) + F(7)) / F(4)` - I can greatly accelerate this, even do it in my head by doing ``` (F(6) * (1 + 7)) / F(4) = 5 * 6 * 8 = 240 ``` Basically, I'm going to generate such expressions and would like the computer to be smart, not compute all factorials by multiplying to 1, i.e using my example not actually do ``` (6*5*4*3*2 + 7*6*5*4*3*2) / 4*3*2 ``` I've actually started developing a Factorial class, but I'm new to python and numpy and was wondering if this is a problem that's already solved.
2016/02/11
[ "https://Stackoverflow.com/questions/35328941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
As @Oleg has suggested, you can do this with sympy: ``` import numpy as np import sympy as sp # preparation n = sp.symbols("n") F = sp.factorial # create the equation f = (F(n) + F(n + 1)) / F(n - 2) print(f) # => (factorial(n) + factorial(n + 1))/factorial(n - 2) # reduce it f = f.simplify() print(f) # => n*(n - 1)*(n + 2) # evaluate it in SymPy # Note: very slow! print(f.subs(n, 6)) # => 240 # turn it into a numpy function # Note: much faster! f = sp.lambdify(n, f, "numpy") a = np.arange(2, 10) print(f(a)) # => [ 8 30 72 140 240 378 560 792] ```
Maybe you could look into increasing the efficiency using table lookups if space efficiency isn't a major concern. It would greatly reduce the number of repeated calculations. The following isn't terribly efficient, but it's the basic idea. ``` cache = {1:1} def cached_factorial(n): if (n in cache): return cache[n] else: result = n * cached_factorial(n-1) cache[n] = result return result ```
34,394,578
I am using python 2.7.8. I have a website which contains text written with bullets list which is ordered list aka <**ol**> . I want to extract those text i.e ``` Coffee Tea Milk ``` My html code: ``` <!DOCTYPE html> <html> <body> <ol type="I"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol> <ol type="a"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol> <ol type="1"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol> </body> </html> ``` The code which is i am constantly trying is not working bcz on the way i am every time getting Error. Python code: ``` import urllib2 from urllib2 import Request import re from bs4 import BeautifulSoup url = "http://www.sanfoundry.com/c-programming-questions-answers-variable-names-1/" #url="http://www.sanfoundry.com/c-programming-questions-answers-variable-names-2/" req = Request(url) resp = urllib2.urlopen(req) htmls = resp.read() c=0; soup = BeautifulSoup(htmls, 'lxml') #skipp portion of code res2 = soup.find('h1',attrs={"class":"entry-title"}) br = soup.find('span',attrs={'class':'IL_ADS'}) br = soup.find('p').text # separate title for question in soup.find_all(text=re.compile(r"^\d+\.")): answers = [br.next_sibling.strip() for br in question.find_next_siblings("br")] #s = ''.join([i for i in question if not i.isdigit()]) if not answers: break print question.encode('utf-8') ul = question.find_next_sibling("ul") print(ul.get_text(' ', strip=True)) ``` but when i run this code i got also Error: ``` Traceback (most recent call last): File "C:\Users\DELL\Desktop\python\s\fyp\crawldataextraction.py", line 47, in <module> print(ul.get_text(' ', strip=True)) AttributeError: 'NoneType' object has no attribute 'get_text' ```
2015/12/21
[ "https://Stackoverflow.com/questions/34394578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3440716/" ]
You can see why it is that beautifulsoup function does not work for your variable 'ul" by inserting this line while commenting out the line you previously had. ``` print ul """print(ul.get_text(' ', strip=True))""" ``` What is happening is that your variable ul is storing the string: 1. C99 standard guarantees uniqueness of \_\_\_\_ characters for internal names. None 2. C99 standard guarantess uniqueness of \_\_\_\_\_ characters for external names. None 3. Which of the following is not a valid variable name declaration? None 4. Which of the following is not a valid variable name declaration? None 5. Variable names beginning with underscore is not encouraged. Why? None 6. All keywords in C are in None 7. Variable name resolving (number of significant characters for uniqueness of variable) depends on None 8. Which of the following is not a valid C variable name? None 9. Which of the following is true for variable names in C? None But since there is no ul tag for beautifulsoup to find inside of ul, your ul.get\_text method does not work. So in this case, the way I would go about stripping the spaces would be to use regex. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Answer about removing number and dots. ``` import urllib2 from urllib2 import Request import re from bs4 import BeautifulSoup url = "http://www.sanfoundry.com/c-programming-questions-answers-variable-names-1/" #url="http://www.sanfoundry.com/c-programming-questions-answers-variable-names-2/" req = Request(url) resp = urllib2.urlopen(req) htmls = resp.read() c = 0 soup = BeautifulSoup(htmls, 'lxml') # skipp portion of code res2 = soup.find('h1', attrs={"class": "entry-title"}) br = soup.find('span', attrs={'class': 'IL_ADS'}) br = soup.find('p').text # separate title for question in soup.find_all(text=re.compile(r"^\d+\.")): answers = [br.next_sibling.strip() for br in question.find_next_siblings("br")] # s = ''.join([i for i in question if not i.isdigit()]) if not answers: break ul = question.encode('utf-8') ol = re.compile('[\d][.]') ol = ol.sub(' ', str(ul)) print ol """print(ul.get_text(' ', strip=True))""" ``` Output: ``` C99 standard guarantees uniqueness of ____ characters for internal names. C99 standard guarantess uniqueness of _____ characters for external names. Which of the following is not a valid variable name declaration? Which of the following is not a valid variable name declaration? Variable names beginning with underscore is not encouraged. Why? All keywords in C are in Variable name resolving (number of significant characters for uniqueness of variable) depends on Which of the following is not a valid C variable name? Which of the following is true for variable names in C? ``` I used regex to compile the pattern of number followed by a dot. Then used the re.sub() function to replace it with a space.
I never used the BeautifulSoup, but I do this with regular expression: ``` import re html = """<!DOCTYPE html> <html> <body> <ol type="I"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol> <ol type="a"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol> <ol type="1"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ol> </body> </html>""" regexp = re.compile('<li>(\w+)<\/li>') result = regexp.findall(html) for i in result: print(i) ```
4,387,847
Assuming i have a class that implements several methods. We want a user to chose to which methods to run among the exisiting methods or he can decide to add any method on\_the\_fly. from example ``` class RemoveNoise(): pass ``` then methods are added as wanted ``` RemoveNoise.raw = Raw() RemoveNoise.bais = Bias() etc ``` he can even write a new one ``` def new(): pass ``` and also add the `new()` method ``` RemoveNoise.new=new run(RemoveNoise) ``` `run()` is a function that evaluates such a class. I want to save the class\_with\_the\_methods\_used and link this class to the object created. Any hints on how to solve this in python?
2010/12/08
[ "https://Stackoverflow.com/questions/4387847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535019/" ]
Functions can be added to a class at runtime. ``` class Foo(object): pass def bar(self): print 42 Foo.bar = bar Foo().bar() ```
There is no solving needed, you just do it. Here is your code, with the small changes needed: ``` class RemoveNoise(): pass RemoveNoise.raw = Raw RemoveNoise.bias = Bias def new(self): pass RemoveNoise.new=new instance = RemoveNoise() ``` It's that simple. Python is wonderful. Why on earth you would need this is beyond me, though.
4,387,847
Assuming i have a class that implements several methods. We want a user to chose to which methods to run among the exisiting methods or he can decide to add any method on\_the\_fly. from example ``` class RemoveNoise(): pass ``` then methods are added as wanted ``` RemoveNoise.raw = Raw() RemoveNoise.bais = Bias() etc ``` he can even write a new one ``` def new(): pass ``` and also add the `new()` method ``` RemoveNoise.new=new run(RemoveNoise) ``` `run()` is a function that evaluates such a class. I want to save the class\_with\_the\_methods\_used and link this class to the object created. Any hints on how to solve this in python?
2010/12/08
[ "https://Stackoverflow.com/questions/4387847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535019/" ]
Functions can be added to a class at runtime. ``` class Foo(object): pass def bar(self): print 42 Foo.bar = bar Foo().bar() ```
Well, here's some code that does what I think you're asking for -- although I'm not really sure what you meant by "**save**" when you wrote "I want to save the class\_with\_the\_methods\_used". Also note that using an `exec` statement on user input can be *extremely* dangerous if it comes from an untrusted source. ``` import copy # an empty "template" class class Generic(): pass # predefined functions that create common methods def Raw(): def raw(self): print 'in Raw method of instance', id(self) return raw def Bias(): def bias(self): print 'in Bias method of instance', id(self) return bias def user_new_function(definition): tempdict = {} exec definition in tempdict return tempdict['new'] # create a new class RemoveNoise = copy.deepcopy(Generic) RemoveNoise.__name__ = 'RemoveNoise' # change the class name of the copy # add a couple of predefined methods RemoveNoise.raw = Raw() RemoveNoise.bias = Bias() # add user defined 'new' method user_new_def = """\ def new(self): print 'in user defined method "new" of instance', id(self) """ RemoveNoise.new = user_new_function(user_new_def) # create and use an instance of dynamically defined class instance = RemoveNoise() print 'RemoveNoise instance "{}" created'.format(id(instance)) # RemoveNoise instance "11974736" created instance.raw() # in Raw method of instance 11974736 instance.bias() # in Bias method of instance 11974736 instance.new() # in user defined method "new" of instance 11974736 ```
4,387,847
Assuming i have a class that implements several methods. We want a user to chose to which methods to run among the exisiting methods or he can decide to add any method on\_the\_fly. from example ``` class RemoveNoise(): pass ``` then methods are added as wanted ``` RemoveNoise.raw = Raw() RemoveNoise.bais = Bias() etc ``` he can even write a new one ``` def new(): pass ``` and also add the `new()` method ``` RemoveNoise.new=new run(RemoveNoise) ``` `run()` is a function that evaluates such a class. I want to save the class\_with\_the\_methods\_used and link this class to the object created. Any hints on how to solve this in python?
2010/12/08
[ "https://Stackoverflow.com/questions/4387847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535019/" ]
There is no solving needed, you just do it. Here is your code, with the small changes needed: ``` class RemoveNoise(): pass RemoveNoise.raw = Raw RemoveNoise.bias = Bias def new(self): pass RemoveNoise.new=new instance = RemoveNoise() ``` It's that simple. Python is wonderful. Why on earth you would need this is beyond me, though.
Well, here's some code that does what I think you're asking for -- although I'm not really sure what you meant by "**save**" when you wrote "I want to save the class\_with\_the\_methods\_used". Also note that using an `exec` statement on user input can be *extremely* dangerous if it comes from an untrusted source. ``` import copy # an empty "template" class class Generic(): pass # predefined functions that create common methods def Raw(): def raw(self): print 'in Raw method of instance', id(self) return raw def Bias(): def bias(self): print 'in Bias method of instance', id(self) return bias def user_new_function(definition): tempdict = {} exec definition in tempdict return tempdict['new'] # create a new class RemoveNoise = copy.deepcopy(Generic) RemoveNoise.__name__ = 'RemoveNoise' # change the class name of the copy # add a couple of predefined methods RemoveNoise.raw = Raw() RemoveNoise.bias = Bias() # add user defined 'new' method user_new_def = """\ def new(self): print 'in user defined method "new" of instance', id(self) """ RemoveNoise.new = user_new_function(user_new_def) # create and use an instance of dynamically defined class instance = RemoveNoise() print 'RemoveNoise instance "{}" created'.format(id(instance)) # RemoveNoise instance "11974736" created instance.raw() # in Raw method of instance 11974736 instance.bias() # in Bias method of instance 11974736 instance.new() # in user defined method "new" of instance 11974736 ```
53,469,407
I got into automating tasks on the web using python. I have tried requests/urllib3/requests-html but they don't get me the right elements, because they get only the `html` (not the updated version with `javascript`). Some recommended Selenium, but it opens a browser with the `webdriver`. I need a way to get elements after they get updated, and maybe after they get updated for a second time. The reason I don't want it to open a browser is I'm running my script on a hosting-scripts service.
2018/11/25
[ "https://Stackoverflow.com/questions/53469407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9534986/" ]
Don't overthink this. It seems that everything you have in your object gets allocated there, so use smart pointers: ``` std::vector<std::unique_ptr<Object>> pointer_vector; ```
Every object that you create with `new` will have to be `delete`ed at some point. It's your responsibility to do that. In your case the easiest solution is to add it in the destructor for your `Problem` class. ``` Problem::~Problem() { for (auto ptr : pointer_vector) delete ptr; } ``` If you ever remove objects from the vector, you have to make sure that they are `delete`d there as well. **Please Note:** the proper way to do this is however to use smart pointers as Matthieu already said in his answer.
58,194,852
I am trying to load a pkl file, ``` pkl_file = open(sys.argv[1], 'rb') world = pickle.load(pkl_file) ``` but I get an error from these lines ``` Traceback (most recent call last): File "E:/python/test.py", line 186, in <module> world = pickle.load(pkl_file) ModuleNotFoundError: No module named 'numpy.core.multiarray\r' ``` I am using Windows 10, python 3.7, and installed four packages (numpy 1.17.2, opencv-python 4.1.1.26, pip 19.2.3, setuptools 41.2.0 ). I have tried to change "rb" to "r", but still got the error, how can I fix this?
2019/10/02
[ "https://Stackoverflow.com/questions/58194852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7548018/" ]
I think there are two problems here. First, your pickle is or contains a [NumPy](https://numpy.org/) object, which is not part of the standard library. Therefore you must ensure that NumPy is installed into your current Python environment and imported **before** you try to load the pickled object. Depending on your setup, installation may be as simple as, ``` pip install numpy ``` Then you must add the line, ```py import numpy as np ``` to the top of your script. Second, it looks like Python is encountering [this issue](https://stackoverflow.com/questions/8527241/python-pickle-fix-r-characters-before-loading), where your binary file was erroneously saved as text on Windows, resulting in resulted in each `'\n'` being converted to `'\r\n'`. To fix this, you must re-convert to `'\r\n'` back to `'\n'`. So long as the file isn't **huge**, this usually isn't very painful. Here is a relatively complete example: ```py import sys import numpy as np src = sys.argv[1] # path to your file data = open(src).read().replace('\r\n', '\n') # read and replace file contents dst = src + ".tmp" open(dst, "w").write(data) # save a temporary file world = pickle.load(open(dst, "rb"), encoding='latin1') ```
Ok, I just had to figure this out for myself, and I solved it. All you have to do is change all the "\r\n" to "\n". You can do this in multiple ways. You can go into Notepad++ and change line endings from CR LF to just LF. Or programmatically you can do ``` open(newfile, 'w', newline = '\n').write(open(oldfile, 'r').read()) ```
31,575,359
I recently downloaded some software that requires one to change to the directory with python files, and run `python setup.py install --user` in the Terminal. One then checks whether the code is running correctly by trying `from [x] import [y]` This works on my Terminal. However, when I then try `from [x] import [y]` in the notebook, it never works. So, this makes me think I must install the `setup.py` file within the iPython notebook. How does one do this?
2015/07/22
[ "https://Stackoverflow.com/questions/31575359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4596596/" ]
What about using the following selector: `input[id^='something_stuff_'][id$='_work']` It will get inputs with id starting with "something\_stuff\_" and finishing with "\_work".
An approach to this problem would be to use classes instead of ids and have things that are styled the same to be classed the same. for example: ``` <input id="something_stuff_01_work" class="input_class"> <input id="something_stuff_02_work" class="input_class"> <input id="something_stuff_03_work" class="input_class"> ``` Then select the class instead of the id. ``` .input_class { sweetstyleofawesomeness; } ```
31,575,359
I recently downloaded some software that requires one to change to the directory with python files, and run `python setup.py install --user` in the Terminal. One then checks whether the code is running correctly by trying `from [x] import [y]` This works on my Terminal. However, when I then try `from [x] import [y]` in the notebook, it never works. So, this makes me think I must install the `setup.py` file within the iPython notebook. How does one do this?
2015/07/22
[ "https://Stackoverflow.com/questions/31575359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4596596/" ]
What about using the following selector: `input[id^='something_stuff_'][id$='_work']` It will get inputs with id starting with "something\_stuff\_" and finishing with "\_work".
CSS does not support regexes in selectors. Use classes or starts-from and ends-with attribute selectors.
31,575,359
I recently downloaded some software that requires one to change to the directory with python files, and run `python setup.py install --user` in the Terminal. One then checks whether the code is running correctly by trying `from [x] import [y]` This works on my Terminal. However, when I then try `from [x] import [y]` in the notebook, it never works. So, this makes me think I must install the `setup.py` file within the iPython notebook. How does one do this?
2015/07/22
[ "https://Stackoverflow.com/questions/31575359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4596596/" ]
What about using the following selector: `input[id^='something_stuff_'][id$='_work']` It will get inputs with id starting with "something\_stuff\_" and finishing with "\_work".
Try prefixing the numeric id with \3. I came across this today, it was the selector generated using chrometools, I'd not seen it before, and it works using Chromium Webdriver: #\37 Full selector used is "#\37 > div > div.cell-text". This was a selector to select an element with id = "7". It (prefixing with \3) seems to work throughout the document I am looking at automating, with my current setup.
31,575,359
I recently downloaded some software that requires one to change to the directory with python files, and run `python setup.py install --user` in the Terminal. One then checks whether the code is running correctly by trying `from [x] import [y]` This works on my Terminal. However, when I then try `from [x] import [y]` in the notebook, it never works. So, this makes me think I must install the `setup.py` file within the iPython notebook. How does one do this?
2015/07/22
[ "https://Stackoverflow.com/questions/31575359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4596596/" ]
An approach to this problem would be to use classes instead of ids and have things that are styled the same to be classed the same. for example: ``` <input id="something_stuff_01_work" class="input_class"> <input id="something_stuff_02_work" class="input_class"> <input id="something_stuff_03_work" class="input_class"> ``` Then select the class instead of the id. ``` .input_class { sweetstyleofawesomeness; } ```
Try prefixing the numeric id with \3. I came across this today, it was the selector generated using chrometools, I'd not seen it before, and it works using Chromium Webdriver: #\37 Full selector used is "#\37 > div > div.cell-text". This was a selector to select an element with id = "7". It (prefixing with \3) seems to work throughout the document I am looking at automating, with my current setup.
31,575,359
I recently downloaded some software that requires one to change to the directory with python files, and run `python setup.py install --user` in the Terminal. One then checks whether the code is running correctly by trying `from [x] import [y]` This works on my Terminal. However, when I then try `from [x] import [y]` in the notebook, it never works. So, this makes me think I must install the `setup.py` file within the iPython notebook. How does one do this?
2015/07/22
[ "https://Stackoverflow.com/questions/31575359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4596596/" ]
CSS does not support regexes in selectors. Use classes or starts-from and ends-with attribute selectors.
Try prefixing the numeric id with \3. I came across this today, it was the selector generated using chrometools, I'd not seen it before, and it works using Chromium Webdriver: #\37 Full selector used is "#\37 > div > div.cell-text". This was a selector to select an element with id = "7". It (prefixing with \3) seems to work throughout the document I am looking at automating, with my current setup.
43,994,599
Thanks to [Python Library](https://docs.python.org/2/library/telnetlib.html "Library") i was able to use their example to telnet to Cisco switches, I am using this for learning purposes, specifically learning python. However, although all the code seem generally easy to read, I am a bit confused as to the following: 1- why use the if statement below 2- why use the "\n" after the username and password write method 3- why am i not getting the output on my bash terminal when the changes are infact committed and successful ``` HOST = "172.16.1.76" user = raw_input("Enter your Telnet username : ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("Username: ") tn.write(user + '\n') <----- 2 if password: <----- 1 tn.read_until("Password: ") tn.write(password + "\n") <------2 tn.write("show run \n") time.sleep(5) output = tn.read_all() <----- 3 print output print "=" * 30 print "Configuration Complete." ``` I am not sure as to why using the if statement above, typically once you input in the Username, you get the password prompt right afterward. why cant we just type : ``` tn.read_until("Username: ") tn.write(user + '\n') tn.read_until("Password: ") tn.write(password + "\n") ``` As for the second point, why use the '\n' after the passwords and username in the write method if we going to hit enter after we add them anyway?
2017/05/16
[ "https://Stackoverflow.com/questions/43994599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736707/" ]
It looks like `PyCrypto` is [not being maintained currently](https://github.com/dlitz/pycrypto/issues/168). So, it's better you switch to [PyCryptodome](https://pypi.python.org/pypi/pycryptodome). ``` pip install pycryptodome ``` If you still want to use PyCrypto you could still try, > > <https://packaging.python.org/extensions/#setting-up-a-build-environment-on-windows> > > > <https://stackoverflow.com/a/33338523/887007> > > > <https://stackoverflow.com/a/27327236/887007> > > >
If doing `python -m Cryptodome.SelfTest` is giving you an error, you can do: ``` pip uninstall pycryptodome ``` and then: ``` easy_install pycryptodome ``` Even after this, running `python -m Cryptodome.SelfTest` was giving me an error, but when I re-ran the file, it worked.
18,615,524
I'm trying to get the valid python list from the response of a server like you can see below: > > window.\_\_search.list=[{"order":"1","base":"LAW","n":"148904","access":{"css":"avail\_yes","title":"\u042 > 2\u0435\u043a\u0441\u0442\u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0434\u043e\u0441\u0442\u0443\u043f\u0435\u043d"},"title":"\"\u0410\u0440\u0431\u0438\u0442\u0440\u0430\u0436\u043d\u044b\u0439\u043f\u0440\u043e\u0446\u0435\u0441\u0441\u0443\u0430\u043b\u044c\u043d\u044b\u0439\u043a\u043e\u0434\u0435\u043a\u0441\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u043e\u0439\u0424\u0435\u0434\u0435\u0440\u0430\u0446\u0438\u0438\" \u043e\u0442 24.07.2002 N 95-\u0424\u0417 (\u0440\u0435\u0434. \u043e\u0442 02.07.2013) (\u0441 \u0438\u0437\u043c. \u0438 \u0434\u043e\u043f.,\u0432\u0441\u0442\u0443\u043f\u0430 \u044e\u0449\u0438\u043c\u0438\u0432 \u0441\u0438\u043b\u0443 \u0441 01.08.2013)"}, ... }]; > > > I did it through cutting off "window.\_\_search.list=" and ";" from the string using `data = json.loads(re.search(r"(?=\[)(.*?)\s*(?=\;)", url).group(1))` and then it was looked like standard JSON: > > [{u'access': {u'css': u'avail\_yes', u'title': u'\u0422\u0435\u043a\u0441\u0442\u0434\u043e\u043a\u04 > 43\u043c\u0435\u043d\u0442\u0430 \u0434\u043e\u0441\u0442\u0443\u043f\u0435\u043d'},u'title': u'"\u0410\u0440\u0431\u0438\u0442\u0440\u0430\u0436\u043d\u044b\u0439\u043f\u0440\u043e\u0446\u0435\u0441\u0441\u0443\u0430\u043b\u044c\u043d\u044b\u0439\u043a\u043e\u0434\u0435\u043a\u0441\u0420\u043e\u0441\u0441\u0438\u0439\u0441\u043a\u043e\u0439\u0424\u0435\u0434\u0435\u0440\u0430\u0446\u0438\u0438" \u043e\u0442 24.07.2002 N 95-\u0424\u0417 (\u04 > 40\u0435\u0434. \u043e\u0442 02.07.2013) (\u0441 \u0438\u0437\u043c. \u0438 \u0434\u043e > \u043f.,\u0432\u0441\u0442\u0443\u043f\u0430\u044e\u0449\u0438\u043c\u0438 \u0432 \u0441 > \u0438\u043b\u0443 \u0441 01.08.2013)', u'base': u'LAW', u'order': u'1', u'n': u'148904'}, ... }] > > > But sometimes, during iterating an others urls I get an error like this: ``` File "/Developer/Python/test.py", line 123, in order_search data = json.loads(re.search(r"(?=\[)(.*?)\s*(?=\;)", url).group(1)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads return _default_decoder.decode(s) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Invalid \uXXXX escape: line 1 column 20235 (char 20235) ``` How can I fix it, or maybe there's an another way to get valid JSON (desirable using native libraries)?
2013/09/04
[ "https://Stackoverflow.com/questions/18615524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1621838/" ]
Probably, your regular expression has found char ';' somewhere in the middle of a response, and because of this you get an error, because, using your regular expression, you might have received an incomplete, cropped response, and that's why you could not convert it into JSON. Yes, I agree with user RickyA that sometimes using a native tools, a code will easier to read than trying to make up RegEx. But here, I'd rather to use exactly regular expression, something like this: ``` data = re.search(r'(?=\[)(.*?)[\;]*$', response).group(1) ``` > > > ``` > /(?=\[)(.*?)[\;]*$/ > (?=\[) Positive Lookahead > \[ Literal [ > 1st Capturing group (.*?) > . 0 to infinite times [lazy] Any character (except newline) > Char class [\;] 0 to infinite times [greedy] matches: > \; The character ; > $ End of string > > ``` > > I believe you meant that the variable '**url**' means a response from a server, then maybe better to use name of variable '**response**' instead of '**url**'. And, if you've some troubles with using RegEx, I advise you to use an editor of regular expressions, like [RegEx 101](http://regex101.com).This is the online regular expression editor, which explains each block of inputted expression.
What about: ``` response = response.strip() #get rid of whitespaces response = response[response.find("["):] #trim everything before the first '[' if response[-1:] == ";": #if last char == ";" response = response[:-1] #trim it ``` Seems like a big overkill to do this with regex.
21,067,730
I have this piece of code in my views.py for a django app: ``` for i in range(0,10): row = cursor.fetchone() tablestring = tablestring + "<tr><td>" + row[0] + "</td><td>" + + str(row[3]) + "</td></tr>" ``` This works fine when I load the page but if I change the range to (0,20) or anything higher, I just get a blank page. My question is: what is causing this limitation? Is it something with python or django or with the host (pythonanywhere)? Also, I'm just starting with django and I understand this may not be the best code. If you have any suggestions to make it neater or more efficient they would be appreciated. Thanks for the help Edit: here is my query: ``` cursor.execute("""SELECT title, movie_url, movie_id, cScore FROM movies""") ```
2014/01/11
[ "https://Stackoverflow.com/questions/21067730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754604/" ]
you should really use [django orm](https://docs.djangoproject.com/en/dev/topics/db/queries/) and write those table markups in a [template](https://docs.djangoproject.com/en/dev/topics/templates/), follow this [tutorial](https://docs.djangoproject.com/en/dev/intro/tutorial01/) to get the basic concepts
My first guess would be that there are less than 20 rows, so once you run out of them `row` will be None and your attempt to index it will throw an exception. As for improving the code: Like Yossi suggested, you should probably go with an ORM. An ORM (Object Relational Mapper) lets you access a database in a more object-oriented way, which can make for cleaner code as well as avoid bugs related to argument escaping (on the other hand, it may not be ideal if you want to create really complex queries, for that SQL is still the best IMHO). I also agree with Guy in that you should using a template system instead of concatenating HTML strings.
29,386,310
I am downloading a compressed file from the internet: ``` with lzma.open(urllib.request.urlopen(url)) as file: for line in file: ... ``` After having downloaded and processed a a large part of the file, I eventually get the error: > > File "/usr/lib/python3.4/lzma.py", line 225, in \_fill\_buffer raise > EOFError("Compressed file ended before the " EOFError: Compressed file > ended before the end-of-stream marker was reached > > > I am thinking that it might be caused by an internet connection that drops or the server not responding for some time. If that is the case, is there anyway to make it keep trying, until connection is reestablished, instead of throwing an exception. I don't think it is a problem with the file, as I have manually downloaded many files like it from the same website manually and decompressed it. I have also been able to download and decompress some smaller files with Python. The file I am trying to download has a compressed size of about 20 GB.
2015/04/01
[ "https://Stackoverflow.com/questions/29386310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4424589/" ]
from the [urllib.urlopen docs:](https://docs.python.org/2/library/urllib.html) > > One caveat: the read() method, if the size argument is omitted or > negative, may not read until the end of the data stream; there is no > good way to determine that the entire stream from a socket has been > read in the general case. > > > Maybe the lzma.open trips on huge size/connection errors/timeout because of the above.
Assuming you need to download a big file, it is better to use the "write and binary" mode when writing content to a file in python. You may also try to use the [python requests](http://docs.python-requests.org/en/master/) module more than the urllib module: Please see below a working code: ``` import requests url="http://www.google.com" with open("myoutputfile.ext","wb") as f: f.write( requests.get(url).content ) ``` Could you test that piece of code and answer back if it doesn't solve your issue. Best regards
29,386,310
I am downloading a compressed file from the internet: ``` with lzma.open(urllib.request.urlopen(url)) as file: for line in file: ... ``` After having downloaded and processed a a large part of the file, I eventually get the error: > > File "/usr/lib/python3.4/lzma.py", line 225, in \_fill\_buffer raise > EOFError("Compressed file ended before the " EOFError: Compressed file > ended before the end-of-stream marker was reached > > > I am thinking that it might be caused by an internet connection that drops or the server not responding for some time. If that is the case, is there anyway to make it keep trying, until connection is reestablished, instead of throwing an exception. I don't think it is a problem with the file, as I have manually downloaded many files like it from the same website manually and decompressed it. I have also been able to download and decompress some smaller files with Python. The file I am trying to download has a compressed size of about 20 GB.
2015/04/01
[ "https://Stackoverflow.com/questions/29386310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4424589/" ]
It's probably liblzma bug. As a workaround try adding: ``` lzma._BUFFER_SIZE = 1023 ``` before calling `lzma.open()`.
Assuming you need to download a big file, it is better to use the "write and binary" mode when writing content to a file in python. You may also try to use the [python requests](http://docs.python-requests.org/en/master/) module more than the urllib module: Please see below a working code: ``` import requests url="http://www.google.com" with open("myoutputfile.ext","wb") as f: f.write( requests.get(url).content ) ``` Could you test that piece of code and answer back if it doesn't solve your issue. Best regards
29,386,310
I am downloading a compressed file from the internet: ``` with lzma.open(urllib.request.urlopen(url)) as file: for line in file: ... ``` After having downloaded and processed a a large part of the file, I eventually get the error: > > File "/usr/lib/python3.4/lzma.py", line 225, in \_fill\_buffer raise > EOFError("Compressed file ended before the " EOFError: Compressed file > ended before the end-of-stream marker was reached > > > I am thinking that it might be caused by an internet connection that drops or the server not responding for some time. If that is the case, is there anyway to make it keep trying, until connection is reestablished, instead of throwing an exception. I don't think it is a problem with the file, as I have manually downloaded many files like it from the same website manually and decompressed it. I have also been able to download and decompress some smaller files with Python. The file I am trying to download has a compressed size of about 20 GB.
2015/04/01
[ "https://Stackoverflow.com/questions/29386310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4424589/" ]
Have you tried using the requests library? I believe it provides an abstraction over urllib. The following solution should work for you, but it uses the requests library instead of urllib (but requests > urllib anyway!). Let me know if you prefer to continue using urllib. ``` import os import requests def download(url, chunk_s=1024, fname=None): if not fname: fname = url.split('/')[-1] req = requests.get(url, stream=True) with open(fname, 'wb') as fh: for chunk in req.iter_content(chunk_size=chunk_s): if chunk: fh.write(chunk) return os.path.join(os.getcwd(), fname) ```
Assuming you need to download a big file, it is better to use the "write and binary" mode when writing content to a file in python. You may also try to use the [python requests](http://docs.python-requests.org/en/master/) module more than the urllib module: Please see below a working code: ``` import requests url="http://www.google.com" with open("myoutputfile.ext","wb") as f: f.write( requests.get(url).content ) ``` Could you test that piece of code and answer back if it doesn't solve your issue. Best regards
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
**AWS Beanstalk:** It is Deploy and manage applications in the AWS cloud without worrying about the infrastructure that runs yor web applications with Elastic Beanstalk. No need to worry about EC2 or else installations. **AWS OpsWorks** AWS OpsWorks is nothing but an application management service that makes it easy for the new DevOps users to model & manage the entire their application
You should use OpsWorks in place of CloudFormation if you need to deploy an application that requires updates to its EC2 instances. If your application uses a lot of AWS resources and services, including EC2, use a combination of CloudFormation and OpsWorks If your application will need other AWS resources, such as database or storage service. In this scenario, use CloudFormation to deploy Elastic Beanstalk along with the other resources.
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
In Opsworks you can share "roles" of layers across a stack to use less resources by combining the specific jobs an underlying instance maybe doing. Layer Compatibility List (as long as security groups are properly set): ``` HA Proxy : custom, db-master, and memcached. MySQL : custom, lb, memcached, monitoring-master, nodejs-app, php-app, rails-app, and web. Java : custom, db-master, and memcached. Node.js : custom, db-master, memcached, and monitoring-master PHP : custom, db-master, memcached, monitoring-master, and rails-app. Rails : custom, db-master, memcached, monitoring-master, php-app. Static : custom, db-master, memcached. Custom : custom, db-master, lb, memcached, monitoring-master, nodejs-app, php-app, rails-app, and web Ganglia : custom, db-master, memcached, php-app, rails-app. Memcached : custom, db-master, lb, monitoring-master, nodejs-app, php-app, rails-app, and web. ``` reference : <http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html>
**AWS OpsWorks** - This is a part of AWS management service. It helps to configure the application using scripting. It uses Chef as the devops framework for this application management and operation. There are templates which can be used for configuration of server, database, storage. The templates can also be customized to perform any other task. DevOps Engineers have control on application's dependencies and infrastructure. **AWS Beanstalk** - It provides the environment for language like Java, Node Js, Python, Ruby Go. Elastic Bean stalk provide the resource to run the application. Developers not to worry about the infrastructure and they don't have control on infrastructure. **AWS CloudFormation** - CloudFormation has sample templates to manage the AWS resources in order.
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
> > I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CLoudFormation? > > > The answer is: it depends. AWS OpsWorks and AWS Beanstalk are (I've been told) simply different ways of managing your infrastructure, depending on how you think about it. CloudFormation is simply a way of templatizing your infrastructure. Personally, I'm more familiar with Elastic Beanstalk, but to each their own. I prefer it because it can do deployments via Git. It is public information that Elastic Beanstalk uses CloudFormation under the hood to launch its environments. For my projects, I use both in tandem. I use CloudFormation to construct a custom-configured VPC environment, S3 buckets and DynamoDB tables that I use for my app. Then I launch an Elastic Beanstalk environment inside of the custom VPC which knows how to speak to the S3/DynamoDB resources. > > I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. > > > Under the hood, OpsWorks and Elastic Beanstalk use EC2 + CloudWatch + Auto Scaling, which is capable of handling the loads you're talking about. RDS provides support for scalable SQL-based databases. > > Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 > > > Depending on what you mean by "*some* hardware resources", you can always launch standalone EC2 instances alongside OpsWorks or Elastic Beanstalk environments. At present, Elastic Beanstalk supports one webapp per environment. I don't recall what OpsWorks supports. > > The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. > > > All of this is fully supported by AWS. OpsWorks and Elastic Beanstalk have *optimized* themselves for an array of development environments (Ruby, Python and PHP are all on the list), while EC2 provides raw servers where you can install anything you'd like.
In Opsworks you can share "roles" of layers across a stack to use less resources by combining the specific jobs an underlying instance maybe doing. Layer Compatibility List (as long as security groups are properly set): ``` HA Proxy : custom, db-master, and memcached. MySQL : custom, lb, memcached, monitoring-master, nodejs-app, php-app, rails-app, and web. Java : custom, db-master, and memcached. Node.js : custom, db-master, memcached, and monitoring-master PHP : custom, db-master, memcached, monitoring-master, and rails-app. Rails : custom, db-master, memcached, monitoring-master, php-app. Static : custom, db-master, memcached. Custom : custom, db-master, lb, memcached, monitoring-master, nodejs-app, php-app, rails-app, and web Ganglia : custom, db-master, memcached, php-app, rails-app. Memcached : custom, db-master, lb, monitoring-master, nodejs-app, php-app, rails-app, and web. ``` reference : <http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html>
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
As many others have commented AWS Beanstalk, AWS OpsWorks and AWS Cloud Formation offers different solutions for different problems. In order to acomplish with ``` I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. ``` And taking into consideration you are in migration process I strongly recommend you to start taking a look at AWS Lambda & AWS DynamoDB solution (or hybrid one). Both two are designed for **auto** scaling in a simple way and may be a very cheap solution.
Just use terraform and ECS or EKS. opsworks, elastic beanstalk and cloudformation old tech now. -)
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
**AWS OpsWorks** - This is a part of AWS management service. It helps to configure the application using scripting. It uses Chef as the devops framework for this application management and operation. There are templates which can be used for configuration of server, database, storage. The templates can also be customized to perform any other task. DevOps Engineers have control on application's dependencies and infrastructure. **AWS Beanstalk** - It provides the environment for language like Java, Node Js, Python, Ruby Go. Elastic Bean stalk provide the resource to run the application. Developers not to worry about the infrastructure and they don't have control on infrastructure. **AWS CloudFormation** - CloudFormation has sample templates to manage the AWS resources in order.
As many others have commented AWS Beanstalk, AWS OpsWorks and AWS Cloud Formation offers different solutions for different problems. In order to acomplish with ``` I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. ``` And taking into consideration you are in migration process I strongly recommend you to start taking a look at AWS Lambda & AWS DynamoDB solution (or hybrid one). Both two are designed for **auto** scaling in a simple way and may be a very cheap solution.
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
In Opsworks you can share "roles" of layers across a stack to use less resources by combining the specific jobs an underlying instance maybe doing. Layer Compatibility List (as long as security groups are properly set): ``` HA Proxy : custom, db-master, and memcached. MySQL : custom, lb, memcached, monitoring-master, nodejs-app, php-app, rails-app, and web. Java : custom, db-master, and memcached. Node.js : custom, db-master, memcached, and monitoring-master PHP : custom, db-master, memcached, monitoring-master, and rails-app. Rails : custom, db-master, memcached, monitoring-master, php-app. Static : custom, db-master, memcached. Custom : custom, db-master, lb, memcached, monitoring-master, nodejs-app, php-app, rails-app, and web Ganglia : custom, db-master, memcached, php-app, rails-app. Memcached : custom, db-master, lb, monitoring-master, nodejs-app, php-app, rails-app, and web. ``` reference : <http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html>
You should use OpsWorks in place of CloudFormation if you need to deploy an application that requires updates to its EC2 instances. If your application uses a lot of AWS resources and services, including EC2, use a combination of CloudFormation and OpsWorks If your application will need other AWS resources, such as database or storage service. In this scenario, use CloudFormation to deploy Elastic Beanstalk along with the other resources.
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
**AWS Beanstalk:** It is Deploy and manage applications in the AWS cloud without worrying about the infrastructure that runs yor web applications with Elastic Beanstalk. No need to worry about EC2 or else installations. **AWS OpsWorks** AWS OpsWorks is nothing but an application management service that makes it easy for the new DevOps users to model & manage the entire their application
**AWS OpsWorks** - This is a part of AWS management service. It helps to configure the application using scripting. It uses Chef as the devops framework for this application management and operation. There are templates which can be used for configuration of server, database, storage. The templates can also be customized to perform any other task. DevOps Engineers have control on application's dependencies and infrastructure. **AWS Beanstalk** - It provides the environment for language like Java, Node Js, Python, Ruby Go. Elastic Bean stalk provide the resource to run the application. Developers not to worry about the infrastructure and they don't have control on infrastructure. **AWS CloudFormation** - CloudFormation has sample templates to manage the AWS resources in order.
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
In Opsworks you can share "roles" of layers across a stack to use less resources by combining the specific jobs an underlying instance maybe doing. Layer Compatibility List (as long as security groups are properly set): ``` HA Proxy : custom, db-master, and memcached. MySQL : custom, lb, memcached, monitoring-master, nodejs-app, php-app, rails-app, and web. Java : custom, db-master, and memcached. Node.js : custom, db-master, memcached, and monitoring-master PHP : custom, db-master, memcached, monitoring-master, and rails-app. Rails : custom, db-master, memcached, monitoring-master, php-app. Static : custom, db-master, memcached. Custom : custom, db-master, lb, memcached, monitoring-master, nodejs-app, php-app, rails-app, and web Ganglia : custom, db-master, memcached, php-app, rails-app. Memcached : custom, db-master, lb, monitoring-master, nodejs-app, php-app, rails-app, and web. ``` reference : <http://docs.aws.amazon.com/opsworks/latest/userguide/layers.html>
Just use terraform and ECS or EKS. opsworks, elastic beanstalk and cloudformation old tech now. -)