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
|
|---|---|---|---|---|---|
61,353,951
|
I have tried to install Facebook Prophet in Anaconda on Ubuntu following the instructions at:
<https://facebook.github.io/prophet/docs/installation.html#installation-in-python>.
In Anaconda Navigator, when I click on the environment, fbprophet is listed along with the other installed packages. The problem is that when I try to use fbprophet in Jupyter:
```
from fbprophet import Prophet
```
I get an error: "ModuleNotFoundError: No module named 'fbprophet'". It's bizarre because the fbprophet package seems to be installed in my environment according to Anaconda.
Can anyone help, please?
Thanks!
|
2020/04/21
|
[
"https://Stackoverflow.com/questions/61353951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9415043/"
] |
It seems that you have installed the package in a separate environment in anaconda. I think when you are running jupyter notebook, it is running from the base environment, But actually you need to run it from the library environment. So if the case is this you need to install jupyter notebook in the other environment and then run the jypyter notebook from that environment. So at first make sure that you have installed jupyter notebook correctly on the appropriate environment. If you have installed it correctly then open jupyter notebook and in a code cell write the following commands and execute the cell.
First, execute this command in a code cell-
```
!conda install -c conda-forge fbprophet -y
```
Then in another code cell execute this command-
```
!pip install --upgrade plotly
```
Now try to import the library.
|
Recently the fbprophet project renamed to prophet.
If you are referring to it using old name you should install the old version.
```
pip/conda/mamba/whatever install prophet
```
|
61,353,951
|
I have tried to install Facebook Prophet in Anaconda on Ubuntu following the instructions at:
<https://facebook.github.io/prophet/docs/installation.html#installation-in-python>.
In Anaconda Navigator, when I click on the environment, fbprophet is listed along with the other installed packages. The problem is that when I try to use fbprophet in Jupyter:
```
from fbprophet import Prophet
```
I get an error: "ModuleNotFoundError: No module named 'fbprophet'". It's bizarre because the fbprophet package seems to be installed in my environment according to Anaconda.
Can anyone help, please?
Thanks!
|
2020/04/21
|
[
"https://Stackoverflow.com/questions/61353951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9415043/"
] |
It seems that you have installed the package in a separate environment in anaconda. I think when you are running jupyter notebook, it is running from the base environment, But actually you need to run it from the library environment. So if the case is this you need to install jupyter notebook in the other environment and then run the jypyter notebook from that environment. So at first make sure that you have installed jupyter notebook correctly on the appropriate environment. If you have installed it correctly then open jupyter notebook and in a code cell write the following commands and execute the cell.
First, execute this command in a code cell-
```
!conda install -c conda-forge fbprophet -y
```
Then in another code cell execute this command-
```
!pip install --upgrade plotly
```
Now try to import the library.
|
After spending hours scouring the internet for answers to this question and similar questions like "ERROR: Command errored out with exit status 1: when installing "Facebook" "prophet"" what worked for me was quite simply using a sudo pip install at the terminal prompt:
`$ sudo pip install pystan==2.19.1.1 prophet`
After install using prophet instead of fbprophet:
`from prophet import Prophet`
Credit to GitHub issue 1874 - <https://github.com/facebook/prophet/issues/1874>
|
61,353,951
|
I have tried to install Facebook Prophet in Anaconda on Ubuntu following the instructions at:
<https://facebook.github.io/prophet/docs/installation.html#installation-in-python>.
In Anaconda Navigator, when I click on the environment, fbprophet is listed along with the other installed packages. The problem is that when I try to use fbprophet in Jupyter:
```
from fbprophet import Prophet
```
I get an error: "ModuleNotFoundError: No module named 'fbprophet'". It's bizarre because the fbprophet package seems to be installed in my environment according to Anaconda.
Can anyone help, please?
Thanks!
|
2020/04/21
|
[
"https://Stackoverflow.com/questions/61353951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9415043/"
] |
It seems that you have installed the package in a separate environment in anaconda. I think when you are running jupyter notebook, it is running from the base environment, But actually you need to run it from the library environment. So if the case is this you need to install jupyter notebook in the other environment and then run the jypyter notebook from that environment. So at first make sure that you have installed jupyter notebook correctly on the appropriate environment. If you have installed it correctly then open jupyter notebook and in a code cell write the following commands and execute the cell.
First, execute this command in a code cell-
```
!conda install -c conda-forge fbprophet -y
```
Then in another code cell execute this command-
```
!pip install --upgrade plotly
```
Now try to import the library.
|
Window10 + Pycharm.
This works with Python 3.8. and Python 3.9.x:
```
pip install localpip
localpip install fbprophet
```
|
61,353,951
|
I have tried to install Facebook Prophet in Anaconda on Ubuntu following the instructions at:
<https://facebook.github.io/prophet/docs/installation.html#installation-in-python>.
In Anaconda Navigator, when I click on the environment, fbprophet is listed along with the other installed packages. The problem is that when I try to use fbprophet in Jupyter:
```
from fbprophet import Prophet
```
I get an error: "ModuleNotFoundError: No module named 'fbprophet'". It's bizarre because the fbprophet package seems to be installed in my environment according to Anaconda.
Can anyone help, please?
Thanks!
|
2020/04/21
|
[
"https://Stackoverflow.com/questions/61353951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9415043/"
] |
Recently the fbprophet project renamed to prophet.
If you are referring to it using old name you should install the old version.
```
pip/conda/mamba/whatever install prophet
```
|
After spending hours scouring the internet for answers to this question and similar questions like "ERROR: Command errored out with exit status 1: when installing "Facebook" "prophet"" what worked for me was quite simply using a sudo pip install at the terminal prompt:
`$ sudo pip install pystan==2.19.1.1 prophet`
After install using prophet instead of fbprophet:
`from prophet import Prophet`
Credit to GitHub issue 1874 - <https://github.com/facebook/prophet/issues/1874>
|
61,353,951
|
I have tried to install Facebook Prophet in Anaconda on Ubuntu following the instructions at:
<https://facebook.github.io/prophet/docs/installation.html#installation-in-python>.
In Anaconda Navigator, when I click on the environment, fbprophet is listed along with the other installed packages. The problem is that when I try to use fbprophet in Jupyter:
```
from fbprophet import Prophet
```
I get an error: "ModuleNotFoundError: No module named 'fbprophet'". It's bizarre because the fbprophet package seems to be installed in my environment according to Anaconda.
Can anyone help, please?
Thanks!
|
2020/04/21
|
[
"https://Stackoverflow.com/questions/61353951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9415043/"
] |
Recently the fbprophet project renamed to prophet.
If you are referring to it using old name you should install the old version.
```
pip/conda/mamba/whatever install prophet
```
|
Window10 + Pycharm.
This works with Python 3.8. and Python 3.9.x:
```
pip install localpip
localpip install fbprophet
```
|
61,353,951
|
I have tried to install Facebook Prophet in Anaconda on Ubuntu following the instructions at:
<https://facebook.github.io/prophet/docs/installation.html#installation-in-python>.
In Anaconda Navigator, when I click on the environment, fbprophet is listed along with the other installed packages. The problem is that when I try to use fbprophet in Jupyter:
```
from fbprophet import Prophet
```
I get an error: "ModuleNotFoundError: No module named 'fbprophet'". It's bizarre because the fbprophet package seems to be installed in my environment according to Anaconda.
Can anyone help, please?
Thanks!
|
2020/04/21
|
[
"https://Stackoverflow.com/questions/61353951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9415043/"
] |
After spending hours scouring the internet for answers to this question and similar questions like "ERROR: Command errored out with exit status 1: when installing "Facebook" "prophet"" what worked for me was quite simply using a sudo pip install at the terminal prompt:
`$ sudo pip install pystan==2.19.1.1 prophet`
After install using prophet instead of fbprophet:
`from prophet import Prophet`
Credit to GitHub issue 1874 - <https://github.com/facebook/prophet/issues/1874>
|
Window10 + Pycharm.
This works with Python 3.8. and Python 3.9.x:
```
pip install localpip
localpip install fbprophet
```
|
21,866,036
|
When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ?
e.g. this works
```
python -c "import os.path; print os.getcwd()"
```
Shouldn't I explicitly `import os` for `os.getcwd` to be available ?
|
2014/02/18
|
[
"https://Stackoverflow.com/questions/21866036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346286/"
] |
It works and it is reliable. What happens under the hood is when you do
```
import os.path
```
then `os` gets imported and then `os.path`.
|
Yes, you can rely on it always working. Python has to include `os` in the namespace for `os.path` to work.
What won't work is using the `from os import path` notation. In that case, the os module is *not* brought into the namespace, only `path`.
|
21,866,036
|
When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ?
e.g. this works
```
python -c "import os.path; print os.getcwd()"
```
Shouldn't I explicitly `import os` for `os.getcwd` to be available ?
|
2014/02/18
|
[
"https://Stackoverflow.com/questions/21866036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346286/"
] |
This is a good question. If you look at the source code for `os.py` you find this line:
```
sys.modules['os.path'] = path
```
So there's our module. But what's `path`? Well that depends on your OS. For Windows, it's defined in this block:
```
elif 'nt' in _names:
name = 'nt'
linesep = '\r\n'
from nt import *
try:
from nt import _exit
except ImportError:
pass
import ntpath as path
import nt
__all__.extend(_get_exports_list(nt))
del nt
```
Basically, `os.path` is special in this context.
**Short version:** Python does some stuff behind the scenes to make `os.path`. You probably shouldn't rely on it to get other modules. "Explicit is better than implicit" is how the zen goes.
|
It works and it is reliable. What happens under the hood is when you do
```
import os.path
```
then `os` gets imported and then `os.path`.
|
21,866,036
|
When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ?
e.g. this works
```
python -c "import os.path; print os.getcwd()"
```
Shouldn't I explicitly `import os` for `os.getcwd` to be available ?
|
2014/02/18
|
[
"https://Stackoverflow.com/questions/21866036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346286/"
] |
There's an important thing to know about packages, that is that there is a difference between being loaded and being available.
With `import a` you load module `a` (which can be a package) and make it available under the name `a`.
With `from a import b` you load module `a` (which definitely is a package), then load module `a.b` and make *only this* available under the name `b`. Notice that `a` also got loaded in the process, so any initialization this is supposed to do will have happened.
With `import a.b` you load both and make both available (under the names `a` and `a.b`).
|
It works and it is reliable. What happens under the hood is when you do
```
import os.path
```
then `os` gets imported and then `os.path`.
|
21,866,036
|
When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ?
e.g. this works
```
python -c "import os.path; print os.getcwd()"
```
Shouldn't I explicitly `import os` for `os.getcwd` to be available ?
|
2014/02/18
|
[
"https://Stackoverflow.com/questions/21866036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346286/"
] |
This is a good question. If you look at the source code for `os.py` you find this line:
```
sys.modules['os.path'] = path
```
So there's our module. But what's `path`? Well that depends on your OS. For Windows, it's defined in this block:
```
elif 'nt' in _names:
name = 'nt'
linesep = '\r\n'
from nt import *
try:
from nt import _exit
except ImportError:
pass
import ntpath as path
import nt
__all__.extend(_get_exports_list(nt))
del nt
```
Basically, `os.path` is special in this context.
**Short version:** Python does some stuff behind the scenes to make `os.path`. You probably shouldn't rely on it to get other modules. "Explicit is better than implicit" is how the zen goes.
|
Yes, you can rely on it always working. Python has to include `os` in the namespace for `os.path` to work.
What won't work is using the `from os import path` notation. In that case, the os module is *not* brought into the namespace, only `path`.
|
21,866,036
|
When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ?
e.g. this works
```
python -c "import os.path; print os.getcwd()"
```
Shouldn't I explicitly `import os` for `os.getcwd` to be available ?
|
2014/02/18
|
[
"https://Stackoverflow.com/questions/21866036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346286/"
] |
There's an important thing to know about packages, that is that there is a difference between being loaded and being available.
With `import a` you load module `a` (which can be a package) and make it available under the name `a`.
With `from a import b` you load module `a` (which definitely is a package), then load module `a.b` and make *only this* available under the name `b`. Notice that `a` also got loaded in the process, so any initialization this is supposed to do will have happened.
With `import a.b` you load both and make both available (under the names `a` and `a.b`).
|
Yes, you can rely on it always working. Python has to include `os` in the namespace for `os.path` to work.
What won't work is using the `from os import path` notation. In that case, the os module is *not* brought into the namespace, only `path`.
|
57,076,851
|
I want to plot a bode plot of a system with the python control systems library. This is fairly easy. The problem is the plot of the margins. It is no problem to plot the phase margin. But how can I plot the gain margin?
So far, this is a part of my code:
```py
import control as cn
%matplotlib notebook
import matplotlib.pyplot as plt
Ks=2
T1=5
T2=0.3
T3=0.1
Gs=cn.tf(Ks,[T1*T2*T3, T1*T2+T1*T3+T2*T3, T1+T2+T3, 1])
Vr=1
Tn=1
plt.close()
R=cn.tf([Vr*Tn, Vr],[1, 0])
L=Gs*R
gm, pm, wg, wp = cn.margin(L)
_,_,_ = cn.bode(L,dB=True)
plt.axvline(x = wp,color='r')
```
|
2019/07/17
|
[
"https://Stackoverflow.com/questions/57076851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6883478/"
] |
Not the most elegant solution but hey it works for me.
```
###Import modules
import numpy as np
import control as ctl
import matplotlib.pyplot as plt
##Functions
def plot_margins(sys):
mag,phase,omega = ctl.bode(sys,dB=True,Plot=False)
magdB = 20*np.log10(mag)
phase_deg = phase*180.0/np.pi
Gm,Pm,Wcg,Wcp = ctl.margin(sys)
GmdB = 20*np.log10(Gm)
##Plot Gain and Phase
f,(ax1,ax2) = plt.subplots(2,1)
ax1.semilogx(omega,magdB)
ax1.grid(which="both")
ax1.set_xlabel('Frequency (rad/s)')
ax1.set_ylabel('Magnitude (dB)')
ax2.semilogx(omega,phase_deg)
ax2.grid(which="both")
ax2.set_xlabel('Frequency (rad/s)')
ax2.set_ylabel('Phase (deg)')
ax1.set_title('Gm = '+str(np.round(GmdB,2))+' dB (at '+str(np.round(Wcg,2))+' rad/s), Pm = '+str(np.round(Pm,2))+' deg (at '+str(np.round(Wcp,2))+' rad/s)')
###Plot the zero dB line
ax1.plot(omega,0*omega,'k--',lineWidth=2)
###Plot the -180 deg lin
ax2.plot(omega,-180+0*omega,'k--',lineWidth=2)
##Plot the vertical line from -180 to 0 at Wcg
ax2.plot([Wcg,Wcg],[-180,0],'r--',lineWidth=2)
##Plot the vertical line from -180+Pm to 0 at Wcp
ax2.plot([Wcp,Wcp],[-180+Pm,0],'g--',lineWidth=2)
##Plot the vertical line from min(magdB) to 0-GmdB at Wcg
ax1.plot([Wcg,Wcg],[np.min(magdB),0-GmdB],'r--',lineWidth=2)
##Plot the vertical line from min(magdB) to 0db at Wcp
ax1.plot([Wcp,Wcp],[np.min(magdB),0],'g--',lineWidth=2)
return Gm,Pm,Wcg,Wcp
#%%%Actuator Dynamics
G = ctl.tf([1],[1,2,1,0])
Gm,Pm,Wcg,Wcp=plot_margins(G)
plt.show()
```
|
Starting in version 0.8 of `control`, the [`bode_plot`](https://python-control.readthedocs.io/en/0.8.3/generated/control.bode_plot.html) function (also aliased as `bode`) has an option to plot margins.
```py
import control
sys = control.tf([1], [1, 1]) # example transfer function
control.bode_plot(sys, margins=True)
# or
control.bode(sys, margins=True)
```
However, this method does not always look how I would like, especially with multiple transfer functions. If you want more control (pun intended), you can do something similar to @monte-carlo's answer, but by plotting the margins directly on the plot produced by the `bode_plot`/`bode` command.
```py
import control
import matplotlib as plt
sys = control.tf([1], [1, 1]) # example transfer function
control.bode(sys, dB=True)
gm, pm, wg, wp = control.margin(sys)
fig = plt.gcf() # Get a handle to the current figure (the bode plot)
mag_axis, phase_axis = fig.axes # Get the magnitude and phase subplots
mag_axis.plot([wg, wg], [0, control.mag2db(gm)])
phase_axis.plot([wp, wp], [-180, pm])
```
|
467,602
|
Following from this [OS-agnostic question](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python), specifically [this response](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291), similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).
|
2009/01/22
|
[
"https://Stackoverflow.com/questions/467602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
There was a similar question asked:
[How to get current CPU and RAM usage in Python?](https://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python)
There are quite a few answers telling you how to accomplish this in windows.
|
You can try using the systeminfo.exe wrapper I created a while back, it's a bit unorthodox but it seems to do the trick easily enough and without much code.
This should work on 2000/XP/2003 Server, and should work on Vista and Win7 provided they come with systeminfo.exe and it is located on the path.
```
import os, re
def SysInfo():
values = {}
cache = os.popen2("SYSTEMINFO")
source = cache[1].read()
sysOpts = ["Host Name", "OS Name", "OS Version", "Product ID", "System Manufacturer", "System Model", "System type", "BIOS Version", "Domain", "Windows Directory", "Total Physical Memory", "Available Physical Memory", "Logon Server"]
for opt in sysOpts:
values[opt] = [item.strip() for item in re.findall("%s:\w*(.*?)\n" % (opt), source, re.IGNORECASE)][0]
return values
```
You can easily append the rest of the data fields to the sysOpts variable, excluding those that provide multiple lines for their results, like CPU & NIC information. A simple mod to the regexp line should be able to handle that.
Enjoy!
|
467,602
|
Following from this [OS-agnostic question](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python), specifically [this response](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291), similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).
|
2009/01/22
|
[
"https://Stackoverflow.com/questions/467602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
There was a similar question asked:
[How to get current CPU and RAM usage in Python?](https://stackoverflow.com/questions/276052/how-to-get-current-cpu-and-ram-usage-in-python)
There are quite a few answers telling you how to accomplish this in windows.
|
Some answers given can make trouble if the OS language is not native English. I searched for a way to get a wrapper around the `systeminfo.exe` and found the following solution. To make it more comfortable I pack the result in a dictionary:
```
import os
import tempfile
def get_system_info_dict():
tmp_dir=tempfile.gettempdir()
file_path=os.path.join(tmp_dir,'out')
# Call the system command that delivers the needed information
os.system('powershell -Command gcim WIN32_ComputerSystem -Property * >%s'%file_path)
with open(file_path,'r') as fh:
data=fh.read()
os.remove(file_path)
data_dict={}
for line in data.split('\n'):
try:
k,v=line.split(':')
except ValueError:
continue
k = k.strip(' ')
v = v.strip(' ')
if v!='':
data_dict[k]=v
return data_dict
```
Each key of a the resulting dictionary is a property (in English!) and the related value is the data stored for the property.
|
467,602
|
Following from this [OS-agnostic question](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python), specifically [this response](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291), similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).
|
2009/01/22
|
[
"https://Stackoverflow.com/questions/467602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
In Windows, if you want to get info like from the SYSTEMINFO command, you can use the [WMI module.](https://pypi.python.org/pypi/WMI/)
```
import wmi
c = wmi.WMI()
systeminfo = c.Win32_ComputerSystem()[0]
Manufacturer = systeminfo.Manufacturer
Model = systeminfo.Model
```
...
similarly, the os-related info could be got from `osinfo = c.Win32_OperatingSystem()[0]`
the full list of [system info is here](http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx) and [os info is here](http://msdn.microsoft.com/en-us/library/windows/desktop/aa394239%28v=vs.85%29.aspx)
|
You can try using the systeminfo.exe wrapper I created a while back, it's a bit unorthodox but it seems to do the trick easily enough and without much code.
This should work on 2000/XP/2003 Server, and should work on Vista and Win7 provided they come with systeminfo.exe and it is located on the path.
```
import os, re
def SysInfo():
values = {}
cache = os.popen2("SYSTEMINFO")
source = cache[1].read()
sysOpts = ["Host Name", "OS Name", "OS Version", "Product ID", "System Manufacturer", "System Model", "System type", "BIOS Version", "Domain", "Windows Directory", "Total Physical Memory", "Available Physical Memory", "Logon Server"]
for opt in sysOpts:
values[opt] = [item.strip() for item in re.findall("%s:\w*(.*?)\n" % (opt), source, re.IGNORECASE)][0]
return values
```
You can easily append the rest of the data fields to the sysOpts variable, excluding those that provide multiple lines for their results, like CPU & NIC information. A simple mod to the regexp line should be able to handle that.
Enjoy!
|
467,602
|
Following from this [OS-agnostic question](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python), specifically [this response](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291), similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).
|
2009/01/22
|
[
"https://Stackoverflow.com/questions/467602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
You can try using the systeminfo.exe wrapper I created a while back, it's a bit unorthodox but it seems to do the trick easily enough and without much code.
This should work on 2000/XP/2003 Server, and should work on Vista and Win7 provided they come with systeminfo.exe and it is located on the path.
```
import os, re
def SysInfo():
values = {}
cache = os.popen2("SYSTEMINFO")
source = cache[1].read()
sysOpts = ["Host Name", "OS Name", "OS Version", "Product ID", "System Manufacturer", "System Model", "System type", "BIOS Version", "Domain", "Windows Directory", "Total Physical Memory", "Available Physical Memory", "Logon Server"]
for opt in sysOpts:
values[opt] = [item.strip() for item in re.findall("%s:\w*(.*?)\n" % (opt), source, re.IGNORECASE)][0]
return values
```
You can easily append the rest of the data fields to the sysOpts variable, excluding those that provide multiple lines for their results, like CPU & NIC information. A simple mod to the regexp line should be able to handle that.
Enjoy!
|
Some answers given can make trouble if the OS language is not native English. I searched for a way to get a wrapper around the `systeminfo.exe` and found the following solution. To make it more comfortable I pack the result in a dictionary:
```
import os
import tempfile
def get_system_info_dict():
tmp_dir=tempfile.gettempdir()
file_path=os.path.join(tmp_dir,'out')
# Call the system command that delivers the needed information
os.system('powershell -Command gcim WIN32_ComputerSystem -Property * >%s'%file_path)
with open(file_path,'r') as fh:
data=fh.read()
os.remove(file_path)
data_dict={}
for line in data.split('\n'):
try:
k,v=line.split(':')
except ValueError:
continue
k = k.strip(' ')
v = v.strip(' ')
if v!='':
data_dict[k]=v
return data_dict
```
Each key of a the resulting dictionary is a property (in English!) and the related value is the data stored for the property.
|
467,602
|
Following from this [OS-agnostic question](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python), specifically [this response](https://stackoverflow.com/questions/466684/how-can-i-return-system-information-in-python#467291), similar to data available from the likes of /proc/meminfo on Linux, how can I read system information from Windows using Python (including, but not limited to memory usage).
|
2009/01/22
|
[
"https://Stackoverflow.com/questions/467602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
In Windows, if you want to get info like from the SYSTEMINFO command, you can use the [WMI module.](https://pypi.python.org/pypi/WMI/)
```
import wmi
c = wmi.WMI()
systeminfo = c.Win32_ComputerSystem()[0]
Manufacturer = systeminfo.Manufacturer
Model = systeminfo.Model
```
...
similarly, the os-related info could be got from `osinfo = c.Win32_OperatingSystem()[0]`
the full list of [system info is here](http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx) and [os info is here](http://msdn.microsoft.com/en-us/library/windows/desktop/aa394239%28v=vs.85%29.aspx)
|
Some answers given can make trouble if the OS language is not native English. I searched for a way to get a wrapper around the `systeminfo.exe` and found the following solution. To make it more comfortable I pack the result in a dictionary:
```
import os
import tempfile
def get_system_info_dict():
tmp_dir=tempfile.gettempdir()
file_path=os.path.join(tmp_dir,'out')
# Call the system command that delivers the needed information
os.system('powershell -Command gcim WIN32_ComputerSystem -Property * >%s'%file_path)
with open(file_path,'r') as fh:
data=fh.read()
os.remove(file_path)
data_dict={}
for line in data.split('\n'):
try:
k,v=line.split(':')
except ValueError:
continue
k = k.strip(' ')
v = v.strip(' ')
if v!='':
data_dict[k]=v
return data_dict
```
Each key of a the resulting dictionary is a property (in English!) and the related value is the data stored for the property.
|
19,890,824
|
How to store the get Facebook profile picture of a user while logging in through Facebook and saving it in my userprofile model.
I found this link which says how to do so using django-social-auth, <https://gist.github.com/kalamhavij/1662930>. but signals is now deprecated and I have to use pipeline.
Any idea how can I do the same using python-social-auth and pipeline?
|
2013/11/10
|
[
"https://Stackoverflow.com/questions/19890824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683634/"
] |
This is how it worked with me. (from <https://github.com/omab/python-social-auth/issues/80>)
Add the following code to pipeline.py:
```
from requests import request, HTTPError
from django.core.files.base import ContentFile
def save_profile_picture(strategy, user, response, details,
is_new=False,*args,**kwargs):
if is_new and strategy.backend.name == 'facebook':
url = 'http://graph.facebook.com/{0}/picture'.format(response['id'])
try:
response = request('GET', url, params={'type': 'large'})
response.raise_for_status()
except HTTPError:
pass
else:
profile = user.get_profile()
profile.profile_photo.save('{0}_social.jpg'.format(user.username),
ContentFile(response.content))
profile.save()
```
and add to pipelines in settings.py:
```
SOCIAL_AUTH_PIPELINE += (
'<application>.pipelines.save_profile_picture',
)
```
|
Assuming you already configured `SOCIAL_AUTH_PIPELINE`, there aren't many differences with signals approach.
Just create needed pipeline (skipping all imports, they're obvious)
```
def update_avatar(backend, details, response, social_user, uid,\
user, *args, **kwargs):
if backend.__class__ == FacebookBackend:
url = "http://graph.facebook.com/%s/picture?type=large" % response['id']
avatar = urlopen(url)
profile = user.get_profile()
profile.profile_photo.save(slugify(user.username + " social") + '.jpg',
ContentFile(avatar.read()))
profile.save()
```
and add to pipelines:
```
SOCIAL_AUTH_PIPELINE += (
'<application>.pipelines.update_avatar',
)
```
|
19,890,824
|
How to store the get Facebook profile picture of a user while logging in through Facebook and saving it in my userprofile model.
I found this link which says how to do so using django-social-auth, <https://gist.github.com/kalamhavij/1662930>. but signals is now deprecated and I have to use pipeline.
Any idea how can I do the same using python-social-auth and pipeline?
|
2013/11/10
|
[
"https://Stackoverflow.com/questions/19890824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683634/"
] |
Assuming you already configured `SOCIAL_AUTH_PIPELINE`, there aren't many differences with signals approach.
Just create needed pipeline (skipping all imports, they're obvious)
```
def update_avatar(backend, details, response, social_user, uid,\
user, *args, **kwargs):
if backend.__class__ == FacebookBackend:
url = "http://graph.facebook.com/%s/picture?type=large" % response['id']
avatar = urlopen(url)
profile = user.get_profile()
profile.profile_photo.save(slugify(user.username + " social") + '.jpg',
ContentFile(avatar.read()))
profile.save()
```
and add to pipelines:
```
SOCIAL_AUTH_PIPELINE += (
'<application>.pipelines.update_avatar',
)
```
|
The above answers may not work (it did not work for me) as the facebook profile URL does not work anymore without accesstoken. The following answer worked for me.
```
def save_profile(backend, user, response, is_new=False, *args, **kwargs):
if is_new and backend.name == "facebook":
#The main part is how to get the profile picture URL and then do what you need to do
Profile.objects.filter(owner=user).update(
imageUrl='https://graph.facebook.com/{0}/picture/?type=large&access_token={1}'.format(response['id'],
response[
'access_token']))
```
add to the pipeline in setting.py,
```
SOCIAL_AUTH_PIPELINE+ = ('<full_path>.save_profile')
```
|
19,890,824
|
How to store the get Facebook profile picture of a user while logging in through Facebook and saving it in my userprofile model.
I found this link which says how to do so using django-social-auth, <https://gist.github.com/kalamhavij/1662930>. but signals is now deprecated and I have to use pipeline.
Any idea how can I do the same using python-social-auth and pipeline?
|
2013/11/10
|
[
"https://Stackoverflow.com/questions/19890824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683634/"
] |
This is how it worked with me. (from <https://github.com/omab/python-social-auth/issues/80>)
Add the following code to pipeline.py:
```
from requests import request, HTTPError
from django.core.files.base import ContentFile
def save_profile_picture(strategy, user, response, details,
is_new=False,*args,**kwargs):
if is_new and strategy.backend.name == 'facebook':
url = 'http://graph.facebook.com/{0}/picture'.format(response['id'])
try:
response = request('GET', url, params={'type': 'large'})
response.raise_for_status()
except HTTPError:
pass
else:
profile = user.get_profile()
profile.profile_photo.save('{0}_social.jpg'.format(user.username),
ContentFile(response.content))
profile.save()
```
and add to pipelines in settings.py:
```
SOCIAL_AUTH_PIPELINE += (
'<application>.pipelines.save_profile_picture',
)
```
|
The above answers may not work (it did not work for me) as the facebook profile URL does not work anymore without accesstoken. The following answer worked for me.
```
def save_profile(backend, user, response, is_new=False, *args, **kwargs):
if is_new and backend.name == "facebook":
#The main part is how to get the profile picture URL and then do what you need to do
Profile.objects.filter(owner=user).update(
imageUrl='https://graph.facebook.com/{0}/picture/?type=large&access_token={1}'.format(response['id'],
response[
'access_token']))
```
add to the pipeline in setting.py,
```
SOCIAL_AUTH_PIPELINE+ = ('<full_path>.save_profile')
```
|
70,543,710
|
I am learning C# and have been taking a lot of online courses.
I am looking for a simpler/neater way to enumerate a list within a list.
In python we can do something like this in just one line:
```
newListofList=[[n,i] for n,i in enumerate([List1,List2,List3])]
```
Does it have to involve lambda and Linq in C#? if so, what would be the solution? I tried it with Dictionary in C# but my gut tells me this is not a perfect solution.
```
List<List<string>> familyListss = new List<List<string>>();
familyListss.Add(new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" });
familyListss.Add(new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" });
familyListss.Add(new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" });
Dictionary<int, List<string>> familyData = new Dictionary<int, List<string>>();
for (int i = 0; i < familyListss.Count; i++)
{
familyData.Add(i, familyListss[i]);
}
```
|
2021/12/31
|
[
"https://Stackoverflow.com/questions/70543710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740222/"
] |
Just a *constructor* will be enough:
```
List<List<string>> familyListss = new List<List<string>>() {
new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" },
new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" },
new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" }
};
```
If you want to mimic `enumerate` you can use *Linq*, `Select((value, index) => your lambda here)`:
```
using System.Linq;
...
var list = new List<string>() {
"a", "b", "c", "d"};
var result = list
.Select((value, index) => $"item[{index}] = {value}");
Console.Write(string.Join(Environment.NewLine, result));
```
**Outcome:**
```
item[0] = a
item[1] = b
item[2] = c
item[3] = d
```
|
Are you taking about something like this?
```
int i = 0;
familyListss.ForEach(f => { familyData.Add(i, f);i++; });
```
This is refactored from
```
int i = 0;
foreach (var f in familyListss)
{
familyData.Add(i, f);
i++;
}
```
With a small extension method, you can build in an index to foreach to make it one line. Extension methods are worth exploring, and can take annoying, repeated tasks out of your way.
Also see this question:
[C# Convert List<string> to Dictionary<string, string>](https://stackoverflow.com/questions/11581101/c-sharp-convert-liststring-to-dictionarystring-string)
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
Yes, you can. I started learning Django with very little Python knowledge too. As long as you have another language behind your belt, preferably a web based one (as you do), I don't think you're biting off too much at once.
Python's a pretty easy language to pick up too. Just have to get used to the significant white space and lack of semi-colons :P
|
Sure you can!
Django requires minimal knowledge about using python from the command line, but if you're comfortable with that, then there shouldn't be an issue. Django has excellent documentation and a good tutorial aimed at beginners that does not expect you to be a high-level Python programmer.
Here's the link to the beginner's tutorial for Django: <http://docs.djangoproject.com/en/dev/intro/tutorial01/>
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
Yes, you can. I started learning Django with very little Python knowledge too. As long as you have another language behind your belt, preferably a web based one (as you do), I don't think you're biting off too much at once.
Python's a pretty easy language to pick up too. Just have to get used to the significant white space and lack of semi-colons :P
|
Starting from Django it's good way to learn Python in fact. Django allows you to do nice things in a short time, which might be good motivation to dive into that language.
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
Yes, you can. I started learning Django with very little Python knowledge too. As long as you have another language behind your belt, preferably a web based one (as you do), I don't think you're biting off too much at once.
Python's a pretty easy language to pick up too. Just have to get used to the significant white space and lack of semi-colons :P
|
I'm going to disagree with previous answers. You *could* learn Python by learning Django, but I don't think it's a very good idea. You won't really understand why things are the way they are, or how things really work.
My advice would be to follow a Python tutorial first - if you're an experienced programmer already then [Dive Into Python](http://diveintopython.net) is an excellent one - and then run through the Django tutorial. You'll be in a much better shape if you do.
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
Yes, you can. I started learning Django with very little Python knowledge too. As long as you have another language behind your belt, preferably a web based one (as you do), I don't think you're biting off too much at once.
Python's a pretty easy language to pick up too. Just have to get used to the significant white space and lack of semi-colons :P
|
I tried starting just by going through the [Django tutorial](http://docs.djangoproject.com/en/1.2/intro/tutorial01/#intro-tutorial01), which got me going fast, but without enough Python knowledge, I got stuck when starting to write my own first app. Python terms like "tuples", "lists", and "dictionaries" were new to me and I didn't have any background to understand how and why to use them.
Spending time to go through the free [Google Python Class](http://code.google.com/edu/languages/google-python-class/) was well worth it and made many things clear. Otherwise, too much of what's in Django will seem like magic and you'll get stuck as soon as you need to write some functions to manipulate your data.
In short, I found that I could learn Django & Python concurrently, but not just by focusing on Django alone. Besides, learning Python is fun in itself and won't take you more than a day or two to learn the basics. I liked the Google class because it has video lectures and good exercises that focus on the practical use of Python.
Good luck!
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
Sure you can!
Django requires minimal knowledge about using python from the command line, but if you're comfortable with that, then there shouldn't be an issue. Django has excellent documentation and a good tutorial aimed at beginners that does not expect you to be a high-level Python programmer.
Here's the link to the beginner's tutorial for Django: <http://docs.djangoproject.com/en/dev/intro/tutorial01/>
|
Starting from Django it's good way to learn Python in fact. Django allows you to do nice things in a short time, which might be good motivation to dive into that language.
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
I'm going to disagree with previous answers. You *could* learn Python by learning Django, but I don't think it's a very good idea. You won't really understand why things are the way they are, or how things really work.
My advice would be to follow a Python tutorial first - if you're an experienced programmer already then [Dive Into Python](http://diveintopython.net) is an excellent one - and then run through the Django tutorial. You'll be in a much better shape if you do.
|
Sure you can!
Django requires minimal knowledge about using python from the command line, but if you're comfortable with that, then there shouldn't be an issue. Django has excellent documentation and a good tutorial aimed at beginners that does not expect you to be a high-level Python programmer.
Here's the link to the beginner's tutorial for Django: <http://docs.djangoproject.com/en/dev/intro/tutorial01/>
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
I'm going to disagree with previous answers. You *could* learn Python by learning Django, but I don't think it's a very good idea. You won't really understand why things are the way they are, or how things really work.
My advice would be to follow a Python tutorial first - if you're an experienced programmer already then [Dive Into Python](http://diveintopython.net) is an excellent one - and then run through the Django tutorial. You'll be in a much better shape if you do.
|
Starting from Django it's good way to learn Python in fact. Django allows you to do nice things in a short time, which might be good motivation to dive into that language.
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
I tried starting just by going through the [Django tutorial](http://docs.djangoproject.com/en/1.2/intro/tutorial01/#intro-tutorial01), which got me going fast, but without enough Python knowledge, I got stuck when starting to write my own first app. Python terms like "tuples", "lists", and "dictionaries" were new to me and I didn't have any background to understand how and why to use them.
Spending time to go through the free [Google Python Class](http://code.google.com/edu/languages/google-python-class/) was well worth it and made many things clear. Otherwise, too much of what's in Django will seem like magic and you'll get stuck as soon as you need to write some functions to manipulate your data.
In short, I found that I could learn Django & Python concurrently, but not just by focusing on Django alone. Besides, learning Python is fun in itself and won't take you more than a day or two to learn the basics. I liked the Google class because it has video lectures and good exercises that focus on the practical use of Python.
Good luck!
|
Starting from Django it's good way to learn Python in fact. Django allows you to do nice things in a short time, which might be good motivation to dive into that language.
|
3,234,402
|
Now, I'm learning python but I'm PHP web developer. I don't interest about terminal and windows programming. I only want to do web development. So, Can I learn Django ?
|
2010/07/13
|
[
"https://Stackoverflow.com/questions/3234402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215939/"
] |
I'm going to disagree with previous answers. You *could* learn Python by learning Django, but I don't think it's a very good idea. You won't really understand why things are the way they are, or how things really work.
My advice would be to follow a Python tutorial first - if you're an experienced programmer already then [Dive Into Python](http://diveintopython.net) is an excellent one - and then run through the Django tutorial. You'll be in a much better shape if you do.
|
I tried starting just by going through the [Django tutorial](http://docs.djangoproject.com/en/1.2/intro/tutorial01/#intro-tutorial01), which got me going fast, but without enough Python knowledge, I got stuck when starting to write my own first app. Python terms like "tuples", "lists", and "dictionaries" were new to me and I didn't have any background to understand how and why to use them.
Spending time to go through the free [Google Python Class](http://code.google.com/edu/languages/google-python-class/) was well worth it and made many things clear. Otherwise, too much of what's in Django will seem like magic and you'll get stuck as soon as you need to write some functions to manipulate your data.
In short, I found that I could learn Django & Python concurrently, but not just by focusing on Django alone. Besides, learning Python is fun in itself and won't take you more than a day or two to learn the basics. I liked the Google class because it has video lectures and good exercises that focus on the practical use of Python.
Good luck!
|
33,615,096
|
How can I use single quote and double quote same time as string python?
For example:
```
string = "Let's print "Happines" out"
```
result should be Let's print `"Happines"` out
I tried to use backslash but it prints out a `\` before 's that should be.
|
2015/11/09
|
[
"https://Stackoverflow.com/questions/33615096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5230597/"
] |
In python there's lots of ways to write string literals.
For this example you can:
```
print('Let\'s print "Happiness" out')
print("Let's print \"Happiness\" out")
print('''Let's print "Happiness" out''')
print("""Let's print "Happiness" out""")
```
Any of the above will behave as expected.
|
Taking this string:
```
string = "Let's print "Happines" out"
```
If you want to mix quotes, use the triple single quotes:
```
>>> string = '''Let's print "Happines" out'''
>>> print(string)
Let's print "Happines" out
```
Using triple quotes is acceptable too:
```
>>> string = """Let's print "Happines" out"""
>>> print(string)
Let's print "Happines" out
```
|
61,501,891
|
I have an issue with Rsyslog's 'omprog' module when trying to get it to interact with my python (2.7) code. Rsyslog is supposed to send desired messages to python's stdin, yet it does not receive anything. I wonder if anyone else has had better success with this output module?
**Rsyslog.conf**
```
module(load="omprog")
template(name="sshmsg" type="string" string="%msg%")
if ($programname == "myprogram") then {
action(type="omprog"
binary="/usr/sshtrack.py"
template="sshmsg")
}
```
If I replace the binary with a test shell script containing a line below, it works
**test.sh**
```
!#/bin/sh
cat /dev/stdin >> /var/log/ssh2.log
```
I also tried reading stdin in the shell script into a variable using
```
var="$(</dev/stdin)"
```
**and**
```
var="$(cat /dev/stdin)"
```
Neither of the above resulted *var* containing anything
Finally, when trying to read stdin from python script, I get nothing. Sometimes, it says resource unavailable (errno 11) error message.
**sshtrack.py**
```
#!/usr/bin/python
import sys
f = open("/var/log/ssh2.log", "a", 0)
while True:
f.write("Starting\n")
for line in sys.stdin:
f.flush()
msg = line.strip()
if not msg:
break
f.write(msg)
f.write("\n")
f.close()
```
The issue seems similar to [can not read correctly from STDIN](https://stackoverflow.com/questions/9438200/can-not-read-correctly-from-stdin) except adding a non-block flag did nothing.
|
2020/04/29
|
[
"https://Stackoverflow.com/questions/61501891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10192040/"
] |
Here is one approach using `tidyverse`. You can `group_by(Species)` and set `Method` to "Both" if both Bottom fishing and Trolling are included in Method within that Species. Then afterwards, you can `group_by` both Species and Method, and use `fill` to replace `NA` with known values. In the end, use `slice` to keep one row for each Species/Method. This assumes you would have otherwise 1 row for each Species/Method - please let me know if this is not the case.
```
library(tidyverse)
fish_catch %>%
group_by(Species) %>%
mutate(Method = ifelse(all(c("Bottom fishing", "Trolling") %in% Method), "Both", as.character(Method))) %>%
group_by(Species, Method) %>%
fill(c(Bait, Released, Kept), .direction = "updown") %>%
slice(1)
```
**Output**
```
# A tibble: 9 x 5
# Groups: Species, Method [9]
Species Method Bait Released Kept
<chr> <chr> <int> <int> <int>
1 Aethaloperca rogaa Bottom fishing NA NA 2
2 Aprion virescens Bottom fishing NA NA 1
3 Balistidae spp. Bottom fishing NA NA 1
4 Caranx ignobilis Both NA 1 1
5 Epinephelus fasciatus Bottom fishing NA 3 NA
6 Epinephelus multinotatus Bottom fishing NA NA 5
7 Other species Bottom fishing NA 1 NA
8 Thunnus albacares Trolling NA NA 1
9 Variola louti Bottom fishing NA NA 1
```
|
This should get you started. You can add the other columns to the summarize function.
```
library(tidyverse)
fish_catch %>% select(-Bait, -Released, -Kept) %>%
group_by(Species) %>%
summarize(Method = paste0(Method, collapse = "")) %>%
mutate(Method = fct_recode(Method, "both" = "TrollingBottom fishing"))
# A tibble: 9 x 2
Species Method
<chr> <fct>
1 Aethaloperca rogaa Bottom fishing
2 Aprion virescens Bottom fishing
3 Balistidae spp. Bottom fishing
4 Caranx ignobilis both
5 Epinephelus fasciatus Bottom fishing
6 Epinephelus multinotatus Bottom fishing
7 Other species Bottom fishing
8 Thunnus albacares Trolling
9 Variola louti Bottom fishing
```
|
8,011,017
|
Simple problem, how to find the first non-zero digit after decimal point. What I really need is the distance between the decimal point and the first non-zero digit.
I know I could do it with a few lines but I'd like to have some pythonic, nice and clean way to solve this.
So far I have this
```
>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]
```
|
2011/11/04
|
[
"https://Stackoverflow.com/questions/8011017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181337/"
] |
The easiest way seems to be
```
x = 123.0
dist = int(math.log10(abs(x)))
```
I interpreted the second entry in each pair of the list `t` as your desired result, so I chose `int()` to round the logarithm towards zero:
```
>>> [(int(math.log10(abs(x))), y) for x, y in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, -1), (-4, -4)]
```
|
One way to focus on the digits after the decimal point is to remove the integer part of the number, leaving on the fractional part, with something like `x - int(x)`.
Having isolated the fractional part, you could let python do the counting for you with a `%e` presentation (that also helps take care of rounding issues).
```
>>> '%e' % 0.000125
'1.250000e-04'
>>> int(_.partition('-')[2]) - 1
3
```
|
8,011,017
|
Simple problem, how to find the first non-zero digit after decimal point. What I really need is the distance between the decimal point and the first non-zero digit.
I know I could do it with a few lines but I'd like to have some pythonic, nice and clean way to solve this.
So far I have this
```
>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]
```
|
2011/11/04
|
[
"https://Stackoverflow.com/questions/8011017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181337/"
] |
The easiest way seems to be
```
x = 123.0
dist = int(math.log10(abs(x)))
```
I interpreted the second entry in each pair of the list `t` as your desired result, so I chose `int()` to round the logarithm towards zero:
```
>>> [(int(math.log10(abs(x))), y) for x, y in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, -1), (-4, -4)]
```
|
While this can technically be done with one line (excluding the import statement), I added a few extra things to make it more complete.
```
from re import search
# Assuming number is already defined.
# Floats always have a decimal in its string representation.
if isinstance(float, number):
# This gets the substring of zeros immediately following the decimal point
# and returns the length of it.
return len(search("\.(0*)", "5.00060030").group(1))
else:
return -1
# or you can use raise TypeError() if you wanna be more restrictive.
```
This probably isn't of any concern to you but I thought I'd mention it for sake of completeness, in some regions, periods and commas are swapped when it comes to numbers. For example 1,000,000.00 could be 1.000.000,00. Not sure if Python acknowledges this but since it doesn't represent any numbers with thousands separators, you could use the pattern `,(0*)` for the other regions. Again, probably doesn't matter to you but it may to other readers.
|
8,011,017
|
Simple problem, how to find the first non-zero digit after decimal point. What I really need is the distance between the decimal point and the first non-zero digit.
I know I could do it with a few lines but I'd like to have some pythonic, nice and clean way to solve this.
So far I have this
```
>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]
```
|
2011/11/04
|
[
"https://Stackoverflow.com/questions/8011017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181337/"
] |
The easiest way seems to be
```
x = 123.0
dist = int(math.log10(abs(x)))
```
I interpreted the second entry in each pair of the list `t` as your desired result, so I chose `int()` to round the logarithm towards zero:
```
>>> [(int(math.log10(abs(x))), y) for x, y in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, -1), (-4, -4)]
```
|
```
import math
ZerosCount = math.ceil(-math.log10(abs(value) - abs(math.floor(value)))) - 1
```
|
8,011,017
|
Simple problem, how to find the first non-zero digit after decimal point. What I really need is the distance between the decimal point and the first non-zero digit.
I know I could do it with a few lines but I'd like to have some pythonic, nice and clean way to solve this.
So far I have this
```
>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]
```
|
2011/11/04
|
[
"https://Stackoverflow.com/questions/8011017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181337/"
] |
One way to focus on the digits after the decimal point is to remove the integer part of the number, leaving on the fractional part, with something like `x - int(x)`.
Having isolated the fractional part, you could let python do the counting for you with a `%e` presentation (that also helps take care of rounding issues).
```
>>> '%e' % 0.000125
'1.250000e-04'
>>> int(_.partition('-')[2]) - 1
3
```
|
While this can technically be done with one line (excluding the import statement), I added a few extra things to make it more complete.
```
from re import search
# Assuming number is already defined.
# Floats always have a decimal in its string representation.
if isinstance(float, number):
# This gets the substring of zeros immediately following the decimal point
# and returns the length of it.
return len(search("\.(0*)", "5.00060030").group(1))
else:
return -1
# or you can use raise TypeError() if you wanna be more restrictive.
```
This probably isn't of any concern to you but I thought I'd mention it for sake of completeness, in some regions, periods and commas are swapped when it comes to numbers. For example 1,000,000.00 could be 1.000.000,00. Not sure if Python acknowledges this but since it doesn't represent any numbers with thousands separators, you could use the pattern `,(0*)` for the other regions. Again, probably doesn't matter to you but it may to other readers.
|
8,011,017
|
Simple problem, how to find the first non-zero digit after decimal point. What I really need is the distance between the decimal point and the first non-zero digit.
I know I could do it with a few lines but I'd like to have some pythonic, nice and clean way to solve this.
So far I have this
```
>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]
```
|
2011/11/04
|
[
"https://Stackoverflow.com/questions/8011017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181337/"
] |
One way to focus on the digits after the decimal point is to remove the integer part of the number, leaving on the fractional part, with something like `x - int(x)`.
Having isolated the fractional part, you could let python do the counting for you with a `%e` presentation (that also helps take care of rounding issues).
```
>>> '%e' % 0.000125
'1.250000e-04'
>>> int(_.partition('-')[2]) - 1
3
```
|
```
import math
ZerosCount = math.ceil(-math.log10(abs(value) - abs(math.floor(value)))) - 1
```
|
8,011,017
|
Simple problem, how to find the first non-zero digit after decimal point. What I really need is the distance between the decimal point and the first non-zero digit.
I know I could do it with a few lines but I'd like to have some pythonic, nice and clean way to solve this.
So far I have this
```
>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]
```
|
2011/11/04
|
[
"https://Stackoverflow.com/questions/8011017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181337/"
] |
While this can technically be done with one line (excluding the import statement), I added a few extra things to make it more complete.
```
from re import search
# Assuming number is already defined.
# Floats always have a decimal in its string representation.
if isinstance(float, number):
# This gets the substring of zeros immediately following the decimal point
# and returns the length of it.
return len(search("\.(0*)", "5.00060030").group(1))
else:
return -1
# or you can use raise TypeError() if you wanna be more restrictive.
```
This probably isn't of any concern to you but I thought I'd mention it for sake of completeness, in some regions, periods and commas are swapped when it comes to numbers. For example 1,000,000.00 could be 1.000.000,00. Not sure if Python acknowledges this but since it doesn't represent any numbers with thousands separators, you could use the pattern `,(0*)` for the other regions. Again, probably doesn't matter to you but it may to other readers.
|
```
import math
ZerosCount = math.ceil(-math.log10(abs(value) - abs(math.floor(value)))) - 1
```
|
46,215,954
|
I get a .csv file with values inside and one of the columns contains durations in the format hh:mm:ss for example 06:42:13 (6 hours, 42 minutes and 13 seconds). Now I want to compare this time with a given time for example 00:00:00 because I have to handle the information in that row different.
time is the value I got out of the .csv file
```
if time == 00:00:00:
do something
else:
do something different
```
Thats what I want but it obviously doesn't work how I did it. I thought python stored the time as a String but when i compared it like this:
```
if time == "00:00:00":
```
it didn't work either.
Thats how I get the values out of the .csv file:
```
import csv
import_list = []
with open("input.csv", "r") as csvfile:
inputreader = csv.reader(csvfile, delimiter=';')
for row in inputreader:
import_list.append(row)
```
The .csv file looks like this:
```
Name; Duration; Tests; Warnings; Errors
Test1; 06:42:13; 2000; 2; 1
Test2; 00:00:00; 0; 0; 0
```
and so on.
|
2017/09/14
|
[
"https://Stackoverflow.com/questions/46215954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8592446/"
] |
Do this instead:
```
if time.strip() == "00:00:00":
do something
else:
do something different
```
|
Instead of doing string comparisions, using inbuilt `datetime` library to create datetime objects. Use [`datetime.strptime`](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior) to convert date string.
|
46,215,954
|
I get a .csv file with values inside and one of the columns contains durations in the format hh:mm:ss for example 06:42:13 (6 hours, 42 minutes and 13 seconds). Now I want to compare this time with a given time for example 00:00:00 because I have to handle the information in that row different.
time is the value I got out of the .csv file
```
if time == 00:00:00:
do something
else:
do something different
```
Thats what I want but it obviously doesn't work how I did it. I thought python stored the time as a String but when i compared it like this:
```
if time == "00:00:00":
```
it didn't work either.
Thats how I get the values out of the .csv file:
```
import csv
import_list = []
with open("input.csv", "r") as csvfile:
inputreader = csv.reader(csvfile, delimiter=';')
for row in inputreader:
import_list.append(row)
```
The .csv file looks like this:
```
Name; Duration; Tests; Warnings; Errors
Test1; 06:42:13; 2000; 2; 1
Test2; 00:00:00; 0; 0; 0
```
and so on.
|
2017/09/14
|
[
"https://Stackoverflow.com/questions/46215954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8592446/"
] |
Try it like this:
```
if time == " 00:00:00":
...
```
You have a trailing space at the beginning.
Alternatively you can change your code into this:
```
import csv
import_list = []
with open("input.csv", "r") as csvfile:
inputreader = csv.reader(csvfile, delimiter=';')
for row in inputreader:
import_list.append([item.strip() for item in row])
```
|
Do this instead:
```
if time.strip() == "00:00:00":
do something
else:
do something different
```
|
46,215,954
|
I get a .csv file with values inside and one of the columns contains durations in the format hh:mm:ss for example 06:42:13 (6 hours, 42 minutes and 13 seconds). Now I want to compare this time with a given time for example 00:00:00 because I have to handle the information in that row different.
time is the value I got out of the .csv file
```
if time == 00:00:00:
do something
else:
do something different
```
Thats what I want but it obviously doesn't work how I did it. I thought python stored the time as a String but when i compared it like this:
```
if time == "00:00:00":
```
it didn't work either.
Thats how I get the values out of the .csv file:
```
import csv
import_list = []
with open("input.csv", "r") as csvfile:
inputreader = csv.reader(csvfile, delimiter=';')
for row in inputreader:
import_list.append(row)
```
The .csv file looks like this:
```
Name; Duration; Tests; Warnings; Errors
Test1; 06:42:13; 2000; 2; 1
Test2; 00:00:00; 0; 0; 0
```
and so on.
|
2017/09/14
|
[
"https://Stackoverflow.com/questions/46215954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8592446/"
] |
Try it like this:
```
if time == " 00:00:00":
...
```
You have a trailing space at the beginning.
Alternatively you can change your code into this:
```
import csv
import_list = []
with open("input.csv", "r") as csvfile:
inputreader = csv.reader(csvfile, delimiter=';')
for row in inputreader:
import_list.append([item.strip() for item in row])
```
|
Instead of doing string comparisions, using inbuilt `datetime` library to create datetime objects. Use [`datetime.strptime`](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior) to convert date string.
|
22,599,617
|
How do i fix this error, this is the message that i get:
```none
Traceback (most recent call last):
File "C:\Users\Games\Desktop\hendeagon.py", line 28, in <module>
font = pygame.font.SysFont(None, 48)
File "C:\Python33\lib\site-packages\pygame\sysfont.py", line 614, in SysFont
return constructor(fontname, size, set_bold, set_italic)
File "C:\Python33\lib\site-packages\pygame\sysfont.py", line 537, in font_constructor
font = pygame.font.Font(fontpath, size)
pygame.error: font not initialized
```
i need this error fixed for homework by tomorrow.
```python
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
TEXTCOLOR = (255, 255, 255)
WINDOWWIDTH = 500
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
font = pygame.font.SysFont('comicsansms', 48)
basicFont = pygame.font.SysFont(None, 42)
drawText('8', font, windowSurface, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))
windowSurface.fill(BLACK)
pygame.draw.polygon(windowSurface, GREEN, ((158, 80), (181, 88), (214, 111), (229, 153), (216, 191), (181, 212), (135, 207), (102, 181), (89, 149), (102, 109), (130,88)))
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK
del pixArray
windowSurface.blit(text, textRect)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
```
Thank you for attempting to fix this problem that i am having in pygame
|
2014/03/24
|
[
"https://Stackoverflow.com/questions/22599617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3453049/"
] |
[`.attr()`](https://api.jquery.com/attr/) is for HTML attributes, not for CSS properties.
You're looking for [`.css()`](http://api.jquery.com/css/):
```
var cssProp = $(this).css('text-decoration'); // Gets the CSS property's value
$(this).css('text-decoration', 'line-through'); // Sets the CSS property's value
```
|
Text decoration isn't an attribute it's a CSS value. Attributes are things like href, class and id on an HTML element.
Try this:
```
$(this).css("text-decoration", "line-through");
```
|
68,171,360
|
I am trying to create a Neural Network class made up of Neuron objects wired together.
My Neuron class has
1. **Dendrites**
The number of dendrites is specified in the parameters when the class is initialised. The Dendrites are stored in a list whose index stores the voltages of each Dendrite.
eg: `neuron1.dendrites[2]=0.12` volts.
2. **Activation (Threshold) Potential**
The sum of all the dendrite potentials provides the neuron potential. If this potential exceeds the Threshold Potential, my Neuron will fire. There are other neurons connected to the axon of my neuron. The Axon of my Neuron connects to the Dendrites of other Neuron objects. Several Dendrites from other Neurons may connect to the Axon of my Neuron. They will all receive a fixed voltage (outputVoltage) when my Neuron fires. It fires in an All-or-Nothing manner.
3. **Firing state**
When the the Activation Potential is reached, the firing state = on (True)
4. My Neuron class also has a **setConnections()** method. This method receives a python `list` of Dendrites. In this method, I wish to iterate through my internal list of external Dendrites and reset their voltage values. ***This is not working. I cannot figure out why and so seek assistance here.***
I provide a stripped down version of my code below:
```
import threading
class Neuron:
def __init__(self, dendrites, activation_Pot=0.24):
"""
Create a dendrites[] array.
Each element of this array represents the voltage of that dendrite.
We can then loop through the array to sum up the signal strength.
If the signal strength exceeds the Activation potential, then the all-or-nothing threshold has been breached and
we can transmit our signal along the axon.
"""
self.dendrites = [0]*dendrites
self.InputPotential = 0 # This variable will store the sum of all the dendrite voltages. It is being initialised here.
self.activation_Pot = activation_Pot
self.on = True
self.off = False
self.voltsOut = 0.12 # This constant dictates the potential of the axon when the neuron is firing.
self.outputPotential = 0 # This variable SETS the potential of the single axon when the threshold activation potential of the neuron has been reached and the neuron is firing.
self.firing = self.off
self.axonConnections = []
# Launch a thread to check on a timer the sum of all dendrite inputs and fire when output > Activation Potential.
t1 = threading.Thread(target = self.start, args=[])
t1.start()
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
for outputDendrites in self.axonConnections:
outputDendrites = self.outputPotential
def stopFiring(self):
self.outputPotential = 0
self.firing = self.off
print("Neuron has STOPPED firing!")
def setActivation_Pot(self, activation_Pot):
if (activation_Pot >= 0) and (activation_Pot <=1):
self.activation_Pot = activation_Pot
else:
print("activation_Pot value needs to be between 0 and 1")
print("activation_Pot has not been reset.")
print("Please consider re-inputting a valid value.")
def getActivation_Pot(self):
return self.activation_Pot
def setAxonConnections(self, axonConnections):
self.axonConnections = axonConnections
def getAxonConnections(self):
return self.axonConnections
def start(self):
while True:
while True:
self.InputPotential = 0
for dendrite in self.dendrites:
self.InputPotential+=dendrite
if self.InputPotential >= self.activation_Pot:
self.fire()
break
while True:
self.InputPotential = 0
for dendrite in self.dendrites:
self.InputPotential+=dendrite
if self.InputPotential < self.activation_Pot:
self.stopFiring()
break
```
Here is the relevant code from the from the main.py script which is testing the Neuron class:
```
from neuron import Neuron
# Instantiate transmitting neurone...
n0 = Neuron(3, 0.36)
# Instantiate receiving neurones...
n1 = Neuron(3, 0.36)
n2 = Neuron(3, 0.36)
n3 = Neuron(3, 0.36)
# Make the connections: I do this by creating storing my external Dendrites into a list
# and passing that list to the transmitting neuron for it to update the voltages
# of each of these neurons. BUT THESE LIST VARIABLES ARE NOT GETTING UPDATED...
axonConns = [n1.dendrites[0], n2.dendrites[1], n3.dendrites[2]]
n0.setAxonConnections(axonConns) # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED!!
n0.fire() # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED by this fire() method!!
```
I hope that makes sense. In summary: I am passing a list of variables from my main.py script at the line `n0.setAxonConnections(axonConns)`. The variables in this list are not getting updated by the `neuron.fire()` method of my Neuron class. Can someone please explain why? Forgive me, I am a python newbe!
|
2021/06/29
|
[
"https://Stackoverflow.com/questions/68171360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5618307/"
] |
Might not be the best solution, but just my 2c. If you want the other neuron's dendrites to be updated as well, you can declare the connections like so:
```
axonConns = [(n1.dendrites, 0), (n2.dendrites, 1), (n3.dendrites, 2)]
```
You need to pass the list of the dendrites itself, and define which of the dendrites are to be considered in the connection by index. Then change the `fire` method to take the index into account:
```
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
for dendrites, index in self.axonConnections:
dendrites[index] = self.outputPotential
```
EDIT:
To demonstrate why OP's answer is not enough to update neurons outside `fire()`
```
In [1]: x = [1, 2, 3]
...:
...: def foo(val):
...: potential = 100
...: for i in range(len(val)):
...: val[i] = potential
...: return val
...:
...: print(x)
...: print(foo([x[0], x[1], x[2]]))
...: print(x)
...:
[1, 2, 3]
[100, 100, 100]
[1, 2, 3]
```
|
You aren't properly reassigning the values of outputDendrites in your class method.
```
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
# Store the axonConnections into a temporary list for parsing since we'll be changing the values WHILE interating
initial_axonConnections_list = self.axonConnections
for index, outputDendrites in enumerate(initial_axonConnections_list):
outputDendrites = self.outputPotential
# We have stored the value in outputDendrites, but we're not doing anything with it, we have to assign it
self.axonConnections[index] = outputDendrites
```
|
68,171,360
|
I am trying to create a Neural Network class made up of Neuron objects wired together.
My Neuron class has
1. **Dendrites**
The number of dendrites is specified in the parameters when the class is initialised. The Dendrites are stored in a list whose index stores the voltages of each Dendrite.
eg: `neuron1.dendrites[2]=0.12` volts.
2. **Activation (Threshold) Potential**
The sum of all the dendrite potentials provides the neuron potential. If this potential exceeds the Threshold Potential, my Neuron will fire. There are other neurons connected to the axon of my neuron. The Axon of my Neuron connects to the Dendrites of other Neuron objects. Several Dendrites from other Neurons may connect to the Axon of my Neuron. They will all receive a fixed voltage (outputVoltage) when my Neuron fires. It fires in an All-or-Nothing manner.
3. **Firing state**
When the the Activation Potential is reached, the firing state = on (True)
4. My Neuron class also has a **setConnections()** method. This method receives a python `list` of Dendrites. In this method, I wish to iterate through my internal list of external Dendrites and reset their voltage values. ***This is not working. I cannot figure out why and so seek assistance here.***
I provide a stripped down version of my code below:
```
import threading
class Neuron:
def __init__(self, dendrites, activation_Pot=0.24):
"""
Create a dendrites[] array.
Each element of this array represents the voltage of that dendrite.
We can then loop through the array to sum up the signal strength.
If the signal strength exceeds the Activation potential, then the all-or-nothing threshold has been breached and
we can transmit our signal along the axon.
"""
self.dendrites = [0]*dendrites
self.InputPotential = 0 # This variable will store the sum of all the dendrite voltages. It is being initialised here.
self.activation_Pot = activation_Pot
self.on = True
self.off = False
self.voltsOut = 0.12 # This constant dictates the potential of the axon when the neuron is firing.
self.outputPotential = 0 # This variable SETS the potential of the single axon when the threshold activation potential of the neuron has been reached and the neuron is firing.
self.firing = self.off
self.axonConnections = []
# Launch a thread to check on a timer the sum of all dendrite inputs and fire when output > Activation Potential.
t1 = threading.Thread(target = self.start, args=[])
t1.start()
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
for outputDendrites in self.axonConnections:
outputDendrites = self.outputPotential
def stopFiring(self):
self.outputPotential = 0
self.firing = self.off
print("Neuron has STOPPED firing!")
def setActivation_Pot(self, activation_Pot):
if (activation_Pot >= 0) and (activation_Pot <=1):
self.activation_Pot = activation_Pot
else:
print("activation_Pot value needs to be between 0 and 1")
print("activation_Pot has not been reset.")
print("Please consider re-inputting a valid value.")
def getActivation_Pot(self):
return self.activation_Pot
def setAxonConnections(self, axonConnections):
self.axonConnections = axonConnections
def getAxonConnections(self):
return self.axonConnections
def start(self):
while True:
while True:
self.InputPotential = 0
for dendrite in self.dendrites:
self.InputPotential+=dendrite
if self.InputPotential >= self.activation_Pot:
self.fire()
break
while True:
self.InputPotential = 0
for dendrite in self.dendrites:
self.InputPotential+=dendrite
if self.InputPotential < self.activation_Pot:
self.stopFiring()
break
```
Here is the relevant code from the from the main.py script which is testing the Neuron class:
```
from neuron import Neuron
# Instantiate transmitting neurone...
n0 = Neuron(3, 0.36)
# Instantiate receiving neurones...
n1 = Neuron(3, 0.36)
n2 = Neuron(3, 0.36)
n3 = Neuron(3, 0.36)
# Make the connections: I do this by creating storing my external Dendrites into a list
# and passing that list to the transmitting neuron for it to update the voltages
# of each of these neurons. BUT THESE LIST VARIABLES ARE NOT GETTING UPDATED...
axonConns = [n1.dendrites[0], n2.dendrites[1], n3.dendrites[2]]
n0.setAxonConnections(axonConns) # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED!!
n0.fire() # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED by this fire() method!!
```
I hope that makes sense. In summary: I am passing a list of variables from my main.py script at the line `n0.setAxonConnections(axonConns)`. The variables in this list are not getting updated by the `neuron.fire()` method of my Neuron class. Can someone please explain why? Forgive me, I am a python newbe!
|
2021/06/29
|
[
"https://Stackoverflow.com/questions/68171360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5618307/"
] |
By playing around with the following code in python, I thought I had found a solution:
```py
def changeListVars(n):
for i in range(len(n)):
n[i] = n[i]+5
print()
print(n)
x=1
y=2
z=3
m = [x,y,z]
print(len(m))
for i in range(len(m)):
print (m[i])
changeListVars(m)
print()
print(m)
```
The output of above was:
```
3
1
2
3
[6, 7, 8]
[6, 7, 8]
```
Initially, this appears to work. Therefore to fix my code, I amended the two lines:
```py
for i in range(len(self.axonConnections)):
self.axonConnections[i] = self.outputPotential
```
so my new `fire()` method reads as follows:
```py
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
for i in range(len(self.axonConnections)):
self.axonConnections[i] = self.outputPotential
```
The results of the above experiment CLEARLY indicate that python DOES indeed pass variables of a list, *by reference*, by default when passed in an argument.
HOWEVER (thanks to @bdbd) I discovered that the elements of the list remained unchanged. So for example,
```py
print(x, y, z)
```
yields
```py
1 2 3
```
It also means that in my code, while the `axonConn` array (which stores a list of the external dendrite voltages) was getting updated, the dendrites themselves were not getting updated.
After some research and experimentation, I have finally solved the conundrum. First some [necessary background reading](https://web.archive.org/web/20200629063521/http://effbot.org/zone/python-objects.htm):
>
> All Python objects have:
>
>
> 1. a unique identity (an integer, returned by id(x))
> 2. a type (returned by type(x))
> 3. some content
>
>
> You cannot change the identity!
>
>
> You cannot change the type!
>
>
> Some objects allow you to change their content (without changing the
> identity or the type, that is). These are mutable data types and
> include 'list's for example
>
>
> Most objects do not (eg: `string`, `integer`, `tuple`, etc...)
>
>
>
I finally conclude:
1. **python ALWAYS passes by reference!**
2. However, certain data types are immutable (strings, integers, etc..)
3. When references to those are passed to a function; any manipulation of those variables will necessitate a duplicate being made of the variable to store the result of the manipulation.
4. Any duplication of a variable leads to a new reference being created to point to the new value. This is explained well [here](https://web.archive.org/web/20200629063521/http://effbot.org/zone/python-objects.htm).
5. As such, when this happens, the calling function no longer sees the manipulated result. This is because there is no way to re-assign the reference of the argument of the calling function to point to the the new reference. Once the contents of a variable have had to be duplicated, the calling function no longer sees it as the new contents has a new reference.
6. This means mutables such as `list`s can be appended and retain the same reference -hence it appears as if they had been passed by reference.
7. But immutables such as `strings` and `integers` will lose their references following a manipulation because a new object (`string` or `integer` for example) has to be created with that new value. The new object will always have a new reference! *Hence, in these scenarios, the function call will **behave** as if it has been **passed by value!**.*
I provide some code below which illustrates this well:
```py
'''
The results of this block of code suggest that python passes by value.
However, in truth, the output of the code PROVES a reference is passed!
But because the variable's data type is immutable, a new object is created within the function with a NEW reference.
The upshot of this being, behaviour which seems to show that the argument is passed by value, when this is not strictly the case.
'''
# EXAMPLE 1:
class PassByReference:
def __init__(self):
self.variable = 1
print("BEFORE function call, self.variable = " + str(self.variable))
print("BEFORE function call, id(self.variable) = " + str(id(self.variable)))
self.change(self.variable)
print("AFTER function call, self.variable = " + str(self.variable))
print("AFTER function call, id(self.variable) = " + str(id(self.variable)))
def change(self, var):
print("INSIDE modifying function, var TO BE incremented! id(var) BEFORE incrementing = " + str(id(var)))
var = var + 1
print("INSIDE modifying function, var incremented! Now, var = " + str(var))
print("INSIDE modifying function, AFTER var incremented! id(var) AFTER incrementing = " + str(id(var)))
p = PassByReference()
```
Here are further examples which demonstrate the same finding:
```py
'''
The results of all the examples below suggest that python passes by value.
However, in truth, the output of each block of code PROVES a reference is passed!
Where the variable data type is immutable, a new object is created within the function with a NEW reference. The upshot of this being, behaviour which seems to show that the argument is passed by value, when this is not strictly the case.
Where the data type is mutable, the output clearly identifies that the arguments have been passed by reference and have been successfully mutated without losing their object reference so that "By Reference" behaviour manifests.
'''
# EXAMPLE 2:
def changeListVars2(n):
print("From inside the function, BEFORE incrementing n, id(n) = " + str(id(n)))
n = n + 5
print("From inside the function, n = " + str(n))
print("From inside the function, AFTER incrementing n, id(n) = " + str(id(n)))
m = 1
print("Before function call, m = " + str(m))
print("id(m) = " + str(id(m)))
changeListVars2(m)
print("After function call, m = " + str(m))
print("id(m) = " + str(id(m)))
# EXAMPLE 3:
def changeListVars(n):
for i in range(len(n)):
n[i] = n[i]+5
print("From inside the function, n = " + str(n))
x = 1
y = 2
z = 3
m = [x, y, z]
print("Before function call, m = " + str(m))
print("id(x) = " + str(id(x)))
print("id(m) = " + str(id(m)))
changeListVars(m)
print("After function call, m = " + str(m))
print("After function call, id(m) = " + str(id(m)))
print("After function call: [x=" + str(x) + ", y=" + str(y) + ", z=" + str(z) + "]")
print("After function call, id(x) = " + str(id(x)))
print() #a new line to seperate output from the two blocks of code
print() #a new line to seperate output from the two blocks of code
print("ChangeListVars2:")
# EXAMPLE 4:
def swap(a, b):
x = a
print ("id(x) = " + str(id(x)))
print ("id(a) = " + str(id(a)))
print ("id(b) = " + str(id(b)))
a = b
print ("id(a) = " + str(id(a)))
b = x
print ("id(b) = " + str(id(b)))
a[0]= '20'
var1 = ['1','2','3','4']
var2 = ['5','6','7','8','9']
print ("id(var1) = " + str(id(var1)))
print ("id(var2) = " + str(id(var2)))
print()
swap(var1, var2)
print()
print ("id(var1 = )" + str(id(var1)))
print ("id(var2 = )" + str(id(var2)))
print ("var1 = " + str(var1))
print ("var2 = " + str(var2))
```
|
You aren't properly reassigning the values of outputDendrites in your class method.
```
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
# Store the axonConnections into a temporary list for parsing since we'll be changing the values WHILE interating
initial_axonConnections_list = self.axonConnections
for index, outputDendrites in enumerate(initial_axonConnections_list):
outputDendrites = self.outputPotential
# We have stored the value in outputDendrites, but we're not doing anything with it, we have to assign it
self.axonConnections[index] = outputDendrites
```
|
68,171,360
|
I am trying to create a Neural Network class made up of Neuron objects wired together.
My Neuron class has
1. **Dendrites**
The number of dendrites is specified in the parameters when the class is initialised. The Dendrites are stored in a list whose index stores the voltages of each Dendrite.
eg: `neuron1.dendrites[2]=0.12` volts.
2. **Activation (Threshold) Potential**
The sum of all the dendrite potentials provides the neuron potential. If this potential exceeds the Threshold Potential, my Neuron will fire. There are other neurons connected to the axon of my neuron. The Axon of my Neuron connects to the Dendrites of other Neuron objects. Several Dendrites from other Neurons may connect to the Axon of my Neuron. They will all receive a fixed voltage (outputVoltage) when my Neuron fires. It fires in an All-or-Nothing manner.
3. **Firing state**
When the the Activation Potential is reached, the firing state = on (True)
4. My Neuron class also has a **setConnections()** method. This method receives a python `list` of Dendrites. In this method, I wish to iterate through my internal list of external Dendrites and reset their voltage values. ***This is not working. I cannot figure out why and so seek assistance here.***
I provide a stripped down version of my code below:
```
import threading
class Neuron:
def __init__(self, dendrites, activation_Pot=0.24):
"""
Create a dendrites[] array.
Each element of this array represents the voltage of that dendrite.
We can then loop through the array to sum up the signal strength.
If the signal strength exceeds the Activation potential, then the all-or-nothing threshold has been breached and
we can transmit our signal along the axon.
"""
self.dendrites = [0]*dendrites
self.InputPotential = 0 # This variable will store the sum of all the dendrite voltages. It is being initialised here.
self.activation_Pot = activation_Pot
self.on = True
self.off = False
self.voltsOut = 0.12 # This constant dictates the potential of the axon when the neuron is firing.
self.outputPotential = 0 # This variable SETS the potential of the single axon when the threshold activation potential of the neuron has been reached and the neuron is firing.
self.firing = self.off
self.axonConnections = []
# Launch a thread to check on a timer the sum of all dendrite inputs and fire when output > Activation Potential.
t1 = threading.Thread(target = self.start, args=[])
t1.start()
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
for outputDendrites in self.axonConnections:
outputDendrites = self.outputPotential
def stopFiring(self):
self.outputPotential = 0
self.firing = self.off
print("Neuron has STOPPED firing!")
def setActivation_Pot(self, activation_Pot):
if (activation_Pot >= 0) and (activation_Pot <=1):
self.activation_Pot = activation_Pot
else:
print("activation_Pot value needs to be between 0 and 1")
print("activation_Pot has not been reset.")
print("Please consider re-inputting a valid value.")
def getActivation_Pot(self):
return self.activation_Pot
def setAxonConnections(self, axonConnections):
self.axonConnections = axonConnections
def getAxonConnections(self):
return self.axonConnections
def start(self):
while True:
while True:
self.InputPotential = 0
for dendrite in self.dendrites:
self.InputPotential+=dendrite
if self.InputPotential >= self.activation_Pot:
self.fire()
break
while True:
self.InputPotential = 0
for dendrite in self.dendrites:
self.InputPotential+=dendrite
if self.InputPotential < self.activation_Pot:
self.stopFiring()
break
```
Here is the relevant code from the from the main.py script which is testing the Neuron class:
```
from neuron import Neuron
# Instantiate transmitting neurone...
n0 = Neuron(3, 0.36)
# Instantiate receiving neurones...
n1 = Neuron(3, 0.36)
n2 = Neuron(3, 0.36)
n3 = Neuron(3, 0.36)
# Make the connections: I do this by creating storing my external Dendrites into a list
# and passing that list to the transmitting neuron for it to update the voltages
# of each of these neurons. BUT THESE LIST VARIABLES ARE NOT GETTING UPDATED...
axonConns = [n1.dendrites[0], n2.dendrites[1], n3.dendrites[2]]
n0.setAxonConnections(axonConns) # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED!!
n0.fire() # THE LIST VARIABLES OF THE axonConns LIST ARE NOT GETTING UPDATED by this fire() method!!
```
I hope that makes sense. In summary: I am passing a list of variables from my main.py script at the line `n0.setAxonConnections(axonConns)`. The variables in this list are not getting updated by the `neuron.fire()` method of my Neuron class. Can someone please explain why? Forgive me, I am a python newbe!
|
2021/06/29
|
[
"https://Stackoverflow.com/questions/68171360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5618307/"
] |
By playing around with the following code in python, I thought I had found a solution:
```py
def changeListVars(n):
for i in range(len(n)):
n[i] = n[i]+5
print()
print(n)
x=1
y=2
z=3
m = [x,y,z]
print(len(m))
for i in range(len(m)):
print (m[i])
changeListVars(m)
print()
print(m)
```
The output of above was:
```
3
1
2
3
[6, 7, 8]
[6, 7, 8]
```
Initially, this appears to work. Therefore to fix my code, I amended the two lines:
```py
for i in range(len(self.axonConnections)):
self.axonConnections[i] = self.outputPotential
```
so my new `fire()` method reads as follows:
```py
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
for i in range(len(self.axonConnections)):
self.axonConnections[i] = self.outputPotential
```
The results of the above experiment CLEARLY indicate that python DOES indeed pass variables of a list, *by reference*, by default when passed in an argument.
HOWEVER (thanks to @bdbd) I discovered that the elements of the list remained unchanged. So for example,
```py
print(x, y, z)
```
yields
```py
1 2 3
```
It also means that in my code, while the `axonConn` array (which stores a list of the external dendrite voltages) was getting updated, the dendrites themselves were not getting updated.
After some research and experimentation, I have finally solved the conundrum. First some [necessary background reading](https://web.archive.org/web/20200629063521/http://effbot.org/zone/python-objects.htm):
>
> All Python objects have:
>
>
> 1. a unique identity (an integer, returned by id(x))
> 2. a type (returned by type(x))
> 3. some content
>
>
> You cannot change the identity!
>
>
> You cannot change the type!
>
>
> Some objects allow you to change their content (without changing the
> identity or the type, that is). These are mutable data types and
> include 'list's for example
>
>
> Most objects do not (eg: `string`, `integer`, `tuple`, etc...)
>
>
>
I finally conclude:
1. **python ALWAYS passes by reference!**
2. However, certain data types are immutable (strings, integers, etc..)
3. When references to those are passed to a function; any manipulation of those variables will necessitate a duplicate being made of the variable to store the result of the manipulation.
4. Any duplication of a variable leads to a new reference being created to point to the new value. This is explained well [here](https://web.archive.org/web/20200629063521/http://effbot.org/zone/python-objects.htm).
5. As such, when this happens, the calling function no longer sees the manipulated result. This is because there is no way to re-assign the reference of the argument of the calling function to point to the the new reference. Once the contents of a variable have had to be duplicated, the calling function no longer sees it as the new contents has a new reference.
6. This means mutables such as `list`s can be appended and retain the same reference -hence it appears as if they had been passed by reference.
7. But immutables such as `strings` and `integers` will lose their references following a manipulation because a new object (`string` or `integer` for example) has to be created with that new value. The new object will always have a new reference! *Hence, in these scenarios, the function call will **behave** as if it has been **passed by value!**.*
I provide some code below which illustrates this well:
```py
'''
The results of this block of code suggest that python passes by value.
However, in truth, the output of the code PROVES a reference is passed!
But because the variable's data type is immutable, a new object is created within the function with a NEW reference.
The upshot of this being, behaviour which seems to show that the argument is passed by value, when this is not strictly the case.
'''
# EXAMPLE 1:
class PassByReference:
def __init__(self):
self.variable = 1
print("BEFORE function call, self.variable = " + str(self.variable))
print("BEFORE function call, id(self.variable) = " + str(id(self.variable)))
self.change(self.variable)
print("AFTER function call, self.variable = " + str(self.variable))
print("AFTER function call, id(self.variable) = " + str(id(self.variable)))
def change(self, var):
print("INSIDE modifying function, var TO BE incremented! id(var) BEFORE incrementing = " + str(id(var)))
var = var + 1
print("INSIDE modifying function, var incremented! Now, var = " + str(var))
print("INSIDE modifying function, AFTER var incremented! id(var) AFTER incrementing = " + str(id(var)))
p = PassByReference()
```
Here are further examples which demonstrate the same finding:
```py
'''
The results of all the examples below suggest that python passes by value.
However, in truth, the output of each block of code PROVES a reference is passed!
Where the variable data type is immutable, a new object is created within the function with a NEW reference. The upshot of this being, behaviour which seems to show that the argument is passed by value, when this is not strictly the case.
Where the data type is mutable, the output clearly identifies that the arguments have been passed by reference and have been successfully mutated without losing their object reference so that "By Reference" behaviour manifests.
'''
# EXAMPLE 2:
def changeListVars2(n):
print("From inside the function, BEFORE incrementing n, id(n) = " + str(id(n)))
n = n + 5
print("From inside the function, n = " + str(n))
print("From inside the function, AFTER incrementing n, id(n) = " + str(id(n)))
m = 1
print("Before function call, m = " + str(m))
print("id(m) = " + str(id(m)))
changeListVars2(m)
print("After function call, m = " + str(m))
print("id(m) = " + str(id(m)))
# EXAMPLE 3:
def changeListVars(n):
for i in range(len(n)):
n[i] = n[i]+5
print("From inside the function, n = " + str(n))
x = 1
y = 2
z = 3
m = [x, y, z]
print("Before function call, m = " + str(m))
print("id(x) = " + str(id(x)))
print("id(m) = " + str(id(m)))
changeListVars(m)
print("After function call, m = " + str(m))
print("After function call, id(m) = " + str(id(m)))
print("After function call: [x=" + str(x) + ", y=" + str(y) + ", z=" + str(z) + "]")
print("After function call, id(x) = " + str(id(x)))
print() #a new line to seperate output from the two blocks of code
print() #a new line to seperate output from the two blocks of code
print("ChangeListVars2:")
# EXAMPLE 4:
def swap(a, b):
x = a
print ("id(x) = " + str(id(x)))
print ("id(a) = " + str(id(a)))
print ("id(b) = " + str(id(b)))
a = b
print ("id(a) = " + str(id(a)))
b = x
print ("id(b) = " + str(id(b)))
a[0]= '20'
var1 = ['1','2','3','4']
var2 = ['5','6','7','8','9']
print ("id(var1) = " + str(id(var1)))
print ("id(var2) = " + str(id(var2)))
print()
swap(var1, var2)
print()
print ("id(var1 = )" + str(id(var1)))
print ("id(var2 = )" + str(id(var2)))
print ("var1 = " + str(var1))
print ("var2 = " + str(var2))
```
|
Might not be the best solution, but just my 2c. If you want the other neuron's dendrites to be updated as well, you can declare the connections like so:
```
axonConns = [(n1.dendrites, 0), (n2.dendrites, 1), (n3.dendrites, 2)]
```
You need to pass the list of the dendrites itself, and define which of the dendrites are to be considered in the connection by index. Then change the `fire` method to take the index into account:
```
def fire(self):
self.outputPotential = self.voltsOut
self.firing = self.on
print("Neuron is firing!")
for dendrites, index in self.axonConnections:
dendrites[index] = self.outputPotential
```
EDIT:
To demonstrate why OP's answer is not enough to update neurons outside `fire()`
```
In [1]: x = [1, 2, 3]
...:
...: def foo(val):
...: potential = 100
...: for i in range(len(val)):
...: val[i] = potential
...: return val
...:
...: print(x)
...: print(foo([x[0], x[1], x[2]]))
...: print(x)
...:
[1, 2, 3]
[100, 100, 100]
[1, 2, 3]
```
|
56,577,890
|
I am trying to run GitLab's job using their shared Runners,
I've created a `.gitlab-ci.yml` and kept it at my project's root,
Configured AWS creds as the environment variables -
```
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_DEFAULT_REGION
```
under `Settings -> CI / CD -> Variables`
[](https://i.stack.imgur.com/VUVkp.png)
Double checked the branch I've trying to build from is `protected`
**Following is my .gitlab-ci.yml -**
```
stages:
- build
build:
image: python:latest
stage: build
script:
- apt-get update
- apt-get install -y zip unzip
- pip install awscli
- mkdir ~/.aws/
- touch ~/.aws/credentials
- pip install awscli
- printf "[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\nregion = %s\n" "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" "$AWS_DEFAULT_REGION" >> ~/.aws/credentials
- bash cicdScript.sh
```
**CICD script has the aws command -**
```
$(aws s3 ls)
```
**But I still get the following error -**
```
Unable to locate credentials. You can configure credentials by running "aws configure".
```
**Reference -**
<https://medium.com/faun/continuous-static-upload-to-aws-s3-using-gitlab-runners-17f0260a5af2>
|
2019/06/13
|
[
"https://Stackoverflow.com/questions/56577890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433178/"
] |
You can use
```
- pip install awscli
- aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID
- aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY
- aws configure set region $AWS_DEFAULT_REGION
```
instead of
```
- mkdir ~/.aws/
- touch ~/.aws/credentials
- pip install awscli
- printf "[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\nregion = %s\n" "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" "$AWS_DEFAULT_REGION" >> ~/.aws/credentials
```
|
In your code, the profile is set to 'eb-cli' for your credentials
```
printf "[eb-cli]\naws_access_key_id = %s\naws_secret_access_key = %s\nregion = %s\n" "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" "$AWS_DEFAULT_REGION" >> ~/.aws/credentials
```
The command you should use is
```
aws s3 ls --profile eb-cli
```
If you dont pass the profile, [default] will be picked. Since default was not configured the issue is caused.
|
6,074,034
|
I wish to execute os.system('ls') in python. the return value of this statement is an error code integer..but I want to get the contents of the present directory as a string. How to accomplish this?
|
2011/05/20
|
[
"https://Stackoverflow.com/questions/6074034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748051/"
] |
[`os.listdir(".")`](http://docs.python.org/library/os.html#os.listdir)
---
In general, if you want to call a function and get the arguments, you should use [`subprocess.Popen()`](http://docs.python.org/library/subprocess.html#subprocess.Popen). But a lot of the basic directory stuff is in the `os` module so you don't have to do that.
|
Python as build-in functionality like os.listdir() or os.walk() for listing stuff
on the filesystem. Running 'ls' yourself is very bad-style. In general look at the documentation of the subprocess module giving you all flexibility for interacting with external commands.
|
69,563,630
|
I have a huge python list as the following example:
```
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
```
I would like to join this information in this formatting:
```
ls = ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellow cars.']
```
I have tried this code
```
with open ('names.txt', 'r') as text:
lines = text.readlines()
for index,line in enumerate(lines):
if not linha.startswith('name:'):
ls2.append(lines[index]+lines[index+1])
```
But it was not good, since I have something like:
```
ls = ['name: John', 'John has 4 yellow', '4 yellow cars.', 'cars.name: Angelina']
```
Do you have any idea how can I perform this task?
|
2021/10/14
|
[
"https://Stackoverflow.com/questions/69563630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11601412/"
] |
You can use `itertools.groupby`:
```py
import itertools
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
g = itertools.groupby(ls, lambda x: x.startswith('name: '))
output = [''.join(v) for _, v in g]
print(output) # ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellowcars.']
```
It groups the items by whether each item starts with `'name: '`;
1. Items that start with `'name: '` form a group (i.e., `['name: John']`).
2. Next a few items that don't do so form a group (i.e., `['John has ', '4 yellow ', 'cars.']`).
3. Next items that do so form another group (`['name: Angelina']`).
4. ... and so on alternatingly.
Then `join` concatenates the strings in each group.
|
Concatenate all the lines that don't begin with `name:` in a variable, then append that to the result when you get to the next `name:` line.
```
ls2 = []
temp_string = ''
for line in lines:
line = line.rstrip('\n')
if line.startswith('name:'):
if temp_string:
ls2.append(temp_string)
temp_string = ''
ls2.append(line)
else:
temp_string += line
# append the last set of lines
if temp_string:
ls2.append(temp_string)
```
|
69,563,630
|
I have a huge python list as the following example:
```
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
```
I would like to join this information in this formatting:
```
ls = ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellow cars.']
```
I have tried this code
```
with open ('names.txt', 'r') as text:
lines = text.readlines()
for index,line in enumerate(lines):
if not linha.startswith('name:'):
ls2.append(lines[index]+lines[index+1])
```
But it was not good, since I have something like:
```
ls = ['name: John', 'John has 4 yellow', '4 yellow cars.', 'cars.name: Angelina']
```
Do you have any idea how can I perform this task?
|
2021/10/14
|
[
"https://Stackoverflow.com/questions/69563630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11601412/"
] |
You can use `itertools.groupby`:
```py
import itertools
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
g = itertools.groupby(ls, lambda x: x.startswith('name: '))
output = [''.join(v) for _, v in g]
print(output) # ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellowcars.']
```
It groups the items by whether each item starts with `'name: '`;
1. Items that start with `'name: '` form a group (i.e., `['name: John']`).
2. Next a few items that don't do so form a group (i.e., `['John has ', '4 yellow ', 'cars.']`).
3. Next items that do so form another group (`['name: Angelina']`).
4. ... and so on alternatingly.
Then `join` concatenates the strings in each group.
|
I think the logic can be better expressed as "if the current line begins with `name:`, then append it to a new list, and also join the next three lines into one line and append that line too."
```
with open ('names.txt', 'r') as text:
lines = text.readlines()
i = 0
ls2 = []
for i, line in enumerate(lines):
if line.startswith('name:'):
ls2.append(line)
ls2.append(lines[i+1] + lines[i+2] + lines[i+3])
```
|
69,563,630
|
I have a huge python list as the following example:
```
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
```
I would like to join this information in this formatting:
```
ls = ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellow cars.']
```
I have tried this code
```
with open ('names.txt', 'r') as text:
lines = text.readlines()
for index,line in enumerate(lines):
if not linha.startswith('name:'):
ls2.append(lines[index]+lines[index+1])
```
But it was not good, since I have something like:
```
ls = ['name: John', 'John has 4 yellow', '4 yellow cars.', 'cars.name: Angelina']
```
Do you have any idea how can I perform this task?
|
2021/10/14
|
[
"https://Stackoverflow.com/questions/69563630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11601412/"
] |
You can use `itertools.groupby`:
```py
import itertools
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
g = itertools.groupby(ls, lambda x: x.startswith('name: '))
output = [''.join(v) for _, v in g]
print(output) # ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellowcars.']
```
It groups the items by whether each item starts with `'name: '`;
1. Items that start with `'name: '` form a group (i.e., `['name: John']`).
2. Next a few items that don't do so form a group (i.e., `['John has ', '4 yellow ', 'cars.']`).
3. Next items that do so form another group (`['name: Angelina']`).
4. ... and so on alternatingly.
Then `join` concatenates the strings in each group.
|
Maybe don't split into all lines but just split the whole file by name lines and polish the whitespace afterwards?
```
import re
with open('names.txt') as f:
ls = [re.sub(r'\s+', ' ', s.strip())
for s in re.split('(name:.*)', f.read())
if s]
```
Writing your list back to file and using my above code, I get exactly the desired output (with spaces where they should be but no duplicate spaces):
```
['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellow cars.']
```
[Try it online!](https://tio.run/##pZA9T8MwEEB3/4qTOtimxQsgoUodWFk7QocANjnJta07R2l/fcglpYDEllvuS@@ke@Vc25zuHgsNw@p2QagV7H3tilp2RUWGHbzo1Bz9Fp5zm/QGtGRoGwZp7uHsY8z91Lw3xE6KGXhKnz5iamTyXV/Bhwv4wx1Uj7WFXHwy0wV29VRl32sLIxa2CsYImWA85QETRJ5nEoUwVSObDQSMfhesUos15thVzGmpSTyWTBXI///k7/9m6eQdd2@G9CuvxYFIY8eVsBhrr0/POlhcCFEiVqPN5N/d2JEJjnzz8RfBAHxQ6iKM7TB8AQ "Python 3.8 (pre-release) – Try It Online")
|
70,658,581
|
I am looking to create accounts on Brownie for deploying contracts but I am not sure how to do this. I have looked online how to do this and I havent found it.
I am running python 3.7 and have brownie installed and working as intended. I have also run brownie using a gnache cli. Any help would be great!
|
2022/01/10
|
[
"https://Stackoverflow.com/questions/70658581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17855149/"
] |
To create accounts on brownie use
```
brownie accounts new account-name
```
you can then add your private key as well as password encrypt.
You can check to see if this account was made correctly using
```
brownie accounts list
```
|
I understand that you are trying to add accounts through the brownie ./scripts folder:
add.py
```
from brownie import accounts
def add_account():
print(len(accounts)
for i in range(10):
accounts.add() #adds a random account with mnemonic & address to the network
print(len(accounts))
def main():
add_account()
```
You can then execute this in you shell:
>
> brownie run .\scripts\add.py --network [network]
>
>
>
For further information look here:
<https://eth-brownie.readthedocs.io/en/stable/core-accounts.html>
|
51,666,871
|
I have a flask app with a single file (app.py) a large code base size of 6K lines which i want to modularize by making Separate files for each group of route handlers.
Which one is the proper approach
creating Class for similar routes like user and giving member functions like login, register
user.py
```
class User:
def login():
pass
def register():
pass
```
use it like
```
user = User()
user.login()
```
or create a python file user.py and just droping all the functions inside that
user.py
```
def login():
pass
def register():
pass
```
and use it like
```
import user
user.login()
```
from above mentioned approaches which one will use proper memory and more efficient
|
2018/08/03
|
[
"https://Stackoverflow.com/questions/51666871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547270/"
] |
You should almost never use classes for flask routes as they are inherantly static, and so are not really suited for having instances made of them
The easiest solution is just to separate related routes into modules, as shown in the second part of your question.
If I were you I would also look into Flask's blueprints, which are specifically designed to group routes together:
<http://flask.pocoo.org/docs/1.0/blueprints/>
(I would also recommend doing the tutorial for Flask that is available on the Flask website, where you make a small blogging application and blueprints and modularisation are explained <http://flask.pocoo.org/docs/1.0/tutorial/>)
|
The latter is Pythonic.
Don't use classes when you don't need instance data; use modules.
|
66,421,969
|
I have a main folder with some .xlsx, .ipynb, .jpeg and some subfolders in it.
Now I want to convert all my .xlsx files in my main folder to PDFs.
It is a routine work that I have to do everyday, I would appreciate if you teach me how to do it in python.
\*all the files have some data in the first sheet of the workbook
Thank you
|
2021/03/01
|
[
"https://Stackoverflow.com/questions/66421969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13403801/"
] |
Is there anything you have already tried ?
I suggest testing out pywin32.
1. Download pywin32
```sh
python3 -m pip install pywin32
```
2. Write a script to automate.
```py
import win32com.client
from pywintypes import com_error
# Path to original excel file
WB_PATH = r'~/path/to/file.xlsx'
# PDF path when saving
PATH_TO_PDF = r'~/path/to/file.pdf'
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
try:
print('Start conversion to PDF')
# Open
wb = excel.Workbooks.Open(WB_PATH)
# Specify the sheet you want to save by index. 1 is the first (leftmost) sheet.
ws_index_list = [1,2,3,4,5,6,7,8,9,10,11,12]
wb.WorkSheets(ws_index_list).Select()
# Save
wb.ActiveSheet.ExportAsFixedFormat(0, PATH_TO_PDF)
except com_error as e:
print('failed.')
else:
print('Succeeded.')
finally:
wb.Close()
excel.Quit()
```
|
try like this :
```
saveFormat = self.SaveFormat
workbook = self.Workbook(self.dataDir + "Book1.xls")
#Save the document in PDF format
workbook.save(self.dataDir + "OutBook1.pdf", saveFormat.PDF)
\# Print message
print "\n Excel to PDF conversion performed successfully."
```
|
48,924,007
|
I am trying to compare two `strings` in `python 3.6` and if they are not equal then print a message and exit. My current code is:
```
location = 'United States of America'
if location.lower() != 'united states of america' or location.lower() != 'usa':
print('Location was different = {}'.format(location.lower()))
sys.exit()
else:
#do something
```
But the above code is not able to match the two strings and even though they are equal, it enters the loop and prints that they are different. I know its some silly mistake that I am making but unable to figure it out.
|
2018/02/22
|
[
"https://Stackoverflow.com/questions/48924007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2966197/"
] |
Your condition:
```
if location.lower() != 'united states of america' or location.lower() != 'usa':
```
will never be `False`, since `location.lower()` can't be 2 different strings at the same time.
I suspect you want:
```
if location.lower() != 'united states of america' and location.lower() != 'usa':
```
|
You are looking for an AND condition instead of a OR condition in your if statement. If you change that you should be set
|
13,348,880
|
I am trying to compile the source codes for a simulator which uses C++ and Python. However, it gives me this error:
```
Error: can't find Python.h header in ['path-to-my-python/include/python2.6']
Install Python headers (package python-dev on Ubuntu and RedHat)
```
However, I can see that the header file is there and I have set the path to it. How can I fix or diagnosis the problem?
|
2012/11/12
|
[
"https://Stackoverflow.com/questions/13348880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762469/"
] |
I have written my own AutoCompleteBox control, available at <https://github.com/igorkulman/AutoCompleteBox>
|
I don't think there is anything built in, but have you checked open source? This was the first thing that showed up when I binged for it on google:
<http://autocompleteboxwinrt.codeplex.com/SourceControl/changeset/view/19567>
|
13,348,880
|
I am trying to compile the source codes for a simulator which uses C++ and Python. However, it gives me this error:
```
Error: can't find Python.h header in ['path-to-my-python/include/python2.6']
Install Python headers (package python-dev on Ubuntu and RedHat)
```
However, I can see that the header file is there and I have set the path to it. How can I fix or diagnosis the problem?
|
2012/11/12
|
[
"https://Stackoverflow.com/questions/13348880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762469/"
] |
I have written my own AutoCompleteBox control, available at <https://github.com/igorkulman/AutoCompleteBox>
|
There's no built-in AutoCompleteBox control for Windows Store app.
You may consider a third party control such as:
<http://www.telerik.com/products/windows-8/controls/auto-complete.aspx>
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Assuming you want to print every 5th line starting from a specific line number:
```
$ seq 20 | awk 'NR==4{c=4} c && !((++c) % 5)'
4
9
14
19
$ seq 20 | awk 'NR==2{c=4} c && !((++c) % 5)'
2
7
12
17
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
```
`c && !((++c) % 5)` says:
>
> If `c` is set then increment `c` and test if that new value modulo
> `5` is zero.
>
>
>
So no line before `NR==4` can be printed as `c` is never populated before that happens, and then when `c` is set to 4, it's then increment to `5` and `5 % 5` is `0` so the line is printed. `c` gets incremented for every line after that and so `c % 5` continually rotates through `1 2 3 4 0` thus printing every 5th line when `0` occurs and so `!0` is true.
To do the above using values set on the command line rather than hard-coded in the script would be:
```
$ seq 20 | awk -v b=4 -v n=5 'NR==b{c=n-1} c && !((++c) % n)'
4
9
14
19
```
---
EDIT - here's why [I asked](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130366892_73829899):
>
> is your question truly `I want to firs print the 4th row and then continue printing every 5th row after the 4th row` as you stated or is
> it the simpler `I want to print the 4th row out of every 5 rows`?
>
>
>
to which [the OP replied](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130367270_73829899)
>
> what I want to do is what I wrote exactly
>
>
>
and the difference between the possible solutions to THAT problem when you generalize to be able to change "4th" to some other number, e.g. "6th":
>
> I want to firs print the 6th row and then continue printing every 5th
> row after the 6th row
>
>
>
```
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
$ seq 20 | awk 'NR%5==6'
$
```
|
Simply
```
awk 'NR%5 == 4' file
```
will do the job.
Alternatively, if you have GNU `sed`:
```
sed -n 4~5p file
```
---
**Edit:**
A general solution to the problem of printing every *n*th line starting with line *s* using `awk` could be, for example, like that:
```
awk -v s=6 -v n=5 'NR>=s && NR%n == s%n' file
```
(`s%n` could be precomputed and assigned to a variable.)
But using GNU `sed` would be much simpler for this task:
```
sed -n "${s}~${n}p" file
```
where `s` and `n` are shell variables (their values must be positive integers).
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Assuming you want to print every 5th line starting from a specific line number:
```
$ seq 20 | awk 'NR==4{c=4} c && !((++c) % 5)'
4
9
14
19
$ seq 20 | awk 'NR==2{c=4} c && !((++c) % 5)'
2
7
12
17
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
```
`c && !((++c) % 5)` says:
>
> If `c` is set then increment `c` and test if that new value modulo
> `5` is zero.
>
>
>
So no line before `NR==4` can be printed as `c` is never populated before that happens, and then when `c` is set to 4, it's then increment to `5` and `5 % 5` is `0` so the line is printed. `c` gets incremented for every line after that and so `c % 5` continually rotates through `1 2 3 4 0` thus printing every 5th line when `0` occurs and so `!0` is true.
To do the above using values set on the command line rather than hard-coded in the script would be:
```
$ seq 20 | awk -v b=4 -v n=5 'NR==b{c=n-1} c && !((++c) % n)'
4
9
14
19
```
---
EDIT - here's why [I asked](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130366892_73829899):
>
> is your question truly `I want to firs print the 4th row and then continue printing every 5th row after the 4th row` as you stated or is
> it the simpler `I want to print the 4th row out of every 5 rows`?
>
>
>
to which [the OP replied](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130367270_73829899)
>
> what I want to do is what I wrote exactly
>
>
>
and the difference between the possible solutions to THAT problem when you generalize to be able to change "4th" to some other number, e.g. "6th":
>
> I want to firs print the 6th row and then continue printing every 5th
> row after the 6th row
>
>
>
```
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
$ seq 20 | awk 'NR%5==6'
$
```
|
Your code
```
awk '{if(NR==4 || (NR>4 && NR==NR+7)) print $0}' file
```
contain condition `NR==NR+7` which does never hold, in turn what is right to `||` is always false and therefore your code is in fact acting like it would be
```
awk '{if(NR==4) print $0}' file
```
>
> print row 4 first and then the 9th row and then the 14th row using
> awk?
>
>
>
Just provide GNU `AWK` with `;`-sheared conditions describing lines you want that is
```
awk 'NR==4;NR==9;NR==14' file
```
Keep in mind that altering order does *not* change output, so you will get same output for
```
awk 'NR==14;NR==9;NR==4' file
```
*(tested in GNU Awk 5.0.1)*
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Assuming you want to print every 5th line starting from a specific line number:
```
$ seq 20 | awk 'NR==4{c=4} c && !((++c) % 5)'
4
9
14
19
$ seq 20 | awk 'NR==2{c=4} c && !((++c) % 5)'
2
7
12
17
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
```
`c && !((++c) % 5)` says:
>
> If `c` is set then increment `c` and test if that new value modulo
> `5` is zero.
>
>
>
So no line before `NR==4` can be printed as `c` is never populated before that happens, and then when `c` is set to 4, it's then increment to `5` and `5 % 5` is `0` so the line is printed. `c` gets incremented for every line after that and so `c % 5` continually rotates through `1 2 3 4 0` thus printing every 5th line when `0` occurs and so `!0` is true.
To do the above using values set on the command line rather than hard-coded in the script would be:
```
$ seq 20 | awk -v b=4 -v n=5 'NR==b{c=n-1} c && !((++c) % n)'
4
9
14
19
```
---
EDIT - here's why [I asked](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130366892_73829899):
>
> is your question truly `I want to firs print the 4th row and then continue printing every 5th row after the 4th row` as you stated or is
> it the simpler `I want to print the 4th row out of every 5 rows`?
>
>
>
to which [the OP replied](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130367270_73829899)
>
> what I want to do is what I wrote exactly
>
>
>
and the difference between the possible solutions to THAT problem when you generalize to be able to change "4th" to some other number, e.g. "6th":
>
> I want to firs print the 6th row and then continue printing every 5th
> row after the 6th row
>
>
>
```
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
$ seq 20 | awk 'NR%5==6'
$
```
|
* doing it in `awk` without ever using `modulo %` :
>
>
> ```
> jot 30 | mawk 'BEGIN { __+=_+=_+=__=_^=FS="^$" } _-(_+=__*(_==NR))'
>
> ```
>
>
```
4
9
14
19
24
29
```
* generic solution without `modulo %` :
-- `"1st print` ***`17th`*** `row then once every` ***`29`*** `rows after that"`
>
>
> ```
> jot 200 | gawk '__-(__+=___*(NR == __))' FS='^$' __=17 ___=29
>
> ```
>
>
```
17
46
75
104
133
162
191
```
* extremely succinct way if u only want odd-numbered rows :
>
>
> ```
> jot 14 | nawk '_*=--_'
>
> ```
>
>
```
1
3
5
7
9
11
13
```
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Assuming you want to print every 5th line starting from a specific line number:
```
$ seq 20 | awk 'NR==4{c=4} c && !((++c) % 5)'
4
9
14
19
$ seq 20 | awk 'NR==2{c=4} c && !((++c) % 5)'
2
7
12
17
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
```
`c && !((++c) % 5)` says:
>
> If `c` is set then increment `c` and test if that new value modulo
> `5` is zero.
>
>
>
So no line before `NR==4` can be printed as `c` is never populated before that happens, and then when `c` is set to 4, it's then increment to `5` and `5 % 5` is `0` so the line is printed. `c` gets incremented for every line after that and so `c % 5` continually rotates through `1 2 3 4 0` thus printing every 5th line when `0` occurs and so `!0` is true.
To do the above using values set on the command line rather than hard-coded in the script would be:
```
$ seq 20 | awk -v b=4 -v n=5 'NR==b{c=n-1} c && !((++c) % n)'
4
9
14
19
```
---
EDIT - here's why [I asked](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130366892_73829899):
>
> is your question truly `I want to firs print the 4th row and then continue printing every 5th row after the 4th row` as you stated or is
> it the simpler `I want to print the 4th row out of every 5 rows`?
>
>
>
to which [the OP replied](https://stackoverflow.com/questions/73829899/printing-nth-rows-after-a-row-number-in-awk/73829940?noredirect=1#comment130367270_73829899)
>
> what I want to do is what I wrote exactly
>
>
>
and the difference between the possible solutions to THAT problem when you generalize to be able to change "4th" to some other number, e.g. "6th":
>
> I want to firs print the 6th row and then continue printing every 5th
> row after the 6th row
>
>
>
```
$ seq 20 | awk 'NR==6{c=4} c && !((++c) % 5)'
6
11
16
$ seq 20 | awk 'NR%5==6'
$
```
|
Here is another `awk` solution
```
$ seq 30 | awk -v b=14 -v n=5 'NR>=b && !((NR-b)%n)'
14
19
24
29
```
this is just the translation of `sed -n 14~5p`.
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Simply
```
awk 'NR%5 == 4' file
```
will do the job.
Alternatively, if you have GNU `sed`:
```
sed -n 4~5p file
```
---
**Edit:**
A general solution to the problem of printing every *n*th line starting with line *s* using `awk` could be, for example, like that:
```
awk -v s=6 -v n=5 'NR>=s && NR%n == s%n' file
```
(`s%n` could be precomputed and assigned to a variable.)
But using GNU `sed` would be much simpler for this task:
```
sed -n "${s}~${n}p" file
```
where `s` and `n` are shell variables (their values must be positive integers).
|
Your code
```
awk '{if(NR==4 || (NR>4 && NR==NR+7)) print $0}' file
```
contain condition `NR==NR+7` which does never hold, in turn what is right to `||` is always false and therefore your code is in fact acting like it would be
```
awk '{if(NR==4) print $0}' file
```
>
> print row 4 first and then the 9th row and then the 14th row using
> awk?
>
>
>
Just provide GNU `AWK` with `;`-sheared conditions describing lines you want that is
```
awk 'NR==4;NR==9;NR==14' file
```
Keep in mind that altering order does *not* change output, so you will get same output for
```
awk 'NR==14;NR==9;NR==4' file
```
*(tested in GNU Awk 5.0.1)*
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Simply
```
awk 'NR%5 == 4' file
```
will do the job.
Alternatively, if you have GNU `sed`:
```
sed -n 4~5p file
```
---
**Edit:**
A general solution to the problem of printing every *n*th line starting with line *s* using `awk` could be, for example, like that:
```
awk -v s=6 -v n=5 'NR>=s && NR%n == s%n' file
```
(`s%n` could be precomputed and assigned to a variable.)
But using GNU `sed` would be much simpler for this task:
```
sed -n "${s}~${n}p" file
```
where `s` and `n` are shell variables (their values must be positive integers).
|
* doing it in `awk` without ever using `modulo %` :
>
>
> ```
> jot 30 | mawk 'BEGIN { __+=_+=_+=__=_^=FS="^$" } _-(_+=__*(_==NR))'
>
> ```
>
>
```
4
9
14
19
24
29
```
* generic solution without `modulo %` :
-- `"1st print` ***`17th`*** `row then once every` ***`29`*** `rows after that"`
>
>
> ```
> jot 200 | gawk '__-(__+=___*(NR == __))' FS='^$' __=17 ___=29
>
> ```
>
>
```
17
46
75
104
133
162
191
```
* extremely succinct way if u only want odd-numbered rows :
>
>
> ```
> jot 14 | nawk '_*=--_'
>
> ```
>
>
```
1
3
5
7
9
11
13
```
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Simply
```
awk 'NR%5 == 4' file
```
will do the job.
Alternatively, if you have GNU `sed`:
```
sed -n 4~5p file
```
---
**Edit:**
A general solution to the problem of printing every *n*th line starting with line *s* using `awk` could be, for example, like that:
```
awk -v s=6 -v n=5 'NR>=s && NR%n == s%n' file
```
(`s%n` could be precomputed and assigned to a variable.)
But using GNU `sed` would be much simpler for this task:
```
sed -n "${s}~${n}p" file
```
where `s` and `n` are shell variables (their values must be positive integers).
|
Here is another `awk` solution
```
$ seq 30 | awk -v b=14 -v n=5 'NR>=b && !((NR-b)%n)'
14
19
24
29
```
this is just the translation of `sed -n 14~5p`.
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Your code
```
awk '{if(NR==4 || (NR>4 && NR==NR+7)) print $0}' file
```
contain condition `NR==NR+7` which does never hold, in turn what is right to `||` is always false and therefore your code is in fact acting like it would be
```
awk '{if(NR==4) print $0}' file
```
>
> print row 4 first and then the 9th row and then the 14th row using
> awk?
>
>
>
Just provide GNU `AWK` with `;`-sheared conditions describing lines you want that is
```
awk 'NR==4;NR==9;NR==14' file
```
Keep in mind that altering order does *not* change output, so you will get same output for
```
awk 'NR==14;NR==9;NR==4' file
```
*(tested in GNU Awk 5.0.1)*
|
* doing it in `awk` without ever using `modulo %` :
>
>
> ```
> jot 30 | mawk 'BEGIN { __+=_+=_+=__=_^=FS="^$" } _-(_+=__*(_==NR))'
>
> ```
>
>
```
4
9
14
19
24
29
```
* generic solution without `modulo %` :
-- `"1st print` ***`17th`*** `row then once every` ***`29`*** `rows after that"`
>
>
> ```
> jot 200 | gawk '__-(__+=___*(NR == __))' FS='^$' __=17 ___=29
>
> ```
>
>
```
17
46
75
104
133
162
191
```
* extremely succinct way if u only want odd-numbered rows :
>
>
> ```
> jot 14 | nawk '_*=--_'
>
> ```
>
>
```
1
3
5
7
9
11
13
```
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Here is another `awk` solution
```
$ seq 30 | awk -v b=14 -v n=5 'NR>=b && !((NR-b)%n)'
14
19
24
29
```
this is just the translation of `sed -n 14~5p`.
|
Your code
```
awk '{if(NR==4 || (NR>4 && NR==NR+7)) print $0}' file
```
contain condition `NR==NR+7` which does never hold, in turn what is right to `||` is always false and therefore your code is in fact acting like it would be
```
awk '{if(NR==4) print $0}' file
```
>
> print row 4 first and then the 9th row and then the 14th row using
> awk?
>
>
>
Just provide GNU `AWK` with `;`-sheared conditions describing lines you want that is
```
awk 'NR==4;NR==9;NR==14' file
```
Keep in mind that altering order does *not* change output, so you will get same output for
```
awk 'NR==14;NR==9;NR==4' file
```
*(tested in GNU Awk 5.0.1)*
|
73,829,933
|
I have a dataframe
```
import pandas as pd
data_as_dict={'CHROM': {232: 1, 233: 1, 234: 1, 10: 'chr15', 11: 'chr15'}, 'POS_GRCh38': {232: 10506158, 233: 109655507, 234: 113903258, 10: '67165147', 11: '67163292'}, 'REF': {232: 'G', 233: 'CAAA', 234: 'G', 10: 'G', 11: 'C'}, 'Effect_allele': {232: 'A', 233: 'C', 234: 'A', 10: 'C', 11: 'T'}, 'Effect_size': {232: 0.1109, 233: 0.0266, 234: 0.0579, 10: 0.2070141693843261, 11: 0.2151113796169455}, 'TYPE': {232: 'Mavaddat_2019_ER_NEG_Breast', 233: 'Mavaddat_2019_ER_NEG_Breast', 234: 'Mavaddat_2019_ER_NEG_Breast', 10: 'THYROID_PGS', 11: 'THYROID_PGS'}, 'Cancer': {232: 'Breast', 233: 'Breast', 234: 'Breast', 10: 'THYROID', 11: 'THYROID'}, 'Significant_YN': {232: 'Y', 233: 'Y', 234: 'Y', 10: 'Y', 11: 'Y'}}
all_cancers = pd.DataFrame.from_dict(data_as_dict)
```
I want to remove chr from `CHROM` column. I tried `all_cancers['CHROM'] = all_cancers['CHROM'].str.replace(r'chr', '')` which generates NaNs. I know it can be done easily in R with `gsub`, but I wanted to try in python. How do I do it correctly?
|
2022/09/23
|
[
"https://Stackoverflow.com/questions/73829933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4701887/"
] |
Here is another `awk` solution
```
$ seq 30 | awk -v b=14 -v n=5 'NR>=b && !((NR-b)%n)'
14
19
24
29
```
this is just the translation of `sed -n 14~5p`.
|
* doing it in `awk` without ever using `modulo %` :
>
>
> ```
> jot 30 | mawk 'BEGIN { __+=_+=_+=__=_^=FS="^$" } _-(_+=__*(_==NR))'
>
> ```
>
>
```
4
9
14
19
24
29
```
* generic solution without `modulo %` :
-- `"1st print` ***`17th`*** `row then once every` ***`29`*** `rows after that"`
>
>
> ```
> jot 200 | gawk '__-(__+=___*(NR == __))' FS='^$' __=17 ___=29
>
> ```
>
>
```
17
46
75
104
133
162
191
```
* extremely succinct way if u only want odd-numbered rows :
>
>
> ```
> jot 14 | nawk '_*=--_'
>
> ```
>
>
```
1
3
5
7
9
11
13
```
|
45,182,153
|
I saw at [concurrency is not parallelism](https://blog.golang.org/concurrency-is-not-parallelism) slide that golang can do like this:
```
func main() {
go boring("Boring!")
fmt.Println("I'm listening.")
time.Sleep(2 * time.Second)
fmt.Println("You're boring; I'm leaving.")
}
```
The result look like this
```
I'm listening.
boring 0
boring 1
boring 2
boring 3
boring 4
boring 5
You're boring; I'm leaving.
```
Can Python async loop do like this? I'm stuck it at `loop.run_forever` that it will block the main function:
```
import asyncio
import random
import time
import itertools
async def boring(msg):
for i in itertools.count(0):
print(msg, i)
await asyncio.sleep(random.random() % 1e3)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
asyncio.ensure_future(boring('boring!'))
loop.run_forever()
print('Hello')
time.sleep(2)
print('Bye.')
loop.stop()
```
It will then run
```
boring! 0
boring! 1
boring! 2
boring! 3
boring! 4
boring! 5
boring! 6
boring! 7
boring! 8
boring! 9
```
Can python async loop be async?
|
2017/07/19
|
[
"https://Stackoverflow.com/questions/45182153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8218546/"
] |
Instead of sleeping after running run\_until\_complete, you can use [timeouts](https://docs.python.org/3/library/asyncio-task.html#timeouts). This way, it would be something like:
```
async def main():
print('Hello')
try:
await asyncio.wait_for(boring('boring!'), timeout=2.0)
print('Maybe not that boring!')
except:
print('Bye.')
if __name__ == '__main__':
asyncio.run(main())
```
This will also automatically cancel the running task when the timeout happens. If you don't want the task to be canceled after timeout, use `wait` instead of `wait_for`.
|
`loop.run_forever()` if blocking the execution. As your code is running in a single thread, you need to modify your code to something like this:
```
async def boring(msg):
for i in itertools.count(0):
print(msg, i)
await asyncio.sleep(random.random() % 1e3)
async def hello(task):
print('Hello')
await asyncio.sleep(2)
print('Bye.')
task.cancel()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
t = asyncio.ensure_future(boring('boring!'))
loop.run_until_complete(hello(t))
loop.stop()
```
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
I have high hopes for it.
1. This is being worked on by several people from Google. Seeing as how the BDFL is also employed there, this is a positive.
2. Off the bat, they state that this is a branch, and not a fork. As such, it's within the realm of possibility that this will eventually get merged into trunk.
3. Most importantly, **they have a working version**. They're using a version of unladen swallow **right now** for Youtube stuff.
They seem to have their shit together. They have a relatively detailed plan for a project at this stage, and they have a list of tests they use to gauge performance improvements and regressions.
I'm not holding my breath on GIL removal, but even if they never get around to that, the speed increases alone make it awesome.
|
I'm sorry to disappoint you, but when you read [PEP 3146](http://www.python.org/dev/peps/pep-3146/) things look bad.
The improvement is by now minimal and therfore the compiler-code gets more complicated.
Also removing the GIL has many downsides.
Btw. PyPy seems to be faster then Unladen Swallow in [some tests](http://morepypy.blogspot.com/2010/03/hello.html).
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
I have high hopes for it.
1. This is being worked on by several people from Google. Seeing as how the BDFL is also employed there, this is a positive.
2. Off the bat, they state that this is a branch, and not a fork. As such, it's within the realm of possibility that this will eventually get merged into trunk.
3. Most importantly, **they have a working version**. They're using a version of unladen swallow **right now** for Youtube stuff.
They seem to have their shit together. They have a relatively detailed plan for a project at this stage, and they have a list of tests they use to gauge performance improvements and regressions.
I'm not holding my breath on GIL removal, but even if they never get around to that, the speed increases alone make it awesome.
|
Guido just posted an article to his twitter account that is an update to the Jesse Noller article posted earlier. <http://jessenoller.com/2010/01/06/unladen-swallow-python-3s-best-feature/>. Sounds like they are moving ahead as previously mentioned with python 3.
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
Guido just posted an article to his twitter account that is an update to the Jesse Noller article posted earlier. <http://jessenoller.com/2010/01/06/unladen-swallow-python-3s-best-feature/>. Sounds like they are moving ahead as previously mentioned with python 3.
|
I think that a 5 times speed improvement is not all that important for me personally.
It is not an order of magnitude change. Although if you consume CPU power at the scale of Google it can be a worth while investment to have some of your staff work on it.
Many of the speed improvements will likely make it into cpython eventually.
Getting rid of the GIL is interesting in principle but will likely reveal lots of problems with modules that are not thread safe once the GIL is removed.
I do not think I will use Unladen Swallow any time soon but like how giving attention to performance may improve the regular Python versions.
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
Guido just posted an article to his twitter account that is an update to the Jesse Noller article posted earlier. <http://jessenoller.com/2010/01/06/unladen-swallow-python-3s-best-feature/>. Sounds like they are moving ahead as previously mentioned with python 3.
|
They have a quarterly release. So not far away, wait and watch, let them come up with some thing more than just a plan.
If it indeed comes to be true, easy to do away with C and C++ even for performance intensive operations.
Even tho' it is a Google sponsored Open Source project, surprisingly doesn't involve Guido anywhere.
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
I'm sorry to disappoint you, but when you read [PEP 3146](http://www.python.org/dev/peps/pep-3146/) things look bad.
The improvement is by now minimal and therfore the compiler-code gets more complicated.
Also removing the GIL has many downsides.
Btw. PyPy seems to be faster then Unladen Swallow in [some tests](http://morepypy.blogspot.com/2010/03/hello.html).
|
They have a quarterly release. So not far away, wait and watch, let them come up with some thing more than just a plan.
If it indeed comes to be true, easy to do away with C and C++ even for performance intensive operations.
Even tho' it is a Google sponsored Open Source project, surprisingly doesn't involve Guido anywhere.
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
I'm sorry to disappoint you, but when you read [PEP 3146](http://www.python.org/dev/peps/pep-3146/) things look bad.
The improvement is by now minimal and therfore the compiler-code gets more complicated.
Also removing the GIL has many downsides.
Btw. PyPy seems to be faster then Unladen Swallow in [some tests](http://morepypy.blogspot.com/2010/03/hello.html).
|
[This question](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x) discussed many of the same things. My opinion is that it sounds great, but I'm waiting to see what it looks like, and how long it takes to become stable.
I'm particularly concerned with compatibility with existing code and libraries, and how the library-writing community responds to it. Ultimately, aside from personal hobby projects, it's of zero value to me until it can run all my third-party libraries.
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
I have high hopes for it.
1. This is being worked on by several people from Google. Seeing as how the BDFL is also employed there, this is a positive.
2. Off the bat, they state that this is a branch, and not a fork. As such, it's within the realm of possibility that this will eventually get merged into trunk.
3. Most importantly, **they have a working version**. They're using a version of unladen swallow **right now** for Youtube stuff.
They seem to have their shit together. They have a relatively detailed plan for a project at this stage, and they have a list of tests they use to gauge performance improvements and regressions.
I'm not holding my breath on GIL removal, but even if they never get around to that, the speed increases alone make it awesome.
|
They have a quarterly release. So not far away, wait and watch, let them come up with some thing more than just a plan.
If it indeed comes to be true, easy to do away with C and C++ even for performance intensive operations.
Even tho' it is a Google sponsored Open Source project, surprisingly doesn't involve Guido anywhere.
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
[This question](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x) discussed many of the same things. My opinion is that it sounds great, but I'm waiting to see what it looks like, and how long it takes to become stable.
I'm particularly concerned with compatibility with existing code and libraries, and how the library-writing community responds to it. Ultimately, aside from personal hobby projects, it's of zero value to me until it can run all my third-party libraries.
|
I think that a 5 times speed improvement is not all that important for me personally.
It is not an order of magnitude change. Although if you consume CPU power at the scale of Google it can be a worth while investment to have some of your staff work on it.
Many of the speed improvements will likely make it into cpython eventually.
Getting rid of the GIL is interesting in principle but will likely reveal lots of problems with modules that are not thread safe once the GIL is removed.
I do not think I will use Unladen Swallow any time soon but like how giving attention to performance may improve the regular Python versions.
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
[This question](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x) discussed many of the same things. My opinion is that it sounds great, but I'm waiting to see what it looks like, and how long it takes to become stable.
I'm particularly concerned with compatibility with existing code and libraries, and how the library-writing community responds to it. Ultimately, aside from personal hobby projects, it's of zero value to me until it can run all my third-party libraries.
|
Guido just posted an article to his twitter account that is an update to the Jesse Noller article posted earlier. <http://jessenoller.com/2010/01/06/unladen-swallow-python-3s-best-feature/>. Sounds like they are moving ahead as previously mentioned with python 3.
|
714,242
|
What are your opinions and expectations on [Google's Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)? From their project plan:
>
> We want to make Python faster, but we
> also want to make it easy for large,
> well-established applications to
> switch to Unladen Swallow.
>
>
> 1. Produce a version of Python at least 5x faster than CPython.
> 2. Python application performance should be stable.
> 3. Maintain source-level compatibility with CPython
> applications.
> 4. Maintain source-level compatibility with CPython extension
> modules.
> 5. We do not want to maintain a Python implementation forever; we view
> our work as a branch, not a fork.
>
>
>
And even sweeter:
>
> In addition, we intend to remove the
> GIL and fix the state of
> multithreading in Python. We believe
> this is possible through the
> implementation of a more sophisticated
> GC
>
>
>
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
* Jesse Noller: ["Pycon: Unladen-Swallow"](http://jessenoller.com/2009/03/26/pycon-unladen-swallow/)
* ArsTechnica: ["Google searches for holy grail of Python performance"](http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars)
Update: as DNS pointed out, there was related question: [What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?](https://stackoverflow.com/questions/695370/what-is-llvm-and-how-is-replacing-python-vm-with-llvm-increasing-speeds-5x)
|
2009/04/03
|
[
"https://Stackoverflow.com/questions/714242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] |
I think the project has noble goals and with enough time (2-3 years), they will probably reach most of them.
They may not be able to merge their branch back into the trunk because Guido's current view is that cpython should be a reference implementation (ie. it shouldn't do things that are impossible for IronPython and jython to copy.) I've seen reports that this is what kept the cool parts of stackless from being merged into cpython.
|
I think that a 5 times speed improvement is not all that important for me personally.
It is not an order of magnitude change. Although if you consume CPU power at the scale of Google it can be a worth while investment to have some of your staff work on it.
Many of the speed improvements will likely make it into cpython eventually.
Getting rid of the GIL is interesting in principle but will likely reveal lots of problems with modules that are not thread safe once the GIL is removed.
I do not think I will use Unladen Swallow any time soon but like how giving attention to performance may improve the regular Python versions.
|
53,799,912
|
Iam trying to pre-process text as a part of NLP.I am new to it.I am not getting why i am unable to replace the digits
```
para = "support leaders around the world who do not speak for the big
polluters, but who speak for all of humanity, for the indigenous people of
the world, for the first 100 people.In 90's it seems true."
import re
import nltk
sentences = nltk.sent_tokenize(para)
for i in range(len(sentences)):
words = nltk.word_tokenize(sentences[i])
words = [re.sub(r'\d','',words)]
sentences[i] = ' '.join(words)
```
while doing this i am getting following error:
---
```
TypeError Traceback (most recent call last)
<ipython-input-28-000671b45ee1> in <module>()
2 for i in range(len(sentences)):
3 words = nltk.word_tokenize(sentences[i])
----> 4 words = [re.sub(r'\d','',words)].encode('utf8')
5 sentences[i] = ' '.join(words)
~\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
189 a callable, it's passed the match object and must return
190 a replacement string to be used."""
--> 191 return _compile(pattern, flags).sub(repl, string, count)
192
193 def subn(pattern, repl, string, count=0, flags=0):
TypeError: expected string or bytes-like object
```
How can i convert to byte like object. I am confused as i am new to it.
|
2018/12/16
|
[
"https://Stackoverflow.com/questions/53799912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10464351/"
] |
For replacing all digits from a string, you can the `re` module, for matching and replacing regex patterns. From your last example:
```
import re
processed_words = [re.sub('\d',' ', word) for word in tokenized]
```
|
Is this what you want to do? Or am I missing the point?
```
import re
para = """support leaders around the world who do not speak for the big
polluters, but who speak for all of humanity, for the indigenous people of
the world, for the first 100 people.In 90's it seems true."""
tokenized = para.split(' ')
new_para = []
for w in tokenized:
w = re.sub('[0-9]', '', w)
new_para.append(w)
print(' '.join(new_para))
```
|
53,799,912
|
Iam trying to pre-process text as a part of NLP.I am new to it.I am not getting why i am unable to replace the digits
```
para = "support leaders around the world who do not speak for the big
polluters, but who speak for all of humanity, for the indigenous people of
the world, for the first 100 people.In 90's it seems true."
import re
import nltk
sentences = nltk.sent_tokenize(para)
for i in range(len(sentences)):
words = nltk.word_tokenize(sentences[i])
words = [re.sub(r'\d','',words)]
sentences[i] = ' '.join(words)
```
while doing this i am getting following error:
---
```
TypeError Traceback (most recent call last)
<ipython-input-28-000671b45ee1> in <module>()
2 for i in range(len(sentences)):
3 words = nltk.word_tokenize(sentences[i])
----> 4 words = [re.sub(r'\d','',words)].encode('utf8')
5 sentences[i] = ' '.join(words)
~\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
189 a callable, it's passed the match object and must return
190 a replacement string to be used."""
--> 191 return _compile(pattern, flags).sub(repl, string, count)
192
193 def subn(pattern, repl, string, count=0, flags=0):
TypeError: expected string or bytes-like object
```
How can i convert to byte like object. I am confused as i am new to it.
|
2018/12/16
|
[
"https://Stackoverflow.com/questions/53799912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10464351/"
] |
The error is trying to tell you that you called `re.sub` with something that is not a string (ignore the "or bytes" and the "-like" parts: you have real strings to work with). The culprit is `words`: The function `nltk.word_tokenize()` returns a list, and you cannot pass the whole thing to `re.sub`. You need another for-loop, or a comprehension. Here it is with a comprehension, applying `re.sub` to each element `w` of `words`.
```
sentences = nltk.sent_tokenize(para)
for i in range(len(sentences)):
words = nltk.word_tokenize(sentences[i])
words = [re.sub(r'\d','',w) for w in words]
sentences[i] = ' '.join(words)
```
While we're at it, I recommend replacing your loop over numbers with a loop over the list elements. Much nicer this way, but you must store the results in a new list:
```
sentences = nltk.sent_tokenize(para)
clean = []
for sent in sentences:
words = nltk.word_tokenize(sent)
words = [re.sub(r'\d','',w) for w in words]
clean.append(' '.join(words))
```
PS. You could simplify your code by applying the replacement to whole sentences, or even to the entire paragraph before you split it. But that's not relevant to your problem...
|
Is this what you want to do? Or am I missing the point?
```
import re
para = """support leaders around the world who do not speak for the big
polluters, but who speak for all of humanity, for the indigenous people of
the world, for the first 100 people.In 90's it seems true."""
tokenized = para.split(' ')
new_para = []
for w in tokenized:
w = re.sub('[0-9]', '', w)
new_para.append(w)
print(' '.join(new_para))
```
|
53,799,912
|
Iam trying to pre-process text as a part of NLP.I am new to it.I am not getting why i am unable to replace the digits
```
para = "support leaders around the world who do not speak for the big
polluters, but who speak for all of humanity, for the indigenous people of
the world, for the first 100 people.In 90's it seems true."
import re
import nltk
sentences = nltk.sent_tokenize(para)
for i in range(len(sentences)):
words = nltk.word_tokenize(sentences[i])
words = [re.sub(r'\d','',words)]
sentences[i] = ' '.join(words)
```
while doing this i am getting following error:
---
```
TypeError Traceback (most recent call last)
<ipython-input-28-000671b45ee1> in <module>()
2 for i in range(len(sentences)):
3 words = nltk.word_tokenize(sentences[i])
----> 4 words = [re.sub(r'\d','',words)].encode('utf8')
5 sentences[i] = ' '.join(words)
~\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
189 a callable, it's passed the match object and must return
190 a replacement string to be used."""
--> 191 return _compile(pattern, flags).sub(repl, string, count)
192
193 def subn(pattern, repl, string, count=0, flags=0):
TypeError: expected string or bytes-like object
```
How can i convert to byte like object. I am confused as i am new to it.
|
2018/12/16
|
[
"https://Stackoverflow.com/questions/53799912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10464351/"
] |
For replacing all digits from a string, you can the `re` module, for matching and replacing regex patterns. From your last example:
```
import re
processed_words = [re.sub('\d',' ', word) for word in tokenized]
```
|
The error is trying to tell you that you called `re.sub` with something that is not a string (ignore the "or bytes" and the "-like" parts: you have real strings to work with). The culprit is `words`: The function `nltk.word_tokenize()` returns a list, and you cannot pass the whole thing to `re.sub`. You need another for-loop, or a comprehension. Here it is with a comprehension, applying `re.sub` to each element `w` of `words`.
```
sentences = nltk.sent_tokenize(para)
for i in range(len(sentences)):
words = nltk.word_tokenize(sentences[i])
words = [re.sub(r'\d','',w) for w in words]
sentences[i] = ' '.join(words)
```
While we're at it, I recommend replacing your loop over numbers with a loop over the list elements. Much nicer this way, but you must store the results in a new list:
```
sentences = nltk.sent_tokenize(para)
clean = []
for sent in sentences:
words = nltk.word_tokenize(sent)
words = [re.sub(r'\d','',w) for w in words]
clean.append(' '.join(words))
```
PS. You could simplify your code by applying the replacement to whole sentences, or even to the entire paragraph before you split it. But that's not relevant to your problem...
|
47,740,542
|
```
def lines(file):
for line in file:
yield line
yield '\n'
def blocks(file):
block = []
for line in lines(file):
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
with open(r'test_input.txt', 'r') as f:
lines = lines(f)
file = blocks(lines)
for line in file:
print(line)
```
I got this error message:
```
TypeError: 'generator' object is not callable
```
I don't know what happened. Does it because generator in python3.6 is different from 2.X?
|
2017/12/10
|
[
"https://Stackoverflow.com/questions/47740542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9080044/"
] |
Your issue is caused by this line:
```
lines = lines(f)
```
With this assignment, you're overwriting the `lines` generator function with its own return value. That means that when `blocks` tries to call `lines` again (which seems a little buggy to me, but not the main issue), it gets the generator object instead of the function it expected.
Pick a different name for the assignment, or just pass `f` to `blocks`, since it will call `lines` itself.
|
Your problem is not related to Python3. This error exists with Python 2.6.
I do not know exactly what you try to do but your code do not throws error replacing `blocks` function with :
```
def blocks(file):
block = []
for line in file: # here, replace lines(file) with file
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
```
However, I don't understand what you try to do with `lines()`
If this answer is not suitable to you, I encourage you to edit your question with more detail on what the functions are supposed to do.
|
27,224,458
|
I'm using Python's Scrapy to do some web scraping, and I'm trying to get the text in the last td of my last tr in the html below.
```
<table class="infobox" style="float: right; width: 225px; text-align: left; -moz-border-radius:10px; font-size: 85%" cellpadding="2">
<tr style="vertical-align: top;">
<td> <b>Name</b> </td>
<td> Abraham Lincoln
</td>
</tr>
<tr style="vertical-align: top;">
<td> <b>Sex</b> </td>
<td> Male
</td>
</tr>
<tr style="vertical-align: top;">
<td> <b>Occupation </b>
</td>
<td> Former King of <a href="/wiki/Mars" title="Mars">Mars</a>,
<br />Former President of the United States
</td>
</tr>
</table>
```
Currently, I have this written inside my scrapy's parse function.
```
def parse(self, response):
sel = Selector(response)
data = sel.xpath("//table[@class='infobox']")
occupation = data.xpath("tr[td/b[contains(.,'Occupation')]]/td[position()>1]/text()").extract()
print occupation
```
The printed result is:
```
[u' Former King of ', u',', u'Former President of the United States\n']
```
What I'd like to actually get is.. something along the lines of (the most important change would be Mars being added to Former King of):
```
[u'Former King of Mars', u'Former President of the United States']
```
I'm aware of the | union in xpath, and I could have written something more in occupation to capture the "Mars" text in the a tag, however, I want to be able to join the a tag text with the td text to output "Former King of Mars" as one of the elements of the printed list. I think with a union, Mars would appear as it's own element inside the list, which is not quite what I need. Anyway, I was hoping there would be some way in xpath I could join the children text of the parent td so that I could get "Former King of Mars" as an element of the outputted list. Also, there could potentially be multiple a tags within a td like for example.. "King" could be inside an a tag as well. Another requirement would be to keep "Former President of the United States" a separate element (somehow recognize the br tag?). I'm not sure what's the best way to go about handling these cases, but I think if there's a way to do it in xpath, it'll be better than working with a list in python because xpath still has reference to the dom tree. What do you guys think?
Thanks!
|
2014/12/01
|
[
"https://Stackoverflow.com/questions/27224458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3892678/"
] |
You should create user because tests create test database (not your) everytime.
```
User.objects.create_user(username=<client_username>, password=<client_password>)
```
Now create Client and login
```
self.c = django.test.client.Client()
self.c.login(username=<client_username>, password=<client_password>)
```
|
You can override request headers for every client request like this example:
```
def test_report_wrong_password(self):
headers = dict()
headers['HTTP_AUTHORIZATION'] = 'Basic ' + base64.b64encode('user_name:password')
response = self.client.post(
'/report/',
content_type='application/json',
data=json.dumps(JSON_DATA),
**headers)
self.assertEqual(response.status_code, 401)
```
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
Don't confuse "Twisted" with "`twistd`". When you use "`twistd`", you *are* running the program with Python. "`twistd`" is a Python program that, among other things, can load an application from a `.tac` file (as you're doing here).
The "Twisted Command Prompt" is a Twisted installer-provided convenience to help out people on Windows. All it is doing is setting `%PATH%` to include the directory containing the "`twistd`" program. You could run twistd from a normal command prompt if you set your %PATH% properly or invoke it with the full path.
If you're not satisfied with this, perhaps you can expand your question to include a description of the problems you're having when using "`twistd`".
|
Maybe one of `run` or `runApp` in [twisted.scripts.twistd](http://twistedmatrix.com/documents/9.0.0/api/twisted.scripts.twistd.html) modules will work for you. Please let me know if it does, it will be nice to know!
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
I don't know if it's the best way to do this but what I do is instead of:
```
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
you can do:
```
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
```
Sumarized if you want to have the two options (twistd and python):
```
if __name__ == '__main__':
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
else:
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
Hope it helps!
|
Don't confuse "Twisted" with "`twistd`". When you use "`twistd`", you *are* running the program with Python. "`twistd`" is a Python program that, among other things, can load an application from a `.tac` file (as you're doing here).
The "Twisted Command Prompt" is a Twisted installer-provided convenience to help out people on Windows. All it is doing is setting `%PATH%` to include the directory containing the "`twistd`" program. You could run twistd from a normal command prompt if you set your %PATH% properly or invoke it with the full path.
If you're not satisfied with this, perhaps you can expand your question to include a description of the problems you're having when using "`twistd`".
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
On windows you can create .bat file with your command in it, use full paths, then just click on it to start up.
For example I use:
```
runfileserver.bat:
C:\program_files\python26\Scripts\twistd.py -y C:\source\python\twisted\fileserver.tac
```
|
I haven't used twisted myself. However, you may try seeing if the twistd is a python file itself. I would take a guess that it is simply managing loading the appropriate twisted libraries from the correct path.
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
Don't confuse "Twisted" with "`twistd`". When you use "`twistd`", you *are* running the program with Python. "`twistd`" is a Python program that, among other things, can load an application from a `.tac` file (as you're doing here).
The "Twisted Command Prompt" is a Twisted installer-provided convenience to help out people on Windows. All it is doing is setting `%PATH%` to include the directory containing the "`twistd`" program. You could run twistd from a normal command prompt if you set your %PATH% properly or invoke it with the full path.
If you're not satisfied with this, perhaps you can expand your question to include a description of the problems you're having when using "`twistd`".
|
On windows you can create .bat file with your command in it, use full paths, then just click on it to start up.
For example I use:
```
runfileserver.bat:
C:\program_files\python26\Scripts\twistd.py -y C:\source\python\twisted\fileserver.tac
```
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
Don't confuse "Twisted" with "`twistd`". When you use "`twistd`", you *are* running the program with Python. "`twistd`" is a Python program that, among other things, can load an application from a `.tac` file (as you're doing here).
The "Twisted Command Prompt" is a Twisted installer-provided convenience to help out people on Windows. All it is doing is setting `%PATH%` to include the directory containing the "`twistd`" program. You could run twistd from a normal command prompt if you set your %PATH% properly or invoke it with the full path.
If you're not satisfied with this, perhaps you can expand your question to include a description of the problems you're having when using "`twistd`".
|
I am successfully using the simple Twisted Web server on Windows for Flask web sites.
Are others also successfully using Twisted on Windows, to validate that configuration?
```
new_app.py
if __name__ == "__main__":
reactor_args = {}
def run_twisted_wsgi():
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
resource = WSGIResource(reactor, reactor.getThreadPool(), app)
site = Site(resource)
reactor.listenTCP(5000, site)
reactor.run(**reactor_args)
if app.debug:
# Disable twisted signal handlers in development only.
reactor_args['installSignalHandlers'] = 0
# Turn on auto reload.
import werkzeug.serving
run_twisted_wsgi = werkzeug.serving.run_with_reloader(run_twisted_wsgi)
run_twisted_wsgi()
old_app.py
if __name__ == "__main__":
app.run()
```
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
I haven't used twisted myself. However, you may try seeing if the twistd is a python file itself. I would take a guess that it is simply managing loading the appropriate twisted libraries from the correct path.
|
I am successfully using the simple Twisted Web server on Windows for Flask web sites.
Are others also successfully using Twisted on Windows, to validate that configuration?
```
new_app.py
if __name__ == "__main__":
reactor_args = {}
def run_twisted_wsgi():
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
resource = WSGIResource(reactor, reactor.getThreadPool(), app)
site = Site(resource)
reactor.listenTCP(5000, site)
reactor.run(**reactor_args)
if app.debug:
# Disable twisted signal handlers in development only.
reactor_args['installSignalHandlers'] = 0
# Turn on auto reload.
import werkzeug.serving
run_twisted_wsgi = werkzeug.serving.run_with_reloader(run_twisted_wsgi)
run_twisted_wsgi()
old_app.py
if __name__ == "__main__":
app.run()
```
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
I don't know if it's the best way to do this but what I do is instead of:
```
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
you can do:
```
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
```
Sumarized if you want to have the two options (twistd and python):
```
if __name__ == '__main__':
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
else:
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
Hope it helps!
|
On windows you can create .bat file with your command in it, use full paths, then just click on it to start up.
For example I use:
```
runfileserver.bat:
C:\program_files\python26\Scripts\twistd.py -y C:\source\python\twisted\fileserver.tac
```
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
I don't know if it's the best way to do this but what I do is instead of:
```
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
you can do:
```
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
```
Sumarized if you want to have the two options (twistd and python):
```
if __name__ == '__main__':
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
else:
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
Hope it helps!
|
I am successfully using the simple Twisted Web server on Windows for Flask web sites.
Are others also successfully using Twisted on Windows, to validate that configuration?
```
new_app.py
if __name__ == "__main__":
reactor_args = {}
def run_twisted_wsgi():
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
resource = WSGIResource(reactor, reactor.getThreadPool(), app)
site = Site(resource)
reactor.listenTCP(5000, site)
reactor.run(**reactor_args)
if app.debug:
# Disable twisted signal handlers in development only.
reactor_args['installSignalHandlers'] = 0
# Turn on auto reload.
import werkzeug.serving
run_twisted_wsgi = werkzeug.serving.run_with_reloader(run_twisted_wsgi)
run_twisted_wsgi()
old_app.py
if __name__ == "__main__":
app.run()
```
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
I don't know if it's the best way to do this but what I do is instead of:
```
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
you can do:
```
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
```
Sumarized if you want to have the two options (twistd and python):
```
if __name__ == '__main__':
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
else:
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
Hope it helps!
|
Maybe one of `run` or `runApp` in [twisted.scripts.twistd](http://twistedmatrix.com/documents/9.0.0/api/twisted.scripts.twistd.html) modules will work for you. Please let me know if it does, it will be nice to know!
|
1,897,939
|
I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
from twisted.internet import protocol
from twisted.application import service, internet
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
However, to run this application as a Twisted server, I have to run it via the "Twisted Command Prompt", with the command:
```
twistd -y chatserver.py
```
Is there any way to change the code (set Twisted configuration settings, etc) so that I can simply run it via:
```
python chatserver.py
```
I've Googled, but the search terms seem to be too vague to return any meaningful responses.
Thanks.
|
2009/12/13
|
[
"https://Stackoverflow.com/questions/1897939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117603/"
] |
Maybe one of `run` or `runApp` in [twisted.scripts.twistd](http://twistedmatrix.com/documents/9.0.0/api/twisted.scripts.twistd.html) modules will work for you. Please let me know if it does, it will be nice to know!
|
I haven't used twisted myself. However, you may try seeing if the twistd is a python file itself. I would take a guess that it is simply managing loading the appropriate twisted libraries from the correct path.
|
57,652,922
|
Say I want to use [black](https://black.readthedocs.io/en/stable/index.html) as an API, and do something like:
```
import black
black.format("some python code")
```
Formatting code by calling the `black` binary with `Popen` is an alternative, but that's not what I'm asking.
|
2019/08/26
|
[
"https://Stackoverflow.com/questions/57652922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2142577/"
] |
You could try using `format_str`:
```
from black import format_str, FileMode
res = format_str("some python code", mode=FileMode())
print(res)
```
|
Use `black.format_file_contents`.
*e.g.*
```py
import black
mode = black.FileMode()
fast = False
out = black.format_file_contents("some python code", fast, mode)
```
<https://github.com/psf/black/blob/19.3b0/black.py#L642>
|
38,788,816
|
I need to install dryscrape for python but I got error, what's the problem?
```
C:\Users\parvij\Anaconda3\Scripts>pip install dryscrape
```
I got this:
```
Collecting dryscrape
Collecting webkit-server>=1.0 (from dryscrape)
Using cached webkit-server-1.0.tar.gz
Collecting xvfbwrapper (from dryscrape)
Requirement already satisfied (use --upgrade to upgrade): lxml in c:\users\parvij\anaconda3\lib\site-packages (from dryscrape)
Building wheels for collected packages: webkit-server
Running setup.py bdist_wheel for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\parvij\AppData\Local\Temp\tmp71w59qv6pip-wheel- --python-tag cp35:
running bdist_wheel
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Failed building wheel for webkit-server
Running setup.py clean for webkit-server
Failed to build webkit-server
Installing collected packages: webkit-server, xvfbwrapper, dryscrape
Running setup.py install for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open',open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Command "c:\users\parvij\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\parvij\AppData\Local\Temp\pip-build-o7nlv0dz\webkit-server\
```
my operating system is windows 8
my python version is 3.5
|
2016/08/05
|
[
"https://Stackoverflow.com/questions/38788816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4042278/"
] |
Need to install <http://www.qt.io>. Also, The 5.6+ version of Qt removes the Qt WebKit module in favor of the new module Qt WebEngine. So far, webkit-server has not been ported to WebEngine (and likely won't be in the near future), so Qt <= 5.5 is a requirement.
|
From the [doc](http://dryscrape.readthedocs.io/en/latest/installation.html), you have to installed also [requirements](https://github.com/niklasb/dryscrape/blob/master/requirements.txt).
You can do this as follow
```
pip install -r requirements.txt
```
After this retry to install **dryscrape**.
|
38,788,816
|
I need to install dryscrape for python but I got error, what's the problem?
```
C:\Users\parvij\Anaconda3\Scripts>pip install dryscrape
```
I got this:
```
Collecting dryscrape
Collecting webkit-server>=1.0 (from dryscrape)
Using cached webkit-server-1.0.tar.gz
Collecting xvfbwrapper (from dryscrape)
Requirement already satisfied (use --upgrade to upgrade): lxml in c:\users\parvij\anaconda3\lib\site-packages (from dryscrape)
Building wheels for collected packages: webkit-server
Running setup.py bdist_wheel for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\parvij\AppData\Local\Temp\tmp71w59qv6pip-wheel- --python-tag cp35:
running bdist_wheel
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Failed building wheel for webkit-server
Running setup.py clean for webkit-server
Failed to build webkit-server
Installing collected packages: webkit-server, xvfbwrapper, dryscrape
Running setup.py install for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open',open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Command "c:\users\parvij\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\parvij\AppData\Local\Temp\pip-build-o7nlv0dz\webkit-server\
```
my operating system is windows 8
my python version is 3.5
|
2016/08/05
|
[
"https://Stackoverflow.com/questions/38788816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4042278/"
] |
Download webkit-server from github
```
git clone https://github.com/niklasb/webkit-server.git webkit-server
```
Change in webkit-server/setup.py :
```
shutil.copy('src/webkit_server', self.build_purelib)
shutil.copy('src/webkit_server', self.build_platlib)
```
to
```
shutil.copy('src/webkit_server.pro', self.build_purelib)
shutil.copy('src/webkit_server.pro', self.build_platlib)
```
then
```
cd webkit-server
python setup.py install
```
There you go.
|
From the [doc](http://dryscrape.readthedocs.io/en/latest/installation.html), you have to installed also [requirements](https://github.com/niklasb/dryscrape/blob/master/requirements.txt).
You can do this as follow
```
pip install -r requirements.txt
```
After this retry to install **dryscrape**.
|
38,788,816
|
I need to install dryscrape for python but I got error, what's the problem?
```
C:\Users\parvij\Anaconda3\Scripts>pip install dryscrape
```
I got this:
```
Collecting dryscrape
Collecting webkit-server>=1.0 (from dryscrape)
Using cached webkit-server-1.0.tar.gz
Collecting xvfbwrapper (from dryscrape)
Requirement already satisfied (use --upgrade to upgrade): lxml in c:\users\parvij\anaconda3\lib\site-packages (from dryscrape)
Building wheels for collected packages: webkit-server
Running setup.py bdist_wheel for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\parvij\AppData\Local\Temp\tmp71w59qv6pip-wheel- --python-tag cp35:
running bdist_wheel
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Failed building wheel for webkit-server
Running setup.py clean for webkit-server
Failed to build webkit-server
Installing collected packages: webkit-server, xvfbwrapper, dryscrape
Running setup.py install for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open',open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Command "c:\users\parvij\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\parvij\AppData\Local\Temp\pip-build-o7nlv0dz\webkit-server\
```
my operating system is windows 8
my python version is 3.5
|
2016/08/05
|
[
"https://Stackoverflow.com/questions/38788816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4042278/"
] |
Download webkit-server from github
```
git clone https://github.com/niklasb/webkit-server.git webkit-server
```
Change in webkit-server/setup.py :
```
shutil.copy('src/webkit_server', self.build_purelib)
shutil.copy('src/webkit_server', self.build_platlib)
```
to
```
shutil.copy('src/webkit_server.pro', self.build_purelib)
shutil.copy('src/webkit_server.pro', self.build_platlib)
```
then
```
cd webkit-server
python setup.py install
```
There you go.
|
Need to install <http://www.qt.io>. Also, The 5.6+ version of Qt removes the Qt WebKit module in favor of the new module Qt WebEngine. So far, webkit-server has not been ported to WebEngine (and likely won't be in the near future), so Qt <= 5.5 is a requirement.
|
38,788,816
|
I need to install dryscrape for python but I got error, what's the problem?
```
C:\Users\parvij\Anaconda3\Scripts>pip install dryscrape
```
I got this:
```
Collecting dryscrape
Collecting webkit-server>=1.0 (from dryscrape)
Using cached webkit-server-1.0.tar.gz
Collecting xvfbwrapper (from dryscrape)
Requirement already satisfied (use --upgrade to upgrade): lxml in c:\users\parvij\anaconda3\lib\site-packages (from dryscrape)
Building wheels for collected packages: webkit-server
Running setup.py bdist_wheel for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\parvij\AppData\Local\Temp\tmp71w59qv6pip-wheel- --python-tag cp35:
running bdist_wheel
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Failed building wheel for webkit-server
Running setup.py clean for webkit-server
Failed to build webkit-server
Installing collected packages: webkit-server, xvfbwrapper, dryscrape
Running setup.py install for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open',open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Command "c:\users\parvij\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\parvij\AppData\Local\Temp\pip-build-o7nlv0dz\webkit-server\
```
my operating system is windows 8
my python version is 3.5
|
2016/08/05
|
[
"https://Stackoverflow.com/questions/38788816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4042278/"
] |
Need to install <http://www.qt.io>. Also, The 5.6+ version of Qt removes the Qt WebKit module in favor of the new module Qt WebEngine. So far, webkit-server has not been ported to WebEngine (and likely won't be in the near future), so Qt <= 5.5 is a requirement.
|
Need do install `qt4` and `libqtwebkit-dev` for compile `webkit-server`, then follow the steps of [@Erwan Clügairtz](https://stackoverflow.com/a/42809856/11831316)
`sudo apt install libqtwebkit-dev qt4`
|
38,788,816
|
I need to install dryscrape for python but I got error, what's the problem?
```
C:\Users\parvij\Anaconda3\Scripts>pip install dryscrape
```
I got this:
```
Collecting dryscrape
Collecting webkit-server>=1.0 (from dryscrape)
Using cached webkit-server-1.0.tar.gz
Collecting xvfbwrapper (from dryscrape)
Requirement already satisfied (use --upgrade to upgrade): lxml in c:\users\parvij\anaconda3\lib\site-packages (from dryscrape)
Building wheels for collected packages: webkit-server
Running setup.py bdist_wheel for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\Users\parvij\AppData\Local\Temp\tmp71w59qv6pip-wheel- --python-tag cp35:
running bdist_wheel
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Failed building wheel for webkit-server
Running setup.py clean for webkit-server
Failed to build webkit-server
Installing collected packages: webkit-server, xvfbwrapper, dryscrape
Running setup.py install for webkit-server ... error
Complete output from command c:\users\parvij\anaconda3\python.exe -u -c"import setuptools,tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open',open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile:
running install
running build
'make' is not recognized as an internal or external command,
operable program or batch file.
error: [Errno 2] No such file or directory: 'src/webkit_server'
----------------------------------------
Command "c:\users\parvij\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\parvij\\AppData\\Local\\Temp\\pip-build-o7nlv0dz\\webkit-server\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\parvij\AppData\Local\Temp\pip-tyzalid7-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\parvij\AppData\Local\Temp\pip-build-o7nlv0dz\webkit-server\
```
my operating system is windows 8
my python version is 3.5
|
2016/08/05
|
[
"https://Stackoverflow.com/questions/38788816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4042278/"
] |
Download webkit-server from github
```
git clone https://github.com/niklasb/webkit-server.git webkit-server
```
Change in webkit-server/setup.py :
```
shutil.copy('src/webkit_server', self.build_purelib)
shutil.copy('src/webkit_server', self.build_platlib)
```
to
```
shutil.copy('src/webkit_server.pro', self.build_purelib)
shutil.copy('src/webkit_server.pro', self.build_platlib)
```
then
```
cd webkit-server
python setup.py install
```
There you go.
|
Need do install `qt4` and `libqtwebkit-dev` for compile `webkit-server`, then follow the steps of [@Erwan Clügairtz](https://stackoverflow.com/a/42809856/11831316)
`sudo apt install libqtwebkit-dev qt4`
|
33,464,208
|
Is there a pythonic/efficient way to carry out a simple decrement operation on each element (or more accurately a subset of the elements) in a list of objects of an arbitrary class?
I potentially have a large-ish (~ 10K) list of objects, each of which is updated periodically on the basis of a countdown "time to update" (TTU) value.
The simple way to handle this would be to decrement this value in each element as below:
```
def BatesNumber(start = 0):
n = start
while True:
yield n
n += 1
class foo:
index = BatesNumber()
def __init__(self, ttu):
self.id = next(foo.index)
self.time = ttu
self.ttu = ttu
def __repr__(self):
return "#{}:{}/{}".format(self.id, self.ttu, self.time)
def Decrement(self):
self.ttu -= 1
def Reset(self):
print("Reset {} to {}".format(self.id, self.time))
self.ttu = self.time
def IsReadyForUpdate(self):
if self.ttu == 0:
return True
else:
return False
bar = [foo(i) for i in range(10, 20, 2)]
for n in range(50):
for p in bar:
if p.IsReadyForUpdate():
print("{} {}".format(n, p))
p.Reset()
else:
p.Decrement()
```
So I guess what I am after is some Pythonic way of "vectorising" the decrement operation - i.e. decrement all the elements in the list in a suitably elegant way; and, ideally, returning those elements which require update/reset.
I could (although it seems a bit unnecessarily horrible) produce a list which is ordered on the TTU value, and have all the TTU values relative to their neighbour. That way I would only require one decrement per cycle, but then when I reset the counter I have the pain of rebuilding the list. I suppose that this would be better for a very long list with quite high TTU values.
I presume the best/Pythonic way to check which of the elements is ready for update is using a list comprehension.
Any advice?
|
2015/11/01
|
[
"https://Stackoverflow.com/questions/33464208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171112/"
] |
Perhaps you could replace your flat list with a priority queue using the `heapq` module. The priorities would be the current time, plus the object's `ttu`. When the current time matched the top element's priority, you'd pop it off, do whatever your updating was, and then push it back into the queue with a new priority.
The code would look something like this:
```
import heapq
items = [foo(i) for i in range(10,20)]
queue = [(f.ttu, f.id, f) for f in items]
heapq.heapify(queue)
for t in range(50):
while t >= queue[0][0]:
_, _, f = heapq.heappop(queue)
# update f here
heapq.heappush(queue, (t + f.ttu, f.id, f))
```
I'm using the object's `id` attribute as a tie breaker when two objects need to be updated at the same time. If you wanted to, you could make the priority queue implementation easier by implementing a `__lt__` operator in the objects to allow them to be compared directly. If you made them track their own update times, the queue could just contain the objects directly (like the `items` list) rather than tuples to make them sort in order of priority.
Something like:
```
class foo:
index = BatesNumber()
def __init__(self, ttu):
self.id = next(index)
self.next_update = ttu
self.ttu = ttu
def __lt__(self, other):
return (self.next_update, self.id) < (other.next_update, other.id)
# ideally you'd also write __eq__, __gt__, etc. methods, but heapq only needs __lt__
def update(self):
self.next_update += self.ttu
# maybe do other update stuff here?
```
By the way, your `BatesNumber` class is essentially identical to `itertools.count`.
|
I think your code is already good; maybe you could add a single method called something like "beat" for performing both things:
* checking if the object is ready to update and in that case handle the update,
* or decrement in the other case;
it would make your loop a little cleaner and simpler. It won't help much for the "vectorization" part of your question but it would go deeper in the "object oriented" way of programming.
For the "vectorization" part; will your list change much during the whole process? One idea could be: have a separate Numpy array containing the values to be decremented and have the table matching your list by the index. Of course it will not be very convenient if you have to suppress instances during the computation but if it isn't the case, it may be the way to go.
|
39,029,068
|
I want to be able to execute the following code:
```
import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=k
```
Which should return the same output as:
```
z=numpy.zeros(4)
for i in range(6):
z[i]=z[i-1]
```
If I execute the first code block, I get an expected error message:
```
File "<ipython-input-982-3ba4e617a74a>", line 1, in <module>
z[i]=(k)
ValueError: could not convert string to float: 'z[i-1]'
```
How can I pass the text from the string into the loop so that it functions as an equation, as if the characters from the string were typed by hand?
|
2016/08/18
|
[
"https://Stackoverflow.com/questions/39029068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5510581/"
] |
I think you're looking for the [builtin `eval()`](https://docs.python.org/2/library/functions.html#eval)
Consider:
```
>>> z = numpy.zeros(4)
>>> k = "10 + z[i-1]"
>>> for i in range(1, 4):
... z[i] = eval(k)
...
>>> z
array([ 0., 10., 20., 30.])
```
I made the expression a little more complex so you could see interesting output.
|
Do it as following:
```
import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=eval(k)
```
But note eval can be a security problem: <http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.