qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
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 V... | 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** an... | 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... |
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... | 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... | 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 la... | 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/Pyth... |
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.HTTPS... | 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 ... |
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 ... | 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))
Impo... |
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 ... | 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 tha... |
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 ... | 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 locatio... |
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 ... | 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 ... | 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 tha... | `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 ... | 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 locatio... |
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 ... | 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 ... | 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 ... | 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 tha... | 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))
Impo... |
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 ... | 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))
Impo... |
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... | 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 g... | 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 familia... |
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 g... | 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... |
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 g... | 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... | 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 familia... |
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 cola... | 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) => ....,
... | 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... | 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: ""
};
... | * 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 ... |
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... | 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'],
... | 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 pyinstall... |
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 King... | 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());
})!;... | 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 allowe... |
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.... | 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_Ch... | ```
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} tim... |
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.... | 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.
'''
... | `(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.... | 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_Ch... | `(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.... | 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 ... | 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.ti... |
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.... | 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 ... | 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.
'''
... |
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.... | 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.
'''
... | ```
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} tim... |
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.... | 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.ti... | ```
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} tim... |
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.... | 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_Ch... | 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.ti... |
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.... | 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.
'''
... | 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_Ch... |
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.... | 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.
'''
... | 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 = dateti... |
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 ... | 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 ca... | 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_wi... |
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 ... | 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 ca... | 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 ... | 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=... | 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_wi... |
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 ... | 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=... | 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:

i try to find the relationship between the original and the flipped. since i can't go to negative coordinates in python, what i dec... | 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 im... |
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:

i try to find the relationship between the original and the flipped. since i can't go to negative coordinates in python, what i dec... | 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])
... |
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:

i try to find the relationship between the original and the flipped. since i can't go to negative coordinates in python, what i dec... | 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 im... | 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])
... |
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.in... | 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 ... | 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.in... | 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 ... | 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... |
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... | 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,
... | ```
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,
... |
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... | 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,
... | 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 ... |
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... | 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,
... | 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)
`... |
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... | 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,
... | 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 ... |
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... | 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,
... | 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)
`... |
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).... | 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 ha... | >
> 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, t... |
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
``... | 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 `.ba... | 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_S... |
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
``... | 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 PYTHO... | 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_S... |
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 ... | 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 [[... | 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 [[... | 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 [[... | 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_... | 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 ... | 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? Consi... |
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_... | 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 ... | 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_... | 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? Consi... | 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... | 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 increasin... | 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
level... | 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
level... | 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",
remoteDirect... |
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.p... | 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 an... | 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 th... |
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`
... | 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 th... | `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.const... | 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_poo... | 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 p... |
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>
</articl... | 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
<art... | 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... |
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.... | 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 ... | 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"
```
[](https://i.sta... | 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 ... | 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"
```
[](https://i.sta... | 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, includ... | 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 ... |
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"
```
[](https://i.sta... | 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, includ... | 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);
valu... | 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... |
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... | 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 `impor... | 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 hav... |
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.assertTr... | 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 ... | 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 ... |
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.assertTr... | 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 ... | 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.assertTr... | 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 ... | 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 d... |
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.assertTr... | 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 d... | 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 my... |
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.assertTr... | 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 d... | 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.assertTr... | 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 d... | 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 ... |
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.assertTr... | 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(uni... | 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 my... |
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.assertTr... | 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(uni... | 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 d... |
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.assertTr... | 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 my... | 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 ... |
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.assertTr... | 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 my... | 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... | 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 `... | 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... | 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... | 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 `... | 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... | 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.date... | 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?
**... |
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()
... | 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
```
... |
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... | 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 ... | 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" r... |
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 a... | 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... | 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/... |
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 a... | 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... | 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 i... |
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"></scrip... |
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 py... | 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 be... | 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 py... | 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 be... | 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]... |
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 py... | 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 be... | **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 n... |
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 py... | 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 be... | 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... |
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 py... | 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]... |
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 py... | 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 n... | 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 py... | 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... |
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 py... | 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 n... | 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]... |
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 py... | 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... | 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]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.