qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
sequencelengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
33,426,483
I have created my Rails app on OpenShift. It uses Python and a package installed from PIP. How do I upgrade to a newer Python version (currently it is 2.6) ? Visible cartridges: ``` user@debian:~$ rhc cartridges jbossas-7 JBoss Application Server 7 web jboss-dv-6.1.0 (!) JBoss Data Virtualization 6 web jbosseap-6 (*) JBoss Enterprise Application Platform 6 web jboss-unified-push-1 (!) JBoss Unified Push Server 1.0.0.Beta1 web jboss-unified-push-2 (!) JBoss Unified Push Server 1.0.0.Beta2 web jenkins-1 Jenkins Server web nodejs-0.10 Node.js 0.10 web perl-5.10 Perl 5.10 web php-5.3 PHP 5.3 web php-5.4 PHP 5.4 web zend-6.1 PHP 5.4 with Zend Server 6.1 web python-2.6 Python 2.6 web python-2.7 Python 2.7 web python-3.3 Python 3.3 web ruby-1.8 Ruby 1.8 web ruby-1.9 Ruby 1.9 web ruby-2.0 Ruby 2.0 web jbossews-1.0 Tomcat 6 (JBoss EWS 1.0) web jbossews-2.0 Tomcat 7 (JBoss EWS 2.0) web jboss-vertx-2.1 (!) Vert.x 2.1 web jboss-wildfly-8 (!) WildFly Application Server 8.2.1.Final web jboss-wildfly-9 (!) WildFly Application Server 9 web diy-0.1 Do-It-Yourself 0.1 web cron-1.4 Cron 1.4 addon jenkins-client-1 Jenkins Client addon mongodb-2.4 MongoDB 2.4 addon mysql-5.1 MySQL 5.1 addon mysql-5.5 MySQL 5.5 addon phpmyadmin-4 phpMyAdmin 4.0 addon postgresql-8.4 PostgreSQL 8.4 addon postgresql-9.2 PostgreSQL 9.2 addon rockmongo-1.1 RockMongo 1.1 addon switchyard-0 SwitchYard 0.8.0 addon haproxy-1.4 Web Load Balancer addon Note: Web cartridges can only be added to new applications. (*) denotes a cartridge with additional usage costs. (!) denotes a cartridge that will not receive automatic security updates. ``` And then trying to install a newer Python ... ``` user@debian:~$ rhc add-cartridge --app myappname python-3.3 Short Name Full name ========== ========= cron-1.4 Cron 1.4 jenkins-client-1 Jenkins Client mongodb-2.4 MongoDB 2.4 mysql-5.1 MySQL 5.1 mysql-5.5 MySQL 5.5 phpmyadmin-4 phpMyAdmin 4.0 postgresql-8.4 PostgreSQL 8.4 postgresql-9.2 PostgreSQL 9.2 rockmongo-1.1 RockMongo 1.1 switchyard-0 SwitchYard 0.8.0 haproxy-1.4 Web Load Balancer There are no cartridges that match 'python-3.3'. ``` If it's possible to install a newer version of Python, how do I install PIP?
2015/10/29
[ "https://Stackoverflow.com/questions/33426483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1906809/" ]
If you have installed phpMyAdmin in your linux server (centos/RHEL/debian), and tried to access phpMyAdmin in most cases you will get this 403 forbidden error. I have seen this issue very often if you are installing phpmyadmin using yum or by apt-get. By default phpmyadmin installed path is **/usr/share/phpmyadmin** and the apache configuration file is located in /**etc/httpd/conf.d/phpmyadmin.conf**. Forbidden You don't have permission to access **/phpmyadmin/** on this server. To fix: ``` nano /etc/httpd/conf.d/phpmyadmin.conf ``` Remove or comment the first two lines in below. > > > ``` > #Order Allow,Deny > #Deny from all > > ``` > > ``` Allow from 127.0.0.1 ``` Restart the apache server. ``` service httpd restart ```
I was running into the same issue with a new install of Fedora 25, Apache, MariaDB and PHP. The router is on 192.168.1.1 and the Fedora 25 server is sitting at 192.168.1.100 which is a staic address handed out by the router. The laptop was getting a random ip in the range of 192.168.1.101 to 150. The change I made to the /etc/httpd/conf.d/phpMyAdmin.conf was instances of ``` Require ip 127.0.0.1 ``` to ``` Require ip 127.0.0.1 192.168.1.1/24 ``` This worked for me. The idea came from the process of inserting the ip address of the laptop into the .conf file behind the reference to 127.0.0.1 and I was able to get access. So instead of doing the more secure thing of handing out a static ip address to the laptop I let the phpMyAdmin.conf file open to a range of ip address on the local subnet, if that is the right terminology. If there are drawbacks to doing this let me know so that I can make the appropriate changes.
19,223,676
I'm using passenger with apache to run my ruby application. I've noticed that passenger crashes from time to time (apache is still working), and I need to manually restart apache to make it work again. A look at the log makes me think it occurs when apache changes the log file (archives the current an create a new one). This is what a `tail -F` on tha apache errors log file looks like: ``` tail: ‘/var/log/apache2/error.log’ has become inaccessible: No such file or directory tail: ‘/var/log/apache2/error.log’ has appeared; following end of new file [ 2013-10-06 05:05:27.2678 10498/7f3f0cf82740 agents/Watchdog/Main.cpp:459 ]: Options: { 'analytics_log_user' => 'nobody', 'default_group' => 'nogroup', 'default_python' => 'python', 'default_ruby' => '/usr/bin/ruby1.9.1', 'default_user' => 'nobody', 'log_level' => '0', 'max_instances_per_app' => '0', 'max_pool_size' => '6', 'passenger_root' => '/var/lib/gems/1.9.1/gems/passenger-4.0.14', 'pool_idle_time' => '300', 'temp_dir' => '/tmp', 'union_station_gateway_address' => 'gateway.unionstationapp.com', 'union_station_gateway_port' => '443', 'user_switching' => 'true', 'web_server_pid' => '18659', 'web_server_type' => 'apache', 'web_server_worker_gid' => '1000', 'web_server_worker_uid' => '1001' } [Sun Oct 06 05:05:27 2013] [error] *** Passenger could not be initialized because of this error: Unable to start the Phusion Passenger watchdog because it encountered the following error during startup: Tried to reuse existing server instance directory /tmp/passenger.1.0.18659, but it has wrong permissions [Sun Oct 06 05:05:27 2013] [notice] Apache/2.2.22 (Ubuntu) PHP/5.4.9-4ubuntu2.2 Phusion_Passenger/4.0.14 configured -- resuming normal operations ``` * The message mentions a file in `/tmp` with wrong permissisons, why are they wrong? what should they be? how to make them right? * The last message "*resuming normal operations*" seems wrong too since passenger is down. Is it a bug? What does it mean? * What should I do to prevent this from happening?
2013/10/07
[ "https://Stackoverflow.com/questions/19223676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149237/" ]
Ah, I see that you are on version 4.0.14. Please upgrade to the latest version, which is 4.0.20. Versions prior to 4.0.17 or so didn't properly support /tmp directories with the setgid flag.
In my case, restart apache solve this problem. ``` $ /etc/init.d/httpd stop $ /etc/init.d/httpd start ```
4,658,008
I have a rather long setup, then three questions at the end. On OS X, the System Python framework contains three executables (let me give them short names): ``` > F=/System/Library/Frameworks/Python.framework/Versions/2.6 > A=$F/bin/python2.6 > B=$F/Resources/Python.app/Contents/MacOS/Python > C=$F/Python ``` $A and $B are clearly too small to be Python itself. ``` > ls -s $A; ls -s $B; ls -s $C 16 /System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 16 /System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python 3152 /System/Library/Frameworks/Python.framework/Versions/2.6/Python > $A Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) > $B Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) > $C -bash: /System/Library/Frameworks/Python.framework/Versions/2.6/Python: cannot execute binary file ``` Despite equal size and apparently, effect, the first two are different, e.g.: ``` > cmp -lc $A $B ``` Also, in /usr/bin, python2.6 is a symlink to $C, but there is also: ``` > D=/usr/bin/python > ls -s $D 48 /usr/bin/python ``` I want to sort out how these are connected; the command `which` doesn't help. ``` > export DYLD_PRINT_LIBRARIES=1 > $A .. dyld: loaded: /System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python dyld: loaded: /System/Library/Frameworks/Python.framework/Versions/2.6/Python ``` Summary: $A loads $B followed by $C; $B loads $C; $D loads $B followed by $C So my questions are: 1. Is this documented anywhere? 2. What roles do these play? 3. Most important, what tools would be useful in tracing connections like this?
2011/01/11
[ "https://Stackoverflow.com/questions/4658008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215679/" ]
The Apple-supplied Pythons in OS X 10.6 are built and installed using the standard Python *framework* build option, with a few customization tweaks. It is not in Apple's documentation because the specific layout is not an Apple invention; it has evolved over the years by the Python project using other OS X framework layouts as a starting point. If you install a version of Python on OS X using one of the python.org installers, say from [here](http://www.python.org/download/releases/2.6.6/), you will see the same pattern, with the framework rooted at `/Library/Frameworks/` rather than `/System/Library/Frameworks`. So, if you are really curious, you can download the source and look at the `configure` script and `Makefile` templates. It can be heavy reading, though. Apple also makes available [here](http://www.opensource.apple.com/) the source used to build open source components, including Python, in each OS X release along with the customization patches so, in theory, you can see exactly how Apple built what it released. That said, to address your questions, in Python 2.6: `$A` is the pythonw wrapper that ensures Python is recognized as a GUI application by OS X (see the source of `pythonw.c` [here](http://svn.python.org/view/python/branches/release26-maint/Mac/Tools/pythonw.c?view=markup)). Note, the Apple version of pythonw has been customized to add the preferred execution modes (see Apple's `man 1 python`). A somewhat different approach to this is provided in the upstream source of newer versions of Python (2.7 and 3.2). `$B` is the actual executable of the Python interpreter. It is what is `exec`ed by the pythonw executable, `$A`. You should be able to easily verify that by actually running Python and looking at the value of `sys.executable` but there is a bug with the Apple-supplied Python 2.6 (probably due to the added feature mentioned above) that causes the wrong value to be assigned to it. The python.org Python 2.6.6 shows the correct value: ``` $ cd /Library/Frameworks/Python.framework/Versions/2.6 $ ./bin/python2.6 -c 'import sys;print(sys.executable)' /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python` ``` `$C` is the shared library containing all of the interpreter's loadable modules. You can see that by using `otool` on `$B`: ``` $ cd /System/Library/Frameworks/Python.framework/Versions/2.6 $ cd Resources/Python.app/Contents/MacOS/ $ otool -L ./Python Python: /System/Library/Frameworks/Python.framework/Versions/2.6/Python (compatibility version 2.6.0, current version 2.6.1) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0) ```
The tools to use are ls and file. ls -l will give what the symbolic link goes to. The size of a symbolic link is the number of chafracters in the path it points to. file x will give the type of the file e.g. ``` file /System/Library/Frameworks/Python.framework/Versions/2.6/Python /System/Library/Frameworks/Python.framework/Versions/2.6/Python: Mach-O universal binary with 3 architectures /System/Library/Frameworks/Python.framework/Versions/2.6/Python (for architecture x86_64): Mach-O 64-bit dynamically linked shared library x86_64 /System/Library/Frameworks/Python.framework/Versions/2.6/Python (for architecture i386): Mach-O dynamically linked shared library i386 /System/Library/Frameworks/Python.framework/Versions/2.6/Python (for architecture ppc7400): Mach-O dynamically linked shared library ppc ``` OSX Frameworks are described in [Apple developer docs](http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPFrameworks/Frameworks.html%23//apple_ref/doc/uid/10000183i) /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python and /System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 are the actual python interpreter, I think they are hard links to the same binary. /usr/bin/python is the python on the path - I think it is hard linked to /usr/bin/pythonw. These are wrappers that call exec to the real python interpreter in /System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 see [python bug tracker](http://bugs.python.org/issue6834) /System/Library/Frameworks/Python.framework/Versions/Current is a symlink to System/Library/Frameworks/Python.framework/Versions/2.6 using the standard OSX Framework versioning /System/Library/Frameworks/Python.framework/Versions/2.6/Python is the shared library that does all the work - set up as a library so that you can write programs in other languages that can embed a python interpreter. For other details look at [Python docs](http://docs.python.org/using/mac.html) but I suspect you would have to search the [apple python mailing list](http://www.python.org/community/sigs/current/pythonmac-sig/)
49,577,050
I am trying to interact with a database stored in back4app using python. After sending my GET request, I get "{'message': 'Not Found', 'error': {}}". My python code is as follows: ``` import json, http.client, urllib.parse # create a connection to the server url = "parseapi.back4app.com" connection = http.client.HTTPSConnection(url) connection.connect() # define parameter for GET request params = urllib.parse.urlencode({"where":json.dumps({"Name": "Dru Love"})}) # perform GET request connection.request('GET', '/parse/classes/PGA?%s' % params, '', { "X-Parse-Application-Id": "app_id", "X-Parse-REST-API-Key": "api_key" }) # store response in result variable result = json.loads(connection.getresponse().read()) connection.close() print(result) ``` Response: ``` {'message': 'Not Found', 'error': {}} ```
2018/03/30
[ "https://Stackoverflow.com/questions/49577050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5983936/" ]
You CPP file doesn't include the .h file and it doesn't have `extern "C"` declarations of its own. So, the methods are compiled with C++ signatures, so they cannot be found by the JVM, which expects `extern "C"` signatures as per the .h file. The easy fix is to include the .h file.
Solution!!!! I fixed it by doing some research and through trial and error i figured out that my imports were messing up the DLL Cpp file: ``` /* Replace "dll.h" with the name of your header */ #include "IGNORE.h" #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <time.h> JNIEXPORT jint JNICALL Java_NativeRandom_next__I (JNIEnv *env, jclass clazz, jint i){ srand(time(NULL)); int n = (rand()%i)+1; return n; } JNIEXPORT jint JNICALL Java_NativeRandom_next__II (JNIEnv *env, jclass clazz, jint seed, jint i){ srand(seed); int n =(rand()%i)+1; return n; } ``` Header file: ``` /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class NativeRandom */ #ifndef _Included_NativeRandom #define _Included_NativeRandom #ifdef __cplusplus extern "C" { #endif /* * Class: NativeRandom * Method: next * Signature: (I)I */ JNIEXPORT jint JNICALL Java_NativeRandom_next__I (JNIEnv *, jclass, jint); /* * Class: NativeRandom * Method: next * Signature: (II)I */ JNIEXPORT jint JNICALL Java_NativeRandom_next__II (JNIEnv *, jclass, jint, jint); #ifdef __cplusplus } #endif #endif ```
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
Try importing win32api at the top, ``` import win32api import speech_recognition as sr import pyttsx3 ```
I did the following when I experienced the same problem: When we look at these lines in the error, ``` File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` The `pywintypes.py` is searching for the `(pywintypes39.dll)` files in the `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib` directory hence I copied the two files 'pythoncom39.dll' and 'pywintypes39.dll' present in the 'pywin32\_system32' folder, to the `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib` directory. It solved the problem for me.
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
On Command prompt type `python -m site` to get the site-package. Now navigate to the `site-package` folder and go to `pywin32_system32` to copy `pythoncom39.dll` and `pywintypes39.dll` Navigate one step back to `site-package` folder and got `win32` and paste the file.
You've commented that you dumped the project you were working on. But I thought I answer anyway for those who still get this error or are going to. I had the same issue but there was no solution to the problem that I could find online. So I decided to read the error message and to understand what it says **Notice that `File <path>` the errors are referring to.** The `<path>` is `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\...`. In this folder, there is a directory called `pywin32_system32`. That's the directory you're looking for. The problem was that pypiwin32 was installed but not in the Python PATH that it should have! For example: My Python location is `C:\Program Files\Python39` My Python path in `System Environment Variables` is set to `C:\Program Files\Python39` When I ran the command `pip install pypiwin32`, it was installed on `C:\Users\<user>\AppData\Roaming\Python\Python39\site-packages` which is not the right directory. Inside the directory, `pywin32_system32`, is the file you are looking for (`pywintypes39.dll`). \*\*All you have to do is to copy the `pywin32_system32` folder from `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\` to `<Python_PATH>\site-packages\`\*\* (`C:\Program Files\Python39\sitepackages\` for example.) Sorry if the answer came a little too late! I hope what I wrote is not confusing because I tried my best to explain it in simple words.
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
On Command prompt type `python -m site` to get the site-package. Now navigate to the `site-package` folder and go to `pywin32_system32` to copy `pythoncom39.dll` and `pywintypes39.dll` Navigate one step back to `site-package` folder and got `win32` and paste the file.
Even thou the question is already answered, I had that issue now and used the answer from DecodedIntel, but even thou it works, you can see another issue in the future after using pip install NewModule and there's a way to fix it once and for all. My Python location is C:\Program Files\Python39 My PIP Modules location is C:\Users<user>\AppData\Roaming\Python\Python39\site-packages To fix it you can use Windows HARD LINK Directory JUNCTION Use /J to create a hard link pointing to a directory, also known as a directory junction: mklink /J Link Target [MSDOS MKLINK Cmd help description](https://i.stack.imgur.com/lQCXc.png) So, for example, if you wanted to create a directory junction (a hard link to a folder) at C:\LinkToFolder that pointed to C:\Users\Name\OriginalFolder, you’d run the following command: mklink /J C:\LinkToFolder C:\Users\Name\OriginalFolder You’ll need to put quotation marks around paths with spaces. For example, if the folders are instead named C:\Link To Folder and C:\Users\Name\Original Folder, you’d use the following command instead: mklink /J "C:\Link To Folder" "C:\Users\Name\Original Folder" If you see the message “You do not have sufficient privilege to perform this operation.”, you need to launch the Command Prompt as Administrator before running the command. C:\Users\MyUserName\AppData\Roaming\Python>mklink /j Python39 "C:\Program Files\Python39" Junction created for Python39 <<===>> C:\Program Files\Python39
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
On Command prompt type `python -m site` to get the site-package. Now navigate to the `site-package` folder and go to `pywin32_system32` to copy `pythoncom39.dll` and `pywintypes39.dll` Navigate one step back to `site-package` folder and got `win32` and paste the file.
try uninstall pywin32 and install it again, works for me
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
You've commented that you dumped the project you were working on. But I thought I answer anyway for those who still get this error or are going to. I had the same issue but there was no solution to the problem that I could find online. So I decided to read the error message and to understand what it says **Notice that `File <path>` the errors are referring to.** The `<path>` is `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\...`. In this folder, there is a directory called `pywin32_system32`. That's the directory you're looking for. The problem was that pypiwin32 was installed but not in the Python PATH that it should have! For example: My Python location is `C:\Program Files\Python39` My Python path in `System Environment Variables` is set to `C:\Program Files\Python39` When I ran the command `pip install pypiwin32`, it was installed on `C:\Users\<user>\AppData\Roaming\Python\Python39\site-packages` which is not the right directory. Inside the directory, `pywin32_system32`, is the file you are looking for (`pywintypes39.dll`). \*\*All you have to do is to copy the `pywin32_system32` folder from `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\` to `<Python_PATH>\site-packages\`\*\* (`C:\Program Files\Python39\sitepackages\` for example.) Sorry if the answer came a little too late! I hope what I wrote is not confusing because I tried my best to explain it in simple words.
`pywintypes` is a part of Python for Windows extensions, or its know as pywin32 you will need to install it. and i am not sure it will work but you can try this `pip install pypiwin32`.
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
try uninstall pywin32 and install it again, works for me
Even thou the question is already answered, I had that issue now and used the answer from DecodedIntel, but even thou it works, you can see another issue in the future after using pip install NewModule and there's a way to fix it once and for all. My Python location is C:\Program Files\Python39 My PIP Modules location is C:\Users<user>\AppData\Roaming\Python\Python39\site-packages To fix it you can use Windows HARD LINK Directory JUNCTION Use /J to create a hard link pointing to a directory, also known as a directory junction: mklink /J Link Target [MSDOS MKLINK Cmd help description](https://i.stack.imgur.com/lQCXc.png) So, for example, if you wanted to create a directory junction (a hard link to a folder) at C:\LinkToFolder that pointed to C:\Users\Name\OriginalFolder, you’d run the following command: mklink /J C:\LinkToFolder C:\Users\Name\OriginalFolder You’ll need to put quotation marks around paths with spaces. For example, if the folders are instead named C:\Link To Folder and C:\Users\Name\Original Folder, you’d use the following command instead: mklink /J "C:\Link To Folder" "C:\Users\Name\Original Folder" If you see the message “You do not have sufficient privilege to perform this operation.”, you need to launch the Command Prompt as Administrator before running the command. C:\Users\MyUserName\AppData\Roaming\Python>mklink /j Python39 "C:\Program Files\Python39" Junction created for Python39 <<===>> C:\Program Files\Python39
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
try uninstall pywin32 and install it again, works for me
C:\Users\lenevo\AppData\Roaming\Python\Python39\site-packages\win32\lib . Just copy the two files 'pythoncom39.dll' and 'pywintypes39.dll' from the 'pywin32\_system32' folder in the lib folder "C:\Users\lenevo\AppData\Roaming\Python\Python39\site-packages\win32\lib "
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
try uninstall pywin32 and install it again, works for me
`pywintypes` is a part of Python for Windows extensions, or its know as pywin32 you will need to install it. and i am not sure it will work but you can try this `pip install pypiwin32`.
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
You've commented that you dumped the project you were working on. But I thought I answer anyway for those who still get this error or are going to. I had the same issue but there was no solution to the problem that I could find online. So I decided to read the error message and to understand what it says **Notice that `File <path>` the errors are referring to.** The `<path>` is `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\...`. In this folder, there is a directory called `pywin32_system32`. That's the directory you're looking for. The problem was that pypiwin32 was installed but not in the Python PATH that it should have! For example: My Python location is `C:\Program Files\Python39` My Python path in `System Environment Variables` is set to `C:\Program Files\Python39` When I ran the command `pip install pypiwin32`, it was installed on `C:\Users\<user>\AppData\Roaming\Python\Python39\site-packages` which is not the right directory. Inside the directory, `pywin32_system32`, is the file you are looking for (`pywintypes39.dll`). \*\*All you have to do is to copy the `pywin32_system32` folder from `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\` to `<Python_PATH>\site-packages\`\*\* (`C:\Program Files\Python39\sitepackages\` for example.) Sorry if the answer came a little too late! I hope what I wrote is not confusing because I tried my best to explain it in simple words.
I did the following when I experienced the same problem: When we look at these lines in the error, ``` File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` The `pywintypes.py` is searching for the `(pywintypes39.dll)` files in the `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib` directory hence I copied the two files 'pythoncom39.dll' and 'pywintypes39.dll' present in the 'pywin32\_system32' folder, to the `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib` directory. It solved the problem for me.
65,573,140
I was making a virtual assistant in python, but I see the following error. ``` ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` I am using Windows 10 and Python 3.9 Here is the code ``` import speech_recognition as sr import pyttsx3 listner=sr.Recognizer() engine=pyttsx3.init() engine.say('Hello Vishal. I am Cisco') engine.say('What do you want me to do?') engine.runAndWait() try: with sr.Microphone() as source: print('listening...') voice=listner.listen(source) command = listner.recognize_google(voice) command=command.lower() if "cisco" in command: print(command) except: print('Something went wrong') ``` Also when I run this program The console prints this: ``` enter code hraceback (most recent call last): File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Program Files (x86)\Python\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\visha\Documents\Python\Basic.py", line 4, in <module> engine=pyttsx3.init() File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module> import pythoncom File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module> import pywintypes File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module> __import_pywin32_system_module__("pywintypes", globals()) File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) PS C:\Users\visha\Documents\Python> ere ``` I am a beginner so I don't have much idea. Thanks in advance for your help
2021/01/05
[ "https://Stackoverflow.com/questions/65573140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14856292/" ]
On Command prompt type `python -m site` to get the site-package. Now navigate to the `site-package` folder and go to `pywin32_system32` to copy `pythoncom39.dll` and `pywintypes39.dll` Navigate one step back to `site-package` folder and got `win32` and paste the file.
I did the following when I experienced the same problem: When we look at these lines in the error, ``` File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__ raise ImportError("No system module '%s' (%s)" % (modname, filename)) ImportError: No system module 'pywintypes' (pywintypes39.dll) ``` The `pywintypes.py` is searching for the `(pywintypes39.dll)` files in the `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib` directory hence I copied the two files 'pythoncom39.dll' and 'pywintypes39.dll' present in the 'pywin32\_system32' folder, to the `C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib` directory. It solved the problem for me.
73,678,506
I want to get and parse the python (python2) version. This way (which works): ``` python2 -V 2>&1 | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/' ``` For some reason, python2 is showing the version using the -V argument on its error output. Because this is doing nothing: ``` python2 -V | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/' ``` So it needs to be redirected `2>&1` to get parsed (stderr to stdout). Ok, but I'd like to avoid the error shown if a user launching this command has no python2 installed. The desired output on screen for a user who not have python2 installed is nothing. How can I do that? because I need the error output shown to parse the version. I already did a solution doing before a conditional `if` statement using the hash command to know if the python2 command is present or not... so I have a working workaround which avoids the possibility of launching the python2 command if it is not present... but just curiosity. Forget about python2. Let's suppose is any other command which is redirecting stderr to stdout. Is there a possibility (bash trick) to parse its output without showing it if there is an error? Any idea?
2022/09/11
[ "https://Stackoverflow.com/questions/73678506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5300329/" ]
Print output only if the line starts with `Python 2`: ``` python2 -V 2>&1 | sed -n 's/^Python 2\.\([0-9]*\).*/2\1/p' ``` or, ``` command -v python2 >/dev/null && python2 -V 2>&1 | sed ... ```
Include the next line in your script ``` command python2 >/dev/null 2>&1 || {echo "python2 not installed or in PATH"; exit 1; } ``` EDITED: Changed `which` into `command`
28,434,920
I've been following the djangogirl's tutorial here <http://tutorial.djangogirls.org/en/deploy/README.html> on deploying a django app on Heroku. I am a complete newbie at this so a lot of the stuff just seems like black magic to me, and I have a very fuzzy idea of what is going on. However, I seem to have been able to get everything going smoothly from creating my app to pushing it onto a remote repository and running the web process. ``` >heroku create >git push heroku master >heroku ps:scale web=1 ``` When I open the url of the app after this, I get a 'requested url not found on this server' error page, which the tutorial says is expected since I have not filled up the empty database. So it says to run ``` >heroku run python manage.py migrate >heroku run python manage.py createsuperuser ``` When I ran them both commands seemed to execute fine. I tried running `manage.py migrate` again just to be sure but it simply said that there were no more migrations to apply. I can log in fine into the admin page, but trying to open the app url itself still gives me a 'requested url was not found on this server' error page, even after I applied migrations. Like I said, I'm a real newbie, so I'm at a lost as to how I should troubleshoot this. I've been following the tutorial step-by-step and have no clue where I've went wrong. Help is much appreciated. **EDIT:** Here is the output from `heroku info -s`: ``` addons=heroku-postgresql:hobby-dev archived_at= buildpack_provided_description=Python create_status=complete created_at=2015/02/10 05:02:00 -0800 domain_name=aqiblog.herokuapp.com dynos=1 git_url=https://git.heroku.com/aqiblog.git id=33873439 name=aqiblog owner_delinquent=false owner_email=*** owner_name=*** region=us released_at=2015/02/10 05:33:50 -0800 repo_migrate_status=complete repo_size=9458 requested_stack= slug_size=53579300 stack=cedar-14 updated_at=2015/02/10 06:04:30 -0800 web_url=https://aqiblog.herokuapp.com/ workers=0 ``` Here is the output from `heroku logs`. To my untrained eye nothing seems out of the ordinary: ``` 2015-02-10T14:04:49.315067+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=15e74a24-32e9-4a74-ab2f-696c63853b72 fwd="183 .90.125.206" dyno=web.1 connect=1ms service=4ms status=404 bytes=267 2015-02-10T14:06:59.516339+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=12b8b705-4820-46c4-9195-a04740ad138a fwd="183 .90.125.206" dyno=web.1 connect=6ms service=7ms status=404 bytes=267 2015-02-10T14:20:16.661117+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=599be313-368a-4f66-900f-a459ef42b9ff fwd="183 .90.125.206" dyno=web.1 connect=1ms service=5ms status=404 bytes=267 2015-02-10T14:30:13.477370+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=91f04bfd-e7b9-41a4-b905-4b7d26861cc5 fw d="183.90.125.206" dyno=web.1 connect=2ms service=43ms status=302 bytes=391 2015-02-10T14:30:13.800060+00:00 heroku[router]: at=info method=GET path="/admin /login/?next=/admin/" host=aqiblog.herokuapp.com request_id=301b7aee-0f48-432f-a 9a9-6696b14fe6be fwd="183.90.125.206" dyno=web.1 connect=1ms service=55ms status =200 bytes=2368 2015-02-10T14:30:14.193976+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=d04f60ed-eef6-4678-a 3f0-e133b55df175 fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms status= 304 bytes=136 2015-02-10T14:30:14.463950+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/login.css" host=aqiblog.herokuapp.com request_id=35ba7b7f-8ca2-40e5- b274-5a33138a7478 fwd="183.90.125.206" dyno=web.1 connect=3ms service=6ms status =304 bytes=136 2015-02-10T14:30:14.845040+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=6b9ba7e5-b520-46d2 -ae47-776340e6eac4 fwd="183.90.125.206" dyno=web.1 connect=3ms service=4ms statu s=304 bytes=136 2015-02-10T14:30:31.563636+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=8cb9b343-f93d-4f14- 9803-592614b17b2f fwd="183.90.125.206" dyno=web.1 connect=2ms service=132ms stat us=302 bytes=625 2015-02-10T14:30:31.910829+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=12df9c3c-4b60-4446-9094-ef567912c19f fw d="183.90.125.206" dyno=web.1 connect=1ms service=68ms status=200 bytes=3837 2015-02-10T14:30:32.260761+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/dashboard.css" host=aqiblog.herokuapp.com request_id=194ab120-f85f-4 78f-bd05-2bd5b424177d fwd="183.90.125.206" dyno=web.1 connect=2ms service=4ms st atus=304 bytes=136 2015-02-10T14:30:32.558809+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_addlink.gif" host=aqiblog.herokuapp.com request_id=b1867188-e93 5-42eb-a12e-3342d6b09fd2 fwd="183.90.125.206" dyno=web.1 connect=2ms service=3ms status=304 bytes=136 2015-02-10T14:30:32.556672+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/default-bg.gif" host=aqiblog.herokuapp.com request_id=c9cd25cf-5bd9- 49ca-acb8-78c14d1cdffd fwd="183.90.125.206" dyno=web.1 connect=2ms service=4ms s tatus=304 bytes=136 2015-02-10T14:30:32.958179+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_changelink.gif" host=aqiblog.herokuapp.com request_id=46672886- 026d-4e44-bbda-0a46c738688f fwd="183.90.125.206" dyno=web.1 connect=3ms service= 4ms status=304 bytes=136 2015-02-10T14:30:37.016120+00:00 heroku[router]: at=info method=GET path="/admin /blog/post/" host=aqiblog.herokuapp.com request_id=024f5a16-2afa-46ae-901f-d9c95 d7ffac8 fwd="183.90.125.206" dyno=web.1 connect=2ms service=89ms status=200 byte s=3466 2015-02-10T14:30:37.392657+00:00 heroku[router]: at=info method=GET path="/admin /jsi18n/" host=aqiblog.herokuapp.com request_id=175746a8-6269-499c-9539-e94442df 3740 fwd="183.90.125.206" dyno=web.1 connect=3ms service=45ms status=200 bytes=2 551 2015-02-10T14:30:37.353918+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/changelists.css" host=aqiblog.herokuapp.com request_id=4b1968b8-5977 -49d2-92c7-7f8e6f83bcce fwd="183.90.125.206" dyno=web.1 connect=2ms service=5ms status=200 bytes=5523 2015-02-10T14:30:37.353954+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/core.js" host=aqiblog.herokuapp.com request_id=2765ef40-cf94-4e80-af2 3-df2bd41c29fd fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms status=20 0 bytes=7182 2015-02-10T14:30:37.664695+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/admin/RelatedObjectLookups.js" host=aqiblog.herokuapp.com request_id= ab90b0a5-c743-4a36-8cf8-a45bcdb26c10 fwd="183.90.125.206" dyno=web.1 connect=2ms service=3ms status=200 bytes=3515 2015-02-10T14:30:37.676047+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.min.js" host=aqiblog.herokuapp.com request_id=d793e5e6-f05c-41 7a-bc14-c726b217a873 fwd="183.90.125.206" dyno=web.1 connect=2ms service=11ms st atus=200 bytes=92913 2015-02-10T14:30:37.672663+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.init.js" host=aqiblog.herokuapp.com request_id=7494223b-6a43-4 861-93c6-8a902e8f0b1f fwd="183.90.125.206" dyno=web.1 connect=3ms service=3ms st atus=200 bytes=608 2015-02-10T14:30:37.922666+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/actions.min.js" host=aqiblog.herokuapp.com request_id=4481557e-e808-4 5c7-9948-2856409b9f9c fwd="183.90.125.206" dyno=web.1 connect=3ms service=4ms st atus=200 bytes=3320 2015-02-10T14:30:39.773435+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/tooltag-add.png" host=aqiblog.herokuapp.com request_id=d1e06eca-e54e -44a4-b4c6-b834751c52b8 fwd="183.90.125.206" dyno=web.1 connect=3ms service=3ms status=200 bytes=371 2015-02-10T14:30:39.795367+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg-reverse.gif" host=aqiblog.herokuapp.com request_id=7df78871-e 7a8-4a47-9260-7b1f715b2293 fwd="183.90.125.206" dyno=web.1 connect=2ms service=2 ms status=304 bytes=136 2015-02-10T14:30:43.715783+00:00 heroku[router]: at=info method=GET path="/admin /blog/" host=aqiblog.herokuapp.com request_id=c8c26fb6-7c06-424a-96a3-ed7d7acf52 15 fwd="183.90.125.206" dyno=web.1 connect=2ms service=62ms status=200 bytes=260 6 2015-02-10T14:30:44.051139+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=a9525efc-ca5b-40a2-b 79c-0d1c7ea8f323 fwd="183.90.125.206" dyno=web.1 connect=3ms service=2ms status= 304 bytes=136 2015-02-10T14:30:46.623963+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=6e2f037e-1156-4ecb-ab9a-c629746701bc fw d="183.90.125.206" dyno=web.1 connect=3ms service=67ms status=200 bytes=3837 2015-02-10T14:33:37.383948+00:00 heroku[router]: at=info method=GET path="/admin /auth/user/" host=aqiblog.herokuapp.com request_id=2e7aca9b-bf1a-4bca-a64e-4958c 50d2bc3 fwd="183.90.125.206" dyno=web.1 connect=1ms service=107ms status=200 byt es=6954 2015-02-10T14:33:37.795450+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=427f5971-4d88-4876-b d34-3d61219d0ee0 fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms status= 304 bytes=136 2015-02-10T14:33:38.115038+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/changelists.css" host=aqiblog.herokuapp.com request_id=1011a5b1-f3e3 -4ccd-bb79-decbb9f04bab fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms status=304 bytes=136 2015-02-10T14:33:38.144837+00:00 heroku[router]: at=info method=GET path="/admin /jsi18n/" host=aqiblog.herokuapp.com request_id=713139f7-188f-4dbb-8c06-f187256f 7f69 fwd="183.90.125.206" dyno=web.1 connect=1ms service=45ms status=200 bytes=2 551 2015-02-10T14:33:38.404063+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.init.js" host=aqiblog.herokuapp.com request_id=5135b182-dc2e-4 a74-b8a2-5d6c0ab12db4 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms st atus=304 bytes=136 2015-02-10T14:33:38.400444+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/core.js" host=aqiblog.herokuapp.com request_id=de86c5af-1a29-430f-a65 1-dc6cf1fd48bf fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms status=30 4 bytes=136 2015-02-10T14:33:38.415586+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.min.js" host=aqiblog.herokuapp.com request_id=19c89d3d-5d23-41 09-979e-b8bb3f42199a fwd="183.90.125.206" dyno=web.1 connect=4ms service=2ms sta tus=304 bytes=136 2015-02-10T14:33:38.408607+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_searchbox.png" host=aqiblog.herokuapp.com request_id=c5a70735-1 712-4040-9eb5-6b7dee13abd2 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1 ms status=200 bytes=620 2015-02-10T14:33:38.406036+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/admin/RelatedObjectLookups.js" host=aqiblog.herokuapp.com request_id= 893d6f5c-af8b-4532-8aa3-6934250950c4 fwd="183.90.125.206" dyno=web.1 connect=0ms service=2ms status=304 bytes=136 2015-02-10T14:33:38.412860+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/actions.min.js" host=aqiblog.herokuapp.com request_id=2dcac6b1-bb61-4 ccd-b2ec-25ecacf72228 fwd="183.90.125.206" dyno=web.1 connect=1ms service=4ms st atus=304 bytes=136 2015-02-10T14:33:38.772975+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/changelist-bg.gif" host=aqiblog.herokuapp.com request_id=4e6c781c-37 35-43f8-9e00-6b553737b3a6 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1m s status=200 bytes=301 2015-02-10T14:33:38.674202+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon-yes.gif" host=aqiblog.herokuapp.com request_id=e9851dfa-c05f-49 09-a4c4-367907fb285c fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms sta tus=200 bytes=551 2015-02-10T14:33:38.777309+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=e1f74192-01f4-4036 -9a9d-79526979186a fwd="183.90.125.206" dyno=web.1 connect=0ms service=2ms statu s=304 bytes=136 2015-02-10T14:33:38.790954+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg-selected.gif" host=aqiblog.herokuapp.com request_id=1fa8c87c- 67f7-473d-b783-bdff4120a7ce fwd="183.90.125.206" dyno=web.1 connect=2ms service= 2ms status=200 bytes=517 2015-02-10T14:33:38.784201+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/sorting-icons.gif" host=aqiblog.herokuapp.com request_id=c712ebb1-65 e6-45ab-96b5-7a993386ce77 fwd="183.90.125.206" dyno=web.1 connect=0ms service=2m s status=200 bytes=621 2015-02-10T14:33:43.504537+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=4de8523a-32a3-4038-baca-1da937d8bcc2 fw d="183.90.125.206" dyno=web.1 connect=1ms service=63ms status=200 bytes=3837 2015-02-10T14:33:43.831076+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/dashboard.css" host=aqiblog.herokuapp.com request_id=e0bb91fd-3202-4 003-adb3-c56c968cace9 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms st atus=304 bytes=136 2015-02-10T14:33:47.175588+00:00 heroku[router]: at=info method=GET path="/admin /logout/" host=aqiblog.herokuapp.com request_id=9262fa61-6ca5-471d-b640-267022e8 51a7 fwd="183.90.125.206" dyno=web.1 connect=1ms service=76ms status=200 bytes=1 695 2015-02-10T14:33:54.172429+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=8cf14925-254e-464e-9989-97663a447176 fwd="183 .90.125.206" dyno=web.1 connect=0ms service=5ms status=404 bytes=267 2015-02-10T14:57:48.546469+00:00 heroku[api]: Starting process with command `pyt hon manage.py migrate` by aquietimmanence@gmail.com 2015-02-10T14:57:54.603274+00:00 heroku[run.5781]: Awaiting client 2015-02-10T14:57:54.648369+00:00 heroku[run.5781]: Starting process with command `python manage.py migrate` 2015-02-10T14:57:54.901926+00:00 heroku[run.5781]: State changed from starting t o up 2015-02-10T14:57:57.659853+00:00 heroku[run.5781]: State changed from up to comp lete 2015-02-10T14:57:57.650205+00:00 heroku[run.5781]: Process exited with status 0 2015-02-10T15:35:07.305786+00:00 heroku[web.1]: Stopping all processes with SIGT ERM 2015-02-10T15:35:08.786505+00:00 heroku[web.1]: Process exited with status 143 2015-02-10T15:35:05.251964+00:00 heroku[web.1]: Idling 2015-02-10T15:35:05.253030+00:00 heroku[web.1]: State changed from up to down 2015-02-10T15:48:14.796557+00:00 heroku[web.1]: Unidling 2015-02-10T15:48:20.976179+00:00 app[web.1]: serving on http://0.0.0.0:22300 2015-02-10T15:48:14.800364+00:00 heroku[web.1]: State changed from down to start ing 2015-02-10T15:48:19.187658+00:00 heroku[web.1]: Starting process with command `w aitress-serve --port=22300 mysite.wsgi:application` 2015-02-10T15:48:21.486158+00:00 heroku[web.1]: State changed from starting to u p 2015-02-10T15:48:31.912164+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=8db52772-ce7d-4c5d-a b49-07cbe01ebaf7 fwd="183.90.125.206" dyno=web.1 connect=1ms service=2ms status= 200 bytes=14265 2015-02-10T15:48:22.898514+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=df78cf63-b28a-4986-947b-82b7229b6c22 fwd="183 .90.125.206" dyno=web.1 connect=1ms service=22ms status=404 bytes=267 2015-02-10T15:48:32.904690+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/login.css" host=aqiblog.herokuapp.com request_id=f01a7d1e-d3da-4ce2- a596-49c502c148a9 fwd="183.90.125.206" dyno=web.1 connect=6ms service=6ms status =200 bytes=1208 2015-02-10T15:48:31.526354+00:00 heroku[router]: at=info method=GET path="/admin /login/?next=/admin/" host=aqiblog.herokuapp.com request_id=28cd2f09-49fe-4327-a b6c-4fadd62b32db fwd="183.90.125.206" dyno=web.1 connect=2ms service=32ms status =200 bytes=2368 2015-02-10T15:48:33.516041+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=ad4a834a-814a-4a95 -926f-9356f0ee8939 fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms statu s=200 bytes=517 2015-02-10T15:48:31.127574+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=1a5c7e5a-e4b7-4a9d-a141-df959928fe81 fw d="183.90.125.206" dyno=web.1 connect=1ms service=16ms status=302 bytes=390 2015-02-10T15:49:01.840359+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=4287d109-c80e-4e43- acc1-b047f63af3bc fwd="183.90.125.206" dyno=web.1 connect=2ms service=140ms stat us=200 bytes=2540 2015-02-10T15:49:02.187422+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_error.gif" host=aqiblog.herokuapp.com request_id=feb59db0-4c11- 495b-80f2-a5923fc73c6f fwd="183.90.125.206" dyno=web.1 connect=2ms service=3ms s tatus=200 bytes=571 2015-02-10T15:49:21.789377+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg-reverse.gif" host=aqiblog.herokuapp.com request_id=36deb932-f 4b7-433b-99dc-5926493a7c89 fwd="183.90.125.206" dyno=web.1 connect=2ms service=3 ms status=200 bytes=430 2015-02-10T15:49:22.319427+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=5fdd060f-1513-4816- a6eb-203c999af731 fwd="183.90.125.206" dyno=web.1 connect=3ms service=134ms stat us=200 bytes=2540 2015-02-10T15:49:56.826400+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=f3d1e006-6e9c-436b- bf1a-c4d4f05532d4 fwd="183.90.125.206" dyno=web.1 connect=10ms service=187ms sta tus=200 bytes=2540 2015-0 2-10T15:49:57.955395+00:00 heroku[router]: at=info method=GET path="/static/admi n/css/login.css" host=aqiblog.herokuapp.com request_id=a918b235-0698-4ce4-80d0-a 96d8dfc0610 fwd="183.90.125.206" dyno=web.1 connect=1ms service=6ms status=304 b ytes=136 2015-02-10T15:49:59.906654+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=15773995-4c99-459a-9 029-ee456371f894 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms status= 304 bytes=136 2015-02-10T15:50:01.261517+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_error.gif" host=aqiblog.herokuapp.com request_id=3b313279-e294- 42c0-8aa5-f41debcb637e fwd="183.90.125.206" dyno=web.1 connect=4ms service=5ms s tatus=304 bytes=136 2015-02-10T15:50:05.242912+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=6a0162e3-ec3b-445c -b8df-82d5ac6febb2 fwd="183.90.125.206" dyno=web.1 connect=1ms service=2ms statu s=304 bytes=136 2015-02-10T15:57:25.175840+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=0d15d2cb-81e6-4482-bb62-b6182a994ad7 fwd="183 .90.125.206" dyno=web.1 connect=1ms service=5ms status=404 bytes=267 2015-02-10T15:59:35.740276+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=7b4581c2-94d7-4835-a46c-632690169036 fwd="180 .255.248.125" dyno=web.1 connect=1ms service=5ms status=404 bytes=267 2015-02-10T15:59:36.759656+00:00 heroku[router]: at=info method=GET path="/favic on.ico" host=aqiblog.herokuapp.com request_id=2f3cc9e1-c086-4725-b9ab-1ec6973c41 16 fwd="180.255.248.125" dyno=web.1 connect=1ms service=5ms status=404 bytes=278 2015-02-10T17:00:33.167613+00:00 heroku[web.1]: Idling 2015-02-10T17:00:33.168670+00:00 heroku[web.1]: State changed from up to down 2015-02-10T17:00:36.185466+00:00 heroku[web.1]: Stopping all processes with SIGT ERM 2015-02-10T17:00:37.952348+00:00 heroku[web.1]: Process exited with status 143 2015-02-10T17:34:28.848841+00:00 heroku[web.1]: Unidling 2015-02-10T17:34:28.849165+00:00 heroku[web.1]: State changed from down to start ing 2015-02-10T17:34:36.106173+00:00 heroku[web.1]: Starting process with command `w aitress-serve --port=31126 mysite.wsgi:application` 2015-02-10T17:34:38.613422+00:00 app[web.1]: serving on http://0.0.0.0:31126 2015-02-10T17:34:39.197559+00:00 heroku[web.1]: State changed from starting to u p 2015-02-10T17:34:40.974208+00:00 heroku[router]: at=info method=GET path="/admin " host=aqiblog.herokuapp.com request_id=42a56ba0-c220-4c9c-916f-0eede44bfee9 fwd ="79.199.237.241" dyno=web.1 connect=3ms service=22ms status=301 bytes=257 2015-02-10T17:34:41.125316+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=3388a9c4-f5ee-40a5-9ac8-a05d7568854e fw d="79.199.237.241" dyno=web.1 connect=3ms service=20ms status=302 bytes=390 2015-02-10T17:34:41.293835+00:00 heroku[router]: at=info method=GET path="/admin /login/?next=/admin/" host=aqiblog.herokuapp.com request_id=3ae35f86-8510-4cf3-a 0e5-f2a0ce41248b fwd="79.199.237.241" dyno=web.1 connect=2ms service=43ms status =200 bytes=2368 2015-02-10T17:34:41.985024+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=19153867-5c26-41ca-a 8aa-d62e8094a02b fwd="79.199.237.241" dyno=web.1 connect=3ms service=5ms status= 200 bytes=14265 2015-02-10T17:34:42.139780+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/login.css" host=aqiblog.herokuapp.com request_id=7b798b7b-7850-43b4- 927b-2343eacc5582 fwd="79.199.237.241" dyno=web.1 connect=5ms service=5ms status =200 bytes=1208 2015-02-10T17:34:43.024133+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=20fa5217-01eb-4615 -bd4f-b53aaee0421c fwd="79.199.237.241" dyno=web.1 connect=3ms service=5ms statu s=200 bytes=517 2015-02-10T17:34:44.289787+00:00 heroku[router]: at=info method=GET path="/favic on.ico" host=aqiblog.herokuapp.com request_id=4bfc9795-d61c-402c-afd5-08bfe0564b 38 fwd="79.199.237.241" dyno=web.1 connect=4ms service=11ms status=404 bytes=278 2015-02-10T17:34:44.446558+00:00 heroku[router]: at=info method=GET path="/favic on.ico" host=aqiblog.herokuapp.com request_id=131a1b9d-cac0-4410-ae02-0ab562e6b2 2b fwd="79.199.237.241" dyno=web.1 connect=2ms service=7ms status=404 bytes=278 2015-02-10T17:35:08.338710+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=4fd6af83-32f4-4ba2-8117-1e0914ac8882 fwd="79. 199.237.241" dyno=web.1 connect=4ms service=9ms status=404 bytes=267 2015-02-10T18:41:59.962983+00:00 heroku[web.1]: Idling 2015-02-10T18:41:59.963483+00:00 heroku[web.1]: State changed from up to down 2015-02-10T18:42:04.360383+00:00 heroku[web.1]: Stopping all processes with SIGT ERM 2015-02-10T18:42:06.591219+00:00 heroku[web.1]: Process exited with status 143 ``` Also, I'm working on Windows 8, and I'm still new to working with the commandline, so if this requires any command line troubleshooting I'd appreciate greatly if you could give me Windows commands (though I'd gladly search up Windows equivalents if you give me Unix commands)
2015/02/10
[ "https://Stackoverflow.com/questions/28434920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If a method does not return anything, then that method must have some side-effect such as changing a property of the class. Test that side-effect, e.g. test the value of said property.
In the strictest sense, if you ware testing only the ReadCities method, your mock shouldn't be testing that engine.ReadFile actually did something (you would have another unit test for that). You should isolate this method by mocking the call to engine.ReadFile (which I think you've done, but I'm not completely familiar with Moq). In any case, what you'll likely need to do is create a public accessor for \_geoDbCities that you can check in your Assert.
28,434,920
I've been following the djangogirl's tutorial here <http://tutorial.djangogirls.org/en/deploy/README.html> on deploying a django app on Heroku. I am a complete newbie at this so a lot of the stuff just seems like black magic to me, and I have a very fuzzy idea of what is going on. However, I seem to have been able to get everything going smoothly from creating my app to pushing it onto a remote repository and running the web process. ``` >heroku create >git push heroku master >heroku ps:scale web=1 ``` When I open the url of the app after this, I get a 'requested url not found on this server' error page, which the tutorial says is expected since I have not filled up the empty database. So it says to run ``` >heroku run python manage.py migrate >heroku run python manage.py createsuperuser ``` When I ran them both commands seemed to execute fine. I tried running `manage.py migrate` again just to be sure but it simply said that there were no more migrations to apply. I can log in fine into the admin page, but trying to open the app url itself still gives me a 'requested url was not found on this server' error page, even after I applied migrations. Like I said, I'm a real newbie, so I'm at a lost as to how I should troubleshoot this. I've been following the tutorial step-by-step and have no clue where I've went wrong. Help is much appreciated. **EDIT:** Here is the output from `heroku info -s`: ``` addons=heroku-postgresql:hobby-dev archived_at= buildpack_provided_description=Python create_status=complete created_at=2015/02/10 05:02:00 -0800 domain_name=aqiblog.herokuapp.com dynos=1 git_url=https://git.heroku.com/aqiblog.git id=33873439 name=aqiblog owner_delinquent=false owner_email=*** owner_name=*** region=us released_at=2015/02/10 05:33:50 -0800 repo_migrate_status=complete repo_size=9458 requested_stack= slug_size=53579300 stack=cedar-14 updated_at=2015/02/10 06:04:30 -0800 web_url=https://aqiblog.herokuapp.com/ workers=0 ``` Here is the output from `heroku logs`. To my untrained eye nothing seems out of the ordinary: ``` 2015-02-10T14:04:49.315067+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=15e74a24-32e9-4a74-ab2f-696c63853b72 fwd="183 .90.125.206" dyno=web.1 connect=1ms service=4ms status=404 bytes=267 2015-02-10T14:06:59.516339+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=12b8b705-4820-46c4-9195-a04740ad138a fwd="183 .90.125.206" dyno=web.1 connect=6ms service=7ms status=404 bytes=267 2015-02-10T14:20:16.661117+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=599be313-368a-4f66-900f-a459ef42b9ff fwd="183 .90.125.206" dyno=web.1 connect=1ms service=5ms status=404 bytes=267 2015-02-10T14:30:13.477370+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=91f04bfd-e7b9-41a4-b905-4b7d26861cc5 fw d="183.90.125.206" dyno=web.1 connect=2ms service=43ms status=302 bytes=391 2015-02-10T14:30:13.800060+00:00 heroku[router]: at=info method=GET path="/admin /login/?next=/admin/" host=aqiblog.herokuapp.com request_id=301b7aee-0f48-432f-a 9a9-6696b14fe6be fwd="183.90.125.206" dyno=web.1 connect=1ms service=55ms status =200 bytes=2368 2015-02-10T14:30:14.193976+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=d04f60ed-eef6-4678-a 3f0-e133b55df175 fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms status= 304 bytes=136 2015-02-10T14:30:14.463950+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/login.css" host=aqiblog.herokuapp.com request_id=35ba7b7f-8ca2-40e5- b274-5a33138a7478 fwd="183.90.125.206" dyno=web.1 connect=3ms service=6ms status =304 bytes=136 2015-02-10T14:30:14.845040+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=6b9ba7e5-b520-46d2 -ae47-776340e6eac4 fwd="183.90.125.206" dyno=web.1 connect=3ms service=4ms statu s=304 bytes=136 2015-02-10T14:30:31.563636+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=8cb9b343-f93d-4f14- 9803-592614b17b2f fwd="183.90.125.206" dyno=web.1 connect=2ms service=132ms stat us=302 bytes=625 2015-02-10T14:30:31.910829+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=12df9c3c-4b60-4446-9094-ef567912c19f fw d="183.90.125.206" dyno=web.1 connect=1ms service=68ms status=200 bytes=3837 2015-02-10T14:30:32.260761+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/dashboard.css" host=aqiblog.herokuapp.com request_id=194ab120-f85f-4 78f-bd05-2bd5b424177d fwd="183.90.125.206" dyno=web.1 connect=2ms service=4ms st atus=304 bytes=136 2015-02-10T14:30:32.558809+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_addlink.gif" host=aqiblog.herokuapp.com request_id=b1867188-e93 5-42eb-a12e-3342d6b09fd2 fwd="183.90.125.206" dyno=web.1 connect=2ms service=3ms status=304 bytes=136 2015-02-10T14:30:32.556672+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/default-bg.gif" host=aqiblog.herokuapp.com request_id=c9cd25cf-5bd9- 49ca-acb8-78c14d1cdffd fwd="183.90.125.206" dyno=web.1 connect=2ms service=4ms s tatus=304 bytes=136 2015-02-10T14:30:32.958179+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_changelink.gif" host=aqiblog.herokuapp.com request_id=46672886- 026d-4e44-bbda-0a46c738688f fwd="183.90.125.206" dyno=web.1 connect=3ms service= 4ms status=304 bytes=136 2015-02-10T14:30:37.016120+00:00 heroku[router]: at=info method=GET path="/admin /blog/post/" host=aqiblog.herokuapp.com request_id=024f5a16-2afa-46ae-901f-d9c95 d7ffac8 fwd="183.90.125.206" dyno=web.1 connect=2ms service=89ms status=200 byte s=3466 2015-02-10T14:30:37.392657+00:00 heroku[router]: at=info method=GET path="/admin /jsi18n/" host=aqiblog.herokuapp.com request_id=175746a8-6269-499c-9539-e94442df 3740 fwd="183.90.125.206" dyno=web.1 connect=3ms service=45ms status=200 bytes=2 551 2015-02-10T14:30:37.353918+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/changelists.css" host=aqiblog.herokuapp.com request_id=4b1968b8-5977 -49d2-92c7-7f8e6f83bcce fwd="183.90.125.206" dyno=web.1 connect=2ms service=5ms status=200 bytes=5523 2015-02-10T14:30:37.353954+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/core.js" host=aqiblog.herokuapp.com request_id=2765ef40-cf94-4e80-af2 3-df2bd41c29fd fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms status=20 0 bytes=7182 2015-02-10T14:30:37.664695+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/admin/RelatedObjectLookups.js" host=aqiblog.herokuapp.com request_id= ab90b0a5-c743-4a36-8cf8-a45bcdb26c10 fwd="183.90.125.206" dyno=web.1 connect=2ms service=3ms status=200 bytes=3515 2015-02-10T14:30:37.676047+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.min.js" host=aqiblog.herokuapp.com request_id=d793e5e6-f05c-41 7a-bc14-c726b217a873 fwd="183.90.125.206" dyno=web.1 connect=2ms service=11ms st atus=200 bytes=92913 2015-02-10T14:30:37.672663+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.init.js" host=aqiblog.herokuapp.com request_id=7494223b-6a43-4 861-93c6-8a902e8f0b1f fwd="183.90.125.206" dyno=web.1 connect=3ms service=3ms st atus=200 bytes=608 2015-02-10T14:30:37.922666+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/actions.min.js" host=aqiblog.herokuapp.com request_id=4481557e-e808-4 5c7-9948-2856409b9f9c fwd="183.90.125.206" dyno=web.1 connect=3ms service=4ms st atus=200 bytes=3320 2015-02-10T14:30:39.773435+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/tooltag-add.png" host=aqiblog.herokuapp.com request_id=d1e06eca-e54e -44a4-b4c6-b834751c52b8 fwd="183.90.125.206" dyno=web.1 connect=3ms service=3ms status=200 bytes=371 2015-02-10T14:30:39.795367+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg-reverse.gif" host=aqiblog.herokuapp.com request_id=7df78871-e 7a8-4a47-9260-7b1f715b2293 fwd="183.90.125.206" dyno=web.1 connect=2ms service=2 ms status=304 bytes=136 2015-02-10T14:30:43.715783+00:00 heroku[router]: at=info method=GET path="/admin /blog/" host=aqiblog.herokuapp.com request_id=c8c26fb6-7c06-424a-96a3-ed7d7acf52 15 fwd="183.90.125.206" dyno=web.1 connect=2ms service=62ms status=200 bytes=260 6 2015-02-10T14:30:44.051139+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=a9525efc-ca5b-40a2-b 79c-0d1c7ea8f323 fwd="183.90.125.206" dyno=web.1 connect=3ms service=2ms status= 304 bytes=136 2015-02-10T14:30:46.623963+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=6e2f037e-1156-4ecb-ab9a-c629746701bc fw d="183.90.125.206" dyno=web.1 connect=3ms service=67ms status=200 bytes=3837 2015-02-10T14:33:37.383948+00:00 heroku[router]: at=info method=GET path="/admin /auth/user/" host=aqiblog.herokuapp.com request_id=2e7aca9b-bf1a-4bca-a64e-4958c 50d2bc3 fwd="183.90.125.206" dyno=web.1 connect=1ms service=107ms status=200 byt es=6954 2015-02-10T14:33:37.795450+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=427f5971-4d88-4876-b d34-3d61219d0ee0 fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms status= 304 bytes=136 2015-02-10T14:33:38.115038+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/changelists.css" host=aqiblog.herokuapp.com request_id=1011a5b1-f3e3 -4ccd-bb79-decbb9f04bab fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms status=304 bytes=136 2015-02-10T14:33:38.144837+00:00 heroku[router]: at=info method=GET path="/admin /jsi18n/" host=aqiblog.herokuapp.com request_id=713139f7-188f-4dbb-8c06-f187256f 7f69 fwd="183.90.125.206" dyno=web.1 connect=1ms service=45ms status=200 bytes=2 551 2015-02-10T14:33:38.404063+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.init.js" host=aqiblog.herokuapp.com request_id=5135b182-dc2e-4 a74-b8a2-5d6c0ab12db4 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms st atus=304 bytes=136 2015-02-10T14:33:38.400444+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/core.js" host=aqiblog.herokuapp.com request_id=de86c5af-1a29-430f-a65 1-dc6cf1fd48bf fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms status=30 4 bytes=136 2015-02-10T14:33:38.415586+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.min.js" host=aqiblog.herokuapp.com request_id=19c89d3d-5d23-41 09-979e-b8bb3f42199a fwd="183.90.125.206" dyno=web.1 connect=4ms service=2ms sta tus=304 bytes=136 2015-02-10T14:33:38.408607+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_searchbox.png" host=aqiblog.herokuapp.com request_id=c5a70735-1 712-4040-9eb5-6b7dee13abd2 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1 ms status=200 bytes=620 2015-02-10T14:33:38.406036+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/admin/RelatedObjectLookups.js" host=aqiblog.herokuapp.com request_id= 893d6f5c-af8b-4532-8aa3-6934250950c4 fwd="183.90.125.206" dyno=web.1 connect=0ms service=2ms status=304 bytes=136 2015-02-10T14:33:38.412860+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/actions.min.js" host=aqiblog.herokuapp.com request_id=2dcac6b1-bb61-4 ccd-b2ec-25ecacf72228 fwd="183.90.125.206" dyno=web.1 connect=1ms service=4ms st atus=304 bytes=136 2015-02-10T14:33:38.772975+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/changelist-bg.gif" host=aqiblog.herokuapp.com request_id=4e6c781c-37 35-43f8-9e00-6b553737b3a6 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1m s status=200 bytes=301 2015-02-10T14:33:38.674202+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon-yes.gif" host=aqiblog.herokuapp.com request_id=e9851dfa-c05f-49 09-a4c4-367907fb285c fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms sta tus=200 bytes=551 2015-02-10T14:33:38.777309+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=e1f74192-01f4-4036 -9a9d-79526979186a fwd="183.90.125.206" dyno=web.1 connect=0ms service=2ms statu s=304 bytes=136 2015-02-10T14:33:38.790954+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg-selected.gif" host=aqiblog.herokuapp.com request_id=1fa8c87c- 67f7-473d-b783-bdff4120a7ce fwd="183.90.125.206" dyno=web.1 connect=2ms service= 2ms status=200 bytes=517 2015-02-10T14:33:38.784201+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/sorting-icons.gif" host=aqiblog.herokuapp.com request_id=c712ebb1-65 e6-45ab-96b5-7a993386ce77 fwd="183.90.125.206" dyno=web.1 connect=0ms service=2m s status=200 bytes=621 2015-02-10T14:33:43.504537+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=4de8523a-32a3-4038-baca-1da937d8bcc2 fw d="183.90.125.206" dyno=web.1 connect=1ms service=63ms status=200 bytes=3837 2015-02-10T14:33:43.831076+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/dashboard.css" host=aqiblog.herokuapp.com request_id=e0bb91fd-3202-4 003-adb3-c56c968cace9 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms st atus=304 bytes=136 2015-02-10T14:33:47.175588+00:00 heroku[router]: at=info method=GET path="/admin /logout/" host=aqiblog.herokuapp.com request_id=9262fa61-6ca5-471d-b640-267022e8 51a7 fwd="183.90.125.206" dyno=web.1 connect=1ms service=76ms status=200 bytes=1 695 2015-02-10T14:33:54.172429+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=8cf14925-254e-464e-9989-97663a447176 fwd="183 .90.125.206" dyno=web.1 connect=0ms service=5ms status=404 bytes=267 2015-02-10T14:57:48.546469+00:00 heroku[api]: Starting process with command `pyt hon manage.py migrate` by aquietimmanence@gmail.com 2015-02-10T14:57:54.603274+00:00 heroku[run.5781]: Awaiting client 2015-02-10T14:57:54.648369+00:00 heroku[run.5781]: Starting process with command `python manage.py migrate` 2015-02-10T14:57:54.901926+00:00 heroku[run.5781]: State changed from starting t o up 2015-02-10T14:57:57.659853+00:00 heroku[run.5781]: State changed from up to comp lete 2015-02-10T14:57:57.650205+00:00 heroku[run.5781]: Process exited with status 0 2015-02-10T15:35:07.305786+00:00 heroku[web.1]: Stopping all processes with SIGT ERM 2015-02-10T15:35:08.786505+00:00 heroku[web.1]: Process exited with status 143 2015-02-10T15:35:05.251964+00:00 heroku[web.1]: Idling 2015-02-10T15:35:05.253030+00:00 heroku[web.1]: State changed from up to down 2015-02-10T15:48:14.796557+00:00 heroku[web.1]: Unidling 2015-02-10T15:48:20.976179+00:00 app[web.1]: serving on http://0.0.0.0:22300 2015-02-10T15:48:14.800364+00:00 heroku[web.1]: State changed from down to start ing 2015-02-10T15:48:19.187658+00:00 heroku[web.1]: Starting process with command `w aitress-serve --port=22300 mysite.wsgi:application` 2015-02-10T15:48:21.486158+00:00 heroku[web.1]: State changed from starting to u p 2015-02-10T15:48:31.912164+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=8db52772-ce7d-4c5d-a b49-07cbe01ebaf7 fwd="183.90.125.206" dyno=web.1 connect=1ms service=2ms status= 200 bytes=14265 2015-02-10T15:48:22.898514+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=df78cf63-b28a-4986-947b-82b7229b6c22 fwd="183 .90.125.206" dyno=web.1 connect=1ms service=22ms status=404 bytes=267 2015-02-10T15:48:32.904690+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/login.css" host=aqiblog.herokuapp.com request_id=f01a7d1e-d3da-4ce2- a596-49c502c148a9 fwd="183.90.125.206" dyno=web.1 connect=6ms service=6ms status =200 bytes=1208 2015-02-10T15:48:31.526354+00:00 heroku[router]: at=info method=GET path="/admin /login/?next=/admin/" host=aqiblog.herokuapp.com request_id=28cd2f09-49fe-4327-a b6c-4fadd62b32db fwd="183.90.125.206" dyno=web.1 connect=2ms service=32ms status =200 bytes=2368 2015-02-10T15:48:33.516041+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=ad4a834a-814a-4a95 -926f-9356f0ee8939 fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms statu s=200 bytes=517 2015-02-10T15:48:31.127574+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=1a5c7e5a-e4b7-4a9d-a141-df959928fe81 fw d="183.90.125.206" dyno=web.1 connect=1ms service=16ms status=302 bytes=390 2015-02-10T15:49:01.840359+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=4287d109-c80e-4e43- acc1-b047f63af3bc fwd="183.90.125.206" dyno=web.1 connect=2ms service=140ms stat us=200 bytes=2540 2015-02-10T15:49:02.187422+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_error.gif" host=aqiblog.herokuapp.com request_id=feb59db0-4c11- 495b-80f2-a5923fc73c6f fwd="183.90.125.206" dyno=web.1 connect=2ms service=3ms s tatus=200 bytes=571 2015-02-10T15:49:21.789377+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg-reverse.gif" host=aqiblog.herokuapp.com request_id=36deb932-f 4b7-433b-99dc-5926493a7c89 fwd="183.90.125.206" dyno=web.1 connect=2ms service=3 ms status=200 bytes=430 2015-02-10T15:49:22.319427+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=5fdd060f-1513-4816- a6eb-203c999af731 fwd="183.90.125.206" dyno=web.1 connect=3ms service=134ms stat us=200 bytes=2540 2015-02-10T15:49:56.826400+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=f3d1e006-6e9c-436b- bf1a-c4d4f05532d4 fwd="183.90.125.206" dyno=web.1 connect=10ms service=187ms sta tus=200 bytes=2540 2015-0 2-10T15:49:57.955395+00:00 heroku[router]: at=info method=GET path="/static/admi n/css/login.css" host=aqiblog.herokuapp.com request_id=a918b235-0698-4ce4-80d0-a 96d8dfc0610 fwd="183.90.125.206" dyno=web.1 connect=1ms service=6ms status=304 b ytes=136 2015-02-10T15:49:59.906654+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=15773995-4c99-459a-9 029-ee456371f894 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms status= 304 bytes=136 2015-02-10T15:50:01.261517+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_error.gif" host=aqiblog.herokuapp.com request_id=3b313279-e294- 42c0-8aa5-f41debcb637e fwd="183.90.125.206" dyno=web.1 connect=4ms service=5ms s tatus=304 bytes=136 2015-02-10T15:50:05.242912+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=6a0162e3-ec3b-445c -b8df-82d5ac6febb2 fwd="183.90.125.206" dyno=web.1 connect=1ms service=2ms statu s=304 bytes=136 2015-02-10T15:57:25.175840+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=0d15d2cb-81e6-4482-bb62-b6182a994ad7 fwd="183 .90.125.206" dyno=web.1 connect=1ms service=5ms status=404 bytes=267 2015-02-10T15:59:35.740276+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=7b4581c2-94d7-4835-a46c-632690169036 fwd="180 .255.248.125" dyno=web.1 connect=1ms service=5ms status=404 bytes=267 2015-02-10T15:59:36.759656+00:00 heroku[router]: at=info method=GET path="/favic on.ico" host=aqiblog.herokuapp.com request_id=2f3cc9e1-c086-4725-b9ab-1ec6973c41 16 fwd="180.255.248.125" dyno=web.1 connect=1ms service=5ms status=404 bytes=278 2015-02-10T17:00:33.167613+00:00 heroku[web.1]: Idling 2015-02-10T17:00:33.168670+00:00 heroku[web.1]: State changed from up to down 2015-02-10T17:00:36.185466+00:00 heroku[web.1]: Stopping all processes with SIGT ERM 2015-02-10T17:00:37.952348+00:00 heroku[web.1]: Process exited with status 143 2015-02-10T17:34:28.848841+00:00 heroku[web.1]: Unidling 2015-02-10T17:34:28.849165+00:00 heroku[web.1]: State changed from down to start ing 2015-02-10T17:34:36.106173+00:00 heroku[web.1]: Starting process with command `w aitress-serve --port=31126 mysite.wsgi:application` 2015-02-10T17:34:38.613422+00:00 app[web.1]: serving on http://0.0.0.0:31126 2015-02-10T17:34:39.197559+00:00 heroku[web.1]: State changed from starting to u p 2015-02-10T17:34:40.974208+00:00 heroku[router]: at=info method=GET path="/admin " host=aqiblog.herokuapp.com request_id=42a56ba0-c220-4c9c-916f-0eede44bfee9 fwd ="79.199.237.241" dyno=web.1 connect=3ms service=22ms status=301 bytes=257 2015-02-10T17:34:41.125316+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=3388a9c4-f5ee-40a5-9ac8-a05d7568854e fw d="79.199.237.241" dyno=web.1 connect=3ms service=20ms status=302 bytes=390 2015-02-10T17:34:41.293835+00:00 heroku[router]: at=info method=GET path="/admin /login/?next=/admin/" host=aqiblog.herokuapp.com request_id=3ae35f86-8510-4cf3-a 0e5-f2a0ce41248b fwd="79.199.237.241" dyno=web.1 connect=2ms service=43ms status =200 bytes=2368 2015-02-10T17:34:41.985024+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=19153867-5c26-41ca-a 8aa-d62e8094a02b fwd="79.199.237.241" dyno=web.1 connect=3ms service=5ms status= 200 bytes=14265 2015-02-10T17:34:42.139780+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/login.css" host=aqiblog.herokuapp.com request_id=7b798b7b-7850-43b4- 927b-2343eacc5582 fwd="79.199.237.241" dyno=web.1 connect=5ms service=5ms status =200 bytes=1208 2015-02-10T17:34:43.024133+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=20fa5217-01eb-4615 -bd4f-b53aaee0421c fwd="79.199.237.241" dyno=web.1 connect=3ms service=5ms statu s=200 bytes=517 2015-02-10T17:34:44.289787+00:00 heroku[router]: at=info method=GET path="/favic on.ico" host=aqiblog.herokuapp.com request_id=4bfc9795-d61c-402c-afd5-08bfe0564b 38 fwd="79.199.237.241" dyno=web.1 connect=4ms service=11ms status=404 bytes=278 2015-02-10T17:34:44.446558+00:00 heroku[router]: at=info method=GET path="/favic on.ico" host=aqiblog.herokuapp.com request_id=131a1b9d-cac0-4410-ae02-0ab562e6b2 2b fwd="79.199.237.241" dyno=web.1 connect=2ms service=7ms status=404 bytes=278 2015-02-10T17:35:08.338710+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=4fd6af83-32f4-4ba2-8117-1e0914ac8882 fwd="79. 199.237.241" dyno=web.1 connect=4ms service=9ms status=404 bytes=267 2015-02-10T18:41:59.962983+00:00 heroku[web.1]: Idling 2015-02-10T18:41:59.963483+00:00 heroku[web.1]: State changed from up to down 2015-02-10T18:42:04.360383+00:00 heroku[web.1]: Stopping all processes with SIGT ERM 2015-02-10T18:42:06.591219+00:00 heroku[web.1]: Process exited with status 143 ``` Also, I'm working on Windows 8, and I'm still new to working with the commandline, so if this requires any command line troubleshooting I'd appreciate greatly if you could give me Windows commands (though I'd gladly search up Windows equivalents if you give me Unix commands)
2015/02/10
[ "https://Stackoverflow.com/questions/28434920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If a method does not return anything, then that method must have some side-effect such as changing a property of the class. Test that side-effect, e.g. test the value of said property.
You question actually consists of two questions: how to test `void()` methods, and how to test this `ReadCities(string fileName)` method. In response to the first - In case your void method changes the internal state of the object, then that is what you can test for: Example: ``` public class Person { public int age; public void SetAge(int age) { this.age = age; } } ``` Then your test would be ``` var p = new Person(); p.SetAge(12); Assert.AreEqual(p.age, 12); ``` In response to the question how to test that ReadCities method, well, you don't want to Mock it for one. You only mock the stuff you don't want to test - in a test. Add a CSV file to your testproject ( type = content, action = copy always ) and use the `DeploymentItem` attribute to copy the CSV file into the test folder. Then test with ``` var service = new Service(); service.ReadCities(pathToCsvFile); Assert.NotNull(service.Cities); // Actually - you want better assertions ``` So maybe ReadCities might be a void method, you can test the internal state of the object after, so the cities list. If you don't expose the list of cities, there's another thing called the [InternalsVisibleToAttribute](https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute%28v=vs.110%29.aspx) which allows your tests to access private members. However, then we can get into a discussion of whether private members need to be tested in the first place.
28,434,920
I've been following the djangogirl's tutorial here <http://tutorial.djangogirls.org/en/deploy/README.html> on deploying a django app on Heroku. I am a complete newbie at this so a lot of the stuff just seems like black magic to me, and I have a very fuzzy idea of what is going on. However, I seem to have been able to get everything going smoothly from creating my app to pushing it onto a remote repository and running the web process. ``` >heroku create >git push heroku master >heroku ps:scale web=1 ``` When I open the url of the app after this, I get a 'requested url not found on this server' error page, which the tutorial says is expected since I have not filled up the empty database. So it says to run ``` >heroku run python manage.py migrate >heroku run python manage.py createsuperuser ``` When I ran them both commands seemed to execute fine. I tried running `manage.py migrate` again just to be sure but it simply said that there were no more migrations to apply. I can log in fine into the admin page, but trying to open the app url itself still gives me a 'requested url was not found on this server' error page, even after I applied migrations. Like I said, I'm a real newbie, so I'm at a lost as to how I should troubleshoot this. I've been following the tutorial step-by-step and have no clue where I've went wrong. Help is much appreciated. **EDIT:** Here is the output from `heroku info -s`: ``` addons=heroku-postgresql:hobby-dev archived_at= buildpack_provided_description=Python create_status=complete created_at=2015/02/10 05:02:00 -0800 domain_name=aqiblog.herokuapp.com dynos=1 git_url=https://git.heroku.com/aqiblog.git id=33873439 name=aqiblog owner_delinquent=false owner_email=*** owner_name=*** region=us released_at=2015/02/10 05:33:50 -0800 repo_migrate_status=complete repo_size=9458 requested_stack= slug_size=53579300 stack=cedar-14 updated_at=2015/02/10 06:04:30 -0800 web_url=https://aqiblog.herokuapp.com/ workers=0 ``` Here is the output from `heroku logs`. To my untrained eye nothing seems out of the ordinary: ``` 2015-02-10T14:04:49.315067+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=15e74a24-32e9-4a74-ab2f-696c63853b72 fwd="183 .90.125.206" dyno=web.1 connect=1ms service=4ms status=404 bytes=267 2015-02-10T14:06:59.516339+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=12b8b705-4820-46c4-9195-a04740ad138a fwd="183 .90.125.206" dyno=web.1 connect=6ms service=7ms status=404 bytes=267 2015-02-10T14:20:16.661117+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=599be313-368a-4f66-900f-a459ef42b9ff fwd="183 .90.125.206" dyno=web.1 connect=1ms service=5ms status=404 bytes=267 2015-02-10T14:30:13.477370+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=91f04bfd-e7b9-41a4-b905-4b7d26861cc5 fw d="183.90.125.206" dyno=web.1 connect=2ms service=43ms status=302 bytes=391 2015-02-10T14:30:13.800060+00:00 heroku[router]: at=info method=GET path="/admin /login/?next=/admin/" host=aqiblog.herokuapp.com request_id=301b7aee-0f48-432f-a 9a9-6696b14fe6be fwd="183.90.125.206" dyno=web.1 connect=1ms service=55ms status =200 bytes=2368 2015-02-10T14:30:14.193976+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=d04f60ed-eef6-4678-a 3f0-e133b55df175 fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms status= 304 bytes=136 2015-02-10T14:30:14.463950+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/login.css" host=aqiblog.herokuapp.com request_id=35ba7b7f-8ca2-40e5- b274-5a33138a7478 fwd="183.90.125.206" dyno=web.1 connect=3ms service=6ms status =304 bytes=136 2015-02-10T14:30:14.845040+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=6b9ba7e5-b520-46d2 -ae47-776340e6eac4 fwd="183.90.125.206" dyno=web.1 connect=3ms service=4ms statu s=304 bytes=136 2015-02-10T14:30:31.563636+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=8cb9b343-f93d-4f14- 9803-592614b17b2f fwd="183.90.125.206" dyno=web.1 connect=2ms service=132ms stat us=302 bytes=625 2015-02-10T14:30:31.910829+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=12df9c3c-4b60-4446-9094-ef567912c19f fw d="183.90.125.206" dyno=web.1 connect=1ms service=68ms status=200 bytes=3837 2015-02-10T14:30:32.260761+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/dashboard.css" host=aqiblog.herokuapp.com request_id=194ab120-f85f-4 78f-bd05-2bd5b424177d fwd="183.90.125.206" dyno=web.1 connect=2ms service=4ms st atus=304 bytes=136 2015-02-10T14:30:32.558809+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_addlink.gif" host=aqiblog.herokuapp.com request_id=b1867188-e93 5-42eb-a12e-3342d6b09fd2 fwd="183.90.125.206" dyno=web.1 connect=2ms service=3ms status=304 bytes=136 2015-02-10T14:30:32.556672+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/default-bg.gif" host=aqiblog.herokuapp.com request_id=c9cd25cf-5bd9- 49ca-acb8-78c14d1cdffd fwd="183.90.125.206" dyno=web.1 connect=2ms service=4ms s tatus=304 bytes=136 2015-02-10T14:30:32.958179+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_changelink.gif" host=aqiblog.herokuapp.com request_id=46672886- 026d-4e44-bbda-0a46c738688f fwd="183.90.125.206" dyno=web.1 connect=3ms service= 4ms status=304 bytes=136 2015-02-10T14:30:37.016120+00:00 heroku[router]: at=info method=GET path="/admin /blog/post/" host=aqiblog.herokuapp.com request_id=024f5a16-2afa-46ae-901f-d9c95 d7ffac8 fwd="183.90.125.206" dyno=web.1 connect=2ms service=89ms status=200 byte s=3466 2015-02-10T14:30:37.392657+00:00 heroku[router]: at=info method=GET path="/admin /jsi18n/" host=aqiblog.herokuapp.com request_id=175746a8-6269-499c-9539-e94442df 3740 fwd="183.90.125.206" dyno=web.1 connect=3ms service=45ms status=200 bytes=2 551 2015-02-10T14:30:37.353918+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/changelists.css" host=aqiblog.herokuapp.com request_id=4b1968b8-5977 -49d2-92c7-7f8e6f83bcce fwd="183.90.125.206" dyno=web.1 connect=2ms service=5ms status=200 bytes=5523 2015-02-10T14:30:37.353954+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/core.js" host=aqiblog.herokuapp.com request_id=2765ef40-cf94-4e80-af2 3-df2bd41c29fd fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms status=20 0 bytes=7182 2015-02-10T14:30:37.664695+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/admin/RelatedObjectLookups.js" host=aqiblog.herokuapp.com request_id= ab90b0a5-c743-4a36-8cf8-a45bcdb26c10 fwd="183.90.125.206" dyno=web.1 connect=2ms service=3ms status=200 bytes=3515 2015-02-10T14:30:37.676047+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.min.js" host=aqiblog.herokuapp.com request_id=d793e5e6-f05c-41 7a-bc14-c726b217a873 fwd="183.90.125.206" dyno=web.1 connect=2ms service=11ms st atus=200 bytes=92913 2015-02-10T14:30:37.672663+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.init.js" host=aqiblog.herokuapp.com request_id=7494223b-6a43-4 861-93c6-8a902e8f0b1f fwd="183.90.125.206" dyno=web.1 connect=3ms service=3ms st atus=200 bytes=608 2015-02-10T14:30:37.922666+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/actions.min.js" host=aqiblog.herokuapp.com request_id=4481557e-e808-4 5c7-9948-2856409b9f9c fwd="183.90.125.206" dyno=web.1 connect=3ms service=4ms st atus=200 bytes=3320 2015-02-10T14:30:39.773435+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/tooltag-add.png" host=aqiblog.herokuapp.com request_id=d1e06eca-e54e -44a4-b4c6-b834751c52b8 fwd="183.90.125.206" dyno=web.1 connect=3ms service=3ms status=200 bytes=371 2015-02-10T14:30:39.795367+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg-reverse.gif" host=aqiblog.herokuapp.com request_id=7df78871-e 7a8-4a47-9260-7b1f715b2293 fwd="183.90.125.206" dyno=web.1 connect=2ms service=2 ms status=304 bytes=136 2015-02-10T14:30:43.715783+00:00 heroku[router]: at=info method=GET path="/admin /blog/" host=aqiblog.herokuapp.com request_id=c8c26fb6-7c06-424a-96a3-ed7d7acf52 15 fwd="183.90.125.206" dyno=web.1 connect=2ms service=62ms status=200 bytes=260 6 2015-02-10T14:30:44.051139+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=a9525efc-ca5b-40a2-b 79c-0d1c7ea8f323 fwd="183.90.125.206" dyno=web.1 connect=3ms service=2ms status= 304 bytes=136 2015-02-10T14:30:46.623963+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=6e2f037e-1156-4ecb-ab9a-c629746701bc fw d="183.90.125.206" dyno=web.1 connect=3ms service=67ms status=200 bytes=3837 2015-02-10T14:33:37.383948+00:00 heroku[router]: at=info method=GET path="/admin /auth/user/" host=aqiblog.herokuapp.com request_id=2e7aca9b-bf1a-4bca-a64e-4958c 50d2bc3 fwd="183.90.125.206" dyno=web.1 connect=1ms service=107ms status=200 byt es=6954 2015-02-10T14:33:37.795450+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=427f5971-4d88-4876-b d34-3d61219d0ee0 fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms status= 304 bytes=136 2015-02-10T14:33:38.115038+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/changelists.css" host=aqiblog.herokuapp.com request_id=1011a5b1-f3e3 -4ccd-bb79-decbb9f04bab fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms status=304 bytes=136 2015-02-10T14:33:38.144837+00:00 heroku[router]: at=info method=GET path="/admin /jsi18n/" host=aqiblog.herokuapp.com request_id=713139f7-188f-4dbb-8c06-f187256f 7f69 fwd="183.90.125.206" dyno=web.1 connect=1ms service=45ms status=200 bytes=2 551 2015-02-10T14:33:38.404063+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.init.js" host=aqiblog.herokuapp.com request_id=5135b182-dc2e-4 a74-b8a2-5d6c0ab12db4 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms st atus=304 bytes=136 2015-02-10T14:33:38.400444+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/core.js" host=aqiblog.herokuapp.com request_id=de86c5af-1a29-430f-a65 1-dc6cf1fd48bf fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms status=30 4 bytes=136 2015-02-10T14:33:38.415586+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/jquery.min.js" host=aqiblog.herokuapp.com request_id=19c89d3d-5d23-41 09-979e-b8bb3f42199a fwd="183.90.125.206" dyno=web.1 connect=4ms service=2ms sta tus=304 bytes=136 2015-02-10T14:33:38.408607+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_searchbox.png" host=aqiblog.herokuapp.com request_id=c5a70735-1 712-4040-9eb5-6b7dee13abd2 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1 ms status=200 bytes=620 2015-02-10T14:33:38.406036+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/admin/RelatedObjectLookups.js" host=aqiblog.herokuapp.com request_id= 893d6f5c-af8b-4532-8aa3-6934250950c4 fwd="183.90.125.206" dyno=web.1 connect=0ms service=2ms status=304 bytes=136 2015-02-10T14:33:38.412860+00:00 heroku[router]: at=info method=GET path="/stati c/admin/js/actions.min.js" host=aqiblog.herokuapp.com request_id=2dcac6b1-bb61-4 ccd-b2ec-25ecacf72228 fwd="183.90.125.206" dyno=web.1 connect=1ms service=4ms st atus=304 bytes=136 2015-02-10T14:33:38.772975+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/changelist-bg.gif" host=aqiblog.herokuapp.com request_id=4e6c781c-37 35-43f8-9e00-6b553737b3a6 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1m s status=200 bytes=301 2015-02-10T14:33:38.674202+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon-yes.gif" host=aqiblog.herokuapp.com request_id=e9851dfa-c05f-49 09-a4c4-367907fb285c fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms sta tus=200 bytes=551 2015-02-10T14:33:38.777309+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=e1f74192-01f4-4036 -9a9d-79526979186a fwd="183.90.125.206" dyno=web.1 connect=0ms service=2ms statu s=304 bytes=136 2015-02-10T14:33:38.790954+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg-selected.gif" host=aqiblog.herokuapp.com request_id=1fa8c87c- 67f7-473d-b783-bdff4120a7ce fwd="183.90.125.206" dyno=web.1 connect=2ms service= 2ms status=200 bytes=517 2015-02-10T14:33:38.784201+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/sorting-icons.gif" host=aqiblog.herokuapp.com request_id=c712ebb1-65 e6-45ab-96b5-7a993386ce77 fwd="183.90.125.206" dyno=web.1 connect=0ms service=2m s status=200 bytes=621 2015-02-10T14:33:43.504537+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=4de8523a-32a3-4038-baca-1da937d8bcc2 fw d="183.90.125.206" dyno=web.1 connect=1ms service=63ms status=200 bytes=3837 2015-02-10T14:33:43.831076+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/dashboard.css" host=aqiblog.herokuapp.com request_id=e0bb91fd-3202-4 003-adb3-c56c968cace9 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms st atus=304 bytes=136 2015-02-10T14:33:47.175588+00:00 heroku[router]: at=info method=GET path="/admin /logout/" host=aqiblog.herokuapp.com request_id=9262fa61-6ca5-471d-b640-267022e8 51a7 fwd="183.90.125.206" dyno=web.1 connect=1ms service=76ms status=200 bytes=1 695 2015-02-10T14:33:54.172429+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=8cf14925-254e-464e-9989-97663a447176 fwd="183 .90.125.206" dyno=web.1 connect=0ms service=5ms status=404 bytes=267 2015-02-10T14:57:48.546469+00:00 heroku[api]: Starting process with command `pyt hon manage.py migrate` by aquietimmanence@gmail.com 2015-02-10T14:57:54.603274+00:00 heroku[run.5781]: Awaiting client 2015-02-10T14:57:54.648369+00:00 heroku[run.5781]: Starting process with command `python manage.py migrate` 2015-02-10T14:57:54.901926+00:00 heroku[run.5781]: State changed from starting t o up 2015-02-10T14:57:57.659853+00:00 heroku[run.5781]: State changed from up to comp lete 2015-02-10T14:57:57.650205+00:00 heroku[run.5781]: Process exited with status 0 2015-02-10T15:35:07.305786+00:00 heroku[web.1]: Stopping all processes with SIGT ERM 2015-02-10T15:35:08.786505+00:00 heroku[web.1]: Process exited with status 143 2015-02-10T15:35:05.251964+00:00 heroku[web.1]: Idling 2015-02-10T15:35:05.253030+00:00 heroku[web.1]: State changed from up to down 2015-02-10T15:48:14.796557+00:00 heroku[web.1]: Unidling 2015-02-10T15:48:20.976179+00:00 app[web.1]: serving on http://0.0.0.0:22300 2015-02-10T15:48:14.800364+00:00 heroku[web.1]: State changed from down to start ing 2015-02-10T15:48:19.187658+00:00 heroku[web.1]: Starting process with command `w aitress-serve --port=22300 mysite.wsgi:application` 2015-02-10T15:48:21.486158+00:00 heroku[web.1]: State changed from starting to u p 2015-02-10T15:48:31.912164+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=8db52772-ce7d-4c5d-a b49-07cbe01ebaf7 fwd="183.90.125.206" dyno=web.1 connect=1ms service=2ms status= 200 bytes=14265 2015-02-10T15:48:22.898514+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=df78cf63-b28a-4986-947b-82b7229b6c22 fwd="183 .90.125.206" dyno=web.1 connect=1ms service=22ms status=404 bytes=267 2015-02-10T15:48:32.904690+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/login.css" host=aqiblog.herokuapp.com request_id=f01a7d1e-d3da-4ce2- a596-49c502c148a9 fwd="183.90.125.206" dyno=web.1 connect=6ms service=6ms status =200 bytes=1208 2015-02-10T15:48:31.526354+00:00 heroku[router]: at=info method=GET path="/admin /login/?next=/admin/" host=aqiblog.herokuapp.com request_id=28cd2f09-49fe-4327-a b6c-4fadd62b32db fwd="183.90.125.206" dyno=web.1 connect=2ms service=32ms status =200 bytes=2368 2015-02-10T15:48:33.516041+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=ad4a834a-814a-4a95 -926f-9356f0ee8939 fwd="183.90.125.206" dyno=web.1 connect=1ms service=3ms statu s=200 bytes=517 2015-02-10T15:48:31.127574+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=1a5c7e5a-e4b7-4a9d-a141-df959928fe81 fw d="183.90.125.206" dyno=web.1 connect=1ms service=16ms status=302 bytes=390 2015-02-10T15:49:01.840359+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=4287d109-c80e-4e43- acc1-b047f63af3bc fwd="183.90.125.206" dyno=web.1 connect=2ms service=140ms stat us=200 bytes=2540 2015-02-10T15:49:02.187422+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_error.gif" host=aqiblog.herokuapp.com request_id=feb59db0-4c11- 495b-80f2-a5923fc73c6f fwd="183.90.125.206" dyno=web.1 connect=2ms service=3ms s tatus=200 bytes=571 2015-02-10T15:49:21.789377+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg-reverse.gif" host=aqiblog.herokuapp.com request_id=36deb932-f 4b7-433b-99dc-5926493a7c89 fwd="183.90.125.206" dyno=web.1 connect=2ms service=3 ms status=200 bytes=430 2015-02-10T15:49:22.319427+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=5fdd060f-1513-4816- a6eb-203c999af731 fwd="183.90.125.206" dyno=web.1 connect=3ms service=134ms stat us=200 bytes=2540 2015-02-10T15:49:56.826400+00:00 heroku[router]: at=info method=POST path="/admi n/login/?next=/admin/" host=aqiblog.herokuapp.com request_id=f3d1e006-6e9c-436b- bf1a-c4d4f05532d4 fwd="183.90.125.206" dyno=web.1 connect=10ms service=187ms sta tus=200 bytes=2540 2015-0 2-10T15:49:57.955395+00:00 heroku[router]: at=info method=GET path="/static/admi n/css/login.css" host=aqiblog.herokuapp.com request_id=a918b235-0698-4ce4-80d0-a 96d8dfc0610 fwd="183.90.125.206" dyno=web.1 connect=1ms service=6ms status=304 b ytes=136 2015-02-10T15:49:59.906654+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=15773995-4c99-459a-9 029-ee456371f894 fwd="183.90.125.206" dyno=web.1 connect=0ms service=1ms status= 304 bytes=136 2015-02-10T15:50:01.261517+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/icon_error.gif" host=aqiblog.herokuapp.com request_id=3b313279-e294- 42c0-8aa5-f41debcb637e fwd="183.90.125.206" dyno=web.1 connect=4ms service=5ms s tatus=304 bytes=136 2015-02-10T15:50:05.242912+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=6a0162e3-ec3b-445c -b8df-82d5ac6febb2 fwd="183.90.125.206" dyno=web.1 connect=1ms service=2ms statu s=304 bytes=136 2015-02-10T15:57:25.175840+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=0d15d2cb-81e6-4482-bb62-b6182a994ad7 fwd="183 .90.125.206" dyno=web.1 connect=1ms service=5ms status=404 bytes=267 2015-02-10T15:59:35.740276+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=7b4581c2-94d7-4835-a46c-632690169036 fwd="180 .255.248.125" dyno=web.1 connect=1ms service=5ms status=404 bytes=267 2015-02-10T15:59:36.759656+00:00 heroku[router]: at=info method=GET path="/favic on.ico" host=aqiblog.herokuapp.com request_id=2f3cc9e1-c086-4725-b9ab-1ec6973c41 16 fwd="180.255.248.125" dyno=web.1 connect=1ms service=5ms status=404 bytes=278 2015-02-10T17:00:33.167613+00:00 heroku[web.1]: Idling 2015-02-10T17:00:33.168670+00:00 heroku[web.1]: State changed from up to down 2015-02-10T17:00:36.185466+00:00 heroku[web.1]: Stopping all processes with SIGT ERM 2015-02-10T17:00:37.952348+00:00 heroku[web.1]: Process exited with status 143 2015-02-10T17:34:28.848841+00:00 heroku[web.1]: Unidling 2015-02-10T17:34:28.849165+00:00 heroku[web.1]: State changed from down to start ing 2015-02-10T17:34:36.106173+00:00 heroku[web.1]: Starting process with command `w aitress-serve --port=31126 mysite.wsgi:application` 2015-02-10T17:34:38.613422+00:00 app[web.1]: serving on http://0.0.0.0:31126 2015-02-10T17:34:39.197559+00:00 heroku[web.1]: State changed from starting to u p 2015-02-10T17:34:40.974208+00:00 heroku[router]: at=info method=GET path="/admin " host=aqiblog.herokuapp.com request_id=42a56ba0-c220-4c9c-916f-0eede44bfee9 fwd ="79.199.237.241" dyno=web.1 connect=3ms service=22ms status=301 bytes=257 2015-02-10T17:34:41.125316+00:00 heroku[router]: at=info method=GET path="/admin /" host=aqiblog.herokuapp.com request_id=3388a9c4-f5ee-40a5-9ac8-a05d7568854e fw d="79.199.237.241" dyno=web.1 connect=3ms service=20ms status=302 bytes=390 2015-02-10T17:34:41.293835+00:00 heroku[router]: at=info method=GET path="/admin /login/?next=/admin/" host=aqiblog.herokuapp.com request_id=3ae35f86-8510-4cf3-a 0e5-f2a0ce41248b fwd="79.199.237.241" dyno=web.1 connect=2ms service=43ms status =200 bytes=2368 2015-02-10T17:34:41.985024+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/base.css" host=aqiblog.herokuapp.com request_id=19153867-5c26-41ca-a 8aa-d62e8094a02b fwd="79.199.237.241" dyno=web.1 connect=3ms service=5ms status= 200 bytes=14265 2015-02-10T17:34:42.139780+00:00 heroku[router]: at=info method=GET path="/stati c/admin/css/login.css" host=aqiblog.herokuapp.com request_id=7b798b7b-7850-43b4- 927b-2343eacc5582 fwd="79.199.237.241" dyno=web.1 connect=5ms service=5ms status =200 bytes=1208 2015-02-10T17:34:43.024133+00:00 heroku[router]: at=info method=GET path="/stati c/admin/img/nav-bg.gif" host=aqiblog.herokuapp.com request_id=20fa5217-01eb-4615 -bd4f-b53aaee0421c fwd="79.199.237.241" dyno=web.1 connect=3ms service=5ms statu s=200 bytes=517 2015-02-10T17:34:44.289787+00:00 heroku[router]: at=info method=GET path="/favic on.ico" host=aqiblog.herokuapp.com request_id=4bfc9795-d61c-402c-afd5-08bfe0564b 38 fwd="79.199.237.241" dyno=web.1 connect=4ms service=11ms status=404 bytes=278 2015-02-10T17:34:44.446558+00:00 heroku[router]: at=info method=GET path="/favic on.ico" host=aqiblog.herokuapp.com request_id=131a1b9d-cac0-4410-ae02-0ab562e6b2 2b fwd="79.199.237.241" dyno=web.1 connect=2ms service=7ms status=404 bytes=278 2015-02-10T17:35:08.338710+00:00 heroku[router]: at=info method=GET path="/" hos t=aqiblog.herokuapp.com request_id=4fd6af83-32f4-4ba2-8117-1e0914ac8882 fwd="79. 199.237.241" dyno=web.1 connect=4ms service=9ms status=404 bytes=267 2015-02-10T18:41:59.962983+00:00 heroku[web.1]: Idling 2015-02-10T18:41:59.963483+00:00 heroku[web.1]: State changed from up to down 2015-02-10T18:42:04.360383+00:00 heroku[web.1]: Stopping all processes with SIGT ERM 2015-02-10T18:42:06.591219+00:00 heroku[web.1]: Process exited with status 143 ``` Also, I'm working on Windows 8, and I'm still new to working with the commandline, so if this requires any command line troubleshooting I'd appreciate greatly if you could give me Windows commands (though I'd gladly search up Windows equivalents if you give me Unix commands)
2015/02/10
[ "https://Stackoverflow.com/questions/28434920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You question actually consists of two questions: how to test `void()` methods, and how to test this `ReadCities(string fileName)` method. In response to the first - In case your void method changes the internal state of the object, then that is what you can test for: Example: ``` public class Person { public int age; public void SetAge(int age) { this.age = age; } } ``` Then your test would be ``` var p = new Person(); p.SetAge(12); Assert.AreEqual(p.age, 12); ``` In response to the question how to test that ReadCities method, well, you don't want to Mock it for one. You only mock the stuff you don't want to test - in a test. Add a CSV file to your testproject ( type = content, action = copy always ) and use the `DeploymentItem` attribute to copy the CSV file into the test folder. Then test with ``` var service = new Service(); service.ReadCities(pathToCsvFile); Assert.NotNull(service.Cities); // Actually - you want better assertions ``` So maybe ReadCities might be a void method, you can test the internal state of the object after, so the cities list. If you don't expose the list of cities, there's another thing called the [InternalsVisibleToAttribute](https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute%28v=vs.110%29.aspx) which allows your tests to access private members. However, then we can get into a discussion of whether private members need to be tested in the first place.
In the strictest sense, if you ware testing only the ReadCities method, your mock shouldn't be testing that engine.ReadFile actually did something (you would have another unit test for that). You should isolate this method by mocking the call to engine.ReadFile (which I think you've done, but I'm not completely familiar with Moq). In any case, what you'll likely need to do is create a public accessor for \_geoDbCities that you can check in your Assert.
73,880,813
I'm a beginner into python language. I want to develop an android app. I've wrote some code and few days ago I wanted to see how my app looks on mobile before continue. I've tried all methods to convert .py to .apk but failed. I've tried with google colab, I've installed a VM... but nothing worked. If I use google colab, after all I receive an .apk, but when I install it on my phone, doesn't work... The app opens, but closes imediatly. If I use VM I receive this error: [error message](https://i.stack.imgur.com/hIYxo.png) This is a picture of all my components: [components](https://i.stack.imgur.com/uCYJl.png) For google colab I'm using this commands : !pip install buildozer !pip install cython==0.29.19 !sudo apt-get install -y python3-pip build-essential git python3 python3-dev ffmpeg libsdl2-dev libsdl2-image-dev libsdl2-mixer-dev libsdl2-ttf-dev libportmidi-dev libswscale-dev libavformat-dev libavcodec-dev zlib1g-dev !sudo apt-get install -y libgstreamer1.0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good !sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev zlib1g-dev libssl-dev openssl libgdbm-dev libgdbm-compat-dev liblzma-dev libreadline-dev libncursesw5-dev libffi-dev uuid-dev libffi6 !sudo apt-get install libffi-dev !buildozer init !buildozer -v android debug !buildozer android clean This is a picture with my google colab: [google colab & buildozer.spec](https://i.stack.imgur.com/67S5k.png) I've tried all tutorials I've found on internet but nothing worked. The code works perfectly on PC! Please, help me!
2022/09/28
[ "https://Stackoverflow.com/questions/73880813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20109886/" ]
Create an interface that describes the data you want to store in the context: ``` interface AuthContextType { currentUser: IUser; login: (email: string, password: string) => ......, signup: (email: string, password: string) => ...., logout: () => void, recoverPassword: (email: string) => ...., update: (data: any) => .... } ``` Create an object that describes the initial state: ``` const initialState = { currentUser: null, login: (email: string, ....) => console.error('No AuthProvider supplied. Wrap this component with a AuthProvider to use this functionality.'), ... }; ``` Then create the context: ``` const AuthContext = createContext<AuthContextType>(initialState); ```
You can either type `createContext` with `YourInterface | null` as in ```js const AuthContext = createContext<YourInterface|null>(null); ``` or type cast an empty object as in ```js const AuthContext = createContext({} as YourInterface) ```
60,715,443
I've create a pretty standard linked list in python with a Node class and LinkedList class. I've also added in methods for LinkedList as follows: 1. add(newNode): Adds an element to the linked list 2. addBefore(valueToFind, newNode): Adds a new node before an element with the value specified. 3. printClean: Prints the linked list I'm trying to use the addBefore method to perform an insertion, however it will not work if the insertion isn't on the head. I'm not sure why. ``` class Node: def __init__(self, dataval =None): self.dataval = dataval self.nextval = None class LinkedList: def __init__(self, headval =None): self.headval = headval def add(self, newNode): # The linked list is empty if(self.headval is None): self.headval = newNode else: # Add to the end of the linked list currentNode = self.headval while currentNode is not None: # Found the last element if(currentNode.nextval is None): currentNode.nextval = newNode break else: currentNode = currentNode.nextval def addBefore(self, valueToFind, newNode): currentNode = self.headval previousNode = None while currentNode is not None: # We found the element we will insert before if (currentNode.dataval == valueToFind): # Set our new node's next value to the current element newNode.nextval = currentNode # If we are inserting at the head position if (previousNode is None): self.headval = newNode else: # Change previous node's next to our new node previousNode.nexval = newNode return 0 # Update loop variables previousNode = currentNode currentNode = currentNode.nextval return -1 def printClean(self): currentNode = self.headval while currentNode is not None: print(currentNode.dataval, end='') if(currentNode.nextval != None): print("->", end='') currentNode = currentNode.nextval else: return testLinkedList = LinkedList() testLinkedList.add(Node("Monday")) testLinkedList.add(Node("Wednesday")) testLinkedList.addBefore("Wednesday", Node("Tuesday")) testLinkedList.printClean() ``` > > Monday->Wednesday > > >
2020/03/17
[ "https://Stackoverflow.com/questions/60715443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1607450/" ]
Each line to list, then `map()`, `join()` with `\n` would be fine ``` this.setState({ body: value.blocks.map(x => x.text).join("\n") }); ``` ``` import React from "react"; import Body from "./Body"; class App extends React.Component { constructor(props) { super(props); this.state = { body: "" }; } changeBodyHandler = value => { this.setState({ body: value.blocks.map(x => x.text).join("\n") }); }; render() { console.log(this.state.body); return ( <div> <Body label="Body" name="body" value={this.state.body} onChange={this.changeBodyHandler} /> </div> ); } } export default App; ``` --- [![enter image description here](https://i.stack.imgur.com/bFa3H.jpg)](https://i.stack.imgur.com/bFa3H.jpg) Try it online: [![Edit awesome-hamilton-l3h7k](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/awesome-hamilton-l3h7k?fontsize=14&hidenavigation=1&theme=dark)
* If you want with break line like as it is in editor, add `<p>` tag while concatination. ``` changeBodyHandler = value => { let data =value.block; let text = ""; data.map(index => { text = text +"<p>" +index.text+"</p>"; }); this.setState({ body: text }); }; ``` * And if you want to display the data in same way somewher use `dangerouslySetInnerHTML` ``` <div dangerouslySetInnerHTML={{__html: this.state.body}} /> ```
67,168,199
I'm trying to build an executable from a simple python script using pyvisa-py but I'm running into error after I run the executable generated by pyinstaller. Here what my small python code looks like ``` import pyvisa as visa import tkinter as tk root = tk.Tk() root.title("SCPI test") canvas1 = tk.Canvas(root, width=200, height=100, bg='lightsteelblue2', relief='raised') canvas1.pack() def test_1(): rm = visa.ResourceManager("@py") res_list = rm.list_resources() print('res_list :', res_list) len_list = len(res_list) print('len_list :', len_list) if not len_list: print("No equipment found.") try: inst = rm.open_resource('USB0::0x1AB1::0x0588::DS1K00005888::INSTR') print(inst.query("*IDN?")) except ValueError: print("No device found.") Launch_prgm = tk.Button(text="Device detect", command=test_1, bg='green', fg='white', font=('helvetica', 12, 'bold')) canvas1.create_window(100, 50, window=Launch_prgm) root.mainloop() ``` When I run this code in Pycharm or by directly running the .py file from a terminal outside Pycharm it is working well. But when I build the executable using pyinstaller I got the following error. ``` Exception in Tkinter callback Traceback (most recent call last): File "pyvisa/highlevel.py", line 2833, in get_wrapper_class File "importlib/__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'pyvisa_py' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "pyvisa/highlevel.py", line 2838, in get_wrapper_class File "importlib/__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'pyvisa-py' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "tkinter/__init__.py", line 1705, in __call__ File "test_ea_psu.py", line 17, in test_1 File "pyvisa/highlevel.py", line 3015, in __new__ File "pyvisa/highlevel.py", line 2926, in open_visa_library File "pyvisa/highlevel.py", line 2849, in get_wrapper_class ValueError: Wrapper not found: No package named pyvisa_py ``` Apparently I'm not the only one having problems with pyvisa and pyinstaller. Many people on github had this issue as well. <https://github.com/pyvisa/pyvisa-py/issues/216> I'm using python 3.6 on Zorin OS (an ubuntu like OS). When I do python3 -m visa info I got the following info showing ``` python3 -m visa info /usr/local/lib/python3.6/dist-packages/visa.py:23: FutureWarning: The visa module provided by PyVISA is being deprecated. You can replace `import visa` by `import pyvisa as visa` to achieve the same effect. The reason for the deprecation is the possible conflict with the visa package provided by the https://github.com/visa-sdk/visa-python which can result in hard to debug situations. FutureWarning, Machine Details: Platform ID: Linux-5.4.0-67-generic-x86_64-with-Zorin-15-bionic Processor: x86_64 Python: Implementation: CPython Executable: /usr/bin/python3 Version: 3.6.9 Compiler: GCC 8.4.0 Bits: 64bit Build: Jan 26 2021 15:33:00 (#default) Unicode: UCS4 PyVISA Version: 1.11.3 Backends: ivi: Version: 1.11.3 (bundled with PyVISA) Binary library: Not found py: Version: 0.5.2 ASRL INSTR: Available via PySerial (3.5) USB INSTR: Available via PyUSB (1.1.1). Backend: libusb1 USB RAW: Available via PyUSB (1.1.1). Backend: libusb1 TCPIP INSTR: Available TCPIP SOCKET: Available GPIB INSTR: Please install linux-gpib (Linux) or gpib-ctypes (Windows, Linux) to use this resource type. Note that installing gpib-ctypes will give you access to a broader range of funcionality. No module named 'gpib' ``` Also I installed pyvisa and pyvisa-py using pycharm package installer builtin function (work the same as pip3) If I do list pip3 I got ``` Package Version ------------------------- ---------------------- altgraph 0.17 apturl 0.5.2 asn1crypto 0.24.0 Brlapi 0.6.6 certifi 2018.1.18 chardet 3.0.4 chrome-gnome-shell 0.0.0 colorama 0.4.4 command-not-found 0.3 configparser 5.0.2 crayons 0.4.0 cryptography 2.1.4 cupshelpers 1.0 cycler 0.10.0 dataclasses 0.8 defer 1.0.6 defusedxml 0.7.1 distro-info 0.18ubuntu0.18.04.1 ea-psu-controller 1.1.0 et-xmlfile 1.0.1 httplib2 0.9.2 idna 2.6 importlib-metadata 4.0.0 iso8601 0.1.14 keyring 10.6.0 keyrings.alt 3.0 language-selector 0.1 launchpadlib 1.10.6 lazr.restfulclient 0.13.5 lazr.uri 1.0.3 louis 3.5.0 lxml 4.6.2 m3u8 0.8.0 macaroonbakery 1.1.3 Mako 1.0.7 MarkupSafe 1.0 matplotlib 2.1.1 netifaces 0.10.4 numpy 1.13.3 oauth 1.0.1 olefile 0.45.1 openpyxl 3.0.7 pexpect 4.2.1 Pillow 5.1.0 pip 21.0.1 power 1.4 protobuf 3.0.0 psutil 5.4.2 pycairo 1.16.2 pycrypto 2.6.1 pycups 1.9.73 pygobject 3.26.1 pyinstaller 4.3 pyinstaller-hooks-contrib 2021.1 pymacaroons 0.13.0 PyNaCl 1.1.2 pyparsing 2.2.0 pyRFC3339 1.0 pyserial 3.5 python-apt 1.6.5-ubuntu0.5-zorin1 python-dateutil 2.6.1 python-debian 0.1.32 pytz 2018.3 pyusb 1.1.1 PyVISA 1.11.3 PyVISA-py 0.5.2 pyxdg 0.25 PyYAML 3.12 reportlab 3.4.0 requests 2.18.4 requests-unixsocket 0.1.5 SecretStorage 2.3.1 selenium 3.141.0 setuptools 56.0.0 simplejson 3.13.2 six 1.11.0 system-service 0.3 typing-extensions 3.7.4.3 ubuntu-drivers-common 0.0.0 ufw 0.36 urllib3 1.22 wadllib 1.3.2 webdriver-manager 3.3.0 wheel 0.30.0 xkit 0.0.0 zipp 3.4.1 zope.interface 4.3.2 zorin-appearance 3.0 zorin-connect 1.0 zorin-exec-guard 1.0 ``` I have experience using pyinstaller with other python code I have written in the past but I'm a beginner with pyvisa. I spent my whole last night trying to figure out what was the problem but I coudn't so that's why I'm asking here for help. Sorry if the same question have been posted before I searched everywhere a solution but didn't find any.
2021/04/19
[ "https://Stackoverflow.com/questions/67168199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13849963/" ]
You can always add missing site-package(s) in your list of hidden imports in your `.spec` file. Specifically for missing '`pyvisa_py`' module you can write following `test.spec` file: ``` # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['test.py'], pathex=['/home/user/test/source'], binaries=[], datas=[('/path/to/python/site-packages/pyvisa_py','pyvisa_py')], hiddenimports=['pyvisa_py'], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='test', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='test') ``` Note: you can get your '`/path/to/python/site-packages/`' using command `python -m site`
Recently I was searching for similar issue with another library. What I understood is that in such cases, 1. Make sure that the packages are installed via pip. 2. If it still has a problem, try to copy the entire library folder from *"<python\_env\_path>/lib/site-packages/"* to the *"dist"* folder created by pyinstaller. 3. In rare case, just see if renaming the import to match the folder name. Ref: <https://github.com/pm4py/pm4py-ws/blob/master/WINDOWS_COMPILING.txt> Note: python\_env\_path is the path to env folder inside the python installation or the actual python installation folder if you don't have a virtual environment.
69,583,271
Here is a toy example of my pandas dataframe: ``` country_market language_market 0 United States English 1 United States French 2 Not used Not used 3 Canada OR United States English 4 Germany English 5 United Kingdom French 6 United States German 7 United Kingdom English 8 United Kingdom English 9 Not used Not used 10 United States French 11 United States English 12 United Kingdom English 13 United States French 14 Not used English 15 Not used English 16 United States French 17 United States Not used 18 Not used English 19 United States German ``` I want to add a column `top_country` that shows whether the value in `country_market` is one of the top two most commonly seen countries in the data. If it is, I want the new `top_country` column show the value in `country_market` and if not, then I want it to show "Other". I want to repeat this process for`language_market` (and a whole load of other market columns I don't show here). This is how I'd like the data to look after processing: ``` country_market language_market top_country top_language 0 United States English United States English 1 United States French United States French 2 Not used Not used Not used Other 3 Canada OR United States English Other English 4 Germany English Other English 5 United Kingdom French Other French 6 United States German United States Other 7 United Kingdom English Other English 8 United Kingdom English Other English 9 Not used Not used Not used Other 10 United States French United States French 11 United States English United States English 12 United Kingdom English Other English 13 United States French United States French 14 Not used English Not used English 15 Not used English Not used English 16 United States French United States French 17 United States Not used United States Other 18 Not used English Not used English 19 United States German United States Other ``` I made a function `original_top_markets_function` to do this, but I couldn't figure how to pass the `value_counts` part of my function to pandas `apply`. I kept getting `AttributeError: 'str' object has no attribute 'value_counts'`. ``` def original_top_markets_function(x): top2 = x.value_counts().nlargest(2).index for i in x: if i in top2: return i else: return 'Other' ``` I know this is because `apply` is looking at each element in my target column, but I also need the function to consider the whole column at once, so that I can use `value_counts`. I don't know how to do that. So I have come up with this `top_markets` function as a solution, using a list, which does what I want, but isn't very efficient. I'll need to apply this function to lots of different market columns, so I'd like something more pythonic. ``` def top_markets(x): top2 = x.value_counts().nlargest(2).index results = [] for i in x: if i in top2: results.append(i) else: results.append('Other') return results ``` Here's a reproducible example. Please can somehow help me fix my `top_markets` function so I can use it with `apply`? ``` import pandas as pd d = {0: {'country_market': 'United States', 'language_market': 'English'}, 1: {'country_market': 'United States', 'language_market': 'French'}, 2: {'country_market': 'Not used', 'language_market': 'Not used'}, 3: {'country_market': 'Canada OR United States', 'language_market': 'English'}, 4: {'country_market': 'Germany', 'language_market': 'English'}, 5: {'country_market': 'United Kingdom', 'language_market': 'French'}, 6: {'country_market': 'United States', 'language_market': 'German'}, 7: {'country_market': 'United Kingdom', 'language_market': 'English'}, 8: {'country_market': 'United Kingdom', 'language_market': 'English'}, 9: {'country_market': 'Not used', 'language_market': 'Not used'}, 10: {'country_market': 'United States', 'language_market': 'French'}, 11: {'country_market': 'United States', 'language_market': 'English'}, 12: {'country_market': 'United Kingdom', 'language_market': 'English'}, 13: {'country_market': 'United States', 'language_market': 'French'}, 14: {'country_market': 'Not used', 'language_market': 'English'}, 15: {'country_market': 'Not used', 'language_market': 'English'}, 16: {'country_market': 'United States', 'language_market': 'French'}, 17: {'country_market': 'United States', 'language_market': 'Not used'}, 18: {'country_market': 'Not used', 'language_market': 'English'}, 19: {'country_market': 'United States', 'language_market': 'German'}} df = pd.DataFrame.from_dict(d, orient='index') def top_markets(x): top2 = x.value_counts().nlargest(2).index results = [] for i in x: if i in top2: results.append(i) else: results.append('Other') return results df['top_country'] = top_markets(df['country_market']) df['top_language'] = top_markets(df['language_market']) df ```
2021/10/15
[ "https://Stackoverflow.com/questions/69583271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5269252/" ]
There is no such much-upgraded plugin now, which can help you. But for a workaround, we do have [volume\_watcher: ^2.0.1](https://pub.dev/packages/volume_watcher), which gives a callback when the volume is changed. ``` VolumeWatcher.addListener((volume) { print("Current Volume :" + volume.toString()); })!; ``` ***Note:*** Volume carries from 0 to 1, where 0 means no volume and 1 means max volume.
I needed the same functionality (listen to volume down, don't change volume when listening) and it didn't exist yet in Flutter so I made a plugin for it myself, you can find it here: <https://pub.dev/packages/flutter_android_volume_keydown> It only works on Android because overriding iOS hardware buttons is not allowed by the app store guidelines.
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
Here's another solution: ``` from datetime import datetime from pytz import timezone from dateutil.relativedelta import relativedelta utcnow = timezone('utc').localize(datetime.utcnow()) # generic time here = utcnow.astimezone(timezone('US/Eastern')).replace(tzinfo=None) there = utcnow.astimezone(timezone('Asia/Ho_Chi_Minh')).replace(tzinfo=None) offset = relativedelta(here, there) offset.hours ``` Here what we're doing is converting a time to two different time zones. Then, we remove the time zone information so that when you calculate the difference between the two using relativedelta, we trick it into thinking that these are two different moments in time instead of the same moment in different time zones. The above result will return -11, however this amount can change throughout the year since US/Eastern observes DST and Asia/Ho\_Chi\_Minh does not.
``` from datetime import datetime from zoneinfo import ZoneInfo dt = datetime.now() # 2020-09-13 tz0, tz1 = "Europe/Berlin", "US/Eastern" # +2 vs. -4 hours rel. to UTC utcoff0, utcoff1 = dt.astimezone(ZoneInfo(tz0)).utcoffset(), dt.astimezone(ZoneInfo(tz1)).utcoffset() print(f"hours offset between {tz0} -> {tz1} timezones: {(utcoff1-utcoff0).total_seconds()/3600}") >>> hours offset between Europe/Berlin -> US/Eastern timezones: -6.0 ``` * a way to do this with **Python 3.9**'s standard library.
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
Here is a solution using the Python library Pytz which solves the issue of ambiguous times at the end of daylight saving time. ```py from pytz import timezone import pandas as pd def tz_diff(date, tz1, tz2): ''' Returns the difference in hours between timezone1 and timezone2 for a given date. ''' date = pd.to_datetime(date) return (tz1.localize(date) - tz2.localize(date).astimezone(tz1))\ .seconds/3600 ``` The examples below calculate the difference in hours between UTC and Australia time for the first of January and first of June respectively. Notice how daylight savings are taken into consideration. ```py utc = timezone('UTC') aus = timezone('Australia/Sydney') tz_diff('2017-01-01', utc, aus) # 11.0 tz_diff('2017-06-01', utc, aus) # 10.0 ``` Thanks
`(tz_from.localize(date) - tz_to.localize(date)).seconds/3600.0` Where tz\_from and tz\_to are the starting and ending timezones. You must specify a particular date.
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
Here's another solution: ``` from datetime import datetime from pytz import timezone from dateutil.relativedelta import relativedelta utcnow = timezone('utc').localize(datetime.utcnow()) # generic time here = utcnow.astimezone(timezone('US/Eastern')).replace(tzinfo=None) there = utcnow.astimezone(timezone('Asia/Ho_Chi_Minh')).replace(tzinfo=None) offset = relativedelta(here, there) offset.hours ``` Here what we're doing is converting a time to two different time zones. Then, we remove the time zone information so that when you calculate the difference between the two using relativedelta, we trick it into thinking that these are two different moments in time instead of the same moment in different time zones. The above result will return -11, however this amount can change throughout the year since US/Eastern observes DST and Asia/Ho\_Chi\_Minh does not.
`(tz_from.localize(date) - tz_to.localize(date)).seconds/3600.0` Where tz\_from and tz\_to are the starting and ending timezones. You must specify a particular date.
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
The first thing you have to know is that the offset between two time zones depends not only on the time zones in question, but on the date you're asking about. For example, the dates on which Daylight Savings Time began and ended changed in the US in 2007. While fundamental time zone logistics change only infrequently in any single location, the rate of change globally is impossible to ignore. Therefore, you have to incorporate the date in question into your function. Having completed the necessary preface, the actual function isn't too hard to write if you take advantage of the [pendulum](https://pypi.python.org/pypi/pendulum) library. It should look something like this: ``` import pendulum def tz_diff(home, away, on=None): """ Return the difference in hours between the away time zone and home. `home` and `away` may be any values which pendulum parses as timezones. However, recommended use is to specify the full formal name. See https://gist.github.com/pamelafox/986163 As not all time zones are separated by an integer number of hours, this function returns a float. As time zones are political entities, their definitions can change over time. This is complicated by the fact that daylight savings time does not start and end on the same days uniformly across the globe. This means that there are certain days of the year when the returned value between `Europe/Berlin` and `America/New_York` is _not_ `6.0`. By default, this function always assumes that you want the current definition. If you prefer to specify, set `on` to the date of your choice. It should be a `Pendulum` object. This function returns the number of hours which must be added to the home time in order to get the away time. For example, ```python >>> tz_diff('Europe/Berlin', 'America/New_York') -6.0 >>> tz_diff('Europe/Berlin', 'Asia/Kabul') 2.5 ``` """ if on is None: on = pendulum.today() diff = (on.set(tz=home) - on.set(tz=away)).total_hours() # what about the diff from Tokyo to Honolulu? Right now the result is -19.0 # it should be 5.0; Honolulu is naturally east of Tokyo, just not so around # the date line if abs(diff) > 12.0: if diff < 0.0: diff += 24.0 else: diff -= 24.0 return diff ``` As stated in the documentation, you may not get a stable result for this between any two given locations as you sweep across the days of the year. However, implementing a variant which chooses the median result over the days of the current year is an exercise left for the reader.
I created two functions to deal with timezone. ``` import datetime import pytz def diff_hours_tz(from_tz_name, to_tz_name, negative=False): """ Returns difference hours between timezones res = diff_hours_tz("UTC", "Europe/Paris") : 2 """ from_tz = pytz.timezone(from_tz_name) to_tz = pytz.timezone(to_tz_name) utc_dt = datetime.datetime.now(datetime.timezone.utc) dt_from = dt_to = datetime.datetime.utcnow() dt_from = from_tz.localize(dt_from) dt_to = to_tz.localize(dt_to) from_d = dt_from - utc_dt if from_d.days < 0: return diff_hours_tz(to_tz_name, from_tz_name, True) dt_delta = dt_from - dt_to negative_int = -1 if negative else 1 return int(dt_delta.seconds/3600)*negative_int def dt_tz_to_tz(dt, from_tz_name, to_tz_name): """ Apply difference hours between timezones to a datetime object dt_new = dt_tz_to_tz(datetime.datetime.now(), "UTC", "Europe/Paris") """ hours = diff_hours_tz(from_tz_name, to_tz_name) return dt+datetime.timedelta(hours=hours) # Usage example res = diff_hours_tz("Europe/Paris", "America/New_York") # Result : -6 res = diff_hours_tz("UTC", "Europe/Paris") # Result : 2 now = datetime.datetime.now() # Result : 2019-06-18 15:10:31.720105 dt_new = dt_tz_to_tz(now, "UTC", "Europe/Paris") # Result : 2019-06-18 17:10:31.720105 dt_new = dt_tz_to_tz(now, "Europe/Paris", "America/New_York") # Result : 2019-06-18 09:10:31.720105 dt_new = dt_tz_to_tz(now, "America/New_York", "Europe/Paris") # Result : 2019-06-18 21:10:31.720105 ``` I hope it will help !
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
The first thing you have to know is that the offset between two time zones depends not only on the time zones in question, but on the date you're asking about. For example, the dates on which Daylight Savings Time began and ended changed in the US in 2007. While fundamental time zone logistics change only infrequently in any single location, the rate of change globally is impossible to ignore. Therefore, you have to incorporate the date in question into your function. Having completed the necessary preface, the actual function isn't too hard to write if you take advantage of the [pendulum](https://pypi.python.org/pypi/pendulum) library. It should look something like this: ``` import pendulum def tz_diff(home, away, on=None): """ Return the difference in hours between the away time zone and home. `home` and `away` may be any values which pendulum parses as timezones. However, recommended use is to specify the full formal name. See https://gist.github.com/pamelafox/986163 As not all time zones are separated by an integer number of hours, this function returns a float. As time zones are political entities, their definitions can change over time. This is complicated by the fact that daylight savings time does not start and end on the same days uniformly across the globe. This means that there are certain days of the year when the returned value between `Europe/Berlin` and `America/New_York` is _not_ `6.0`. By default, this function always assumes that you want the current definition. If you prefer to specify, set `on` to the date of your choice. It should be a `Pendulum` object. This function returns the number of hours which must be added to the home time in order to get the away time. For example, ```python >>> tz_diff('Europe/Berlin', 'America/New_York') -6.0 >>> tz_diff('Europe/Berlin', 'Asia/Kabul') 2.5 ``` """ if on is None: on = pendulum.today() diff = (on.set(tz=home) - on.set(tz=away)).total_hours() # what about the diff from Tokyo to Honolulu? Right now the result is -19.0 # it should be 5.0; Honolulu is naturally east of Tokyo, just not so around # the date line if abs(diff) > 12.0: if diff < 0.0: diff += 24.0 else: diff -= 24.0 return diff ``` As stated in the documentation, you may not get a stable result for this between any two given locations as you sweep across the days of the year. However, implementing a variant which chooses the median result over the days of the current year is an exercise left for the reader.
Here is a solution using the Python library Pytz which solves the issue of ambiguous times at the end of daylight saving time. ```py from pytz import timezone import pandas as pd def tz_diff(date, tz1, tz2): ''' Returns the difference in hours between timezone1 and timezone2 for a given date. ''' date = pd.to_datetime(date) return (tz1.localize(date) - tz2.localize(date).astimezone(tz1))\ .seconds/3600 ``` The examples below calculate the difference in hours between UTC and Australia time for the first of January and first of June respectively. Notice how daylight savings are taken into consideration. ```py utc = timezone('UTC') aus = timezone('Australia/Sydney') tz_diff('2017-01-01', utc, aus) # 11.0 tz_diff('2017-06-01', utc, aus) # 10.0 ``` Thanks
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
Here is a solution using the Python library Pytz which solves the issue of ambiguous times at the end of daylight saving time. ```py from pytz import timezone import pandas as pd def tz_diff(date, tz1, tz2): ''' Returns the difference in hours between timezone1 and timezone2 for a given date. ''' date = pd.to_datetime(date) return (tz1.localize(date) - tz2.localize(date).astimezone(tz1))\ .seconds/3600 ``` The examples below calculate the difference in hours between UTC and Australia time for the first of January and first of June respectively. Notice how daylight savings are taken into consideration. ```py utc = timezone('UTC') aus = timezone('Australia/Sydney') tz_diff('2017-01-01', utc, aus) # 11.0 tz_diff('2017-06-01', utc, aus) # 10.0 ``` Thanks
``` from datetime import datetime from zoneinfo import ZoneInfo dt = datetime.now() # 2020-09-13 tz0, tz1 = "Europe/Berlin", "US/Eastern" # +2 vs. -4 hours rel. to UTC utcoff0, utcoff1 = dt.astimezone(ZoneInfo(tz0)).utcoffset(), dt.astimezone(ZoneInfo(tz1)).utcoffset() print(f"hours offset between {tz0} -> {tz1} timezones: {(utcoff1-utcoff0).total_seconds()/3600}") >>> hours offset between Europe/Berlin -> US/Eastern timezones: -6.0 ``` * a way to do this with **Python 3.9**'s standard library.
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
I created two functions to deal with timezone. ``` import datetime import pytz def diff_hours_tz(from_tz_name, to_tz_name, negative=False): """ Returns difference hours between timezones res = diff_hours_tz("UTC", "Europe/Paris") : 2 """ from_tz = pytz.timezone(from_tz_name) to_tz = pytz.timezone(to_tz_name) utc_dt = datetime.datetime.now(datetime.timezone.utc) dt_from = dt_to = datetime.datetime.utcnow() dt_from = from_tz.localize(dt_from) dt_to = to_tz.localize(dt_to) from_d = dt_from - utc_dt if from_d.days < 0: return diff_hours_tz(to_tz_name, from_tz_name, True) dt_delta = dt_from - dt_to negative_int = -1 if negative else 1 return int(dt_delta.seconds/3600)*negative_int def dt_tz_to_tz(dt, from_tz_name, to_tz_name): """ Apply difference hours between timezones to a datetime object dt_new = dt_tz_to_tz(datetime.datetime.now(), "UTC", "Europe/Paris") """ hours = diff_hours_tz(from_tz_name, to_tz_name) return dt+datetime.timedelta(hours=hours) # Usage example res = diff_hours_tz("Europe/Paris", "America/New_York") # Result : -6 res = diff_hours_tz("UTC", "Europe/Paris") # Result : 2 now = datetime.datetime.now() # Result : 2019-06-18 15:10:31.720105 dt_new = dt_tz_to_tz(now, "UTC", "Europe/Paris") # Result : 2019-06-18 17:10:31.720105 dt_new = dt_tz_to_tz(now, "Europe/Paris", "America/New_York") # Result : 2019-06-18 09:10:31.720105 dt_new = dt_tz_to_tz(now, "America/New_York", "Europe/Paris") # Result : 2019-06-18 21:10:31.720105 ``` I hope it will help !
``` from datetime import datetime from zoneinfo import ZoneInfo dt = datetime.now() # 2020-09-13 tz0, tz1 = "Europe/Berlin", "US/Eastern" # +2 vs. -4 hours rel. to UTC utcoff0, utcoff1 = dt.astimezone(ZoneInfo(tz0)).utcoffset(), dt.astimezone(ZoneInfo(tz1)).utcoffset() print(f"hours offset between {tz0} -> {tz1} timezones: {(utcoff1-utcoff0).total_seconds()/3600}") >>> hours offset between Europe/Berlin -> US/Eastern timezones: -6.0 ``` * a way to do this with **Python 3.9**'s standard library.
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
Here's another solution: ``` from datetime import datetime from pytz import timezone from dateutil.relativedelta import relativedelta utcnow = timezone('utc').localize(datetime.utcnow()) # generic time here = utcnow.astimezone(timezone('US/Eastern')).replace(tzinfo=None) there = utcnow.astimezone(timezone('Asia/Ho_Chi_Minh')).replace(tzinfo=None) offset = relativedelta(here, there) offset.hours ``` Here what we're doing is converting a time to two different time zones. Then, we remove the time zone information so that when you calculate the difference between the two using relativedelta, we trick it into thinking that these are two different moments in time instead of the same moment in different time zones. The above result will return -11, however this amount can change throughout the year since US/Eastern observes DST and Asia/Ho\_Chi\_Minh does not.
I created two functions to deal with timezone. ``` import datetime import pytz def diff_hours_tz(from_tz_name, to_tz_name, negative=False): """ Returns difference hours between timezones res = diff_hours_tz("UTC", "Europe/Paris") : 2 """ from_tz = pytz.timezone(from_tz_name) to_tz = pytz.timezone(to_tz_name) utc_dt = datetime.datetime.now(datetime.timezone.utc) dt_from = dt_to = datetime.datetime.utcnow() dt_from = from_tz.localize(dt_from) dt_to = to_tz.localize(dt_to) from_d = dt_from - utc_dt if from_d.days < 0: return diff_hours_tz(to_tz_name, from_tz_name, True) dt_delta = dt_from - dt_to negative_int = -1 if negative else 1 return int(dt_delta.seconds/3600)*negative_int def dt_tz_to_tz(dt, from_tz_name, to_tz_name): """ Apply difference hours between timezones to a datetime object dt_new = dt_tz_to_tz(datetime.datetime.now(), "UTC", "Europe/Paris") """ hours = diff_hours_tz(from_tz_name, to_tz_name) return dt+datetime.timedelta(hours=hours) # Usage example res = diff_hours_tz("Europe/Paris", "America/New_York") # Result : -6 res = diff_hours_tz("UTC", "Europe/Paris") # Result : 2 now = datetime.datetime.now() # Result : 2019-06-18 15:10:31.720105 dt_new = dt_tz_to_tz(now, "UTC", "Europe/Paris") # Result : 2019-06-18 17:10:31.720105 dt_new = dt_tz_to_tz(now, "Europe/Paris", "America/New_York") # Result : 2019-06-18 09:10:31.720105 dt_new = dt_tz_to_tz(now, "America/New_York", "Europe/Paris") # Result : 2019-06-18 21:10:31.720105 ``` I hope it will help !
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
Here is a solution using the Python library Pytz which solves the issue of ambiguous times at the end of daylight saving time. ```py from pytz import timezone import pandas as pd def tz_diff(date, tz1, tz2): ''' Returns the difference in hours between timezone1 and timezone2 for a given date. ''' date = pd.to_datetime(date) return (tz1.localize(date) - tz2.localize(date).astimezone(tz1))\ .seconds/3600 ``` The examples below calculate the difference in hours between UTC and Australia time for the first of January and first of June respectively. Notice how daylight savings are taken into consideration. ```py utc = timezone('UTC') aus = timezone('Australia/Sydney') tz_diff('2017-01-01', utc, aus) # 11.0 tz_diff('2017-06-01', utc, aus) # 10.0 ``` Thanks
Here's another solution: ``` from datetime import datetime from pytz import timezone from dateutil.relativedelta import relativedelta utcnow = timezone('utc').localize(datetime.utcnow()) # generic time here = utcnow.astimezone(timezone('US/Eastern')).replace(tzinfo=None) there = utcnow.astimezone(timezone('Asia/Ho_Chi_Minh')).replace(tzinfo=None) offset = relativedelta(here, there) offset.hours ``` Here what we're doing is converting a time to two different time zones. Then, we remove the time zone information so that when you calculate the difference between the two using relativedelta, we trick it into thinking that these are two different moments in time instead of the same moment in different time zones. The above result will return -11, however this amount can change throughout the year since US/Eastern observes DST and Asia/Ho\_Chi\_Minh does not.
46,736,529
How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.org/pypi/pytz).
2017/10/13
[ "https://Stackoverflow.com/questions/46736529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/504550/" ]
Here is a solution using the Python library Pytz which solves the issue of ambiguous times at the end of daylight saving time. ```py from pytz import timezone import pandas as pd def tz_diff(date, tz1, tz2): ''' Returns the difference in hours between timezone1 and timezone2 for a given date. ''' date = pd.to_datetime(date) return (tz1.localize(date) - tz2.localize(date).astimezone(tz1))\ .seconds/3600 ``` The examples below calculate the difference in hours between UTC and Australia time for the first of January and first of June respectively. Notice how daylight savings are taken into consideration. ```py utc = timezone('UTC') aus = timezone('Australia/Sydney') tz_diff('2017-01-01', utc, aus) # 11.0 tz_diff('2017-06-01', utc, aus) # 10.0 ``` Thanks
Here is a code snippet to get the difference between UTC and US/Eastern, but it should work for any two timezones. ``` # The following algorithm will work no matter what is the local timezone of the server, # but for the purposes of this discussion, let's assume that the local timezone is UTC. local_timestamp = datetime.now() # Assume that utc_timestamp == 2019-01-01 12:00. utc_timestamp = pytz.utc.localize(local_timestamp) # If it was 12:00 in New York, it would be 20:00 in UTC. So us_eastern_timestamp is a UTC # timestamp with the value of 2019-01-01 20:00. us_eastern_timestamp = timezone("US/Eastern").localize(local_timestamp).astimezone(pytz.utc) # delta is a Python timedelta object representing the interval between the two timestamps, # which, in our example, is -8 hours. delta = utc_timestamp - us_eastern_timestamp # In the last line, we convert the timedelta into an integer representing the number of # hours. print round(delta.total_seconds() / 60.0 / 60.0) ```
28,744,759
I have a question concerning stdin buffer content inspection. This acclaimed line of code: ``` int c; while((c = getchar()) != '\n' && c != EOF); ``` deals efficiently with discarding stdin-buffer garbage, in case there is a garbage found. In case the buffer is empty, the program execution wouldn't go past it. Is there a way of checking if there is garbage in the stdin-buffer at all (no matter if it's there by user error, typeahead or whichever reason), and executing the "fflush-replacement line" from above only in case there is a garbage found? I'd prefer to keep it programmatically all in plain-UNIX-flavor-of standard C, without having to use special parsing tools, no yacc, bison, python, ruby, shell scripts etc., no Windows API, please. Thanks in advance! **UPDATE:** I hope this example tells a bit more of my question: ``` //... //this line should make sure stdin buffer is free from accidentally typed content int c; while (( c = getchar()) != '\n' && c != EOF); //this line won't show in case buffer is already clean printf("Please enter an arbitrary number of float or symbolic values:\n"); //this line should read the real input user is being asked for char* p = fgets(text, TEXT_SIZE, stdin); if(p != NULL) parse_and_process(text); //... ``` The problem happens when there is no accidental input. The "garbage" is here considered anything that may stay in the buffer at the moment *printf( )* prompt would appear. Is there a way of getting around the first line in case the buffer is already clean?
2015/02/26
[ "https://Stackoverflow.com/questions/28744759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3078414/" ]
> > You can not give a background color into `include` tag. > > > **Why ?** Its obvious , if you could able to give the background color to `include` tag then it would be all messed up with your `include` color and another color which might be applied to that `layout` which has already included . However, you can also override all the layout parameters (any android:layout\_\* attributes) of the included layout's root view by specifying them in the tag. (quoting from [https://developer.android.com/training/improving-layouts/reusing-layouts.html#Includ](https://developer.android.com/training/improving-layouts/reusing-layouts.html#Include) )
Try this: ``` <include android:id="@+id/list_item_section_text" android:layout_width="fill_parent" android:layout_height="match_parent" layout="@android:layout/preference_category"/> ``` in preference category layout: ``` <LinearLayout android:id="@+id/preference_category" android:layout_width="fill_parent" android:layout_height="match_parent" android:background="@colors/white"/> ``` otherwise changes in RUNTIME ``` preference_category.setBackgroundResource(R.id.bckResource); ```
28,744,759
I have a question concerning stdin buffer content inspection. This acclaimed line of code: ``` int c; while((c = getchar()) != '\n' && c != EOF); ``` deals efficiently with discarding stdin-buffer garbage, in case there is a garbage found. In case the buffer is empty, the program execution wouldn't go past it. Is there a way of checking if there is garbage in the stdin-buffer at all (no matter if it's there by user error, typeahead or whichever reason), and executing the "fflush-replacement line" from above only in case there is a garbage found? I'd prefer to keep it programmatically all in plain-UNIX-flavor-of standard C, without having to use special parsing tools, no yacc, bison, python, ruby, shell scripts etc., no Windows API, please. Thanks in advance! **UPDATE:** I hope this example tells a bit more of my question: ``` //... //this line should make sure stdin buffer is free from accidentally typed content int c; while (( c = getchar()) != '\n' && c != EOF); //this line won't show in case buffer is already clean printf("Please enter an arbitrary number of float or symbolic values:\n"); //this line should read the real input user is being asked for char* p = fgets(text, TEXT_SIZE, stdin); if(p != NULL) parse_and_process(text); //... ``` The problem happens when there is no accidental input. The "garbage" is here considered anything that may stay in the buffer at the moment *printf( )* prompt would appear. Is there a way of getting around the first line in case the buffer is already clean?
2015/02/26
[ "https://Stackoverflow.com/questions/28744759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3078414/" ]
> > You can not give a background color into `include` tag. > > > **Why ?** Its obvious , if you could able to give the background color to `include` tag then it would be all messed up with your `include` color and another color which might be applied to that `layout` which has already included . However, you can also override all the layout parameters (any android:layout\_\* attributes) of the included layout's root view by specifying them in the tag. (quoting from [https://developer.android.com/training/improving-layouts/reusing-layouts.html#Includ](https://developer.android.com/training/improving-layouts/reusing-layouts.html#Include) )
for me `android:background="@color/colorSecondary"` to `<include>` tag is working fine
28,744,759
I have a question concerning stdin buffer content inspection. This acclaimed line of code: ``` int c; while((c = getchar()) != '\n' && c != EOF); ``` deals efficiently with discarding stdin-buffer garbage, in case there is a garbage found. In case the buffer is empty, the program execution wouldn't go past it. Is there a way of checking if there is garbage in the stdin-buffer at all (no matter if it's there by user error, typeahead or whichever reason), and executing the "fflush-replacement line" from above only in case there is a garbage found? I'd prefer to keep it programmatically all in plain-UNIX-flavor-of standard C, without having to use special parsing tools, no yacc, bison, python, ruby, shell scripts etc., no Windows API, please. Thanks in advance! **UPDATE:** I hope this example tells a bit more of my question: ``` //... //this line should make sure stdin buffer is free from accidentally typed content int c; while (( c = getchar()) != '\n' && c != EOF); //this line won't show in case buffer is already clean printf("Please enter an arbitrary number of float or symbolic values:\n"); //this line should read the real input user is being asked for char* p = fgets(text, TEXT_SIZE, stdin); if(p != NULL) parse_and_process(text); //... ``` The problem happens when there is no accidental input. The "garbage" is here considered anything that may stay in the buffer at the moment *printf( )* prompt would appear. Is there a way of getting around the first line in case the buffer is already clean?
2015/02/26
[ "https://Stackoverflow.com/questions/28744759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3078414/" ]
If you are not "too-deep-view-tree-paranoia" type of guy, you can **wrap your `include` in `FrameLayout`**: ``` <FrameLayout android:id="@+id/list_item_section_text" android:layout_width="fill_parent" android:layout_height="match_parent" android:background="%YOUR_BACKGROUND%"> <include layout="@android:layout/preference_category"/> </FrameLayout> ``` **EDIT**: Of course, don't forget to remove `android:background` from your `preference_category.xml` layout first.
Try this: ``` <include android:id="@+id/list_item_section_text" android:layout_width="fill_parent" android:layout_height="match_parent" layout="@android:layout/preference_category"/> ``` in preference category layout: ``` <LinearLayout android:id="@+id/preference_category" android:layout_width="fill_parent" android:layout_height="match_parent" android:background="@colors/white"/> ``` otherwise changes in RUNTIME ``` preference_category.setBackgroundResource(R.id.bckResource); ```
28,744,759
I have a question concerning stdin buffer content inspection. This acclaimed line of code: ``` int c; while((c = getchar()) != '\n' && c != EOF); ``` deals efficiently with discarding stdin-buffer garbage, in case there is a garbage found. In case the buffer is empty, the program execution wouldn't go past it. Is there a way of checking if there is garbage in the stdin-buffer at all (no matter if it's there by user error, typeahead or whichever reason), and executing the "fflush-replacement line" from above only in case there is a garbage found? I'd prefer to keep it programmatically all in plain-UNIX-flavor-of standard C, without having to use special parsing tools, no yacc, bison, python, ruby, shell scripts etc., no Windows API, please. Thanks in advance! **UPDATE:** I hope this example tells a bit more of my question: ``` //... //this line should make sure stdin buffer is free from accidentally typed content int c; while (( c = getchar()) != '\n' && c != EOF); //this line won't show in case buffer is already clean printf("Please enter an arbitrary number of float or symbolic values:\n"); //this line should read the real input user is being asked for char* p = fgets(text, TEXT_SIZE, stdin); if(p != NULL) parse_and_process(text); //... ``` The problem happens when there is no accidental input. The "garbage" is here considered anything that may stay in the buffer at the moment *printf( )* prompt would appear. Is there a way of getting around the first line in case the buffer is already clean?
2015/02/26
[ "https://Stackoverflow.com/questions/28744759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3078414/" ]
If you are not "too-deep-view-tree-paranoia" type of guy, you can **wrap your `include` in `FrameLayout`**: ``` <FrameLayout android:id="@+id/list_item_section_text" android:layout_width="fill_parent" android:layout_height="match_parent" android:background="%YOUR_BACKGROUND%"> <include layout="@android:layout/preference_category"/> </FrameLayout> ``` **EDIT**: Of course, don't forget to remove `android:background` from your `preference_category.xml` layout first.
for me `android:background="@color/colorSecondary"` to `<include>` tag is working fine
9,170,271
I am trying to flip a picture on its vertical axis, I am doing this in python, and using the Media module. like this: ![enter image description here](https://i.stack.imgur.com/j9woa.jpg) i try to find the relationship between the original and the flipped. since i can't go to negative coordinates in python, what i decided to do is use the middle of the picture as the reference. so i split the picture in half,and this is what i am going to do: [note i create a new blank picture and copy each (x,y) pixel to the corresponding to (-x,y), if the original pixel is after the middle. if its before the middle, i copy the pixel (-x,y) to (x,y) ![enter image description here](https://i.stack.imgur.com/YkhwK.jpg) so i coded it in python, and this is the result. Original: ![enter image description here](https://i.stack.imgur.com/HoYO0.jpg) i got this: ``` import media pic=media.load_picture(media.choose_file()) height=media.get_height(pic) width=media.get_width(pic) new_pic=media.create_picture(width,height) for pixel in pic: x_org=media.get_x(pixel) y_org=media.get_y(pixel) colour=media.get_color(pixel) new_pixel_0=media.get_pixel(new_pic,x_org+mid_width,y_org) #replace with suggested #answer below media.set_color( new_pixel_0,colour) media.show(new_pic) ``` ![enter image description here](https://i.stack.imgur.com/mEpNS.jpg) this is not what i wanted, but i am so confused, i try to find the relationship between the original pixel location and its transformed (x,y)->(-x,y). but i think that's wrong. If anyone could help me with this method it would be great full. at the end of the day i want a picture like this: ![enter image description here](https://i.stack.imgur.com/8aVdU.jpg) <http://www.misterteacher.com/alphabetgeometry/transformations.html#Flip>
2012/02/07
[ "https://Stackoverflow.com/questions/9170271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090782/" ]
Why not just use Python Imaging Library? Flipping an image horizontally is a one-liner, and much faster to boot. ``` from PIL import Image img = Image.open("AFLAC.jpg").transpose(Image.FLIP_LEFT_RIGHT) ```
Your arithmetic is incorrect. Try this instead... ``` new_pixel_0 = media.get_pixel(new_pic, width - x_org, y_org) ``` There is no need to treat the two halves of the image separately. This is essentially negating the *x*-co-ordinate, as your first diagram illustrates, but then slides (or translates) the flipped image by *width* pixels to the right to put it back in the range (0 - *width*).
9,170,271
I am trying to flip a picture on its vertical axis, I am doing this in python, and using the Media module. like this: ![enter image description here](https://i.stack.imgur.com/j9woa.jpg) i try to find the relationship between the original and the flipped. since i can't go to negative coordinates in python, what i decided to do is use the middle of the picture as the reference. so i split the picture in half,and this is what i am going to do: [note i create a new blank picture and copy each (x,y) pixel to the corresponding to (-x,y), if the original pixel is after the middle. if its before the middle, i copy the pixel (-x,y) to (x,y) ![enter image description here](https://i.stack.imgur.com/YkhwK.jpg) so i coded it in python, and this is the result. Original: ![enter image description here](https://i.stack.imgur.com/HoYO0.jpg) i got this: ``` import media pic=media.load_picture(media.choose_file()) height=media.get_height(pic) width=media.get_width(pic) new_pic=media.create_picture(width,height) for pixel in pic: x_org=media.get_x(pixel) y_org=media.get_y(pixel) colour=media.get_color(pixel) new_pixel_0=media.get_pixel(new_pic,x_org+mid_width,y_org) #replace with suggested #answer below media.set_color( new_pixel_0,colour) media.show(new_pic) ``` ![enter image description here](https://i.stack.imgur.com/mEpNS.jpg) this is not what i wanted, but i am so confused, i try to find the relationship between the original pixel location and its transformed (x,y)->(-x,y). but i think that's wrong. If anyone could help me with this method it would be great full. at the end of the day i want a picture like this: ![enter image description here](https://i.stack.imgur.com/8aVdU.jpg) <http://www.misterteacher.com/alphabetgeometry/transformations.html#Flip>
2012/02/07
[ "https://Stackoverflow.com/questions/9170271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090782/" ]
Why not just use Python Imaging Library? Flipping an image horizontally is a one-liner, and much faster to boot. ``` from PIL import Image img = Image.open("AFLAC.jpg").transpose(Image.FLIP_LEFT_RIGHT) ```
Here is a simple function to flip an image using scipy and numpy: ``` import numpy as np from scipy.misc import imread, imshow import matplotlib.pyplot as plt def flip_image(file_name): img = imread(file_name) flipped_img = np.ndarray((img.shape), dtype='uint8') flipped_img[:,:,0] = np.fliplr(img[:,:,0]) flipped_img[:,:,1] = np.fliplr(img[:,:,1]) flipped_img[:,:,2] = np.fliplr(img[:,:,2]) plt.imshow(flipped_img) return flipped_img ```
9,170,271
I am trying to flip a picture on its vertical axis, I am doing this in python, and using the Media module. like this: ![enter image description here](https://i.stack.imgur.com/j9woa.jpg) i try to find the relationship between the original and the flipped. since i can't go to negative coordinates in python, what i decided to do is use the middle of the picture as the reference. so i split the picture in half,and this is what i am going to do: [note i create a new blank picture and copy each (x,y) pixel to the corresponding to (-x,y), if the original pixel is after the middle. if its before the middle, i copy the pixel (-x,y) to (x,y) ![enter image description here](https://i.stack.imgur.com/YkhwK.jpg) so i coded it in python, and this is the result. Original: ![enter image description here](https://i.stack.imgur.com/HoYO0.jpg) i got this: ``` import media pic=media.load_picture(media.choose_file()) height=media.get_height(pic) width=media.get_width(pic) new_pic=media.create_picture(width,height) for pixel in pic: x_org=media.get_x(pixel) y_org=media.get_y(pixel) colour=media.get_color(pixel) new_pixel_0=media.get_pixel(new_pic,x_org+mid_width,y_org) #replace with suggested #answer below media.set_color( new_pixel_0,colour) media.show(new_pic) ``` ![enter image description here](https://i.stack.imgur.com/mEpNS.jpg) this is not what i wanted, but i am so confused, i try to find the relationship between the original pixel location and its transformed (x,y)->(-x,y). but i think that's wrong. If anyone could help me with this method it would be great full. at the end of the day i want a picture like this: ![enter image description here](https://i.stack.imgur.com/8aVdU.jpg) <http://www.misterteacher.com/alphabetgeometry/transformations.html#Flip>
2012/02/07
[ "https://Stackoverflow.com/questions/9170271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090782/" ]
Your arithmetic is incorrect. Try this instead... ``` new_pixel_0 = media.get_pixel(new_pic, width - x_org, y_org) ``` There is no need to treat the two halves of the image separately. This is essentially negating the *x*-co-ordinate, as your first diagram illustrates, but then slides (or translates) the flipped image by *width* pixels to the right to put it back in the range (0 - *width*).
Here is a simple function to flip an image using scipy and numpy: ``` import numpy as np from scipy.misc import imread, imshow import matplotlib.pyplot as plt def flip_image(file_name): img = imread(file_name) flipped_img = np.ndarray((img.shape), dtype='uint8') flipped_img[:,:,0] = np.fliplr(img[:,:,0]) flipped_img[:,:,1] = np.fliplr(img[:,:,1]) flipped_img[:,:,2] = np.fliplr(img[:,:,2]) plt.imshow(flipped_img) return flipped_img ```
39,030,546
Try to run Example 7-11 of **High Performance Python** **cython\_np.pyx** ``` #cython_np.pyx import numpy as np cimport numpy as np def calculate_z(int maxiter, double complex[:] zs, double complex[:] cs): cdef unsigned int i, n cdef double complex z, c cdef int[:] output = np.empty(len(zs), dtype = np.int32) for i in range(len(zs)): n = 0 z = zs[i] c = cs[i] while n < maxiter and (z.real * z.real + z.imag * z.imag) < 4: z = z * z + c n += 1 output[i] = n return output ``` **setup.py** ``` from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext':build_ext}, ext_modules = [Extension("calculate", ["cythonfn.pyx"])] ) ``` In the terminal , ubuntu 16.04 ``` python3 setup.py build_ext --inplace ``` get some warning ``` running build_ext cythoning cythonfn.pyx to cythonfn.c building 'calculate' extension x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c cythonfn.c -o build/temp.linux-x86_64-3.5/cythonfn.o In file included from /usr/include/python3.5m/numpy/ndarraytypes.h:1777:0, from /usr/include/python3.5m/numpy/ndarrayobject.h:18, from /usr/include/python3.5m/numpy/arrayobject.h:4, from cythonfn.c:274: /usr/include/python3.5m/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp] #warning "Using deprecated NumPy API, disable it by " \ ^ In file included from /usr/include/python3.5m/numpy/ndarrayobject.h:27:0, from /usr/include/python3.5m/numpy/arrayobject.h:4, from cythonfn.c:274: /usr/include/python3.5m/numpy/__multiarray_api.h:1448:1: warning: ‘_import_array’ defined but not used [-Wunused-function] _import_array(void) ^ x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.5/cythonfn.o -o MY_DIR/calculate.cpython-35m-x86_64-linux-gnu.so ``` when I try to run use function **calculate.calculate.z** in Ipython, it says ``` TypeError: a bytes-like object is required, not 'list' ``` [detail of using calculate.z](http://i.stack.imgur.com/UQfFM.png) Any idea about the warning?
2016/08/19
[ "https://Stackoverflow.com/questions/39030546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6536252/" ]
I can't see any obvious "faults" with your sql. However, if student 12345 is missing in any way data from (dcis, studentsdcid, guardianid, externalident, student\_number) or there are no matching data in any of the tables. Then no record will be returned since you are using inner joins. 2 suggestions: \*Try changing the inner joins to left joins when you try searching for student 12345. If it returns any data you will then see what might be missing \*Try searching for a student which appear in the list from the first sql statement. If this still does not return any record then you might have to restructure your sql statement
That's probably cause no any record matches with those condition in place since it's `AND`. Try making that last condition to a `OR` condition and see like ``` WHERE pcs.SCHOOLID=9 AND pcs.FIELD_NAME='web_password' AND s.ENROLL_STATUS=0 OR s.STUDENT_NUMBER=12345 ```
39,030,546
Try to run Example 7-11 of **High Performance Python** **cython\_np.pyx** ``` #cython_np.pyx import numpy as np cimport numpy as np def calculate_z(int maxiter, double complex[:] zs, double complex[:] cs): cdef unsigned int i, n cdef double complex z, c cdef int[:] output = np.empty(len(zs), dtype = np.int32) for i in range(len(zs)): n = 0 z = zs[i] c = cs[i] while n < maxiter and (z.real * z.real + z.imag * z.imag) < 4: z = z * z + c n += 1 output[i] = n return output ``` **setup.py** ``` from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext':build_ext}, ext_modules = [Extension("calculate", ["cythonfn.pyx"])] ) ``` In the terminal , ubuntu 16.04 ``` python3 setup.py build_ext --inplace ``` get some warning ``` running build_ext cythoning cythonfn.pyx to cythonfn.c building 'calculate' extension x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c cythonfn.c -o build/temp.linux-x86_64-3.5/cythonfn.o In file included from /usr/include/python3.5m/numpy/ndarraytypes.h:1777:0, from /usr/include/python3.5m/numpy/ndarrayobject.h:18, from /usr/include/python3.5m/numpy/arrayobject.h:4, from cythonfn.c:274: /usr/include/python3.5m/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp] #warning "Using deprecated NumPy API, disable it by " \ ^ In file included from /usr/include/python3.5m/numpy/ndarrayobject.h:27:0, from /usr/include/python3.5m/numpy/arrayobject.h:4, from cythonfn.c:274: /usr/include/python3.5m/numpy/__multiarray_api.h:1448:1: warning: ‘_import_array’ defined but not used [-Wunused-function] _import_array(void) ^ x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.5/cythonfn.o -o MY_DIR/calculate.cpython-35m-x86_64-linux-gnu.so ``` when I try to run use function **calculate.calculate.z** in Ipython, it says ``` TypeError: a bytes-like object is required, not 'list' ``` [detail of using calculate.z](http://i.stack.imgur.com/UQfFM.png) Any idea about the warning?
2016/08/19
[ "https://Stackoverflow.com/questions/39030546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6536252/" ]
I can't see any obvious "faults" with your sql. However, if student 12345 is missing in any way data from (dcis, studentsdcid, guardianid, externalident, student\_number) or there are no matching data in any of the tables. Then no record will be returned since you are using inner joins. 2 suggestions: \*Try changing the inner joins to left joins when you try searching for student 12345. If it returns any data you will then see what might be missing \*Try searching for a student which appear in the list from the first sql statement. If this still does not return any record then you might have to restructure your sql statement
I am not writing the whole query,just a sample one below Using OR Condition: ``` SELECT pcs.Student_Number as SNUMBER, pcs.STRING_VALUE as PW, s.GUARDIANEMAIL as GEMAIL, s.WEB_ID as LOGIN, s.FIRST_NAME as FN, s.LAST_NAME as LN, pec.EMAILADDRESS as EMAIL FROM PVSIS_CUSTOM_STUDENTS pcs INNER JOIN STUDENTS s ON pcs.STUDENT_NUMBER = s.STUDENT_NUMBER INNER JOIN GuardianStudent gs ON s.DCID = gs.STUDENTSDCID INNER JOIN PCAS_EMAILCONTACT pec ON gs.GUARDIANID = pec.EXTERNALIDENT WHERE pcs.SCHOOLID=9 AND pcs.FIELD_NAME='web_password' AND s.ENROLL_STATUS=0 AND s.STUDENT_NUMBER=12345 OR <other Student details> ```
9,434,205
The code below is streaming the twitter public timeline for a variable which output any tweets to the console. I'd like the save the same variables (status.text, status.author.screen\_name, status.created\_at, status.source) into an sqlite database. I'm getting an syntax error when my script sees a tweet and nothing is written to the sqlite database. the error: ``` $ python stream-v5.py @lunchboxhq Filtering the public timeline for "@lunchboxhq"RT @LunchboxHQ: test 2 LunchboxHQ 2012-02-29 18:03:42 Echofon Encountered Exception: near "?": syntax error ``` the code: ``` import sys import tweepy import webbrowser import sqlite3 as lite # Query terms Q = sys.argv[1:] sqlite3file='/var/www/twitter.lbox.com/html/stream5_log.sqlite' CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) con = lite.connect(sqlite3file) cur = con.cursor() cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): try: print "%s\t%s\t%s\t%s" % (status.text, status.author.screen_name, status.created_at, status.source,) cur.executemany("INSERT INTO TWEETS(?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) except Exception, e: print >> sys.stderr, 'Encountered Exception:', e pass def on_error(self, status_code): print >> sys.stderr, 'Encountered error with status code:', status_code return True # Don't kill the stream def on_timeout(self): print >> sys.stderr, 'Timeout...' return True # Don't kill the stream streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60) print >> sys.stderr, 'Filtering the public timeline for "%s"' % (' '.join(sys.argv[1:]),) streaming_api.filter(follow=None, track=Q) ```
2012/02/24
[ "https://Stackoverflow.com/questions/9434205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039166/" ]
You are missing a closing parenthesis on the last line of the following code (lines 34–37 from what you posted): ``` cur.executemany("INSERT INTO TWEETS(?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source) ``` Just add a parenthesis to close the method call immediately after your tuple parameter.
``` import sqlite3 as lite con = lite.connect('test.db') cur = con.cursor() cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") ``` then later: ``` cur.executemany("INSERT INTO TWEETS(?, ?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) ```
9,434,205
The code below is streaming the twitter public timeline for a variable which output any tweets to the console. I'd like the save the same variables (status.text, status.author.screen\_name, status.created\_at, status.source) into an sqlite database. I'm getting an syntax error when my script sees a tweet and nothing is written to the sqlite database. the error: ``` $ python stream-v5.py @lunchboxhq Filtering the public timeline for "@lunchboxhq"RT @LunchboxHQ: test 2 LunchboxHQ 2012-02-29 18:03:42 Echofon Encountered Exception: near "?": syntax error ``` the code: ``` import sys import tweepy import webbrowser import sqlite3 as lite # Query terms Q = sys.argv[1:] sqlite3file='/var/www/twitter.lbox.com/html/stream5_log.sqlite' CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) con = lite.connect(sqlite3file) cur = con.cursor() cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): try: print "%s\t%s\t%s\t%s" % (status.text, status.author.screen_name, status.created_at, status.source,) cur.executemany("INSERT INTO TWEETS(?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) except Exception, e: print >> sys.stderr, 'Encountered Exception:', e pass def on_error(self, status_code): print >> sys.stderr, 'Encountered error with status code:', status_code return True # Don't kill the stream def on_timeout(self): print >> sys.stderr, 'Timeout...' return True # Don't kill the stream streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60) print >> sys.stderr, 'Filtering the public timeline for "%s"' % (' '.join(sys.argv[1:]),) streaming_api.filter(follow=None, track=Q) ```
2012/02/24
[ "https://Stackoverflow.com/questions/9434205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039166/" ]
``` import sqlite3 as lite con = lite.connect('test.db') cur = con.cursor() cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") ``` then later: ``` cur.executemany("INSERT INTO TWEETS(?, ?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) ```
Full disclosure: still new to this stuff. However, I got your code working by changing it to: ``` cur.execute("INSERT INTO TWEETS VALUES(?,?,?,?)", (status.text, status.author.screen_name, status.created_at, status.source)) con.commit() ``` It seems to me that you're reading in one status at a time. The executemany method would be for when you have more than one status. For example: `(['sometext', 'bob','2013-02-01','Twitter for Android'], ['someothertext', 'helga', '2013-01-31', 'MacSomething'])` I'm definitely not a wizard and am not sure what sort of impact the commit() has on every entry... I'm guessing the performance is terrible, but it works for a single term in the query. Thanks for posting your code, I finally learned how to do streaming.
9,434,205
The code below is streaming the twitter public timeline for a variable which output any tweets to the console. I'd like the save the same variables (status.text, status.author.screen\_name, status.created\_at, status.source) into an sqlite database. I'm getting an syntax error when my script sees a tweet and nothing is written to the sqlite database. the error: ``` $ python stream-v5.py @lunchboxhq Filtering the public timeline for "@lunchboxhq"RT @LunchboxHQ: test 2 LunchboxHQ 2012-02-29 18:03:42 Echofon Encountered Exception: near "?": syntax error ``` the code: ``` import sys import tweepy import webbrowser import sqlite3 as lite # Query terms Q = sys.argv[1:] sqlite3file='/var/www/twitter.lbox.com/html/stream5_log.sqlite' CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) con = lite.connect(sqlite3file) cur = con.cursor() cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): try: print "%s\t%s\t%s\t%s" % (status.text, status.author.screen_name, status.created_at, status.source,) cur.executemany("INSERT INTO TWEETS(?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) except Exception, e: print >> sys.stderr, 'Encountered Exception:', e pass def on_error(self, status_code): print >> sys.stderr, 'Encountered error with status code:', status_code return True # Don't kill the stream def on_timeout(self): print >> sys.stderr, 'Timeout...' return True # Don't kill the stream streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60) print >> sys.stderr, 'Filtering the public timeline for "%s"' % (' '.join(sys.argv[1:]),) streaming_api.filter(follow=None, track=Q) ```
2012/02/24
[ "https://Stackoverflow.com/questions/9434205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039166/" ]
``` import sqlite3 as lite con = lite.connect('test.db') cur = con.cursor() cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") ``` then later: ``` cur.executemany("INSERT INTO TWEETS(?, ?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) ```
I'm quite new to tweepy . But these are the modifications that worked for me . You need to add VALUES after INSERT INTO TWEETS . Also , don't forget to commit the changes . This is the link I referred to : [related post](https://stackoverflow.com/questions/9470308/tweepy-stream-to-sqlite-database-syntax-error?lq=1) ``` cur.execute("INSERT INTO TWEETS VALUES(?, ?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) con.commit() ```
9,434,205
The code below is streaming the twitter public timeline for a variable which output any tweets to the console. I'd like the save the same variables (status.text, status.author.screen\_name, status.created\_at, status.source) into an sqlite database. I'm getting an syntax error when my script sees a tweet and nothing is written to the sqlite database. the error: ``` $ python stream-v5.py @lunchboxhq Filtering the public timeline for "@lunchboxhq"RT @LunchboxHQ: test 2 LunchboxHQ 2012-02-29 18:03:42 Echofon Encountered Exception: near "?": syntax error ``` the code: ``` import sys import tweepy import webbrowser import sqlite3 as lite # Query terms Q = sys.argv[1:] sqlite3file='/var/www/twitter.lbox.com/html/stream5_log.sqlite' CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) con = lite.connect(sqlite3file) cur = con.cursor() cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): try: print "%s\t%s\t%s\t%s" % (status.text, status.author.screen_name, status.created_at, status.source,) cur.executemany("INSERT INTO TWEETS(?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) except Exception, e: print >> sys.stderr, 'Encountered Exception:', e pass def on_error(self, status_code): print >> sys.stderr, 'Encountered error with status code:', status_code return True # Don't kill the stream def on_timeout(self): print >> sys.stderr, 'Timeout...' return True # Don't kill the stream streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60) print >> sys.stderr, 'Filtering the public timeline for "%s"' % (' '.join(sys.argv[1:]),) streaming_api.filter(follow=None, track=Q) ```
2012/02/24
[ "https://Stackoverflow.com/questions/9434205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039166/" ]
You are missing a closing parenthesis on the last line of the following code (lines 34–37 from what you posted): ``` cur.executemany("INSERT INTO TWEETS(?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source) ``` Just add a parenthesis to close the method call immediately after your tuple parameter.
Full disclosure: still new to this stuff. However, I got your code working by changing it to: ``` cur.execute("INSERT INTO TWEETS VALUES(?,?,?,?)", (status.text, status.author.screen_name, status.created_at, status.source)) con.commit() ``` It seems to me that you're reading in one status at a time. The executemany method would be for when you have more than one status. For example: `(['sometext', 'bob','2013-02-01','Twitter for Android'], ['someothertext', 'helga', '2013-01-31', 'MacSomething'])` I'm definitely not a wizard and am not sure what sort of impact the commit() has on every entry... I'm guessing the performance is terrible, but it works for a single term in the query. Thanks for posting your code, I finally learned how to do streaming.
9,434,205
The code below is streaming the twitter public timeline for a variable which output any tweets to the console. I'd like the save the same variables (status.text, status.author.screen\_name, status.created\_at, status.source) into an sqlite database. I'm getting an syntax error when my script sees a tweet and nothing is written to the sqlite database. the error: ``` $ python stream-v5.py @lunchboxhq Filtering the public timeline for "@lunchboxhq"RT @LunchboxHQ: test 2 LunchboxHQ 2012-02-29 18:03:42 Echofon Encountered Exception: near "?": syntax error ``` the code: ``` import sys import tweepy import webbrowser import sqlite3 as lite # Query terms Q = sys.argv[1:] sqlite3file='/var/www/twitter.lbox.com/html/stream5_log.sqlite' CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_TOKEN = '' ACCESS_TOKEN_SECRET = '' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) con = lite.connect(sqlite3file) cur = con.cursor() cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): try: print "%s\t%s\t%s\t%s" % (status.text, status.author.screen_name, status.created_at, status.source,) cur.executemany("INSERT INTO TWEETS(?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) except Exception, e: print >> sys.stderr, 'Encountered Exception:', e pass def on_error(self, status_code): print >> sys.stderr, 'Encountered error with status code:', status_code return True # Don't kill the stream def on_timeout(self): print >> sys.stderr, 'Timeout...' return True # Don't kill the stream streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60) print >> sys.stderr, 'Filtering the public timeline for "%s"' % (' '.join(sys.argv[1:]),) streaming_api.filter(follow=None, track=Q) ```
2012/02/24
[ "https://Stackoverflow.com/questions/9434205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039166/" ]
You are missing a closing parenthesis on the last line of the following code (lines 34–37 from what you posted): ``` cur.executemany("INSERT INTO TWEETS(?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source) ``` Just add a parenthesis to close the method call immediately after your tuple parameter.
I'm quite new to tweepy . But these are the modifications that worked for me . You need to add VALUES after INSERT INTO TWEETS . Also , don't forget to commit the changes . This is the link I referred to : [related post](https://stackoverflow.com/questions/9470308/tweepy-stream-to-sqlite-database-syntax-error?lq=1) ``` cur.execute("INSERT INTO TWEETS VALUES(?, ?, ?, ?)", (status.text, status.author.screen_name, status.created_at, status.source)) con.commit() ```
60,513,468
I read from python3 document, that python use hash table for dict(). So the search time complexity should be O(1) with O(N) as the worst case. However, recently as I took a course, the teacher says that happens only when you use int as the key. If you use a string of length L as keys the search time complexity is O(L). I write a code snippet to test out his honesty ```py import random import string from time import time import matplotlib.pyplot as plt def randomString(stringLength=10): """Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) def test(L): #L: int length of keys N = 1000 # number of keys d = dict() for i in range(N): d[randomString(L)] = None tic = time() for key in d.keys(): d[key] toc = time() - tic tic = time() for key in d.keys(): pass t_idle = time() - tic t_total = toc - t_idle return t_total L = [i * 10000 for i in range(5, 15)] ans = [test(l) for l in L] plt.figure() plt.plot(L, ans) plt.show() ``` The result is very interesting. As you can see, the x-axis is the length of the strings used as keys and the y-axis is the total time to query all 1000 keys in the dictionary. [![enter image description here](https://i.stack.imgur.com/7tkOr.png)](https://i.stack.imgur.com/7tkOr.png) Can anyone explain this result? Please be gentle on me. As you can see, if I ask this basic question, that means I don't have the ability to read python source code or equivalently complex insider document.
2020/03/03
[ "https://Stackoverflow.com/questions/60513468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7037749/" ]
Since a dictionary is a hashtable, and looking up a key in a hashtable requires computing the key's hash, then the time complexity of looking up the key in the dictionary cannot be less than the time complexity of the hash function. In current versions of CPython, a string of length L takes O(L) time to compute the hash of if it's the first time you've hashed that particular string object, and O(1) time if the hash for that string object has already been computed (since the hash is stored): ```py >>> from timeit import timeit >>> s = 'b' * (10**9) # string of length 1 billion >>> timeit(lambda: hash(s), number=1) 0.48574538500002973 # half a second >>> timeit(lambda: hash(s), number=1) 5.301000044255488e-06 # 5 microseconds ``` So that's also how long it takes when you look up the key in a dictionary: ```py >>> s = 'c' * (10**9) # string of length 1 billion >>> d = dict() >>> timeit(lambda: s in d, number=1) 0.48521506899999167 # half a second >>> timeit(lambda: s in d, number=1) 4.491000026973779e-06 # 5 microseconds ``` You also need to be aware that a key in a dictionary is not looked up *only* by its hash: when the hashes match, it still needs to test that the key you looked up is equal to the key used in the dictionary, in case the hash matching is a false positive. Testing equality of strings takes O(L) time in the worst case: ```py >>> s1 = 'a'*(10**9) >>> s2 = 'a'*(10**9) >>> timeit(lambda: s1 == s2, number=1) 0.2006020820001595 ``` So for a key of length L and a dictionary of length n: * If the key is not present in the dictionary, and its hash has already been cached, then it takes O(1) average time to confirm it is absent. * If the key is not present and its hash has not been cached, then it takes O(L) average time because of computing the hash. * If the key is present, it takes O(L) average time to confirm it is present whether or not the hash needs to be computed, because of the equality test. * The worst case is always O(nL) because if every hash collides and the strings are all equal except in the last places, then a slow equality test has to be done n times.
> > only when you use int as the key. If you use a string of length L as keys the search time complexity is O(L) > > > Just to address a point not covered by kaya3's answer.... ### Why people often say a hash table insertion, lookup or erase is a O(1) operation. For many real-world applications of hash tables, the typical length of keys doesn't tend to grow regardless of how many keys you're storing. For example, if you made a hash set to store the names in a telephone book, the average name length for the first 100 people is probably very close to the average length for absolutely everyone. For that reason, the time spent to look for a name is no worse when you have a set of ten million names, versus that initial 100 (this kind of analysis normally ignores the performance impact of CPU cache sizes, and RAM vs disk speeds if your program starts swapping). You can reason about the program without thinking about the length of the names: e.g. inserting a million names is likely to take roughly a thousand times longer than inserting a thousand. Other times, an application has a hash tables where the key may vary significantly. Imagine say a hash set where the keys are binary data encoding videos: one data set is old Standard Definition 24fps video clips, while another is 8k UHD 60fps movies. The time taken to insert these sets of keys won't simply be in the ratio of the numbers of such keys, because there's *vastly* different amounts of work involved in key hashing and comparison. In this case - if you want to reason about insertion time for different sized keys, a big-O performance analysis would be useless without a related factor. You could still describe the relative performance for data sets with similar sized keys considering only the normal hash table performance characteristics. When key hashing times could become a problem, you may well want to consider whether your application design is still a good idea, or whether e.g. you could have used a set of say filenames instead of the raw video data.
38,798,816
I have anaconda installed and also I have downloaded Spark 1.6.2. I am using the following instructions from this answer to configure spark for Jupyter [enter link description here](https://stackoverflow.com/questions/33064031/link-spark-with-ipython-notebook) I have downloaded and unzipped the spark directory as ``` ~/spark ``` Now when I cd into this directory and into bin I see the following ``` SFOM00618927A:spark $ cd bin SFOM00618927A:bin $ ls beeline pyspark run-example.cmd spark-class2.cmd spark-sql sparkR beeline.cmd pyspark.cmd run-example2.cmd spark-shell spark-submit sparkR.cmd load-spark-env.cmd pyspark2.cmd spark-class spark-shell.cmd spark-submit.cmd sparkR2.cmd load-spark-env.sh run-example spark-class.cmd spark-shell2.cmd spark-submit2.cmd ``` I have also added the environment variables as mentioned in the above answer to my .bash\_profile and .profile Now in the spark/bin directory first thing I want to check is if pyspark command works on shell first. So I do this after doing cd spark/bin ``` SFOM00618927A:bin $ pyspark -bash: pyspark: command not found ``` As per the answer after following all the steps I can just do ``` pyspark ``` in terminal in any directory and it should start a jupyter notebook with spark engine. But even the pyspark within the shell is not working forget about making it run on juypter notebook Please advise what is going wrong here. Edit: I did ``` open .profile ``` at home directory and this is what is stored in the path. ``` export PATH=/Users/854319/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/Users/854319/spark/bin export PYSPARK_DRIVER_PYTHON=ipython export PYSPARK_DRIVER_PYTHON_OPTS='notebook' pyspark ```
2016/08/05
[ "https://Stackoverflow.com/questions/38798816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2769240/" ]
1- You need to set `JAVA_HOME` and spark paths for the shell to find them. After setting them in your `.profile` you may want to ``` source ~/.profile ``` to activate the setting in the current session. From your comment I can see you're already having the `JAVA_HOME` issue. Note if you have `.bash_profile` or `.bash_login`, `.profile` will not work as described [here](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_01.html) 2- When you are in `spark/bin` you need to run ``` ./pyspark ``` to tell the shell that the target is in the current folder.
For anyone who came here during or after MacOS Catalina, make sure you're establishing/sourcing variables in **zshrc** and not **bash**. `$ nano ~/.zshrc` ``` # Set Spark Path export SPARK_HOME="YOUR_PATH/spark-3.0.1-bin-hadoop2.7" export PATH="$SPARK_HOME/bin:$PATH" # Set pyspark + jupyter commands export PYSPARK_SUBMIT_ARGS="pyspark-shell" export PYSPARK_DRIVER_PYTHON=jupyter export PYSPARK_DRIVER_PYTHON_OPTS='lab' pyspark ``` `$ source ~/.zshrc` `$ pyspark` # Automatically opens Jupyter Lab w/ PySpark initialized.
38,798,816
I have anaconda installed and also I have downloaded Spark 1.6.2. I am using the following instructions from this answer to configure spark for Jupyter [enter link description here](https://stackoverflow.com/questions/33064031/link-spark-with-ipython-notebook) I have downloaded and unzipped the spark directory as ``` ~/spark ``` Now when I cd into this directory and into bin I see the following ``` SFOM00618927A:spark $ cd bin SFOM00618927A:bin $ ls beeline pyspark run-example.cmd spark-class2.cmd spark-sql sparkR beeline.cmd pyspark.cmd run-example2.cmd spark-shell spark-submit sparkR.cmd load-spark-env.cmd pyspark2.cmd spark-class spark-shell.cmd spark-submit.cmd sparkR2.cmd load-spark-env.sh run-example spark-class.cmd spark-shell2.cmd spark-submit2.cmd ``` I have also added the environment variables as mentioned in the above answer to my .bash\_profile and .profile Now in the spark/bin directory first thing I want to check is if pyspark command works on shell first. So I do this after doing cd spark/bin ``` SFOM00618927A:bin $ pyspark -bash: pyspark: command not found ``` As per the answer after following all the steps I can just do ``` pyspark ``` in terminal in any directory and it should start a jupyter notebook with spark engine. But even the pyspark within the shell is not working forget about making it run on juypter notebook Please advise what is going wrong here. Edit: I did ``` open .profile ``` at home directory and this is what is stored in the path. ``` export PATH=/Users/854319/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/Users/854319/spark/bin export PYSPARK_DRIVER_PYTHON=ipython export PYSPARK_DRIVER_PYTHON_OPTS='notebook' pyspark ```
2016/08/05
[ "https://Stackoverflow.com/questions/38798816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2769240/" ]
Here's my environment vars, hope it will help you: ``` # path to JAVA_HOME export JAVA_HOME=$(/usr/libexec/java_home) #Spark export SPARK_HOME="/usr/local/spark" #version 1.6 export PATH=$PATH:$SPARK_HOME/bin export PYSPARK_SUBMIT_ARGS="--master local[2]" export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH export PYTHONPATH=$SPARK_HOME/python/lib/py4j-0.9-src.zip:$PYTHONPATH export PYSPARK_DRIVER_PYTHON=jupyter export PYSPARK_DRIVER_PYTHON_OPTS='notebook' ``` ^^ Remove the Pyspark\_driver\_python\_opts option if you don't want the notebook to launch, otherwise you can leave this out entirely and use it on your command line when you need it. I have anaconda vars in another line to append to the PATH.
For anyone who came here during or after MacOS Catalina, make sure you're establishing/sourcing variables in **zshrc** and not **bash**. `$ nano ~/.zshrc` ``` # Set Spark Path export SPARK_HOME="YOUR_PATH/spark-3.0.1-bin-hadoop2.7" export PATH="$SPARK_HOME/bin:$PATH" # Set pyspark + jupyter commands export PYSPARK_SUBMIT_ARGS="pyspark-shell" export PYSPARK_DRIVER_PYTHON=jupyter export PYSPARK_DRIVER_PYTHON_OPTS='lab' pyspark ``` `$ source ~/.zshrc` `$ pyspark` # Automatically opens Jupyter Lab w/ PySpark initialized.
38,412,184
I'm trying to free memory allocated to a `CString`and passed to Python using ctypes. However, Python is crashing with a malloc error: ```none python(30068,0x7fff73f79000) malloc: *** error for object 0x103be2490: pointer being freed was not allocated ``` Here are the Rust functions I'm using to pass the pointer to ctypes: ``` #[repr(C)] pub struct Array { pub data: *const c_void, pub len: libc::size_t, } // Build &mut[[f64; 2]] from an Array, so it can be dropped impl<'a> From<Array> for &'a mut [[f64; 2]] { fn from(arr: Array) -> Self { unsafe { slice::from_raw_parts_mut(arr.data as *mut [f64; 2], arr.len) } } } // Build an Array from a Vec, so it can be leaked across the FFI boundary impl<T> From<Vec<T>> for Array { fn from(vec: Vec<T>) -> Self { let array = Array { data: vec.as_ptr() as *const libc::c_void, len: vec.len() as libc::size_t, }; mem::forget(vec); array } } // Build a Vec from an Array, so it can be dropped impl From<Array> for Vec<[f64; 2]> { fn from(arr: Array) -> Self { unsafe { Vec::from_raw_parts(arr.data as *mut [f64; 2], arr.len, arr.len) } } } // Decode an Array into a Polyline impl From<Array> for String { fn from(incoming: Array) -> String { let result: String = match encode_coordinates(&incoming.into(), 5) { Ok(res) => res, // we don't need to adapt the error Err(res) => res }; result } } #[no_mangle] pub extern "C" fn encode_coordinates_ffi(coords: Array) -> *mut c_char { let s: String = coords.into(); CString::new(s).unwrap().into_raw() } ``` And the one I'm using to free the pointer when it's returned by Python ``` pub extern "C" fn drop_cstring(p: *mut c_char) { unsafe { CString::from_raw(p) }; } ``` And the Python function I'm using to convert the pointer to a `str`: ``` def char_array_to_string(res, _func, _args): """ restype is c_void_p to prevent automatic conversion to str which loses pointer access """ converted = cast(res, c_char_p) result = converted.value drop_cstring(converted) return result ``` And the Python function I'm using to generate the `Array` struct to pass into Rust: ``` class _FFIArray(Structure): """ Convert sequence of float lists to a C-compatible void array example: [[1.0, 2.0], [3.0, 4.0]] """ _fields_ = [("data", c_void_p), ("len", c_size_t)] @classmethod def from_param(cls, seq): """ Allow implicit conversions """ return seq if isinstance(seq, cls) else cls(seq) def __init__(self, seq, data_type = c_double): arr = ((c_double * 2) * len(seq))() for i, member in enumerate(seq): arr[i][0] = member[0] arr[i][1] = member[1] self.data = cast(arr, c_void_p) self.len = len(seq) ``` `argtype` and `restype` definitions: ``` encode_coordinates = lib.encode_coordinates_ffi encode_coordinates.argtypes = (_FFIArray,) encode_coordinates.restype = c_void_p encode_coordinates.errcheck = char_array_to_string drop_cstring = lib.drop_cstring drop_cstring.argtypes = (c_char_p,) drop_cstring.restype = None ``` I'm inclined to think it's not the Rust functions, because a dylib crash would cause a segfault (and the FFI tests pass on the Rust side). I can also continue with other operations in Python after calling the FFI functions – the malloc error occurs when the process exits.
2016/07/16
[ "https://Stackoverflow.com/questions/38412184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416626/" ]
Please try this command I have resolved it by this command ``` sudo apt-get install libfontconfig ```
Try add onError event to pipe ``` converter.image(req, { format: "png" , quality: 75 }).pipe(res).on('error', function(e){ console.log(e); }); ```
26,509,222
I have a list of python strings which are in a list. I want to call split method at each string in the list and store the results in another list without using loops because the list is very long. **EDIT1** Here is one example ``` input = ["a,the,an","b,b,c","people,downvoting,it,must,think,first"] output [["a","the","an"],["b","b","c"],["people","downvoting","it","must","think","first"]] ``` The delimiter used for splitting is "," Any trick for this?
2014/10/22
[ "https://Stackoverflow.com/questions/26509222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/623300/" ]
``` [a.split(',') for a in list] Sample: ['a,c,b','1,2,3'] Result: [['a','c','b'],['1','2','3']] ``` If you wanted everything in one list, you could try this (not sure of how efficient it is) ``` output = sum([a.split(',') for a in list],[]) Sample: ['a,c,b','1,2,3'] Result: ['a','c','b','1','2','3'] ```
Use list comprehensions. ``` mystrings = ["hello world", "this is", "a list", "of interesting", "strings"] splitby = " " mysplits = [x.split(splitby) for x in mystrings] ``` No idea if it performs better than a `for` loop, but there you go.
26,509,222
I have a list of python strings which are in a list. I want to call split method at each string in the list and store the results in another list without using loops because the list is very long. **EDIT1** Here is one example ``` input = ["a,the,an","b,b,c","people,downvoting,it,must,think,first"] output [["a","the","an"],["b","b","c"],["people","downvoting","it","must","think","first"]] ``` The delimiter used for splitting is "," Any trick for this?
2014/10/22
[ "https://Stackoverflow.com/questions/26509222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/623300/" ]
``` [a.split(',') for a in list] Sample: ['a,c,b','1,2,3'] Result: [['a','c','b'],['1','2','3']] ``` If you wanted everything in one list, you could try this (not sure of how efficient it is) ``` output = sum([a.split(',') for a in list],[]) Sample: ['a,c,b','1,2,3'] Result: ['a','c','b','1','2','3'] ```
If you want a flat list, and not a list of lists: ``` from itertools import chain list_out = list(reduce(chain, [string.split() for string in lists_in])) ```
26,509,222
I have a list of python strings which are in a list. I want to call split method at each string in the list and store the results in another list without using loops because the list is very long. **EDIT1** Here is one example ``` input = ["a,the,an","b,b,c","people,downvoting,it,must,think,first"] output [["a","the","an"],["b","b","c"],["people","downvoting","it","must","think","first"]] ``` The delimiter used for splitting is "," Any trick for this?
2014/10/22
[ "https://Stackoverflow.com/questions/26509222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/623300/" ]
``` [a.split(',') for a in list] Sample: ['a,c,b','1,2,3'] Result: [['a','c','b'],['1','2','3']] ``` If you wanted everything in one list, you could try this (not sure of how efficient it is) ``` output = sum([a.split(',') for a in list],[]) Sample: ['a,c,b','1,2,3'] Result: ['a','c','b','1','2','3'] ```
I would turn the list to a string and then turn the string back to a list with the split function. Hence running the split function only once. `' '.join(['my', 'very', 'long', 'list']).split(' ');`
27,580,550
I develop python app which connect to Prolog via pyswip. The following code is when I ask a question from prolog. ``` self.prolog = Prolog() self.prolog.consult("Checker.pl") self.prolog.query("playX") ``` This is the sample of my Prolog code ``` playX :- init(B), assert(min_to_move(x/_)),assert(max_to_move(o/_)), play(human, x, B). ``` When query ("playX"), there is a message ``` Exception AttributeError: 'swipl_qid' in <bound method _QueryWrapper.__del__ of <pyswip.prolog._QueryWrapper object at 0x0000000004620288>> ignored ``` What happen? Ps. I use all 64 bit: Python 2.7, SWI-Prolog, pyswip, Visual Studio 2013
2014/12/20
[ "https://Stackoverflow.com/questions/27580550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050141/" ]
In your style.css add this code ``` #toggle-menu li { float: right; list-style-type: none; } ``` See [here](http://i.stack.imgur.com/aznP5.png) for an example of it in action. The reason that dot is there is that you're adding it as a list element -- it's not a full stop, necessarily, just the marker for a new element in an unordered list. `list-style-type:none` gets rid of any style for the list elements.
It's not a full stop, it's a list item bullet. You're using a list with `<li>` tags, and the default behaviour is to put a bullet in front of whatever is inside the `<li>` The real answer here though is that your code isn't very semantically correct. Why is an icon inside of an unordered list in the first place? Consider two other options... 1) Just putting `<a>` containing your icon in front of the nav and leaving it at that 2) Incorporating the font awesome icon in to a :before or :after psuedo-element of the nav menu itself using CSS styling. Information about how to add icons via CSS can be found on the font awesome site.
27,580,550
I develop python app which connect to Prolog via pyswip. The following code is when I ask a question from prolog. ``` self.prolog = Prolog() self.prolog.consult("Checker.pl") self.prolog.query("playX") ``` This is the sample of my Prolog code ``` playX :- init(B), assert(min_to_move(x/_)),assert(max_to_move(o/_)), play(human, x, B). ``` When query ("playX"), there is a message ``` Exception AttributeError: 'swipl_qid' in <bound method _QueryWrapper.__del__ of <pyswip.prolog._QueryWrapper object at 0x0000000004620288>> ignored ``` What happen? Ps. I use all 64 bit: Python 2.7, SWI-Prolog, pyswip, Visual Studio 2013
2014/12/20
[ "https://Stackoverflow.com/questions/27580550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050141/" ]
In your style.css add this code ``` #toggle-menu li { float: right; list-style-type: none; } ``` See [here](http://i.stack.imgur.com/aznP5.png) for an example of it in action. The reason that dot is there is that you're adding it as a list element -- it's not a full stop, necessarily, just the marker for a new element in an unordered list. `list-style-type:none` gets rid of any style for the list elements.
Your toggle-menu class should contain something like ``` list-style: none; ```
27,580,550
I develop python app which connect to Prolog via pyswip. The following code is when I ask a question from prolog. ``` self.prolog = Prolog() self.prolog.consult("Checker.pl") self.prolog.query("playX") ``` This is the sample of my Prolog code ``` playX :- init(B), assert(min_to_move(x/_)),assert(max_to_move(o/_)), play(human, x, B). ``` When query ("playX"), there is a message ``` Exception AttributeError: 'swipl_qid' in <bound method _QueryWrapper.__del__ of <pyswip.prolog._QueryWrapper object at 0x0000000004620288>> ignored ``` What happen? Ps. I use all 64 bit: Python 2.7, SWI-Prolog, pyswip, Visual Studio 2013
2014/12/20
[ "https://Stackoverflow.com/questions/27580550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050141/" ]
It's not a full stop, it's a list item bullet. You're using a list with `<li>` tags, and the default behaviour is to put a bullet in front of whatever is inside the `<li>` The real answer here though is that your code isn't very semantically correct. Why is an icon inside of an unordered list in the first place? Consider two other options... 1) Just putting `<a>` containing your icon in front of the nav and leaving it at that 2) Incorporating the font awesome icon in to a :before or :after psuedo-element of the nav menu itself using CSS styling. Information about how to add icons via CSS can be found on the font awesome site.
Your toggle-menu class should contain something like ``` list-style: none; ```
26,909,770
i am looking for a way to print all internal decimal places of a python decimal. has anyone an idea how to achieve following. The example code is written in Python. ``` from decimal import * bits = 32 precision = Decimal(1) / Decimal(2**bits) val = decimal(1078947848) ``` what happens now for following if i multiply val \* precision i get following result ``` val * precision Decimal('0.2512121219187974929809570312') ``` but i know the last number 2 is not the end of my number, so i can do following which gives me this result ``` "%.100f" % x '0.2512121219187974929809570312500000000000000000000000000000000000000000000000000000000000000000000000' ``` however all the trailing zeros are not desired, and the size of %.100f depends on the given bits. It should be simple math and maybe I should give myself a break, but how can I derive the number of internal decimal places from the given number of bits 32.
2014/11/13
[ "https://Stackoverflow.com/questions/26909770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1446071/" ]
From the [documentation](https://docs.python.org/2/library/decimal.html): > > the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem > > > Your number is 29 digits long, so it's just a little too much for the default precision. Try increasing it. 29 would work for this instance, but you may wish to choose a larger number if you don't know how many decimal places you'll need later. ``` from decimal import * getcontext().prec = 100 bits = 32 precision = Decimal(1) / Decimal(2**bits) val = Decimal(1078947848) print val * precision ``` Result: ``` 0.25121212191879749298095703125000 ``` Also, you can strip those trailing zeroes with a call to `normalize`. ``` >>> print (val * precision).normalize() 0.25121212191879749298095703125 ```
You could take your string representation & eliminate the trailing 0's; what is left are your "internal decimal places", which you can count.
27,183,163
Python 3.4 So maybe it's the turkey digesting, or maybe it's my lack of python wizardry, but my simplistic idea for initializing instances of a class with several members all set to None doesn't seem to be working. To wit: dataA.txt ``` # layername purpose stmLay stmDat topside copper 3 5 levelA trace5 6 8 ``` shouldWork.py ``` #!C:/Python34 import sys import re class LayerDataInn: def __init__( self, layername, purpose, stmLay, stmDat): self.layername = layername self.purpose = purpose self.stmLay = stmLay self.stmDat = stmDat def __init__( self, list_data): self.layername = list_data[0] self.purpose = list_data[1] self.stmLay = list_data[2] self.stmDat = list_data[3] def display( self): print("layername" " purpose:", self.purpose, \ " stmLay:", self.stmLay, \ " stmDat:", self.stmDat ) def toList( self): return [ self.layername, \ self.purpose, \ self.stmLay, \ self.stmDat ] class LayerDataOut: def __init__( self, layername, purpose, stmLay, stmDat, maskColor): self.layername = layername self.purpose = purpose self.stmLay = stmLay self.stmDat = stmDat self.maskColor = maskColor def __init__( self, list_data): self.layername = list_data[0] self.purpose = list_data[1] self.stmLay = list_data[2] self.stmDat = list_data[3] self.maskColor = list_data[4] def display( self): print("layername" " purpose:", self.purpose, \ " stmLay:", self.stmLay, \ " stmDat:", self.stmDat, \ " maskColor:", self.maskColor ) def toList( self): return [ self.layername, \ self.purpose, \ self.stmLay, \ self.stmDat, \ self.maskColor ] class LayerDataOutOut( object): def __init__( self): self.layername = None self.purpose = None self.stmLay = None self.stmDat = None self.maskColor = None def insert( self, *args): if( len( args) == 2): self.layername = list_data[0] self.purpose = list_data[1] self.stmLay = list_data[2] self.stmDat = list_data[3] self.maskColor = list_data[4] if( len( args) == 6): self.layername = layername self.purpose = purpose self.stmLay = stmLay self.stmDat = stmDat self.maskColor = maskColor def display( self): print("layername", self.layername, \ " purpose:", self.purpose, \ " stmLay:", self.stmLay, \ " stmDat:", self.stmDat, \ " maskColor:", self.maskColor ) def toList( self): return [ self.layername, \ self.purpose, \ self.stmLay, \ self.stmDat, \ self.maskColor ] # read the file list_layerInn = [] fn_layerInn = "dataA.txt" with open( fn_layerInn) as fp_layerInn: for line in fp_layerInn: list_layerInn.append( LayerDataInn( line.split())) # list out the file for objLayerInn in list_layerInn: objLayerInn.display() list_layerOut = [] for objLayerInn in list_layerInn: list_objLayerInn = objLayerInn.toList() list_objLayerInn.append("woohoo") list_layerOut.append( LayerDataOut( list_objLayerInn)) # list out the file for objLayerOut in list_layerOut: objLayerOut.display() list_layerOutOut = [] for objLayerInn in list_layerInn: objLayerOutOut = LayerDataOutOut() setattr( objLayerOutOut, layername, getattr( objLayerInn, layername)) # <-- dies here setattr( objLayerOutOut, purpose, getattr( objLayerInn, purpose)) setattr( objLayerOutOut, stmLay, getattr( objLayerInn, stmLay)) setattr( objLayerOutOut, stmDat, getattr( objLayerInn, stmDat)) setattr( objLayerOutOut, maskColor, "wheeee" ) list_layerOutOut.append( objLayerOutOut) # list out the file for objLayerOutOut in list_layerOutOut: objLayerOutOut.display() ``` I would expect that LayerDataOutOut's **init** would add the members with values of None , to be promptly updated with the setattr 's. Overall goal here is to be able to instantiate an instance of a class with all members accounted for and set to None with just a simple call to the class with no arguments, like Java or C++ TIA, Still-learning Steve
2014/11/28
[ "https://Stackoverflow.com/questions/27183163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1201168/" ]
Finally, I was able to fix the problem. I am posting it for others sake. I used ssh **-f** user@server .... this solved my problem. ``` ssh -f root@${server} sh /home/administrator/bin/startServer.sh ```
I ran into a similar issue using the **Publish Over SSH Plugin**. For some reason Jenkins wasn't stopping after executing the remote script. Ticking the below configuration fixed the problem. SSH Publishers > Transfers > Advanced > Exec in pty Hope it helps someone else.
27,183,163
Python 3.4 So maybe it's the turkey digesting, or maybe it's my lack of python wizardry, but my simplistic idea for initializing instances of a class with several members all set to None doesn't seem to be working. To wit: dataA.txt ``` # layername purpose stmLay stmDat topside copper 3 5 levelA trace5 6 8 ``` shouldWork.py ``` #!C:/Python34 import sys import re class LayerDataInn: def __init__( self, layername, purpose, stmLay, stmDat): self.layername = layername self.purpose = purpose self.stmLay = stmLay self.stmDat = stmDat def __init__( self, list_data): self.layername = list_data[0] self.purpose = list_data[1] self.stmLay = list_data[2] self.stmDat = list_data[3] def display( self): print("layername" " purpose:", self.purpose, \ " stmLay:", self.stmLay, \ " stmDat:", self.stmDat ) def toList( self): return [ self.layername, \ self.purpose, \ self.stmLay, \ self.stmDat ] class LayerDataOut: def __init__( self, layername, purpose, stmLay, stmDat, maskColor): self.layername = layername self.purpose = purpose self.stmLay = stmLay self.stmDat = stmDat self.maskColor = maskColor def __init__( self, list_data): self.layername = list_data[0] self.purpose = list_data[1] self.stmLay = list_data[2] self.stmDat = list_data[3] self.maskColor = list_data[4] def display( self): print("layername" " purpose:", self.purpose, \ " stmLay:", self.stmLay, \ " stmDat:", self.stmDat, \ " maskColor:", self.maskColor ) def toList( self): return [ self.layername, \ self.purpose, \ self.stmLay, \ self.stmDat, \ self.maskColor ] class LayerDataOutOut( object): def __init__( self): self.layername = None self.purpose = None self.stmLay = None self.stmDat = None self.maskColor = None def insert( self, *args): if( len( args) == 2): self.layername = list_data[0] self.purpose = list_data[1] self.stmLay = list_data[2] self.stmDat = list_data[3] self.maskColor = list_data[4] if( len( args) == 6): self.layername = layername self.purpose = purpose self.stmLay = stmLay self.stmDat = stmDat self.maskColor = maskColor def display( self): print("layername", self.layername, \ " purpose:", self.purpose, \ " stmLay:", self.stmLay, \ " stmDat:", self.stmDat, \ " maskColor:", self.maskColor ) def toList( self): return [ self.layername, \ self.purpose, \ self.stmLay, \ self.stmDat, \ self.maskColor ] # read the file list_layerInn = [] fn_layerInn = "dataA.txt" with open( fn_layerInn) as fp_layerInn: for line in fp_layerInn: list_layerInn.append( LayerDataInn( line.split())) # list out the file for objLayerInn in list_layerInn: objLayerInn.display() list_layerOut = [] for objLayerInn in list_layerInn: list_objLayerInn = objLayerInn.toList() list_objLayerInn.append("woohoo") list_layerOut.append( LayerDataOut( list_objLayerInn)) # list out the file for objLayerOut in list_layerOut: objLayerOut.display() list_layerOutOut = [] for objLayerInn in list_layerInn: objLayerOutOut = LayerDataOutOut() setattr( objLayerOutOut, layername, getattr( objLayerInn, layername)) # <-- dies here setattr( objLayerOutOut, purpose, getattr( objLayerInn, purpose)) setattr( objLayerOutOut, stmLay, getattr( objLayerInn, stmLay)) setattr( objLayerOutOut, stmDat, getattr( objLayerInn, stmDat)) setattr( objLayerOutOut, maskColor, "wheeee" ) list_layerOutOut.append( objLayerOutOut) # list out the file for objLayerOutOut in list_layerOutOut: objLayerOutOut.display() ``` I would expect that LayerDataOutOut's **init** would add the members with values of None , to be promptly updated with the setattr 's. Overall goal here is to be able to instantiate an instance of a class with all members accounted for and set to None with just a simple call to the class with no arguments, like Java or C++ TIA, Still-learning Steve
2014/11/28
[ "https://Stackoverflow.com/questions/27183163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1201168/" ]
Finally, I was able to fix the problem. I am posting it for others sake. I used ssh **-f** user@server .... this solved my problem. ``` ssh -f root@${server} sh /home/administrator/bin/startServer.sh ```
I got the solution for you my friend. Make sure to add **usePty: true** in the pipeline that you are using which will enable the execution of sudo commands that require a tty (and possibly help in other scenarios too.) ``` sshTransfer( sourceFiles: "target/*.zip", removePrefix: "target", remoteDirectory: "'/root/'yyyy-MM-dd", execTimeout: 300000, usePty: true, verbose: true, execCommand: ''' pkill -f MyExecutable nohup java -jar /home/administrator/app/MyExecutable.jar & echo $! >> /tmp/jenkins/jenkins.pid sleep 1 ''' ) ```
44,214,938
These are the versions that I am working with ``` $ python --version Python 2.7.10 $ pip --version pip 9.0.1 from /Library/Python/2.7/site-packages (python 2.7) ``` Ideally I should be able to install tweepy. But that is not happening. ``` $ pip install tweepy Collecting tweepy Using cached tweepy-3.5.0-py2.py3-none-any.whl Collecting six>=1.7.3 (from tweepy) Using cached six-1.10.0-py2.py3-none-any.whl Requirement already satisfied: requests>=2.4.3 in /Library/Python/2.7/site-packages (from tweepy) Requirement already satisfied: requests-oauthlib>=0.4.1 in /Library/Python/2.7/site-packages (from tweepy) Requirement already satisfied: oauthlib>=0.6.2 in /Library/Python/2.7/site-packages (from requests-oauthlib>=0.4.1->tweepy) Installing collected packages: six, tweepy Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling six-1.4.1: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) ``` A bunch of lines deleted for brevity. It finally ends at ... ``` File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat os.chflags(dst, st.st_flags) OSError: [Errno 1] Operation not permitted: '/tmp/pip-CBvMLu-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info' ``` Can anyone help? **Update** Tried the following as well. But did not solve the problem ``` $ sudo -H pip install tweepy ```
2017/05/27
[ "https://Stackoverflow.com/questions/44214938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6193290/" ]
Install it with: ``` sudo pip install tweepy ``` Looks like a permission problem :)
I got the same problem. The way I solved it was to download python 2.7.13 from the official website and install it. After that, I installed pip with: ``` sudo easy_install pip ``` And after that: ``` pip install tweepy ``` Hope it is still relevant :)
32,531,858
Assume you have a list : ``` mylist=[[1,2,3,4],[2,3,4,5],[3,4,5,6]] ``` any pythonic(2.x) way to unpack the inner lists so that new list should look like ?: ``` mylist_n=[1,2,3,4,2,3,4,5,3,4,5,6] ```
2015/09/11
[ "https://Stackoverflow.com/questions/32531858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2516297/" ]
I think that due the fact that you are setting the text of the button as follows: ``` <asp:LinkButton ID="click_download" runat="server" OnClick="download"><%# Eval("title") %></asp:LinkButton> ``` The `Text` property is not being set correctly. Move the `<%# Eval("title") %>` into the declaration of link button and assign it's value to the `Text` property: ``` <asp:LinkButton ID="click_download" runat="server" OnClick="download" Text='<%# DataBinder.Eval (Container.DataItem, "title") %>'></asp:LinkButton> ```
I don't see where you are setting the text property/attribute for the LinkButton. However, I do see where you have "<%# Eval("title") %>" floating in your tag. Should it say Text="<%# Eval("title") %>". I really don't understand how it is being viewed if it's not set. Are you setting it in the Page\_Load? Hopefully these questions help chase down the problem.
19,325,907
I am working on my first Django website and am having a problem. Whenever I attempt to go on the admin page www.example.com/admin I encounter a 404 page. When I attempt to go on the admin site on my computer using `python manage.py runserver` it works. What info do you guys need to help me to fix my problem? `url.py` ``` from django.conf.urls import patterns, include, url` from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.http import HttpResponseRedirect admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), .... ``` ```
2013/10/11
[ "https://Stackoverflow.com/questions/19325907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2366105/" ]
You must include the Django admin in your `INSTALLED_APPS` in the settings file (it's probably already there, but commented out). You will also need to configure the URLs for the admin site, which should be in your site-wide urls.py, again, probably commented out but there. If you have already done both of these things, please share your urls.py from the project itself.
`python manage.py runserver` enables your application to run locally. You need to deploy your application using WSGI and Apache to access your page from other remove machines. Refer to the configuration details <https://docs.djangoproject.com/en/1.2/howto/deployment/modwsgi/>
34,092,850
I'm trying to apply the expert portion of the tutorial to my own data but I keep running into dimension errors. Here's the code leading up to the error. ``` def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') W_conv1 = weight_variable([1, 8, 1, 4]) b_conv1 = bias_variable([4]) x_image = tf.reshape(tf_in, [-1,2,8,1]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) ``` And then when I try to run this command: ``` W_conv2 = weight_variable([1, 4, 4, 8]) b_conv2 = bias_variable([8]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) ``` I get the following errors: ``` ValueError Traceback (most recent call last) <ipython-input-41-7ab0d7765f8c> in <module>() 3 4 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) ----> 5 h_pool2 = max_pool_2x2(h_conv2) ValueError: ('filter must not be larger than the input: ', 'Filter: [', Dimension(2), 'x', Dimension(2), '] ', 'Input: [', Dimension(1), 'x', Dimension(4), '] ') ``` Just for some background information, the data that I'm dealing with is a CSV file where each row contains 10 features and 1 empty column that can be a 1 or a 0. What I'm trying to get is a probability in the empty column that the column will equal a 1.
2015/12/04
[ "https://Stackoverflow.com/questions/34092850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3849791/" ]
You have to shape the input so it is compatible with both the training tensor and the output. If you input is length 1, your output should be length 1 (length is substituted for dimension). When you're dealing with- ``` def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 1, 1, 1], strides=[1, 1, 1, 1], padding='SAME') ``` Notice how I changed the strides and the ksize to `[1, 1, 1, 1]`. This will match an output to a 1 dimensional input and prevent errors down the road. When you're defining your weight variable (see code below)- ``` def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) ``` you're going to have to make the first 2 numbers conform to the feature tensor that you are using to train your model, the last two numbers will be the dimension of the predicted output (same as the dimension of the input). ``` W_conv1 = weight_variable([1, 10, 1, 1]) b_conv1 = bias_variable([1]) ``` Notice the `[1, 10,` in the beginning which signifies that the feature tensor is going to be a 1x10 feature tensor; the last two numbers `1, 1]` correspond to the dimensions of the input and output tensors/predictors. When you reshape your x\_foo tensor (I call it x\_ [x prime]), you, for whatever reason, have to define it like so- ``` x_ = tf.reshape(x, [-1,1,10,1]) ``` Notice the 1 and 10 in the middle- `...1,10,...`. Once again, these numbers correspond to the dimension of your feature tensor. For every bias variable, you choose the final number of the previously defined variable. For example, if `W_conv1 = weight_variable([1, 10, 1, 1])` appears like so, you take the final number and put that into your bias variable so it can match the dimensions of the input. This is done like so- `b_conv1 = bias_variable([1])`. If you need any more explanation please comment below.
The dimensions you are using for the filter are not matching the output of the hidden layer. Let me see if I understood you: your input is composed of 8 features, and you want to reshape it into a 2x4 matrix, right? The weights you created with `weight_variable([1, 8, 1, 4])` expect a 1x8 input, in one channel, and produce a 1x8 output in 4 channels (or hidden units). The filter you are using sweeps the input in 2x2 squares. However, since the result of the weights is 1x8, they won't match. You should reshape the input as ``` x_image = tf.reshape(tf_in, [-1,2,4,1]) ``` Now, your input is actually 2x4 instead of 1x8. Then you need to change the weight shape to `(2, 4, 1, hidden_units)` to deal with a 2x4 output. It will also produce a 2x4 output, and the 2x2 filter now can be applied. After that, the filter will match the output of the weights. Also note that you will have to change the shape of your second weight matrix to `weight_variable([2, 4, hidden_units, hidden2_units])`
22,767,444
I have the following xml file: ``` <root> <article_date>09/09/2013 <article_time>1 <article_name>aaa1</article_name> <article_link>1aaaaaaa</article_link> </article_time> <article_time>0 <article_name>aaa2</article_name> <article_link>2aaaaaaa</article_link> </article_time> <article_time>1 <article_name>aaa3</article_name> <article_link>3aaaaaaa</article_link> </article_time> <article_time>0 <article_name>aaa4</article_name> <article_link>4aaaaaaa</article_link> </article_time> <article_time>1 <article_name>aaa5</article_name> <article_link>5aaaaaaa</article_link> </article_time> </article_date> </root> ``` I would like to transform it to the following file: ``` <root> <article_date>09/09/2013 <article_time>1 <article_name>aaa1+aaa3+aaa5</article_name> <article_link>1aaaaaaa+3aaaaaaa+5aaaaaaa</article_link> </article_time> <article_time>0 <article_name>aaa2+aaa4</article_name> <article_link>2aaaaaaa+4aaaaaaa</article_link> </article_time> </root> ``` How can I do it in python? My approach to do this task is the following: 1) loop through tags 2) form dictionary key- either 0 or 1, value - 3) for each element in this dictionary find all child nodes: and and append them Since that, I wrote the following code to implement this (ps I am currently struggling with adding elements to the dictionary, but I will overcome this issue): ``` def parse(): list_of_inique_timestamps=[] text_to_merge="" tree=et.parse("~/Documents/test1.xml") root=tree.getroot() for children in root: print children.tag, children.text for child in children: print (child.tag,int(child.text)) if not child.text in list_of_inique_timestamps: list_of_inique_timestamps.append(child.text) print list_of_inique_timestamps ```
2014/03/31
[ "https://Stackoverflow.com/questions/22767444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1146365/" ]
Here's the solution using `xml.etree.ElementTree` from python standard library. The idea is to gather items into `defaultdict(list)` per `article_time` text value: ``` from collections import defaultdict import xml.etree.ElementTree as ET data = """<root> <article_date>09/09/2013 <article_time>1 <article_name>aaa1</article_name> <article_link>1aaaaaaa</article_link> </article_time> <article_time>0 <article_name>aaa2</article_name> <article_link>2aaaaaaa</article_link> </article_time> <article_time>1 <article_name>aaa3</article_name> <article_link>3aaaaaaa</article_link> </article_time> <article_time>0 <article_name>aaa4</article_name> <article_link>4aaaaaaa</article_link> </article_time> <article_time>1 <article_name>aaa5</article_name> <article_link>5aaaaaaa</article_link> </article_time> </article_date> </root> """ tree = ET.fromstring(data) root = ET.Element('root') article_date = ET.SubElement(root, 'article_date') article_date.text = tree.find('.//article_date').text data = defaultdict(list) for article_time in tree.findall('.//article_time'): text = article_time.text.strip() name = article_time.find('./article_name').text link = article_time.find('./article_link').text data[text].append((name, link)) for time_value, items in data.iteritems(): article_time = ET.SubElement(article_date, 'article_time') article_name = ET.SubElement(article_time, 'article_name') article_link = ET.SubElement(article_time, 'article_name') article_time.text = time_value article_name.text = '+'.join(name for (name, _) in items) article_link.text = '+'.join(link for (_, link) in items) print ET.tostring(root) ``` prints (prettified): ``` <root> <article_date>09/09/2013 <article_time>1 <article_name>aaa1+aaa3+aaa5</article_name> <article_name>1aaaaaaa+3aaaaaaa+5aaaaaaa</article_name> </article_time> <article_time>0 <article_name>aaa2+aaa4</article_name> <article_name>2aaaaaaa+4aaaaaaa</article_name> </article_time> </article_date> </root> ``` See, the result is exactly what you were aiming to.
I'll write as much as I have time (and knowledge), but I'm making this a community wiki so other folks can help. I would suggest using [xml](https://docs.python.org/2/library/xml.etree.elementtree.html) or [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) libraries for this. I'll use BeautifulSoup because I can't get xml to work for some reason right now. First, let's get set up: ``` >>> import bs4 >>> soup = bs4.BeautifulSoup('''<root> ... <article_date>09/09/2013 ... <article_time>1 ... <article_name>aaa1</article_name> ... <article_link>1aaaaaaa</article_link> ... </article_time> ... <article_time>0 ... <article_name>aaa2</article_name> ... <article_link>2aaaaaaa</article_link> ... </article_time> ... <article_time>1 ... <article_name>aaa3</article_name> ... <article_link>3aaaaaaa</article_link> ... </article_time> ... <article_time>0 ... <article_name>aaa4</article_name> ... <article_link>4aaaaaaa</article_link> ... </article_time> ... <article_time>1 ... <article_name>aaa5</article_name> ... <article_link>5aaaaaaa</article_link> ... </article_time> ... </root>''') ``` This just produces an internal representation of your xml. We can use the `find_all` method to grab all the article times. ``` >>> children = soup.find_all('article_time') >>> children [<article_time>1 <article_name>aaa1</article_name> <article_link>1aaaaaaa</article_link> </article_time>, <article_time>0 <article_name>aaa2</article_name> <article_link>2aaaaaaa</article_link> </article_time>, <article_time>1 <article_name>aaa3</article_name> <article_link>3aaaaaaa</article_link> </article_time>, <article_time>0 <article_name>aaa4</article_name> <article_link>4aaaaaaa</article_link> </article_time>, <article_time>1 <article_name>aaa5</article_name> <article_link>5aaaaaaa</article_link> </article_time>] ``` The next thing to do is define a key for how we define 'similar' parent nodes. Let's write a `key` function that specifies which part of each child to look at. We'll do some poking around to learn about the structure of each child first. ``` >>> children[0].contents [u'1\n ', <article_name>aaa1</article_name>, u'\n', <article_link>1aaaaaaa</article_link>, u'\n'] >>> children[0].contents[0] u'1\n ' >>> int(children[0].contents[0]) 1 >>> def key(child): ... return int(child.contents[0]) ... >>> key(children[0]) 1 >>> key(children[1]) 0 ``` Okay. Now we can take advantage of python's [itertools.groupby](https://docs.python.org/2/library/itertools.html#itertools.groupby) function, which will group together all the children with the same key (we need to sort first). We will use the newly defined `key` function to specify how to sort, and what defines a group. ``` >>> children = sorted(children, key=key) >>> import itertools >>> groups = itertools.groupby(children, key) ``` `groups` is a generator -- like a list, but we can only iterate through it once. Let's take a look at what makes it up, even though that will mean we have to recreate it later. (We only get a single pass for generators, so by looking at the data, we're losing it. Luckily, it's pretty easy to recreate) ``` >>> for k, g in groups: ... print k, ':\t', list(g) ... 0 : [<article_time>0 <article_name>aaa2</article_name> <article_link>2aaaaaaa</article_link> </article_time>, <article_time>0 <article_name>aaa4</article_name> <article_link>4aaaaaaa</article_link> </article_time>] 1 : [<article_time>1 <article_name>aaa1</article_name> <article_link>1aaaaaaa</article_link> </article_time>, <article_time>1 <article_name>aaa3</article_name> <article_link>3aaaaaaa</article_link> </article_time>, <article_time>1 <article_name>aaa5</article_name> <article_link>5aaaaaaa</article_link> </article_time>] ``` Okay, so `k` specifies what key was used to produce the group, and g is a sequence of the `article_time`s that matched `k`. Sorry, that's all I have time for at the moment. Hopefully this is enough to get you started.
60,959,871
**The problem**: I have a 3-D Numpy Array: `X` `X.shape: (1797, 2, 500)` ``` z=X[..., -1] print(len(z)) print(z.shape) count = 0 for bot in z: print(bot) count+=1 if count == 3: break ``` Above code yields following output: ``` 1797 (1797, 2) [23.293915 36.37388 ] [21.594519 32.874397] [27.29872 26.798382] ``` So, there are 1797 data points - each with a X and a Y coordinate and, there are 500 iterations of these 1797 points. I want a DataFrame such that: ``` Index Column | X-coordinate | Y-coordinate 0 | X[0][0][0] | X[0][1][0] 0 | X[1][0][0] | X[1][1][0] 0 | X[2][0][0] | X[2][1][0] ('0') 1797 times 1 | X[0][0][1] | X[0][1][1] 1 | X[1][0][1] | X[1][1][1] 1 | X[2][0][1] | X[2][1][1] ('1' 1797 times) . . . and so on till 500 ``` I tried techniques mentioned here, but numpy/pandas is really escaping me: 1. [How To Convert a 3D Array To a Dataframe](https://stackoverflow.com/questions/52195426/how-to-convert-a-3d-array-to-a-dataframe) 2. [How to transform a 3d arrays into a dataframe in python](https://stackoverflow.com/questions/35525028/how-to-transform-a-3d-arrays-into-a-dataframe-in-python) 3. [Convert numpy array to pandas dataframe](https://stackoverflow.com/questions/50624046/convert-numpy-array-to-pandas-dataframe) 4. [easy multidimensional numpy ndarray to pandas dataframe method?](https://stackoverflow.com/questions/36853594/easy-multidimensional-numpy-ndarray-to-pandas-dataframe-method) 5. [numpy rollaxis - how exactly does it work?](https://stackoverflow.com/questions/22583792/numpy-rollaxis-how-exactly-does-it-work) Please help me out. Hope I am adhering to the question-asking discipline.
2020/03/31
[ "https://Stackoverflow.com/questions/60959871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7890913/" ]
Here's a solution with sample data: ``` a,b,c = X.shape # in your case # a,b,c = 1797, 500 pd.DataFrame(X.transpose(1,2,0).reshape(2,-1).T, index=np.repeat(np.arange(c),a), columns=['X_coord','Y_coord'] ) ``` Output: ``` X_coord Y_coord 0 0 3 0 6 9 0 12 15 0 18 21 1 1 4 1 7 10 1 13 16 1 19 22 2 2 5 2 8 11 2 14 17 2 20 23 ```
Try this way: ``` index = np.concatenate([np.repeat([i], 1797) for i in range(500)]) df = pd.DataFrame(index=index) df['X-coordinate'] = X[:, 0, :].T.reshape((-1)) df['Y-coordinate'] = X[:, 1, :].T.reshape((-1)) ```
35,475,519
I am facing problem in returned image url, which is not proper. My return image url is `"http://127.0.0.1:8000/showimage/6/E%3A/workspace/tutorial_2/media/Capture1.PNG"` But i need ``` "http://127.0.0.1:8000/media/Capture1.PNG" ``` [![enter image description here](https://i.stack.imgur.com/wZSwF.png)](https://i.stack.imgur.com/wZSwF.png) When i click on `image_url` then image open in new browser tab But currently its shown error: [![enter image description here](https://i.stack.imgur.com/kMDtX.png)](https://i.stack.imgur.com/kMDtX.png) **view.py** ``` from showimage.models import ShowImage from showimage.serializers import ShowImageSerializer from rest_framework import generics # Create your views here. class ShowImageList(generics.ListCreateAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer class ShowImageDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer ``` **model.py** ``` from __future__ import unicode_literals from django.db import models from django.conf import settings # Create your models here. class ShowImage(models.Model): image_name = models.CharField(max_length=255) image_url = models.ImageField(upload_to=settings.MEDIA) ``` **serializer.py** ``` from rest_framework import serializers from showimage.models import ShowImage class ShowImageSerializer (serializers.ModelSerializer): class Meta: model = ShowImage fields = ('id', 'image_name', 'image_url') ``` **settings.py** ``` MEDIA=os.path.join(BASE_DIR, "media") ``` **urls.py** ``` from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^showimage/', include('showimage.urls')), ] ``` I am new in python and also in django-rest-framework. Please also tell me how we extend models or serialize class
2016/02/18
[ "https://Stackoverflow.com/questions/35475519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3526079/" ]
You might want to try this in your settings: ``` MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(BASE_DIR, "media") urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^showimage/', include('showimage.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` And in your models: ``` class ShowImage(models.Model): image_name = models.CharField(max_length=255) image_url = models.ImageField(upload_to="") # or upload_to="images", which would result in your images being at "http://127.0.0.1:8000/media/images/Capture1.PNG" ```
Your code seems correct except one thing you have passed settings.MEDIA in uploads image. you don't need to pass settings.MEDIA in uploads. try this ``` image_url = models.ImageField(upload_to='Dir_name') ``` Dir\_name will create when you'll run script.
35,475,519
I am facing problem in returned image url, which is not proper. My return image url is `"http://127.0.0.1:8000/showimage/6/E%3A/workspace/tutorial_2/media/Capture1.PNG"` But i need ``` "http://127.0.0.1:8000/media/Capture1.PNG" ``` [![enter image description here](https://i.stack.imgur.com/wZSwF.png)](https://i.stack.imgur.com/wZSwF.png) When i click on `image_url` then image open in new browser tab But currently its shown error: [![enter image description here](https://i.stack.imgur.com/kMDtX.png)](https://i.stack.imgur.com/kMDtX.png) **view.py** ``` from showimage.models import ShowImage from showimage.serializers import ShowImageSerializer from rest_framework import generics # Create your views here. class ShowImageList(generics.ListCreateAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer class ShowImageDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer ``` **model.py** ``` from __future__ import unicode_literals from django.db import models from django.conf import settings # Create your models here. class ShowImage(models.Model): image_name = models.CharField(max_length=255) image_url = models.ImageField(upload_to=settings.MEDIA) ``` **serializer.py** ``` from rest_framework import serializers from showimage.models import ShowImage class ShowImageSerializer (serializers.ModelSerializer): class Meta: model = ShowImage fields = ('id', 'image_name', 'image_url') ``` **settings.py** ``` MEDIA=os.path.join(BASE_DIR, "media") ``` **urls.py** ``` from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^showimage/', include('showimage.urls')), ] ``` I am new in python and also in django-rest-framework. Please also tell me how we extend models or serialize class
2016/02/18
[ "https://Stackoverflow.com/questions/35475519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3526079/" ]
Finally, i solve this road block with the help of @Remi Thanks @Remi But some other change i do so that i elaborate solution and fix this issue. **settings.py** ``` STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(BASE_DIR, "media") ``` **urls.py** ``` from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^showimage/', include('showimage.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ```
You might want to try this in your settings: ``` MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(BASE_DIR, "media") urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^showimage/', include('showimage.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` And in your models: ``` class ShowImage(models.Model): image_name = models.CharField(max_length=255) image_url = models.ImageField(upload_to="") # or upload_to="images", which would result in your images being at "http://127.0.0.1:8000/media/images/Capture1.PNG" ```
35,475,519
I am facing problem in returned image url, which is not proper. My return image url is `"http://127.0.0.1:8000/showimage/6/E%3A/workspace/tutorial_2/media/Capture1.PNG"` But i need ``` "http://127.0.0.1:8000/media/Capture1.PNG" ``` [![enter image description here](https://i.stack.imgur.com/wZSwF.png)](https://i.stack.imgur.com/wZSwF.png) When i click on `image_url` then image open in new browser tab But currently its shown error: [![enter image description here](https://i.stack.imgur.com/kMDtX.png)](https://i.stack.imgur.com/kMDtX.png) **view.py** ``` from showimage.models import ShowImage from showimage.serializers import ShowImageSerializer from rest_framework import generics # Create your views here. class ShowImageList(generics.ListCreateAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer class ShowImageDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ShowImage.objects.all() serializer_class = ShowImageSerializer ``` **model.py** ``` from __future__ import unicode_literals from django.db import models from django.conf import settings # Create your models here. class ShowImage(models.Model): image_name = models.CharField(max_length=255) image_url = models.ImageField(upload_to=settings.MEDIA) ``` **serializer.py** ``` from rest_framework import serializers from showimage.models import ShowImage class ShowImageSerializer (serializers.ModelSerializer): class Meta: model = ShowImage fields = ('id', 'image_name', 'image_url') ``` **settings.py** ``` MEDIA=os.path.join(BASE_DIR, "media") ``` **urls.py** ``` from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^showimage/', include('showimage.urls')), ] ``` I am new in python and also in django-rest-framework. Please also tell me how we extend models or serialize class
2016/02/18
[ "https://Stackoverflow.com/questions/35475519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3526079/" ]
Finally, i solve this road block with the help of @Remi Thanks @Remi But some other change i do so that i elaborate solution and fix this issue. **settings.py** ``` STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(BASE_DIR, "media") ``` **urls.py** ``` from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^showimage/', include('showimage.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ```
Your code seems correct except one thing you have passed settings.MEDIA in uploads image. you don't need to pass settings.MEDIA in uploads. try this ``` image_url = models.ImageField(upload_to='Dir_name') ``` Dir\_name will create when you'll run script.
45,317,050
How do I find if a string has atleast 3 alpha numeric characters in python. I'm using regex as `"^.*[a-zA-Z0-9]{3, }.*$"`, but it throws error message everytime. My example string: a&b#cdg1. P lease let me know.
2017/07/26
[ "https://Stackoverflow.com/questions/45317050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8341662/" ]
like this ``` #include <stdio.h> #include <stdarg.h> typedef enum rule { first, total } Rule; int fund(Rule rule, int v1, ...){ switch(rule){ case total: { int total = v1, value; if(v1 == -1) return 0; va_list ap; va_start(ap, v1); value = va_arg(ap, int); while(value != -1){ total += value; value = va_arg(ap, int); } va_end(ap); return total; } break; case first: return v1; } return -1; } int main(void){ printf("first:%d\n", fund(first, 1, 2, 3, 4, -1));//first:1 printf("total:%d\n", fund(total, 7, 5, 3, 1, -1));//total:16 } ```
You mentioned that the end of your arguments is marked by a `-1`. This means you can keep getting more arguments until you get a `-1`. Following is the way you can do it using `va_list` - ``` if(rule == TYPE) { int total = 0; va_list args; va_start(args, rule); int j; while(1){ j = va_arg(args, int); if(j!=-1) total += j; else break; } va_end(args); return total; } ``` You mentioned in the comments that your prototype is ``` int choose(Rule rule, int v1, ...); ``` In that case you need the modifications - At the very top ``` if(v1 == -1) return 0; ``` And ``` int total = v1; va_list args; va_start(args, v1); ``` Demo [Here](https://ideone.com/rWdgtb)
51,411,655
So I'm trying to Dockerize my project which looks like this: ``` project/ main.go package1/ package2/ package3/ ``` And it also requires some outside packages such as github.com/gorilla/mux Note my project is internal on a github.company.com domain so I'm not sure if that matters. So here's my Dockerfile and yes, my GOPATH and GOROOT is set and PLEASE don't just tell me to read <https://golang.org/doc/code.html>. I have and am still am having this issue. ``` ### STAGE 1: Build ### FROM golang:1.10 as builder WORKDIR /go/src/github.company.com/project-repo/project COPY . . RUN go get RUN go install <- ERROR HERE RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o executable -a -installsuffix cgo . ### STAGE 2: Setup ### FROM python:3.6-alpine COPY --from=builder /go/src/github.company.com/project-repo/project/executable /api/executable CMD ["/api/executable"] ``` Then I run: ``` docker build -t myapp . ``` And get this error: ``` main.go: cannot find package github.company.com/project-repo/project/package1 in any of: /usr/local/go/src/github.company.com/project-repo/project/package1 (from $GOROOT) /go/src/github.company.com/project-repo/project/package1 (from $GOPATH) ``` And keep in mind those paths are correct. Why can't go install packages that are within itself?? Main.go imports package1, but for sure reason "go install" doesn't install packages inside itself..
2018/07/18
[ "https://Stackoverflow.com/questions/51411655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4062625/" ]
Wow, golang really is picky about paths! It was just that I had assigned my working directory to the wrong place. There was another file in the tree: ``` WORKDIR /go/src/github.company.com/COMPANY/project-repo/project ```
did you make(`mkdir`) the `WORKDIR` before setting its value?
29,988,923
What is the best way to downgrade icu4c from 55.1 to 54.1 on Mac OS X Mavericks. I tried `brew switch icu4c 54.1` and failed. **Reason to switch back to 54.1** I am trying to setup and use Mapnik. I was able to install Mapnik from homebrew - `brew install mapnik` But, I get the following error when I try to `import mapnik` in python `Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/mapnik/__init__.py", line 69, in <module> from _mapnik import * ImportError: dlopen(/usr/local/lib/python2.7/site-packages/mapnik/_mapnik.so, 2): Library not loaded: /usr/local/opt/icu4c/lib/libicuuc.54.dylib Referenced from: /usr/local/Cellar/mapnik/2.2.0_5/lib/libmapnik.dylib Reason: image not found` Python version on my Mac - Python 2.7.5 (default, Mar 9 2014, 22:15:05) Is switching icu4c back to 54.1 way to go? Or, Am I missing something? Thanks for the help in advance.
2015/05/01
[ "https://Stackoverflow.com/questions/29988923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3983957/" ]
This was Homebrew's fault and should be fixed after `brew update && brew upgrade mapnik`; sorry!
I had the same problem but using Yosemite but I guess it should be fairly the same. I am not sure this is the best way to do it but it worked for me. I tried `brew switch icu4c 54.1` but failed since I did not have that package in the Cellar. My solution was getting ici4c 54.1 in the Cellar. First check if you have the .tar file cached to do this look in `/Library/Caches/Homebrew` for `icu4c-54.1.mavericks.bottle.1.tar.gz` If it is there you can just extract it and put the 54.1 folder in `/usr/local/Cellar/icu4c/` folder then run the `brew switch icu4c 54.1` command. If you don't have the library cached you can download it from here <https://downloads.sf.net/project/machomebrew/Bottles/icu4c-54.1.mavericks.bottle.1.tar.gz> and the same goes for putting the 54.1 folder in the correct place in the cellar and running brew switch.
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
An update to this old question: since Python version 2.7 there is the [load\_tests protocol](https://docs.python.org/2/library/unittest.html#load-tests-protocol) and there is no longer a need to write custom code. It allows you to add a function `load_tests()`, which a test loader will execute to update its collection of unit tests for the current module. Put a function like this in your code module to package the module's own doctests into a test suite for `unittest`: ``` def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite()) return tests ``` Or, put a function like this into your unit test module to add the doctests from another module (for example, `package.code_module`) into the tests suite which is already there: ``` def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(package.code_module)) return tests ``` When `unittest.TestLoader` methods `loadTestsFromModule()`, `loadTestsFromName()` or `discover()` are used unittest uses a test suite including both unit tests and doctests.
First I tried accepted answer from Andrey, but at least when running in Python 3.10 and `python -m unittest discover` it has led to running the test from unittest twice. Then I tried to simplify it and use `load_tests` and to my surprise it worked very well: So just write both `load_tests` and normal `unittest` tests in a single file and it works! ```py import doctest import unittest import my_module_with_doctests class ts(unittest.TestCase): def test_null(self): self.assertTrue(False) # No need in any other extra code here # Load doctests as unittest, see https://docs.python.org/3/library/doctest.html#unittest-api def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(my_module_with_doctests)) return tests ```
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
First I tried accepted answer from Andrey, but at least when running in Python 3.10 and `python -m unittest discover` it has led to running the test from unittest twice. Then I tried to simplify it and use `load_tests` and to my surprise it worked very well: So just write both `load_tests` and normal `unittest` tests in a single file and it works! ```py import doctest import unittest import my_module_with_doctests class ts(unittest.TestCase): def test_null(self): self.assertTrue(False) # No need in any other extra code here # Load doctests as unittest, see https://docs.python.org/3/library/doctest.html#unittest-api def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(my_module_with_doctests)) return tests ```
The zope.testing module provide such a functionality. See <http://www.veit-schiele.de/dienstleistungen/schulungen/testen/doctests> for examples.
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
An update to this old question: since Python version 2.7 there is the [load\_tests protocol](https://docs.python.org/2/library/unittest.html#load-tests-protocol) and there is no longer a need to write custom code. It allows you to add a function `load_tests()`, which a test loader will execute to update its collection of unit tests for the current module. Put a function like this in your code module to package the module's own doctests into a test suite for `unittest`: ``` def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite()) return tests ``` Or, put a function like this into your unit test module to add the doctests from another module (for example, `package.code_module`) into the tests suite which is already there: ``` def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(package.code_module)) return tests ``` When `unittest.TestLoader` methods `loadTestsFromModule()`, `loadTestsFromName()` or `discover()` are used unittest uses a test suite including both unit tests and doctests.
I would recommend to use `pytest --doctest-modules` without any load\_test protocol. You can simply add both the files or directories with your normal pytests and your modules with doctests to that pytest call. > > pytest --doctest-modules path/to/pytest/unittests path/to/modules > > > It discovers and runs all doctests as well. See <https://docs.pytest.org/en/latest/doctest.html>
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
I would recommend to use `pytest --doctest-modules` without any load\_test protocol. You can simply add both the files or directories with your normal pytests and your modules with doctests to that pytest call. > > pytest --doctest-modules path/to/pytest/unittests path/to/modules > > > It discovers and runs all doctests as well. See <https://docs.pytest.org/en/latest/doctest.html>
This code will automatically run the doctests for all the modules in a package without needing to manually add a test suite for each module. This can be used with Tox. ``` import doctest import glob import os import sys if sys.version_info < (2,7,): import unittest2 as unittest else: import unittest import mypackage as source_package def load_module_by_path(path): """Load a python module from its path. Parameters ---------- path : str Path to the module source file. Returns ------- mod : module Loaded module. """ import imp module_file_basename = os.path.basename(path) module_name, ext = os.path.splitext(module_file_basename) mod = imp.load_source(module_name, path) return mod def file_contains_doctests(path): """Scan a python source file to determine if it contains any doctest examples. Parameters ---------- path : str Path to the module source file. Returns ------- flag : bool True if the module source code contains doctest examples. """ with open(path) as f: for line in f: if ">>>" in line: return True return False def load_tests(loader, tests, pattern): """Run doctests for all modules""" source_dir = os.path.dirname(source_package.__path__[0]) python_source_glob = os.path.join(source_dir, source_package.__name__, "*.py") python_source_files = glob.glob(python_source_glob) for python_source_file in python_source_files: if not file_contains_doctests(python_source_file): continue module = load_module_by_path(python_source_file) tests.addTests(doctest.DocTestSuite(module)) return tests ```
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
I would recommend to use `pytest --doctest-modules` without any load\_test protocol. You can simply add both the files or directories with your normal pytests and your modules with doctests to that pytest call. > > pytest --doctest-modules path/to/pytest/unittests path/to/modules > > > It discovers and runs all doctests as well. See <https://docs.pytest.org/en/latest/doctest.html>
The zope.testing module provide such a functionality. See <http://www.veit-schiele.de/dienstleistungen/schulungen/testen/doctests> for examples.
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
I would recommend to use `pytest --doctest-modules` without any load\_test protocol. You can simply add both the files or directories with your normal pytests and your modules with doctests to that pytest call. > > pytest --doctest-modules path/to/pytest/unittests path/to/modules > > > It discovers and runs all doctests as well. See <https://docs.pytest.org/en/latest/doctest.html>
First I tried accepted answer from Andrey, but at least when running in Python 3.10 and `python -m unittest discover` it has led to running the test from unittest twice. Then I tried to simplify it and use `load_tests` and to my surprise it worked very well: So just write both `load_tests` and normal `unittest` tests in a single file and it works! ```py import doctest import unittest import my_module_with_doctests class ts(unittest.TestCase): def test_null(self): self.assertTrue(False) # No need in any other extra code here # Load doctests as unittest, see https://docs.python.org/3/library/doctest.html#unittest-api def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(my_module_with_doctests)) return tests ```
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
In this code i combined unittests and doctests from imported module ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) class ts1(unittest.TestCase): def test_null(self): self.assertTrue(True) testSuite = unittest.TestSuite() testSuite.addTests(unittest.makeSuite(ts)) testSuite.addTest(unittest.makeSuite(ts1)) import doctest import my_module_with_doctests testSuite.addTest(doctest.DocTestSuite(my_module_with_doctests)) unittest.TextTestRunner(verbosity = 2).run(testSuite) ```
This code will automatically run the doctests for all the modules in a package without needing to manually add a test suite for each module. This can be used with Tox. ``` import doctest import glob import os import sys if sys.version_info < (2,7,): import unittest2 as unittest else: import unittest import mypackage as source_package def load_module_by_path(path): """Load a python module from its path. Parameters ---------- path : str Path to the module source file. Returns ------- mod : module Loaded module. """ import imp module_file_basename = os.path.basename(path) module_name, ext = os.path.splitext(module_file_basename) mod = imp.load_source(module_name, path) return mod def file_contains_doctests(path): """Scan a python source file to determine if it contains any doctest examples. Parameters ---------- path : str Path to the module source file. Returns ------- flag : bool True if the module source code contains doctest examples. """ with open(path) as f: for line in f: if ">>>" in line: return True return False def load_tests(loader, tests, pattern): """Run doctests for all modules""" source_dir = os.path.dirname(source_package.__path__[0]) python_source_glob = os.path.join(source_dir, source_package.__name__, "*.py") python_source_files = glob.glob(python_source_glob) for python_source_file in python_source_files: if not file_contains_doctests(python_source_file): continue module = load_module_by_path(python_source_file) tests.addTests(doctest.DocTestSuite(module)) return tests ```
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
In this code i combined unittests and doctests from imported module ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) class ts1(unittest.TestCase): def test_null(self): self.assertTrue(True) testSuite = unittest.TestSuite() testSuite.addTests(unittest.makeSuite(ts)) testSuite.addTest(unittest.makeSuite(ts1)) import doctest import my_module_with_doctests testSuite.addTest(doctest.DocTestSuite(my_module_with_doctests)) unittest.TextTestRunner(verbosity = 2).run(testSuite) ```
I would recommend to use `pytest --doctest-modules` without any load\_test protocol. You can simply add both the files or directories with your normal pytests and your modules with doctests to that pytest call. > > pytest --doctest-modules path/to/pytest/unittests path/to/modules > > > It discovers and runs all doctests as well. See <https://docs.pytest.org/en/latest/doctest.html>
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
This code will automatically run the doctests for all the modules in a package without needing to manually add a test suite for each module. This can be used with Tox. ``` import doctest import glob import os import sys if sys.version_info < (2,7,): import unittest2 as unittest else: import unittest import mypackage as source_package def load_module_by_path(path): """Load a python module from its path. Parameters ---------- path : str Path to the module source file. Returns ------- mod : module Loaded module. """ import imp module_file_basename = os.path.basename(path) module_name, ext = os.path.splitext(module_file_basename) mod = imp.load_source(module_name, path) return mod def file_contains_doctests(path): """Scan a python source file to determine if it contains any doctest examples. Parameters ---------- path : str Path to the module source file. Returns ------- flag : bool True if the module source code contains doctest examples. """ with open(path) as f: for line in f: if ">>>" in line: return True return False def load_tests(loader, tests, pattern): """Run doctests for all modules""" source_dir = os.path.dirname(source_package.__path__[0]) python_source_glob = os.path.join(source_dir, source_package.__name__, "*.py") python_source_files = glob.glob(python_source_glob) for python_source_file in python_source_files: if not file_contains_doctests(python_source_file): continue module = load_module_by_path(python_source_file) tests.addTests(doctest.DocTestSuite(module)) return tests ```
First I tried accepted answer from Andrey, but at least when running in Python 3.10 and `python -m unittest discover` it has led to running the test from unittest twice. Then I tried to simplify it and use `load_tests` and to my surprise it worked very well: So just write both `load_tests` and normal `unittest` tests in a single file and it works! ```py import doctest import unittest import my_module_with_doctests class ts(unittest.TestCase): def test_null(self): self.assertTrue(False) # No need in any other extra code here # Load doctests as unittest, see https://docs.python.org/3/library/doctest.html#unittest-api def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(my_module_with_doctests)) return tests ```
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTrue(True) if __name__ == '__main__': unittest.main() ``` I'd like to add to this suite all of the doctests in module `module1`. How can I do this? I've read the [python docs](http://docs.python.org/library/doctest.html#unittest-api), but I'm not any closer to success, here. Adding the lines ``` import doctest import module1 suite = doctest.DocTestSuite(module1) ``` doesn't work. `unittest.main()` searches through the current file scope and runs every test **case** it finds, right? But DocTestSuite produces a test **suite**. How do I get `unittest.main()` to run the additional cases in the suite? Or am I just confused and deluded?? Once again, I'd be grateful for any help anyone can offer.
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
This code will automatically run the doctests for all the modules in a package without needing to manually add a test suite for each module. This can be used with Tox. ``` import doctest import glob import os import sys if sys.version_info < (2,7,): import unittest2 as unittest else: import unittest import mypackage as source_package def load_module_by_path(path): """Load a python module from its path. Parameters ---------- path : str Path to the module source file. Returns ------- mod : module Loaded module. """ import imp module_file_basename = os.path.basename(path) module_name, ext = os.path.splitext(module_file_basename) mod = imp.load_source(module_name, path) return mod def file_contains_doctests(path): """Scan a python source file to determine if it contains any doctest examples. Parameters ---------- path : str Path to the module source file. Returns ------- flag : bool True if the module source code contains doctest examples. """ with open(path) as f: for line in f: if ">>>" in line: return True return False def load_tests(loader, tests, pattern): """Run doctests for all modules""" source_dir = os.path.dirname(source_package.__path__[0]) python_source_glob = os.path.join(source_dir, source_package.__name__, "*.py") python_source_files = glob.glob(python_source_glob) for python_source_file in python_source_files: if not file_contains_doctests(python_source_file): continue module = load_module_by_path(python_source_file) tests.addTests(doctest.DocTestSuite(module)) return tests ```
The zope.testing module provide such a functionality. See <http://www.veit-schiele.de/dienstleistungen/schulungen/testen/doctests> for examples.
68,640,124
I'm super new to praat parselmouth in python and I am a big fan, as it enables analyzes without Praat. So my struggle is, that I need formants in a specific sampling rate but I cant change it here. If I change the time\_step (and also time window), length of the formant list is not changing. I am mainly using this code: # <http://blog.syntheticspeech.de/2021/03/10/how-to-extract-formant-tracks-with-praat-and-python/> and it looks like that ``` f0min= 75 f0max=300 pointProcess = praat.call(sound, "To PointProcess (periodic, cc)", f0min, f0max) time_step = 0.01 # or 0.002 see picture max_formant_num = 5 max_formant_freq = 5000 # men 5000, women 5500 window_length = 0.01 # or 0.002 see picture preemphasis = 50 formants = praat.call(sound, "To Formant (burg)", time_step, max_formant_num, max_formant_freq, window_length, preemphasis) numPoints = praat.call(pointProcess, "Get number of points") print(numPoints) f1_list = [] f2_list = [] f3_list = [] for point in range(0, numPoints): point += 1 t = praat.call(pointProcess, "Get time from index", point) f1 = praat.call(formants, "Get value at time", 1, t, 'Hertz', 'Linear') f2 = praat.call(formants, "Get value at time", 2, t, 'Hertz', 'Linear') f3 = praat.call(formants, "Get value at time", 3, t, 'Hertz', 'Linear') f1_list.append(f1) f2_list.append(f2) f3_list.append(f3) ``` I can not get the sample rate I'd like (eg 30 Hz). Can someone help? [here I am plotting f1 for both time\_steps, but it is still the same length (323) and timepoints](https://i.stack.imgur.com/QOJia.png)
2021/08/03
[ "https://Stackoverflow.com/questions/68640124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11662481/" ]
In `base R`you can use `sub` and backreference `\\1`: ``` sub("(\\d+:\\d+:\\d+\\.\\d+).*", "\\1", x) [1] "13:30:00.827" "13:30:01.834" ``` or: ``` sub("(.*?)(: <-.*)", "\\1", x) ``` In both cases you divide the string into two capturing groups, the first of which you remember in `sub`s replacement argument. In `stringr` you can use `str_extract` and positive lookahead `(?=...)`: ``` library(stringr) str_extract(x, ".*(?=: <-)") ``` Here you extract that substring that occurs right before the substring `: <-` Data: ``` x <- c("13:30:00.827: <- $HCHDG", "13:30:01.834: <- $HCHDG") ```
This is what you should use: ``` sub(': <- \\$HCHDG', '', dataframe$ColName) ```
68,640,124
I'm super new to praat parselmouth in python and I am a big fan, as it enables analyzes without Praat. So my struggle is, that I need formants in a specific sampling rate but I cant change it here. If I change the time\_step (and also time window), length of the formant list is not changing. I am mainly using this code: # <http://blog.syntheticspeech.de/2021/03/10/how-to-extract-formant-tracks-with-praat-and-python/> and it looks like that ``` f0min= 75 f0max=300 pointProcess = praat.call(sound, "To PointProcess (periodic, cc)", f0min, f0max) time_step = 0.01 # or 0.002 see picture max_formant_num = 5 max_formant_freq = 5000 # men 5000, women 5500 window_length = 0.01 # or 0.002 see picture preemphasis = 50 formants = praat.call(sound, "To Formant (burg)", time_step, max_formant_num, max_formant_freq, window_length, preemphasis) numPoints = praat.call(pointProcess, "Get number of points") print(numPoints) f1_list = [] f2_list = [] f3_list = [] for point in range(0, numPoints): point += 1 t = praat.call(pointProcess, "Get time from index", point) f1 = praat.call(formants, "Get value at time", 1, t, 'Hertz', 'Linear') f2 = praat.call(formants, "Get value at time", 2, t, 'Hertz', 'Linear') f3 = praat.call(formants, "Get value at time", 3, t, 'Hertz', 'Linear') f1_list.append(f1) f2_list.append(f2) f3_list.append(f3) ``` I can not get the sample rate I'd like (eg 30 Hz). Can someone help? [here I am plotting f1 for both time\_steps, but it is still the same length (323) and timepoints](https://i.stack.imgur.com/QOJia.png)
2021/08/03
[ "https://Stackoverflow.com/questions/68640124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11662481/" ]
Using `str_remove` ``` library(stringr) str_remove(x, ":\\s+.*") [1] "13:30:00.827" "13:30:01.834" ``` ### data ``` x <- c("13:30:00.827: <- $HCHDG", "13:30:01.834: <- $HCHDG") ```
This is what you should use: ``` sub(': <- \\$HCHDG', '', dataframe$ColName) ```
68,640,124
I'm super new to praat parselmouth in python and I am a big fan, as it enables analyzes without Praat. So my struggle is, that I need formants in a specific sampling rate but I cant change it here. If I change the time\_step (and also time window), length of the formant list is not changing. I am mainly using this code: # <http://blog.syntheticspeech.de/2021/03/10/how-to-extract-formant-tracks-with-praat-and-python/> and it looks like that ``` f0min= 75 f0max=300 pointProcess = praat.call(sound, "To PointProcess (periodic, cc)", f0min, f0max) time_step = 0.01 # or 0.002 see picture max_formant_num = 5 max_formant_freq = 5000 # men 5000, women 5500 window_length = 0.01 # or 0.002 see picture preemphasis = 50 formants = praat.call(sound, "To Formant (burg)", time_step, max_formant_num, max_formant_freq, window_length, preemphasis) numPoints = praat.call(pointProcess, "Get number of points") print(numPoints) f1_list = [] f2_list = [] f3_list = [] for point in range(0, numPoints): point += 1 t = praat.call(pointProcess, "Get time from index", point) f1 = praat.call(formants, "Get value at time", 1, t, 'Hertz', 'Linear') f2 = praat.call(formants, "Get value at time", 2, t, 'Hertz', 'Linear') f3 = praat.call(formants, "Get value at time", 3, t, 'Hertz', 'Linear') f1_list.append(f1) f2_list.append(f2) f3_list.append(f3) ``` I can not get the sample rate I'd like (eg 30 Hz). Can someone help? [here I am plotting f1 for both time\_steps, but it is still the same length (323) and timepoints](https://i.stack.imgur.com/QOJia.png)
2021/08/03
[ "https://Stackoverflow.com/questions/68640124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11662481/" ]
In `base R`you can use `sub` and backreference `\\1`: ``` sub("(\\d+:\\d+:\\d+\\.\\d+).*", "\\1", x) [1] "13:30:00.827" "13:30:01.834" ``` or: ``` sub("(.*?)(: <-.*)", "\\1", x) ``` In both cases you divide the string into two capturing groups, the first of which you remember in `sub`s replacement argument. In `stringr` you can use `str_extract` and positive lookahead `(?=...)`: ``` library(stringr) str_extract(x, ".*(?=: <-)") ``` Here you extract that substring that occurs right before the substring `: <-` Data: ``` x <- c("13:30:00.827: <- $HCHDG", "13:30:01.834: <- $HCHDG") ```
use \\ for special characters ``` gsub("\\$HCHDG|\\:|<|\\-|\\s+", "", dataframe$ColName) ```
68,640,124
I'm super new to praat parselmouth in python and I am a big fan, as it enables analyzes without Praat. So my struggle is, that I need formants in a specific sampling rate but I cant change it here. If I change the time\_step (and also time window), length of the formant list is not changing. I am mainly using this code: # <http://blog.syntheticspeech.de/2021/03/10/how-to-extract-formant-tracks-with-praat-and-python/> and it looks like that ``` f0min= 75 f0max=300 pointProcess = praat.call(sound, "To PointProcess (periodic, cc)", f0min, f0max) time_step = 0.01 # or 0.002 see picture max_formant_num = 5 max_formant_freq = 5000 # men 5000, women 5500 window_length = 0.01 # or 0.002 see picture preemphasis = 50 formants = praat.call(sound, "To Formant (burg)", time_step, max_formant_num, max_formant_freq, window_length, preemphasis) numPoints = praat.call(pointProcess, "Get number of points") print(numPoints) f1_list = [] f2_list = [] f3_list = [] for point in range(0, numPoints): point += 1 t = praat.call(pointProcess, "Get time from index", point) f1 = praat.call(formants, "Get value at time", 1, t, 'Hertz', 'Linear') f2 = praat.call(formants, "Get value at time", 2, t, 'Hertz', 'Linear') f3 = praat.call(formants, "Get value at time", 3, t, 'Hertz', 'Linear') f1_list.append(f1) f2_list.append(f2) f3_list.append(f3) ``` I can not get the sample rate I'd like (eg 30 Hz). Can someone help? [here I am plotting f1 for both time\_steps, but it is still the same length (323) and timepoints](https://i.stack.imgur.com/QOJia.png)
2021/08/03
[ "https://Stackoverflow.com/questions/68640124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11662481/" ]
Using `str_remove` ``` library(stringr) str_remove(x, ":\\s+.*") [1] "13:30:00.827" "13:30:01.834" ``` ### data ``` x <- c("13:30:00.827: <- $HCHDG", "13:30:01.834: <- $HCHDG") ```
use \\ for special characters ``` gsub("\\$HCHDG|\\:|<|\\-|\\s+", "", dataframe$ColName) ```
1,780,618
Ok so I have the same python code locally and in the gae cloud. when I store an entity locally, the ListProperty field of set element type datetime.datetime looks like so in the Datastore Viewer: ``` 2009-01-01 00:00:00,2010-03-10 00:00:00 ``` when I store same on the cloud, the viewer displays: ``` [datetime.datetime(2009, 1, 1, 0, 0), datetime.datetime(2010, 3, 9, 0, 0)] ``` why the different representation? This wouldn't bother me, only when I query on this field on the cloud the query fails to find the matched entity (it should and it does locally) - leading me to believe it's this differing representation that is causing the trouble. I should repeat - the code is identical. Anyone think of a reason why this is happening and a solution to it? UPDATE: my query is as follows (using filters): ``` from x import y from datetime import datetime from google.appengine.ext import db q = y.EntityType.all().filter('displayDateRange <=',datetime.now()).filter('displayDateRange >=',datetime.now()) usersResult = q.fetch(100) print `len(usersResult)` ``` result should be 1, instead it's 0. Actually it's just the ListProperty with specified value datetime.datetime that is the issue - queries on the StringListProperty is working as expected on the cloud. I tried the raw filter via interactive console on both local and cloud and cloud gives me no results. So it is a datastore thing, I'm assuming it *must* have something to do with the storage format - I only have one entity value in both datastores with the ListProperty looking like: ``` 2009-01-01 00:00:00,2010-03-09 00:00:00 [datetime.datetime(2009, 1, 1, 0, 0), datetime.datetime(2010, 3, 9, 0, 0)] ``` on local and cloud respectively. Any ideas? **Further Update** Replaced the datetime.now() with hardcoded datetime obj - example filter now looks like: ``` y.EntityType.all().filter('displayDateRange <=',datetime(2009,11,24)).filter('displayDateRange >=',datetime(2009,11,24)) ``` Note with the above datetime ListProperty range from 1.1.2009 to 3.9.2010 this should return the above entity - I tried this identical filter on localhost dev server and it did so. The cloud, with it's different representation of the datetime.datetime ListProperty, does not. Note this is taken from the [current best practice for filtering on date range](http://appengine-cookbook.appspot.com/attachment/?id=ahJhcHBlbmdpbmUtY29va2Jvb2tyEQsSCkF0dGFjaG1lbnQY0ygM) Any ideas what could be wrong?
2009/11/23
[ "https://Stackoverflow.com/questions/1780618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/178511/" ]
Ok long story short: it's now classed as a bug in the app engine dev server version and is no longer supported in the production cloud datastore. Filled out a further explanation in a [blog post](http://aleatory.clientsideweb.net/2009/11/28/google-app-engine-datastore-gotchas/), check out point 3.
The problem your see is clearly a conversion to string (calling `__str__` or `__unicode__`) in the local case, while the representation (repr) of your data is displayed on the cloud. But this difference in printing out the results should not be the cause of your failed query on the cloud. What is your exact query? **UPDATE** after knowing the query: I don't really understand why do you use these filter conditions: ``` .filter('displayDateRange <=',datetime.now()).filter('displayDateRange >=',datetime.now()) ``` There are two problems with this: * You call `datetime.now()` twice, which can give you different results, which would result in an empty result set. It is especially true on a loaded server with multiple threads/processes of execution active at the same time. * What you might intended to do with the above pair of filters is checking for equality. But it won't work if the precision of the datetime instance returned by `datetime.now()` and the precision of the datetime stored in the database differs. It is not a good idea to check for equality in the case of floating point numbers and sub-second precision time values in general. What do you want to achieve with such a pair of filter conditions?
55,653,169
I am trying to write some code in python to retrieve some data from Infoblox. To do this i need to Import the Infoblox Module. Can anyone tell me how to do this ?
2019/04/12
[ "https://Stackoverflow.com/questions/55653169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11351903/" ]
Try this ``` path_to_directory="./" files = [arff for arff in os.listdir(path_to_directory) if arff.endswith(".arff")] def toCsv(content): data = False header = "" newContent = [] for line in content: if not data: if "@attribute" in line: attri = line.split() columnName = attri[attri.index("@attribute")+1] header = header + columnName + "," elif "@data" in line: data = True header = header[:-1] header += '\n' newContent.append(header) else: newContent.append(line) return newContent # Main loop for reading and writing files for zzzz,file in enumerate(files): with open(path_to_directory+file , "r") as inFile: content = inFile.readlines() name,ext = os.path.splitext(inFile.name) new = toCsv(content) with open(name+".csv", "w") as outFile: outFile.writelines(new) ```
Take a look at the error trace > > UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 4: ordinal not in range(128) > > > Your error suggests you have some encoding problem with the file. Consider first opening the file with the correct encoding and then loading it to the arff loader ``` import codecs import arff file_ = codecs.load('LMD.rh.arff', 'rb', 'utf-8') # or whatever encoding you have arff.load(file_) # now this should be fine ``` For reference see [here](https://pythonhosted.org/liac-arff/#unicode)
12,391,377
Python [supports chained comparisons](http://docs.python.org/reference/expressions.html#not-in): `1 < 2 < 3` translates to `(1 < 2) and (2 < 3)`. I am trying to make an SQL query using SQLAlchemy which looks like this: ``` results = session.query(Couple).filter(10 < Couple.NumOfResults < 20).all() ``` The results I got were not as expected. I've turned the engine's `echo=True` keyword, and indeed - the generated SQL query only included one of the two comparisons. I can't find any documentation that explicitly says this is forbidden. I assumed that if this type of expression is supported in Python, it should be supported in SQLAlchemy as well. Why doesn't this work? I have one possible solution in mind (shared in answers), but will be glad to hear other opinions.
2012/09/12
[ "https://Stackoverflow.com/questions/12391377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388334/" ]
The reason is that Python actually evaluates something akin to this: ``` _tmp = Couple.NumOfResults (10 < _tmp and _tmp < 20) ``` The `and` operator is unsupported in SQLAlchemy (one should use `and_` instead). And thus - chained comparisons are not allowed in SQLAlchemy. In the original example, one should write this code instead: ``` results = session.query(Couple).filter(and_(10 < Couple.NumOfResults, Couple.NumOfResults < 20)).all() ```
SQLAlchemy won't support Python's chained comparisons. Here is the official reason why from author Michael Bayer: > > unfortunately this is likely impossible from a python perspective. The mechanism of "x < y < z" relies upon the return value of the two individual expressions. a SQLA expression such as "column < 5" returns a BinaryExpression object, which evaluates as True - therefore the second expression is never called and we are never given a chance to detect the chain of expressions. Furthermore, the chain of expressions would need to be detected and converted to BETWEEN, since SQL doesn't support the chained comparison operators. > Not including the detection of chains->BETWEEN part, to make this work would require manipulation of the BinaryExpression object's `__nonzero__()` value based on the direction of the comparison operator, so as to force both comparisons. Adding a basic `__nonzero__()` to BinaryExpression that returns False illustrates that it's tolerated pretty poorly by the current codebase, and at the very least many dozens of "if x:" kinds of checks would need to be converted to "if x is None:", but there might be further issues that are more difficult to resolve. For the outside world it might wreak havoc. > Given that the appropriate SQL operator here is BETWEEN which is easily accessible from the between operator, I don't think the level of bending over backwards and confusing people is worth it so this a "wontfix". > > > See details at: <https://bitbucket.org/zzzeek/sqlalchemy/issues/1394/sql-expressions-dont-support-x-col-y>
28,260,652
New to python, my assignment asks to ask user for input and then find and print the first letter of each word in the sentence so far all I have is ``` phrase = raw_input("Please enter a sentence of 3 or 4 words: ") ``` ^ That is all I have. So say the user enters the phrase "hey how are you" I am supposed to find and print the first letter of every word so it would print "hhay" I know how to index if it is a string that the programmer types but not when a user inputs the data.
2015/02/01
[ "https://Stackoverflow.com/questions/28260652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516441/" ]
This does everything that [Ming](https://stackoverflow.com/users/904117/ming) said in a single line. You can very well understand this code if you read his explanation. ``` phrase = raw_input("Please enter a sentence of 3 or 4 words: ") output = ''.join([x[0] for x in phrase.split()]) print output ``` Update related to comment (Considers only first 3 words): ``` output = ''.join([x[0] for x in phrase.split()])[:3] ``` Ignoring the last word (Total number of words doesn't matter) ``` output = ''.join([x[0] for x in phrase.split()])[:-1] ```
Here are a rough outline of the steps you can take. Since this is an assignment, I will leave actually assembling them into a working program up to you. 1. `raw_input` will produce a string. 2. If you have two strings, one in `foo` and one in `bar`, then you can call [`string.split`](https://docs.python.org/2/library/stdtypes.html#str.split) as `foo.split(bar)`, and the result of that will be a list of strings resulting from splitting the contents of `foo` by the separator `bar`. For example, `'a b c'.split(' ') == ['a', 'b', 'c']`. 3. You can slice a string with brackets to retrieve particular characters from it, counting from zero in the leftmost position. For example, `'abcd'[0] == 'a'`. 4. If you have a string `foo` and a list of strings `bar`, then you can call [`string.join`](https://docs.python.org/2/library/string.html#string.join) as `foo.join(bar)` to produce a single string of the elements of `foo` glued together with `bar`. For example, `'x'.join(['a', 'b', 'c']) == 'axbxc'`. 5. You can `print` the constructed output. This is of course only one of many approaches you could take.
28,260,652
New to python, my assignment asks to ask user for input and then find and print the first letter of each word in the sentence so far all I have is ``` phrase = raw_input("Please enter a sentence of 3 or 4 words: ") ``` ^ That is all I have. So say the user enters the phrase "hey how are you" I am supposed to find and print the first letter of every word so it would print "hhay" I know how to index if it is a string that the programmer types but not when a user inputs the data.
2015/02/01
[ "https://Stackoverflow.com/questions/28260652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516441/" ]
This does everything that [Ming](https://stackoverflow.com/users/904117/ming) said in a single line. You can very well understand this code if you read his explanation. ``` phrase = raw_input("Please enter a sentence of 3 or 4 words: ") output = ''.join([x[0] for x in phrase.split()]) print output ``` Update related to comment (Considers only first 3 words): ``` output = ''.join([x[0] for x in phrase.split()])[:3] ``` Ignoring the last word (Total number of words doesn't matter) ``` output = ''.join([x[0] for x in phrase.split()])[:-1] ```
As an answer to your question "For the next one I have to join the first letters of only the first 3 words and ignore the 4th word. How do I do that?" ``` output = ''.join([x[0] for x in phrase.split()[0:3]]) ``` If instead it is first character of all word but the last then use : ``` output = ''.join([x[0] for x in phrase.split()[0:len(phrase.split()) - 1]]) ```
44,180,066
I am asking if it's possible to create an attribute DictField with DictField in django restframework. If yes! Is it possible to populate it as a normal dictionary in python. I want to use it as a foreign key to store data.
2017/05/25
[ "https://Stackoverflow.com/questions/44180066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8002200/" ]
The best way that i know is to use [momentjs](https://momentjs.com/). I have used it with angular 1.x.x with no problems. It's pretty easy to use, check this out. You can add the following row: ``` nm.pick = moment(nm.pick).format('DD-MM-YYYY'); ``` This should solve your problem,
For `type="date"` binding ```js var app = angular.module("MyApp", []).controller("MyCtrl", function($scope, $filter) { $scope.nm = {}; $scope.nm.pick = new Date($filter('date')(new Date(), "yyyy-MM-dd")); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body ng-app="MyApp" ng-controller="MyCtrl"> <input type="date" required ng-model="nm.pick" id="dpicker "> </body> ``` Reading other answers, I'd advice the same to go with `moment.js` as it is an expert library when playing around with date/time and different timezone.
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database. Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages.
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
Ruby-on-rails, Python and PHP would all be excellent choices for developing a web service in. All the languages are capable (with of course Ruby being the language that Ruby on Rails is written in), have strong frameworks if that is your fancy (Django being a good python example, and something like Drupal or CakePHP being good PHP examples) and can play nicely with MySql. I'd say that it would depend mostly on your past experience and what you'd be the most comfortable with. Assuming that you're developing C# on .NET and have experience with Objective-C PHP may be a good choice because it is most certainly from the C family of languages. So the syntax might be more familiar and a bit easier to deal with. I'm a PHP developer so I'll give you that slant and let more knowledgeable developers with the others give theirs as well. PHP is tightly integrated with Apache, which can make some of the more mundane tasks that you'd have to handle with the others a bit more trivial (though when working with a framework those are usually removed). The [PHP documentation](http://www.php.net/manual/en/) is second to none and is a great resource for getting up and going easily. It has decent speed and there are good caching mechanisms out there to get more performance out of it. I know that getting up and running with PHP on Dreamhost is trivial. I haven't done it in the other instances although it wouldn't surprise me if those were just as easy as well. I'd suggest digging a bit more into the documentation and frameworks for each language to find out what suits you best.
I have developed in Python and PHP and my personal preference would be Python. Django is a great, easy to understand, light-weight framework for Python. [Django Site](http://www.djangoproject.com/) If you went the PHP route, I would recommend Kohana. [Kohana Site](http://www.kohanaphp.com/)
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database. Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages.
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
Ruby-on-rails, Python and PHP would all be excellent choices for developing a web service in. All the languages are capable (with of course Ruby being the language that Ruby on Rails is written in), have strong frameworks if that is your fancy (Django being a good python example, and something like Drupal or CakePHP being good PHP examples) and can play nicely with MySql. I'd say that it would depend mostly on your past experience and what you'd be the most comfortable with. Assuming that you're developing C# on .NET and have experience with Objective-C PHP may be a good choice because it is most certainly from the C family of languages. So the syntax might be more familiar and a bit easier to deal with. I'm a PHP developer so I'll give you that slant and let more knowledgeable developers with the others give theirs as well. PHP is tightly integrated with Apache, which can make some of the more mundane tasks that you'd have to handle with the others a bit more trivial (though when working with a framework those are usually removed). The [PHP documentation](http://www.php.net/manual/en/) is second to none and is a great resource for getting up and going easily. It has decent speed and there are good caching mechanisms out there to get more performance out of it. I know that getting up and running with PHP on Dreamhost is trivial. I haven't done it in the other instances although it wouldn't surprise me if those were just as easy as well. I'd suggest digging a bit more into the documentation and frameworks for each language to find out what suits you best.
This is an extremely subjective question, and even if you gave us the specifics of your web service, we can argue about the best choice all day. I'm a PHP developer, so I could whip off a basic web service with no problems. There's [lots](http://www.kohanaphp.com/) of [simple](http://codeigniter.com/) PHP [frameworks](http://cakephp.org) available that would handle that very nicely. That being said, Python and Django give you some great out-of-the-box functionality, and it's on my list of things to learn. You could achieve something pretty fast with that.
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database. Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages.
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
Ruby-on-rails, Python and PHP would all be excellent choices for developing a web service in. All the languages are capable (with of course Ruby being the language that Ruby on Rails is written in), have strong frameworks if that is your fancy (Django being a good python example, and something like Drupal or CakePHP being good PHP examples) and can play nicely with MySql. I'd say that it would depend mostly on your past experience and what you'd be the most comfortable with. Assuming that you're developing C# on .NET and have experience with Objective-C PHP may be a good choice because it is most certainly from the C family of languages. So the syntax might be more familiar and a bit easier to deal with. I'm a PHP developer so I'll give you that slant and let more knowledgeable developers with the others give theirs as well. PHP is tightly integrated with Apache, which can make some of the more mundane tasks that you'd have to handle with the others a bit more trivial (though when working with a framework those are usually removed). The [PHP documentation](http://www.php.net/manual/en/) is second to none and is a great resource for getting up and going easily. It has decent speed and there are good caching mechanisms out there to get more performance out of it. I know that getting up and running with PHP on Dreamhost is trivial. I haven't done it in the other instances although it wouldn't surprise me if those were just as easy as well. I'd suggest digging a bit more into the documentation and frameworks for each language to find out what suits you best.
**The short answer is, I'd go with PHP.** I have some experience in all two of your three choices: PHP, Ruby with Ruby on Rails. If I had no experience however and I was looking to set out and create a web service that largely just interacts with a database and I wanted it done this weekend, I'd choose PHP. If I had no experience with any of the above languages and I wanted to project done in a couple of weeks, I'd choose rails. I personally have much less experience with with Python and Django so I can't really comment. *Ruby with Ruby on Rails:* I've been working with Ruby and ruby on rails for several years now. I previously had experience in Java (which is roughly analogous to your experience in .Net). I found the transition to rails to be a little bit bumpy. I wanted to jump right in and start understanding how rails works and how to build a web application but with no understanding of ruby this was difficult. There are a lot of example out there that will help you build an application quickly but often times the quickness comes at the expense of understanding. To build solid rails web application you need a good understanding of ruby and of the rails frameworks. Rails is fantastic, but for building something you understand and getting it up and running quickly it may not be your best choice. Also, rails hosting has come a long way (you can tell because we're starting to see many hosts offer it) but there are still some bumps. *PHP*: PHP is fantastic for getting something up and running quickly. You can upload files and immediately see if your result if working. If you keep your database setup clean (and it sounds like you will, because you work with databases all day) the PHP shouldn't be too bad. I would look into an Object Relational Mapper to help keep your PHP even cleaner, I've heard good thinks about [Doctorine](http://www.doctrine-project.org/). *Python*: I would imagine that you'd probably use Django with Python. Because of this you're probably going to come up against the same stumbling blocks that you would with ruby + ruby on rails. If you'd like to start to learn Ruby on Rails, I'd recommend checking out [this thread](https://stackoverflow.com/questions/55574/learning-ruby-on-rails) on stackoverflow. Finally, if you'd like to work with a PHP framework, there's a great thread on that [here on stackoverflow](https://stackoverflow.com/questions/58424/a-lightweight-application-framework-for-php).
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database. Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages.
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
Ruby-on-rails, Python and PHP would all be excellent choices for developing a web service in. All the languages are capable (with of course Ruby being the language that Ruby on Rails is written in), have strong frameworks if that is your fancy (Django being a good python example, and something like Drupal or CakePHP being good PHP examples) and can play nicely with MySql. I'd say that it would depend mostly on your past experience and what you'd be the most comfortable with. Assuming that you're developing C# on .NET and have experience with Objective-C PHP may be a good choice because it is most certainly from the C family of languages. So the syntax might be more familiar and a bit easier to deal with. I'm a PHP developer so I'll give you that slant and let more knowledgeable developers with the others give theirs as well. PHP is tightly integrated with Apache, which can make some of the more mundane tasks that you'd have to handle with the others a bit more trivial (though when working with a framework those are usually removed). The [PHP documentation](http://www.php.net/manual/en/) is second to none and is a great resource for getting up and going easily. It has decent speed and there are good caching mechanisms out there to get more performance out of it. I know that getting up and running with PHP on Dreamhost is trivial. I haven't done it in the other instances although it wouldn't surprise me if those were just as easy as well. I'd suggest digging a bit more into the documentation and frameworks for each language to find out what suits you best.
The first programming I ever did was with PHP, and it's definitely very easy to get going with PHP on Dreamhost (I use Dreamhost for my PHP-based blog as well as Ruby on Rails project hosting). Ruby on Rails is pretty easy to get going on Dreamhost as well, now that they've started using [Passenger](http://www.modrails.com/). I learned Ruby and Ruby on Rails several years after I became comfortable in PHP and I prefer it to PHP because it feels much cleaner and I love the Model View Controller pattern for separation of code and content. I tried to learn Django after that but found myself frustrated because the meaning of "view" was different in Django than in Rails/MVC, so I didn't get very far. If you are doing quick-and-dirty, you might go with PHP. You could look into various frameworks for PHP, such as CakePHP or Symfony, for cleaner, more organized development. If you're willing to spend more time learning (first for the language Ruby, then for the framework Ruby on Rails), you could go with Ruby on Rails. I really enjoy Rails development, but there was a learning curve since I learned both Ruby and Rails at the same time. There's a lot of [information](http://rails.dreamhosters.com/) out there about deploying Rails apps on Dreamhost.
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database. Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages.
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
I have developed in Python and PHP and my personal preference would be Python. Django is a great, easy to understand, light-weight framework for Python. [Django Site](http://www.djangoproject.com/) If you went the PHP route, I would recommend Kohana. [Kohana Site](http://www.kohanaphp.com/)
This is an extremely subjective question, and even if you gave us the specifics of your web service, we can argue about the best choice all day. I'm a PHP developer, so I could whip off a basic web service with no problems. There's [lots](http://www.kohanaphp.com/) of [simple](http://codeigniter.com/) PHP [frameworks](http://cakephp.org) available that would handle that very nicely. That being said, Python and Django give you some great out-of-the-box functionality, and it's on my list of things to learn. You could achieve something pretty fast with that.
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database. Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages.
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
**The short answer is, I'd go with PHP.** I have some experience in all two of your three choices: PHP, Ruby with Ruby on Rails. If I had no experience however and I was looking to set out and create a web service that largely just interacts with a database and I wanted it done this weekend, I'd choose PHP. If I had no experience with any of the above languages and I wanted to project done in a couple of weeks, I'd choose rails. I personally have much less experience with with Python and Django so I can't really comment. *Ruby with Ruby on Rails:* I've been working with Ruby and ruby on rails for several years now. I previously had experience in Java (which is roughly analogous to your experience in .Net). I found the transition to rails to be a little bit bumpy. I wanted to jump right in and start understanding how rails works and how to build a web application but with no understanding of ruby this was difficult. There are a lot of example out there that will help you build an application quickly but often times the quickness comes at the expense of understanding. To build solid rails web application you need a good understanding of ruby and of the rails frameworks. Rails is fantastic, but for building something you understand and getting it up and running quickly it may not be your best choice. Also, rails hosting has come a long way (you can tell because we're starting to see many hosts offer it) but there are still some bumps. *PHP*: PHP is fantastic for getting something up and running quickly. You can upload files and immediately see if your result if working. If you keep your database setup clean (and it sounds like you will, because you work with databases all day) the PHP shouldn't be too bad. I would look into an Object Relational Mapper to help keep your PHP even cleaner, I've heard good thinks about [Doctorine](http://www.doctrine-project.org/). *Python*: I would imagine that you'd probably use Django with Python. Because of this you're probably going to come up against the same stumbling blocks that you would with ruby + ruby on rails. If you'd like to start to learn Ruby on Rails, I'd recommend checking out [this thread](https://stackoverflow.com/questions/55574/learning-ruby-on-rails) on stackoverflow. Finally, if you'd like to work with a PHP framework, there's a great thread on that [here on stackoverflow](https://stackoverflow.com/questions/58424/a-lightweight-application-framework-for-php).
I have developed in Python and PHP and my personal preference would be Python. Django is a great, easy to understand, light-weight framework for Python. [Django Site](http://www.djangoproject.com/) If you went the PHP route, I would recommend Kohana. [Kohana Site](http://www.kohanaphp.com/)
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database. Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages.
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
I have developed in Python and PHP and my personal preference would be Python. Django is a great, easy to understand, light-weight framework for Python. [Django Site](http://www.djangoproject.com/) If you went the PHP route, I would recommend Kohana. [Kohana Site](http://www.kohanaphp.com/)
The first programming I ever did was with PHP, and it's definitely very easy to get going with PHP on Dreamhost (I use Dreamhost for my PHP-based blog as well as Ruby on Rails project hosting). Ruby on Rails is pretty easy to get going on Dreamhost as well, now that they've started using [Passenger](http://www.modrails.com/). I learned Ruby and Ruby on Rails several years after I became comfortable in PHP and I prefer it to PHP because it feels much cleaner and I love the Model View Controller pattern for separation of code and content. I tried to learn Django after that but found myself frustrated because the meaning of "view" was different in Django than in Rails/MVC, so I didn't get very far. If you are doing quick-and-dirty, you might go with PHP. You could look into various frameworks for PHP, such as CakePHP or Symfony, for cleaner, more organized development. If you're willing to spend more time learning (first for the language Ruby, then for the framework Ruby on Rails), you could go with Ruby on Rails. I really enjoy Rails development, but there was a learning curve since I learned both Ruby and Rails at the same time. There's a lot of [information](http://rails.dreamhosters.com/) out there about deploying Rails apps on Dreamhost.
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database. Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages.
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
**The short answer is, I'd go with PHP.** I have some experience in all two of your three choices: PHP, Ruby with Ruby on Rails. If I had no experience however and I was looking to set out and create a web service that largely just interacts with a database and I wanted it done this weekend, I'd choose PHP. If I had no experience with any of the above languages and I wanted to project done in a couple of weeks, I'd choose rails. I personally have much less experience with with Python and Django so I can't really comment. *Ruby with Ruby on Rails:* I've been working with Ruby and ruby on rails for several years now. I previously had experience in Java (which is roughly analogous to your experience in .Net). I found the transition to rails to be a little bit bumpy. I wanted to jump right in and start understanding how rails works and how to build a web application but with no understanding of ruby this was difficult. There are a lot of example out there that will help you build an application quickly but often times the quickness comes at the expense of understanding. To build solid rails web application you need a good understanding of ruby and of the rails frameworks. Rails is fantastic, but for building something you understand and getting it up and running quickly it may not be your best choice. Also, rails hosting has come a long way (you can tell because we're starting to see many hosts offer it) but there are still some bumps. *PHP*: PHP is fantastic for getting something up and running quickly. You can upload files and immediately see if your result if working. If you keep your database setup clean (and it sounds like you will, because you work with databases all day) the PHP shouldn't be too bad. I would look into an Object Relational Mapper to help keep your PHP even cleaner, I've heard good thinks about [Doctorine](http://www.doctrine-project.org/). *Python*: I would imagine that you'd probably use Django with Python. Because of this you're probably going to come up against the same stumbling blocks that you would with ruby + ruby on rails. If you'd like to start to learn Ruby on Rails, I'd recommend checking out [this thread](https://stackoverflow.com/questions/55574/learning-ruby-on-rails) on stackoverflow. Finally, if you'd like to work with a PHP framework, there's a great thread on that [here on stackoverflow](https://stackoverflow.com/questions/58424/a-lightweight-application-framework-for-php).
This is an extremely subjective question, and even if you gave us the specifics of your web service, we can argue about the best choice all day. I'm a PHP developer, so I could whip off a basic web service with no problems. There's [lots](http://www.kohanaphp.com/) of [simple](http://codeigniter.com/) PHP [frameworks](http://cakephp.org) available that would handle that very nicely. That being said, Python and Django give you some great out-of-the-box functionality, and it's on my list of things to learn. You could achieve something pretty fast with that.
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database. Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages.
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
The first programming I ever did was with PHP, and it's definitely very easy to get going with PHP on Dreamhost (I use Dreamhost for my PHP-based blog as well as Ruby on Rails project hosting). Ruby on Rails is pretty easy to get going on Dreamhost as well, now that they've started using [Passenger](http://www.modrails.com/). I learned Ruby and Ruby on Rails several years after I became comfortable in PHP and I prefer it to PHP because it feels much cleaner and I love the Model View Controller pattern for separation of code and content. I tried to learn Django after that but found myself frustrated because the meaning of "view" was different in Django than in Rails/MVC, so I didn't get very far. If you are doing quick-and-dirty, you might go with PHP. You could look into various frameworks for PHP, such as CakePHP or Symfony, for cleaner, more organized development. If you're willing to spend more time learning (first for the language Ruby, then for the framework Ruby on Rails), you could go with Ruby on Rails. I really enjoy Rails development, but there was a learning curve since I learned both Ruby and Rails at the same time. There's a lot of [information](http://rails.dreamhosters.com/) out there about deploying Rails apps on Dreamhost.
This is an extremely subjective question, and even if you gave us the specifics of your web service, we can argue about the best choice all day. I'm a PHP developer, so I could whip off a basic web service with no problems. There's [lots](http://www.kohanaphp.com/) of [simple](http://codeigniter.com/) PHP [frameworks](http://cakephp.org) available that would handle that very nicely. That being said, Python and Django give you some great out-of-the-box functionality, and it's on my list of things to learn. You could achieve something pretty fast with that.