qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
13,283,253 | I just upgraded to Django 1.4 and it has broken a couple things including messaging.
Here's the error I get when trying to change a avatar:
```
'User' object has no attribute 'message_set'
Exception Location: /Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py in inner, line 185
```
Traceback:
```
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "/Users/nb/Desktop/spicestore/apps/avatar/views.py" in change
76. request.user.message_set.create(
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py" in inner
185. return func(self._wrapped, *args)
Exception Type: AttributeError at /avatar/change/
Exception Value: 'User' object has no attribute 'message_set'
```
Also, messaging no longer works on the site. What are the changes in Django 1.4 that could be causing this and has anyone overcome a similar issue? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1328021/"
] | Django introduced a messages app in 1.2 ([release notes](https://docs.djangoproject.com/en/dev/releases/1.2/#messages-framework)), and deprecated the old user messages API.
In Django 1.4, the old message\_set API has been removed completely, so you'll have to update your code. If you follow the [messages docs](https://docs.djangoproject.com/en/dev/ref/contrib/messages/), you should find it pretty straight forward. | What is in your `INSTALLED_APPS` in your `settings.py`?
Do you have `'django.contrib.messages',` included there?
Something like:
```
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
...
``` |
13,283,253 | I just upgraded to Django 1.4 and it has broken a couple things including messaging.
Here's the error I get when trying to change a avatar:
```
'User' object has no attribute 'message_set'
Exception Location: /Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py in inner, line 185
```
Traceback:
```
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "/Users/nb/Desktop/spicestore/apps/avatar/views.py" in change
76. request.user.message_set.create(
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py" in inner
185. return func(self._wrapped, *args)
Exception Type: AttributeError at /avatar/change/
Exception Value: 'User' object has no attribute 'message_set'
```
Also, messaging no longer works on the site. What are the changes in Django 1.4 that could be causing this and has anyone overcome a similar issue? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1328021/"
] | Add
```
from django.contrib import messages
```
And then
```
def foo(request):
messages.add_message(request, messages.INFO, "Your message.")
``` | What is in your `INSTALLED_APPS` in your `settings.py`?
Do you have `'django.contrib.messages',` included there?
Something like:
```
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
...
``` |
13,283,253 | I just upgraded to Django 1.4 and it has broken a couple things including messaging.
Here's the error I get when trying to change a avatar:
```
'User' object has no attribute 'message_set'
Exception Location: /Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py in inner, line 185
```
Traceback:
```
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "/Users/nb/Desktop/spicestore/apps/avatar/views.py" in change
76. request.user.message_set.create(
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py" in inner
185. return func(self._wrapped, *args)
Exception Type: AttributeError at /avatar/change/
Exception Value: 'User' object has no attribute 'message_set'
```
Also, messaging no longer works on the site. What are the changes in Django 1.4 that could be causing this and has anyone overcome a similar issue? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1328021/"
] | Django introduced a messages app in 1.2 ([release notes](https://docs.djangoproject.com/en/dev/releases/1.2/#messages-framework)), and deprecated the old user messages API.
In Django 1.4, the old message\_set API has been removed completely, so you'll have to update your code. If you follow the [messages docs](https://docs.djangoproject.com/en/dev/ref/contrib/messages/), you should find it pretty straight forward. | From Django 1.4 docs
To enable message functionality, in settings.py do the following:
Edit the `MIDDLEWARE_CLASSES` setting and make sure it contains
```
'django.contrib.messages.middleware.MessageMiddleware'
```
If you are using a storage backend that relies on sessions (the default), `django.contrib.sessions.middleware.SessionMiddleware` must be enabled and appear before `MessageMiddleware` in your `MIDDLEWARE_CLASSES`.
Edit the `TEMPLATE_CONTEXT_PROCESSORS` setting and make sure it contains
```
'django.contrib.messages.context_processors.messages'
```
Add `'django.contrib.messages'` to your `INSTALLED_APPS` setting
As far as django-avatar is concerned. Use the master files found here: <https://github.com/chadpaulson/django-avatar/tree/master/avatar> |
13,283,253 | I just upgraded to Django 1.4 and it has broken a couple things including messaging.
Here's the error I get when trying to change a avatar:
```
'User' object has no attribute 'message_set'
Exception Location: /Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py in inner, line 185
```
Traceback:
```
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "/Users/nb/Desktop/spicestore/apps/avatar/views.py" in change
76. request.user.message_set.create(
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py" in inner
185. return func(self._wrapped, *args)
Exception Type: AttributeError at /avatar/change/
Exception Value: 'User' object has no attribute 'message_set'
```
Also, messaging no longer works on the site. What are the changes in Django 1.4 that could be causing this and has anyone overcome a similar issue? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1328021/"
] | Django introduced a messages app in 1.2 ([release notes](https://docs.djangoproject.com/en/dev/releases/1.2/#messages-framework)), and deprecated the old user messages API.
In Django 1.4, the old message\_set API has been removed completely, so you'll have to update your code. If you follow the [messages docs](https://docs.djangoproject.com/en/dev/ref/contrib/messages/), you should find it pretty straight forward. | Add
```
from django.contrib import messages
```
And then
```
def foo(request):
messages.add_message(request, messages.INFO, "Your message.")
``` |
13,283,253 | I just upgraded to Django 1.4 and it has broken a couple things including messaging.
Here's the error I get when trying to change a avatar:
```
'User' object has no attribute 'message_set'
Exception Location: /Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py in inner, line 185
```
Traceback:
```
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "/Users/nb/Desktop/spicestore/apps/avatar/views.py" in change
76. request.user.message_set.create(
File "/Users/nb/Desktop/myenv2/lib/python2.7/site-packages/django/utils/functional.py" in inner
185. return func(self._wrapped, *args)
Exception Type: AttributeError at /avatar/change/
Exception Value: 'User' object has no attribute 'message_set'
```
Also, messaging no longer works on the site. What are the changes in Django 1.4 that could be causing this and has anyone overcome a similar issue? | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1328021/"
] | Add
```
from django.contrib import messages
```
And then
```
def foo(request):
messages.add_message(request, messages.INFO, "Your message.")
``` | From Django 1.4 docs
To enable message functionality, in settings.py do the following:
Edit the `MIDDLEWARE_CLASSES` setting and make sure it contains
```
'django.contrib.messages.middleware.MessageMiddleware'
```
If you are using a storage backend that relies on sessions (the default), `django.contrib.sessions.middleware.SessionMiddleware` must be enabled and appear before `MessageMiddleware` in your `MIDDLEWARE_CLASSES`.
Edit the `TEMPLATE_CONTEXT_PROCESSORS` setting and make sure it contains
```
'django.contrib.messages.context_processors.messages'
```
Add `'django.contrib.messages'` to your `INSTALLED_APPS` setting
As far as django-avatar is concerned. Use the master files found here: <https://github.com/chadpaulson/django-avatar/tree/master/avatar> |
64,518,660 | I am currently working with an API in python and trying to retrieve previous institution ID's from certain authors.
I have come to this point
```py
my_auth.hist_names['affiliation']
```
which outputs:
```
[{'@_fa': 'true',
'@id': '60016491',
'@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/60016491'},
{'@_fa': 'true',
'@id': '60023955',
'@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/60023955'},
{'@_fa': 'true',
'@id': '109604360',
'@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/109604360'},
{'@_fa': 'true',
'@id': '112377026',
'@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/112377026'},
{'@_fa': 'true',
'@id': '112678642',
'@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/112678642'},
{'@_fa': 'true',
'@id': '60031106',
'@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/60031106'}]
```
The type here is list.
I'd like to use this list as a dictionary to retrieve the
`'@id'`
section | 2020/10/24 | [
"https://Stackoverflow.com/questions/64518660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12758690/"
] | @Anton Sizikov,
Thanks for reply, but my problem was another. Unlike Downloadpipelineartifact@2, the DownloadBuildArtifacts@0 task did not work by entering the project name and pipeline for me:
```
- task: DownloadBuildArtifacts@0
inputs:
buildType: 'current'
project: 'Leaf'
pipeline: 'Leaf'
buildVersionToDownload: 'latest'
branchName: 'refs/heads/develop'
downloadType: 'specific'
itemPattern: '**/*.exe'
downloadPath: $(Build.ArtifactStagingDirectory)
```
By chance I decided to create the download task through the azure interface, that made the value of the "pipeline" and "project" fields change their value (would it be the ID?).
Anyway, the task looked like this:
```
- task: DownloadBuildArtifacts@0
inputs:
buildType: 'specific'
project: '8c3c84b6-802b-4187-a1bb-b75ac9c7d48e'
pipeline: '4'
specificBuildWithTriggering: true
buildVersionToDownload: 'latest'
allowPartiallySucceededBuilds: true
downloadType: 'specific'
itemPattern: '**/*.exe'
downloadPath: '$(System.ArtifactsDirectory)'
```
Know, I can identify my artifact downloaded using dir command. | Based on your log I can see that your artifact was downloaded to `$(Build.ArtifactStagingDirectory)` directory, which is `D:\a\1\a` in your case. Then you run `dir` command there:
```sh
Successfully downloaded artifacts to D:\a\1\a
2020-10-24T22:25:48.7993950Z Directory of D:\a\1\a
2020-10-24T22:25:48.7994230Z
2020-10-24T22:25:48.7994896Z 10/24/2020 10:24 PM <DIR> .
2020-10-24T22:25:48.7995491Z 10/24/2020 10:24 PM <DIR> ..
2020-10-24T22:25:48.7999544Z 0 File(s) 0 bytes
2020-10-24T22:25:48.8000346Z 2 Dir(s) 11,552,690,176 bytes free
```
[Download Build Artifacts task](https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/download-build-artifacts?view=azure-devops) works slightly differently comparing to the old task.
It puts the files into a `<downloadPath>/<artifact-name>` directory. You can see there you've got two of them in your expected path.
This is [a known issue](https://github.com/Microsoft/azure-pipelines-tasks/issues/6739). |
32,342,262 | I am looking for a way to search a large string for a large number of equal length substrings.
My current method is basically this:
```
offset = 0
found = []
while offset < len(haystack):
current_chunk = haystack[offset*8:offset*8+8]
if current_chunk in needles:
found.append(current_chunk)
offset += 1
```
This is painfully slow. Is there a better python way of doing this? | 2015/09/01 | [
"https://Stackoverflow.com/questions/32342262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2448592/"
] | More Pythonic, much faster:
```
for needle in needles:
if needle in haystack:
found.append(needle)
```
Edit: With some limited testing here are test results
**This algorithm:**
0.000135183334351
**Your algorithm:**
0.984048128128
Much faster. | I think that you can break it up on a multicore and parallelize your search. Something along the lines of:
```
from multiprocessing import Pool
text = "Your very long string"
"""
A generator function for chopping up a given list into chunks of
length n.
"""
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
def searchHaystack(haystack, needles):
offset = 0
found = []
while offset < len(haystack):
current_chunk = haystack[offset*8:offset*8+8]
if current_chunk in needles:
found.append(current_chunk)
offset += 1
return(needles)
# Build a pool of 8 processes
pool = Pool(processes=8,)
# Fragment the string data into 8 chunks
partitioned_text = list(chunks(text, len(text) / 8))
# Generate all the needles found
all_the_needles = pool.map(searchHaystack, partitioned_text, needles)
``` |
37,661,456 | I would like to use spark jdbc with python. First step was to add a jar:
```
%AddJar http://central.maven.org/maven2/org/apache/hive/hive-jdbc/2.0.0/hive-jdbc-2.0.0.jar -f
```
However, the response:
```
ERROR: Line magic function `%AddJar` not found.
```
How can I add JDBC jar files in a python script? | 2016/06/06 | [
"https://Stackoverflow.com/questions/37661456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033422/"
] | Presently, this is not possible only from a python notebook; but it is understood as an important requirement. What you can do until this is supported, is from the same spark service instance of your python notebook, create a scala notebook and `%AddJar` from there. Then all python notebooks of that same spark service instance can access it. For py notebooks that were active when you added the jar from the scala nb, you will need to restart their kernels.
Note that this works for notebook instances on Jupyter 4+ but not necessarily for earlier IPython notebook instances; check the version from the Help -> About menu from a notebook. Any new notebook instances created recently will be on Jupyter 4+. | I don't think this is possible in Notebook's Python Kernel as %Addjar is scala kernel magic function in notebook.
You would need to rely on the service provider to add this jar to python kernel.
Another thing you could try is sc.addjar() but not sure how would it work.
[Add jar to pyspark when using notebook](https://stackoverflow.com/questions/31677345/add-jar-to-pyspark-when-using-notebook)
Thanks,
Charles. |
37,661,456 | I would like to use spark jdbc with python. First step was to add a jar:
```
%AddJar http://central.maven.org/maven2/org/apache/hive/hive-jdbc/2.0.0/hive-jdbc-2.0.0.jar -f
```
However, the response:
```
ERROR: Line magic function `%AddJar` not found.
```
How can I add JDBC jar files in a python script? | 2016/06/06 | [
"https://Stackoverflow.com/questions/37661456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033422/"
] | I don't think this is possible in Notebook's Python Kernel as %Addjar is scala kernel magic function in notebook.
You would need to rely on the service provider to add this jar to python kernel.
Another thing you could try is sc.addjar() but not sure how would it work.
[Add jar to pyspark when using notebook](https://stackoverflow.com/questions/31677345/add-jar-to-pyspark-when-using-notebook)
Thanks,
Charles. | You can try this:
```
spark.sparkContext.addFile("filename")
``` |
37,661,456 | I would like to use spark jdbc with python. First step was to add a jar:
```
%AddJar http://central.maven.org/maven2/org/apache/hive/hive-jdbc/2.0.0/hive-jdbc-2.0.0.jar -f
```
However, the response:
```
ERROR: Line magic function `%AddJar` not found.
```
How can I add JDBC jar files in a python script? | 2016/06/06 | [
"https://Stackoverflow.com/questions/37661456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033422/"
] | Presently, this is not possible only from a python notebook; but it is understood as an important requirement. What you can do until this is supported, is from the same spark service instance of your python notebook, create a scala notebook and `%AddJar` from there. Then all python notebooks of that same spark service instance can access it. For py notebooks that were active when you added the jar from the scala nb, you will need to restart their kernels.
Note that this works for notebook instances on Jupyter 4+ but not necessarily for earlier IPython notebook instances; check the version from the Help -> About menu from a notebook. Any new notebook instances created recently will be on Jupyter 4+. | You can try this:
```
spark.sparkContext.addFile("filename")
``` |
36,533,759 | I have a file.dat of this type but with a lot more data:
```
Apr 1 18:15 [n1_Cam_A_120213_O.fits]:
4101.77 1. -3.5612 3.561 -0.278635 4.707 6.448 #data1
0.03223 0. 0.05278 0.05278 0.00237 0.4393 0.4125 #error1
4088.9 1. -0.404974 0.405 -0.06538 5.819 0. #data2
0. 0. 0.01559 0.01559 0.00277 0.1717 0. #error2
4116.4 1. -0.225521 0.2255 -0.041111 5.153 0. #data3
0. 0. 0.01947 0.01947 0.00368 0.4748 0. #error3
4120.8 1. -0.382279 0.3823 -0.062194 5.774 0. #data4
0. 0. 0.01873 0.01873 0.00311 0.3565 0. #error4
Apr 1 18:15 [n1_Cam_B_120213_O.fits]:
4101.767 0.9999 -4.57791 4.578 -0.388646 0.03091 7.499 #data1
0.0293 0. 0.03447 0.03447 0.00243 0.00873 0.07529 #error1
4088.9 1. -0.211493 0.2115 -0.080003 2.483 0.
0. 0. 0.01091 0.01091 0.00327 0.1275 0.
4116.4 1. -0.237161 0.2372 -0.040493 5.502 0.
0. 0. 0.02052 0.02052 0.00231 0.5069 0.
4120.8 1. -0.320798 0.3208 -0.108827 2.769 0.
0. 0. 0.0167 0.0167 0.00404 0.1165 0.
```
first row of each dataset contains a name.fits, even rows contain values, and odd rows (except first) contain errors of the values in the row before. Then comes a blank row and starts again.
What I need is to separate the information into different files in this way:
```
name1.fits data1[1] err1[1] data1[2] err1[2] data1[3] err1[3]...
name2.fits data1[1] err1[1] data1[2] err1[2] data1[3] err1[3]...
```
So the next file would be
```
name1.fits data2[1] err2[1] data2[2] err2[2] data2[3] err2[3]...
name2.fits data2[1] err2[1] data2[2] err2[2] data2[3] err2[3]...
```
Then the first new file of my data would look like:
```
n1_Cam_A_120213_O.fits 4101.77 0.03223 1. 0. -3.5612 0.05278 3.561 0.05278 -0.278635 0.00237 4.707 0.4393 6.448 0.4125
n1_Cam_B_120213_O.fits 4101.767 0.0293 0.9999 0. -4.57791 0.03447 4.578 0.03447 -0.388646 0.00243 0.03091 0.00873 7.499 0.07529
```
Here is what I have so far:
```
with open('file.dat','r') as data, open('names.txt', 'a') as nam, open('values.txt', 'a') as val, open('errors.txt', 'a') as err:
for lines in data.readlines():
cols = lines.split()
if "fits" in lines:
header = lines.split()
nam.write(header[3])
elif float(cols[0]) > 1:
#print cols[0]
x=str(cols)
val.write(x)
elif float(cols[0]) < 1:
#print cols[0]
y=str(cols)
err.write(y)
```
I'm just starting with python. I thought in separate name values and errors in different files and then select the rows and columns that I need. But since I'll be dealing with hundreds of rows and files, I would like a more automatic approach. What I want is to read the first 3 rows and write file1, then rows 1,4,5 and write file2, then rows 1,6,7 and write file3, then rows 1,8,9 and write file4, then skip blank row and read rows 11,12,13, and write file1, then rows 11,14,15 and write file2, and so forth (or something like that). | 2016/04/10 | [
"https://Stackoverflow.com/questions/36533759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6184340/"
] | Try to write **system("pause");** before **return 0;** at the end of your program and press ctrl + F5. | Try this:
```
std::cin.get();
if (oper == 1)
ans = num1*num2;
else if(oper == 2)
ans = num1 / num2;
else if(oper == 3)
ans = num1 + num2;
else if(oper == 4)
ans = num1 - num2;
std::cout << ans;
std::cin.get();//this will block and prevent the console from closing until you press a key
return 0;
``` |
57,257,751 | I've created my application in python and I want the application to be executed only one at a time. So I have used the singleton approach:
```py
from math import fmod
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import SIGNAL
import tendo
import pywinusb.hid as hid
import sys
import os
import time
import threading
import UsbHidCB05Connect
if __name__ == "__main__":
just_one = tendo.singleton.SingleInstance()
app = QtGui.QApplication(sys.argv)
screen_UsbHidConnect = ConnectFunction()
screen_UsbHidConnect.show()
sys.exit(app.exec_())
```
When using the pyinstaller to convert it to an exe, I did not get any error, but when I tried to run the exe I get the error: "Failed to execute script mainUsbHidCB05v01"
If in my code I comment the:
```
import tendo
```
and
```
just_one = tendo.singleton.SingleInstance()
```
I convert the script to an exe, and the exe runs without any problem.
But I'm able to have more than one instance / program running, and I don't want that.
I'm using pyinstaller like:
```
pyinstaller --noconsole -F -i cr.ico mainUsbHidCB05v01.py
```
I have also tried pyinstaller without the -F option. The result is the same.
Anyone have any idea why with the singleton option in the code the exe doesn't runs??
Thanks. | 2019/07/29 | [
"https://Stackoverflow.com/questions/57257751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6078511/"
] | >
> Hello, it's me again! So, I have found the solution. I search a lot and I found very different ways to make the program runs only one time (singleinstance).
>
>
>
>
> In summary, it's possible to use a lock file, using the library OS, but if the computer shutdowns in a energy fall, this file will stay locking your application when it returns, since the app was not closed properly. There is other way, when you use TENDO library to create a singleton, there are similar ways for that, but everyone uses some specific DLL, and when you use pyinstaller, adding/importing dll could be a little difficult.
>
>
>
>
> Finally, there is a third way, that creates a socket communication with the PC that verifies if some specific port is being using for the application. That works like a charm to me. The library is: <https://pypi.org/project/Socket-Singleton/>
>
>
>
>
> A simple and workable script:
>
>
>
```
from time import sleep
from Socket_Singleton import Socket_Singleton
#Socket_Singleton(address="127.0.0.1", port=1337, timeout=0, client=True, strict=True)
Socket_Singleton()
print("hello!")
sleep(10)
print("hello 2!")
```
>
> I used it with my app and create an .EXE file using pyinstaller and it works very well.
>
>
> | I had the same problem and I didn't find a way to use the singleinstance of tendo. If You need a solution right now, you can create a file using the "os" library, and put a variable there that when the program is running it is 1, else is 0, so you just have to verify that variable in the beginning of your program.
This is not the best way, but you can use that during the time you need to find a best solution. :) |
5,871,621 | I have a list of cities (simple cvs file) and I want to populate the citeis table while creating the City model.
Class description:
```
class City(models.Model):
city = modeld.CharField('city_name', max_length=50)
class Meta:
berbuse_name =....
...........
def __unicode__(self):
return self.city
```
Now, what I am looking for is how to do it only once, while creating the model(DB table).
I'm trying to do it over here because it sound very logic to me (like building a sql script in MS-sql and other)
EDIT: Ok, I guess I am asking the wrong thing....maybe this: How do I create a python function that will take the cvs file and transform it to json (Again, in the model itself, while it is being build) and should I do it at all???
Can any one please help me with this? | 2011/05/03 | [
"https://Stackoverflow.com/questions/5871621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288219/"
] | We do something like this, usually.
```
import csv
from my_django_app.forms import CityForm
with open( "my file", "rb" ) as source:
rdr = csv.DictReader( source )
for row in rdr:
form= CityForm( **row )
if form.is_valid():
form.save()
else:
print form.errors
```
This validates and loads the data.
After the data is loaded, you can use `django-admin dumpdata` to preserve a JSON fixture from the loaded model. | [Providing initial data for models](http://docs.djangoproject.com/en/1.3/howto/initial-data/). |
30,397,107 | I want to build a simple tool that uses functions from an open source project from GitHub, SourceForge, etc. (e.g., a project such as <https://github.com/vishnubob/python-midi/>).
I searched the documentation but could not find the right way to do this. (I assume I need to point PyCharm at the source somehow and "import")
I am utterly new to PyCharm and Python in general. This is just a test project. I am running PyCharm Pro 4.5 on OS X 10.10.3. PyCharm is up and running and just need to get to these functions.
Thanks so much. | 2015/05/22 | [
"https://Stackoverflow.com/questions/30397107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4929051/"
] | Yes there is a convention. Use `bower` if a package exists. If it doesn't, download the repo into the `vendor` folder. Import the file in your `Brocfile.js`
```
app.import('vendor/path_to/main_js_file.js');
``` | Yes, use bower or place them in `vendor/`. Then register them in `ember-cli-build.js`
Here's the documentation: <https://guides.emberjs.com/v2.14.0/addons-and-dependencies/managing-dependencies/> |
4,589,696 | I apologize up front for the dumbness of this question, but I can't figure it out and its driving me crazy.
In ruby I can do:
```
irb(main):001:0> s = "\t\t\n"
=> "\t\t\n"
irb(main):003:0> puts s
=> nil
irb(main):004:0> puts s.inspect
"\t\t\n"
```
Is there an equivalent of ruby's `inspect` function in python? | 2011/01/04 | [
"https://Stackoverflow.com/questions/4589696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561964/"
] | [`repr()`](http://docs.python.org/library/functions.html#repr):
```
>>> print repr('\t\t\n')
'\t\t\n'
``` | You can use repr or (backticks), I am doing the exactly the same things as you did above.
```
>>> s = "\t\t\n"
>>> s
'\t\t\n'
>>> print s
>>> repr(s)
"'\\t\\t\\n'"
>>> print repr(s)
'\t\t\n'
>>> print `s`
'\t\t\n'
``` |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | Thanks for your responses. Most were very good and provided good links so I'll just say that and answer my own question.
Caspin posted this [link](http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
He also mentioned that Google Tests used ULP comparison and when I looked at the google code I saw that they mentioned the same exact link to cygnus-software.
I wound up implementing some of the algorithms in C as a Python extension and then later found that I could do it in pure Python as well. The code is posted below.
In the end, I will probably just wind up adding ULP differences to my bag of tricks.
It was interesting to see how many floating points are between what should be two equal numbers that never left memory. One of the articles or the google code I read said that 4 was a good number... but here I was able to hit 10.
```
>>> f1 = 25.4
>>> f2 = f1
>>>
>>> for i in xrange(1, 11):
... f2 /= 10.0 # to cm
... f2 *= (1.0 / 2.54) # to in
... f2 *= 25.4 # back to mm
... print 'after %2d loops there are %2d doubles between them' % (i, dulpdiff(f1, f2))
...
after 1 loops there are 1 doubles between them
after 2 loops there are 2 doubles between them
after 3 loops there are 3 doubles between them
after 4 loops there are 4 doubles between them
after 5 loops there are 6 doubles between them
after 6 loops there are 7 doubles between them
after 7 loops there are 8 doubles between them
after 8 loops there are 10 doubles between them
after 9 loops there are 10 doubles between them
after 10 loops there are 10 doubles between them
```
---
Also interesting is how many floating points there are between equal numbers when one of them is written out as a string and read back in.
```
>>> # 0 degrees Fahrenheit is -32 / 1.8 degrees Celsius
... f = -32 / 1.8
>>> s = str(f)
>>> s
'-17.7777777778'
>>> # floats between them...
... fulpdiff(f, float(s))
0
>>> # doubles between them...
... dulpdiff(f, float(s))
6255L
```
---
```
import struct
from functools import partial
# (c) 2010 Eric L. Frederich
#
# Python implementation of algorithms detailed here...
# from http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
def c_mem_cast(x, f=None, t=None):
'''
do a c-style memory cast
In Python...
x = 12.34
y = c_mem_cast(x, 'd', 'l')
... should be equivilent to the following in c...
double x = 12.34;
long y = *(long*)&x;
'''
return struct.unpack(t, struct.pack(f, x))[0]
dbl_to_lng = partial(c_mem_cast, f='d', t='l')
lng_to_dbl = partial(c_mem_cast, f='l', t='d')
flt_to_int = partial(c_mem_cast, f='f', t='i')
int_to_flt = partial(c_mem_cast, f='i', t='f')
def ulp_diff_maker(converter, negative_zero):
'''
Getting the ulp difference of floats and doubles is similar.
Only difference if the offset and converter.
'''
def the_diff(a, b):
# Make a integer lexicographically ordered as a twos-complement int
ai = converter(a)
if ai < 0:
ai = negative_zero - ai
# Make b integer lexicographically ordered as a twos-complement int
bi = converter(b)
if bi < 0:
bi = negative_zero - bi
return abs(ai - bi)
return the_diff
# double ULP difference
dulpdiff = ulp_diff_maker(dbl_to_lng, 0x8000000000000000)
# float ULP difference
fulpdiff = ulp_diff_maker(flt_to_int, 0x80000000 )
# default to double ULP difference
ulpdiff = dulpdiff
ulpdiff.__doc__ = '''
Get the number of doubles between two doubles.
'''
``` | >
> What is the best way to avoid problems
> like this?... In Python or in general.
>
>
>
What problem? You're working with physical measurements. Unless you have some *really* sophisticated equipment, the error in your measurements is going to be several orders of magnitude higher than floating-point epsilon. So why write code that depends on numbers being exact to 16 significant digits?
>
> Should compilers support an option to
> replace all float equality checks with
> a 'close enough' function?
>
>
>
If it did, you'd get some strange results:
```
>>> float.tolerance = 1e-8 # hypothetical "close enough" definition
>>> a = 1.23456789
>>> b = 1.23456790
>>> c = 1.23456791
>>> a == b
True
>>> b == c
True
>>> a == c
False
```
If you think it's hard enough to store floats in a dictionary now, try it with a non-transitive `==` operator! And performance would suck, because the only way to guarantee `x == y` → `hash(x) == hash(y)` would be for every float to have the same hash code. And that'd be inconsistent with ints. |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | The difference is that if you replace `factors[units_to ]` with `1.0 / 2.54`, you're doing:
```
(base_value * 1.0) / 2.54
```
With the dictionary, you're doing:
```
base_value * (1.0 / 2.54)
```
The order of rounding matters. This is easier to see if you do:
```
>>> print (((25.4 / 10.0) * 1.0) / 2.54).__repr__()
1.0
>>> print ((25.4 / 10.0) * (1.0 / 2.54)).__repr__()
0.99999999999999989
```
Note that there is no non-deterministic or undefined behavior. There is a standard, IEEE-754, which implementations must conform to (not to claim they always *do*).
I don't think there should be an *automatic* close enough replacement. That is often an effective way to deal with the problem, but it should be up to the programmer to decide if and how to use it.
Finally, there are of course options for arbitrary-precision arithmetic, including [python-gmp](http://code.google.com/p/python-gmp/) and [decimal](http://docs.python.org/library/decimal.html). Think whether you actually *need* these, because they do have a significant performance impact.
There is no issue with moving between regular registers and cache. You may be thinking of the x86's 80-bit [extended precision](http://en.wikipedia.org/wiki/Extended_precision). | >
> Also interesting is how many floating points there
> are between equal numbers when one of them is
> written out as a string and read back in.
>
>
>
That is arguably a Python bug. That number was written out with just twelve digits. Two uniquely identify a 64-bit double (Python's float type) you need seventeen digits of mantissa. If Python printed out its numbers with 17 digits of precision then you would be guaranteed to get back exactly the same value.
The precision issue is discussed at:
<http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/>
The focus is on 32-bit float (which requires nine digits of mantissa to uniquely identify each number) but it briefly mentions double, and the fact that it requires 17 digits of mantissa. |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | Let me first answer by saying that you should read David Goldberg's classic [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://citeseer.ist.psu.edu/viewdoc/download?doi=10.1.1.102.244&rep=rep1&type=pdf).
As some other commentators already said, the discrepancy you notice is intrinsically due to the floating-point model and has nothing to do with registers, cache or memory.
According to the floating-point model, 2.54 is actually represented as
```
>>> 2859785763380265 * 2 ** -50
2.54
```
This representation, however is not exact:
```
>>> from fractions import Fraction
>>> float(Fraction(2859785763380265, 2 ** 50) - Fraction(254, 100))
3.552713678800501e-17
```
Now, the expression you are evaluating actually is:
```
>>> 25.4 / 10 * (1/2.54)
0.99999999999999989
```
The problem lies in the 1/2.54:
```
>>> Fraction.from_float(1/2.54)
Fraction(1773070719437203, 4503599627370496)
```
But what you would expect is
```
>>> 1/Fraction.from_float(2.54)
Fraction(1125899906842624, 2859785763380265)
```
To answer your questions:
* It *is* a difficult problem, but is clearly deterministic, nothing mysterious there.
* You cannot automatically replace equality with a *close-enough* comparison. The latter requires that you specify a tolerance, which depends on the problem at hand, i.e. on what kind of precision you are expecting from your results. There are also plenty of situations where you really want equality not a *close-enough* comparison. | In order to compare floats in general compare the absolute value of the difference of the floats to a chosen delta that is small enough to fit your needs.
Rhetorical Questions
* This \*\*IS a dangerous problem \*\* as it might hide errors or generate infinite loops if such a comparison is used as stop criteria.
* Modern C/C++ compilers warn for comparison of floats for equality
* All static code checkers I know will output errors for the languages I use
I suppose it is the same for python, as the delta to use for comparison may vary it must be up to the implementer to choose it. What means that no good default transformation can be provided fully automatically. |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | Let me first answer by saying that you should read David Goldberg's classic [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://citeseer.ist.psu.edu/viewdoc/download?doi=10.1.1.102.244&rep=rep1&type=pdf).
As some other commentators already said, the discrepancy you notice is intrinsically due to the floating-point model and has nothing to do with registers, cache or memory.
According to the floating-point model, 2.54 is actually represented as
```
>>> 2859785763380265 * 2 ** -50
2.54
```
This representation, however is not exact:
```
>>> from fractions import Fraction
>>> float(Fraction(2859785763380265, 2 ** 50) - Fraction(254, 100))
3.552713678800501e-17
```
Now, the expression you are evaluating actually is:
```
>>> 25.4 / 10 * (1/2.54)
0.99999999999999989
```
The problem lies in the 1/2.54:
```
>>> Fraction.from_float(1/2.54)
Fraction(1773070719437203, 4503599627370496)
```
But what you would expect is
```
>>> 1/Fraction.from_float(2.54)
Fraction(1125899906842624, 2859785763380265)
```
To answer your questions:
* It *is* a difficult problem, but is clearly deterministic, nothing mysterious there.
* You cannot automatically replace equality with a *close-enough* comparison. The latter requires that you specify a tolerance, which depends on the problem at hand, i.e. on what kind of precision you are expecting from your results. There are also plenty of situations where you really want equality not a *close-enough* comparison. | >
> What is the best way to avoid problems
> like this?... In Python or in general.
>
>
>
What problem? You're working with physical measurements. Unless you have some *really* sophisticated equipment, the error in your measurements is going to be several orders of magnitude higher than floating-point epsilon. So why write code that depends on numbers being exact to 16 significant digits?
>
> Should compilers support an option to
> replace all float equality checks with
> a 'close enough' function?
>
>
>
If it did, you'd get some strange results:
```
>>> float.tolerance = 1e-8 # hypothetical "close enough" definition
>>> a = 1.23456789
>>> b = 1.23456790
>>> c = 1.23456791
>>> a == b
True
>>> b == c
True
>>> a == c
False
```
If you think it's hard enough to store floats in a dictionary now, try it with a non-transitive `==` operator! And performance would suck, because the only way to guarantee `x == y` → `hash(x) == hash(y)` would be for every float to have the same hash code. And that'd be inconsistent with ints. |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | The difference is that if you replace `factors[units_to ]` with `1.0 / 2.54`, you're doing:
```
(base_value * 1.0) / 2.54
```
With the dictionary, you're doing:
```
base_value * (1.0 / 2.54)
```
The order of rounding matters. This is easier to see if you do:
```
>>> print (((25.4 / 10.0) * 1.0) / 2.54).__repr__()
1.0
>>> print ((25.4 / 10.0) * (1.0 / 2.54)).__repr__()
0.99999999999999989
```
Note that there is no non-deterministic or undefined behavior. There is a standard, IEEE-754, which implementations must conform to (not to claim they always *do*).
I don't think there should be an *automatic* close enough replacement. That is often an effective way to deal with the problem, but it should be up to the programmer to decide if and how to use it.
Finally, there are of course options for arbitrary-precision arithmetic, including [python-gmp](http://code.google.com/p/python-gmp/) and [decimal](http://docs.python.org/library/decimal.html). Think whether you actually *need* these, because they do have a significant performance impact.
There is no issue with moving between regular registers and cache. You may be thinking of the x86's 80-bit [extended precision](http://en.wikipedia.org/wiki/Extended_precision). | Let me first answer by saying that you should read David Goldberg's classic [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://citeseer.ist.psu.edu/viewdoc/download?doi=10.1.1.102.244&rep=rep1&type=pdf).
As some other commentators already said, the discrepancy you notice is intrinsically due to the floating-point model and has nothing to do with registers, cache or memory.
According to the floating-point model, 2.54 is actually represented as
```
>>> 2859785763380265 * 2 ** -50
2.54
```
This representation, however is not exact:
```
>>> from fractions import Fraction
>>> float(Fraction(2859785763380265, 2 ** 50) - Fraction(254, 100))
3.552713678800501e-17
```
Now, the expression you are evaluating actually is:
```
>>> 25.4 / 10 * (1/2.54)
0.99999999999999989
```
The problem lies in the 1/2.54:
```
>>> Fraction.from_float(1/2.54)
Fraction(1773070719437203, 4503599627370496)
```
But what you would expect is
```
>>> 1/Fraction.from_float(2.54)
Fraction(1125899906842624, 2859785763380265)
```
To answer your questions:
* It *is* a difficult problem, but is clearly deterministic, nothing mysterious there.
* You cannot automatically replace equality with a *close-enough* comparison. The latter requires that you specify a tolerance, which depends on the problem at hand, i.e. on what kind of precision you are expecting from your results. There are also plenty of situations where you really want equality not a *close-enough* comparison. |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | Thanks for your responses. Most were very good and provided good links so I'll just say that and answer my own question.
Caspin posted this [link](http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
He also mentioned that Google Tests used ULP comparison and when I looked at the google code I saw that they mentioned the same exact link to cygnus-software.
I wound up implementing some of the algorithms in C as a Python extension and then later found that I could do it in pure Python as well. The code is posted below.
In the end, I will probably just wind up adding ULP differences to my bag of tricks.
It was interesting to see how many floating points are between what should be two equal numbers that never left memory. One of the articles or the google code I read said that 4 was a good number... but here I was able to hit 10.
```
>>> f1 = 25.4
>>> f2 = f1
>>>
>>> for i in xrange(1, 11):
... f2 /= 10.0 # to cm
... f2 *= (1.0 / 2.54) # to in
... f2 *= 25.4 # back to mm
... print 'after %2d loops there are %2d doubles between them' % (i, dulpdiff(f1, f2))
...
after 1 loops there are 1 doubles between them
after 2 loops there are 2 doubles between them
after 3 loops there are 3 doubles between them
after 4 loops there are 4 doubles between them
after 5 loops there are 6 doubles between them
after 6 loops there are 7 doubles between them
after 7 loops there are 8 doubles between them
after 8 loops there are 10 doubles between them
after 9 loops there are 10 doubles between them
after 10 loops there are 10 doubles between them
```
---
Also interesting is how many floating points there are between equal numbers when one of them is written out as a string and read back in.
```
>>> # 0 degrees Fahrenheit is -32 / 1.8 degrees Celsius
... f = -32 / 1.8
>>> s = str(f)
>>> s
'-17.7777777778'
>>> # floats between them...
... fulpdiff(f, float(s))
0
>>> # doubles between them...
... dulpdiff(f, float(s))
6255L
```
---
```
import struct
from functools import partial
# (c) 2010 Eric L. Frederich
#
# Python implementation of algorithms detailed here...
# from http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
def c_mem_cast(x, f=None, t=None):
'''
do a c-style memory cast
In Python...
x = 12.34
y = c_mem_cast(x, 'd', 'l')
... should be equivilent to the following in c...
double x = 12.34;
long y = *(long*)&x;
'''
return struct.unpack(t, struct.pack(f, x))[0]
dbl_to_lng = partial(c_mem_cast, f='d', t='l')
lng_to_dbl = partial(c_mem_cast, f='l', t='d')
flt_to_int = partial(c_mem_cast, f='f', t='i')
int_to_flt = partial(c_mem_cast, f='i', t='f')
def ulp_diff_maker(converter, negative_zero):
'''
Getting the ulp difference of floats and doubles is similar.
Only difference if the offset and converter.
'''
def the_diff(a, b):
# Make a integer lexicographically ordered as a twos-complement int
ai = converter(a)
if ai < 0:
ai = negative_zero - ai
# Make b integer lexicographically ordered as a twos-complement int
bi = converter(b)
if bi < 0:
bi = negative_zero - bi
return abs(ai - bi)
return the_diff
# double ULP difference
dulpdiff = ulp_diff_maker(dbl_to_lng, 0x8000000000000000)
# float ULP difference
fulpdiff = ulp_diff_maker(flt_to_int, 0x80000000 )
# default to double ULP difference
ulpdiff = dulpdiff
ulpdiff.__doc__ = '''
Get the number of doubles between two doubles.
'''
``` | >
> Also interesting is how many floating points there
> are between equal numbers when one of them is
> written out as a string and read back in.
>
>
>
That is arguably a Python bug. That number was written out with just twelve digits. Two uniquely identify a 64-bit double (Python's float type) you need seventeen digits of mantissa. If Python printed out its numbers with 17 digits of precision then you would be guaranteed to get back exactly the same value.
The precision issue is discussed at:
<http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/>
The focus is on 32-bit float (which requires nine digits of mantissa to uniquely identify each number) but it briefly mentions double, and the fact that it requires 17 digits of mantissa. |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | Let me first answer by saying that you should read David Goldberg's classic [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://citeseer.ist.psu.edu/viewdoc/download?doi=10.1.1.102.244&rep=rep1&type=pdf).
As some other commentators already said, the discrepancy you notice is intrinsically due to the floating-point model and has nothing to do with registers, cache or memory.
According to the floating-point model, 2.54 is actually represented as
```
>>> 2859785763380265 * 2 ** -50
2.54
```
This representation, however is not exact:
```
>>> from fractions import Fraction
>>> float(Fraction(2859785763380265, 2 ** 50) - Fraction(254, 100))
3.552713678800501e-17
```
Now, the expression you are evaluating actually is:
```
>>> 25.4 / 10 * (1/2.54)
0.99999999999999989
```
The problem lies in the 1/2.54:
```
>>> Fraction.from_float(1/2.54)
Fraction(1773070719437203, 4503599627370496)
```
But what you would expect is
```
>>> 1/Fraction.from_float(2.54)
Fraction(1125899906842624, 2859785763380265)
```
To answer your questions:
* It *is* a difficult problem, but is clearly deterministic, nothing mysterious there.
* You cannot automatically replace equality with a *close-enough* comparison. The latter requires that you specify a tolerance, which depends on the problem at hand, i.e. on what kind of precision you are expecting from your results. There are also plenty of situations where you really want equality not a *close-enough* comparison. | >
> Also interesting is how many floating points there
> are between equal numbers when one of them is
> written out as a string and read back in.
>
>
>
That is arguably a Python bug. That number was written out with just twelve digits. Two uniquely identify a 64-bit double (Python's float type) you need seventeen digits of mantissa. If Python printed out its numbers with 17 digits of precision then you would be guaranteed to get back exactly the same value.
The precision issue is discussed at:
<http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/>
The focus is on 32-bit float (which requires nine digits of mantissa to uniquely identify each number) but it briefly mentions double, and the fact that it requires 17 digits of mantissa. |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | The difference is that if you replace `factors[units_to ]` with `1.0 / 2.54`, you're doing:
```
(base_value * 1.0) / 2.54
```
With the dictionary, you're doing:
```
base_value * (1.0 / 2.54)
```
The order of rounding matters. This is easier to see if you do:
```
>>> print (((25.4 / 10.0) * 1.0) / 2.54).__repr__()
1.0
>>> print ((25.4 / 10.0) * (1.0 / 2.54)).__repr__()
0.99999999999999989
```
Note that there is no non-deterministic or undefined behavior. There is a standard, IEEE-754, which implementations must conform to (not to claim they always *do*).
I don't think there should be an *automatic* close enough replacement. That is often an effective way to deal with the problem, but it should be up to the programmer to decide if and how to use it.
Finally, there are of course options for arbitrary-precision arithmetic, including [python-gmp](http://code.google.com/p/python-gmp/) and [decimal](http://docs.python.org/library/decimal.html). Think whether you actually *need* these, because they do have a significant performance impact.
There is no issue with moving between regular registers and cache. You may be thinking of the x86's 80-bit [extended precision](http://en.wikipedia.org/wiki/Extended_precision). | if I run this
```
x = 0.3+0.3+0.3
if (x != 0.9): print "not equal"
if (x == 0.9): print "equal"
```
it prints "not equal" which is wrong but as
```
x-0.9
```
gives the float error as -1.11022302e-16 i just do something like this:
```
if (x - 0.9 < 10**-8): print "equal (almost)"
```
otherwise you can convert both to strings, I guess:
```
if (str(x) == str(0.9)): print "equal (strings)"
``` |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | if I run this
```
x = 0.3+0.3+0.3
if (x != 0.9): print "not equal"
if (x == 0.9): print "equal"
```
it prints "not equal" which is wrong but as
```
x-0.9
```
gives the float error as -1.11022302e-16 i just do something like this:
```
if (x - 0.9 < 10**-8): print "equal (almost)"
```
otherwise you can convert both to strings, I guess:
```
if (str(x) == str(0.9)): print "equal (strings)"
``` | >
> Also interesting is how many floating points there
> are between equal numbers when one of them is
> written out as a string and read back in.
>
>
>
That is arguably a Python bug. That number was written out with just twelve digits. Two uniquely identify a 64-bit double (Python's float type) you need seventeen digits of mantissa. If Python printed out its numbers with 17 digits of precision then you would be guaranteed to get back exactly the same value.
The precision issue is discussed at:
<http://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/>
The focus is on 32-bit float (which requires nine digits of mantissa to uniquely identify each number) but it briefly mentions double, and the fact that it requires 17 digits of mantissa. |
3,049,101 | I have a piece of code that behaves differently depending on whether I go through a dictionary to get conversion factors or whether I use them directly.
The following piece of code will print `1.0 == 1.0 -> False`
But if you replace `factors[units_from]` with `10.0` and `factors[units_to ]` with `1.0 / 2.54` it will print `1.0 == 1.0 -> True`
```
#!/usr/bin/env python
base = 'cm'
factors = {
'cm' : 1.0,
'mm' : 10.0,
'm' : 0.01,
'km' : 1.0e-5,
'in' : 1.0 / 2.54,
'ft' : 1.0 / 2.54 / 12.0,
'yd' : 1.0 / 2.54 / 12.0 / 3.0,
'mile' : 1.0 / 2.54 / 12.0 / 5280,
'lightyear' : 1.0 / 2.54 / 12.0 / 5280 / 5.87849981e12,
}
# convert 25.4 mm to inches
val = 25.4
units_from = 'mm'
units_to = 'in'
base_value = val / factors[units_from]
ret = base_value * factors[units_to ]
print ret, '==', 1.0, '->', ret == 1.0
```
Let me first say that I am pretty sure what is going on here. I have seen it before in C, just never in Python but since Python in implemented in C we're seeing it.
I know that floating point numbers will change values going from a CPU register to cache and back. I know that comparing what should be two equal variables will return false if one of them was paged out while the other stayed resident in a register.
**Questions**
* What is the best way to avoid problems like this?... In Python or in general.
* Am I doing something completely wrong?
**Side Note**
This is obviously part of a stripped down example but what I'm trying to do is come with with classes of length, volume, etc that can compare against other objects of the same class but with different units.
**Rhetorical Questions**
* If this is a potentially dangerous problem since it makes programs behave in an undetermanistic matter, should compilers warn or error when they detect that you're checking equality of floats
* Should compilers support an option to replace all float equality checks with a 'close enough' function?
* Do compilers already do this and I just can't find the information. | 2010/06/15 | [
"https://Stackoverflow.com/questions/3049101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180464/"
] | Thanks for your responses. Most were very good and provided good links so I'll just say that and answer my own question.
Caspin posted this [link](http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
He also mentioned that Google Tests used ULP comparison and when I looked at the google code I saw that they mentioned the same exact link to cygnus-software.
I wound up implementing some of the algorithms in C as a Python extension and then later found that I could do it in pure Python as well. The code is posted below.
In the end, I will probably just wind up adding ULP differences to my bag of tricks.
It was interesting to see how many floating points are between what should be two equal numbers that never left memory. One of the articles or the google code I read said that 4 was a good number... but here I was able to hit 10.
```
>>> f1 = 25.4
>>> f2 = f1
>>>
>>> for i in xrange(1, 11):
... f2 /= 10.0 # to cm
... f2 *= (1.0 / 2.54) # to in
... f2 *= 25.4 # back to mm
... print 'after %2d loops there are %2d doubles between them' % (i, dulpdiff(f1, f2))
...
after 1 loops there are 1 doubles between them
after 2 loops there are 2 doubles between them
after 3 loops there are 3 doubles between them
after 4 loops there are 4 doubles between them
after 5 loops there are 6 doubles between them
after 6 loops there are 7 doubles between them
after 7 loops there are 8 doubles between them
after 8 loops there are 10 doubles between them
after 9 loops there are 10 doubles between them
after 10 loops there are 10 doubles between them
```
---
Also interesting is how many floating points there are between equal numbers when one of them is written out as a string and read back in.
```
>>> # 0 degrees Fahrenheit is -32 / 1.8 degrees Celsius
... f = -32 / 1.8
>>> s = str(f)
>>> s
'-17.7777777778'
>>> # floats between them...
... fulpdiff(f, float(s))
0
>>> # doubles between them...
... dulpdiff(f, float(s))
6255L
```
---
```
import struct
from functools import partial
# (c) 2010 Eric L. Frederich
#
# Python implementation of algorithms detailed here...
# from http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
def c_mem_cast(x, f=None, t=None):
'''
do a c-style memory cast
In Python...
x = 12.34
y = c_mem_cast(x, 'd', 'l')
... should be equivilent to the following in c...
double x = 12.34;
long y = *(long*)&x;
'''
return struct.unpack(t, struct.pack(f, x))[0]
dbl_to_lng = partial(c_mem_cast, f='d', t='l')
lng_to_dbl = partial(c_mem_cast, f='l', t='d')
flt_to_int = partial(c_mem_cast, f='f', t='i')
int_to_flt = partial(c_mem_cast, f='i', t='f')
def ulp_diff_maker(converter, negative_zero):
'''
Getting the ulp difference of floats and doubles is similar.
Only difference if the offset and converter.
'''
def the_diff(a, b):
# Make a integer lexicographically ordered as a twos-complement int
ai = converter(a)
if ai < 0:
ai = negative_zero - ai
# Make b integer lexicographically ordered as a twos-complement int
bi = converter(b)
if bi < 0:
bi = negative_zero - bi
return abs(ai - bi)
return the_diff
# double ULP difference
dulpdiff = ulp_diff_maker(dbl_to_lng, 0x8000000000000000)
# float ULP difference
fulpdiff = ulp_diff_maker(flt_to_int, 0x80000000 )
# default to double ULP difference
ulpdiff = dulpdiff
ulpdiff.__doc__ = '''
Get the number of doubles between two doubles.
'''
``` | Let me first answer by saying that you should read David Goldberg's classic [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://citeseer.ist.psu.edu/viewdoc/download?doi=10.1.1.102.244&rep=rep1&type=pdf).
As some other commentators already said, the discrepancy you notice is intrinsically due to the floating-point model and has nothing to do with registers, cache or memory.
According to the floating-point model, 2.54 is actually represented as
```
>>> 2859785763380265 * 2 ** -50
2.54
```
This representation, however is not exact:
```
>>> from fractions import Fraction
>>> float(Fraction(2859785763380265, 2 ** 50) - Fraction(254, 100))
3.552713678800501e-17
```
Now, the expression you are evaluating actually is:
```
>>> 25.4 / 10 * (1/2.54)
0.99999999999999989
```
The problem lies in the 1/2.54:
```
>>> Fraction.from_float(1/2.54)
Fraction(1773070719437203, 4503599627370496)
```
But what you would expect is
```
>>> 1/Fraction.from_float(2.54)
Fraction(1125899906842624, 2859785763380265)
```
To answer your questions:
* It *is* a difficult problem, but is clearly deterministic, nothing mysterious there.
* You cannot automatically replace equality with a *close-enough* comparison. The latter requires that you specify a tolerance, which depends on the problem at hand, i.e. on what kind of precision you are expecting from your results. There are also plenty of situations where you really want equality not a *close-enough* comparison. |
45,078,474 | I want to implement import feature with required and optional parameters, to run this in this way:
```
python manage.py import --mode archive
```
where `--mode` is required and `archive` also.
I'm using argparse library.
```
class Command(BaseCommand):
help = 'Import'
def add_arguments(self, parser):
parser.add_argument('--mode',
required=True,
)
parser.add_argument('archive',
required=True,
default=False,
help='Make import archive events'
)
```
But I recived error:
```
TypeError: 'required' is an invalid argument for positionals
``` | 2017/07/13 | [
"https://Stackoverflow.com/questions/45078474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7985656/"
] | You created a positional argument (no `--` option in front of the name). Positional arguments are *always* required. You can't use `required=True` for such options, just drop the `required`. Drop the `default` too; a required argument can't have a default value (it would never be used anyway):
```
parser.add_argument('archive',
help='Make import archive events'
)
```
If you meant for `archive` to be a command-line switch, use `--archive` instead. | I think that `--mode archive` is supposed to mean "mode is archive", in other words `archive` is the *value* of the `--mode` argument, not a separate argument. If it were, it would have to be `--archive` which is not what you want.
Just leave out the definition of `archive`. |
15,768,136 | In python 2.7, I want to run:
$ ./script.py initparms.py
This is a trick to supply a parameter file to script.py, since initparms.py contains several python variables e.g.
```
Ldir = '/home/marzipan/jelly'
LMaps = True
# etc.
```
script.py contains:
```
X = __import__(sys.argv[1])
Ldir = X.Ldir
LMaps = X.Lmaps
# etc.
```
I want to do a bulk promotion of the variables in X so they are available to script.py, without spelling out each one in the code by hand.
Things like
```
import __import__(sys.argv[1])
```
or
```
from sys.argv[1] import *
```
don't work. Almost there perhaps... Any ideas? Thanks! | 2013/04/02 | [
"https://Stackoverflow.com/questions/15768136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021819/"
] | You can use [`execfile`](http://docs.python.org/2/library/functions.html#execfile):
```
execfile(sys.argv[1])
```
Of course, the usual warnings with `exec` or `eval` apply (Your script has no way of knowing whether it is running trusted or untrusted code).
My suggestion would be to not do what you're doing and instead use `configparser` and handling the configuration though there. | You could do something like this:
```
import os
import imp
import sys
try:
module_name = sys.argv[1]
module_info = imp.find_module(module_name, [os.path.abspath(os.path.dirname(__file__))] + sys.path)
module_properties = imp.load_module(module_name, *module_info)
except ImportError:
pass
else:
try:
attrlist = module_properties.__all__
except AttributeError:
attrlist = dir(module_properties)
for attr in attrlist:
if attr.startswith('__'):
continue
globals()[attr] = getattr(module_properties, attr)
```
Little complicated, but gets the job done. |
15,768,136 | In python 2.7, I want to run:
$ ./script.py initparms.py
This is a trick to supply a parameter file to script.py, since initparms.py contains several python variables e.g.
```
Ldir = '/home/marzipan/jelly'
LMaps = True
# etc.
```
script.py contains:
```
X = __import__(sys.argv[1])
Ldir = X.Ldir
LMaps = X.Lmaps
# etc.
```
I want to do a bulk promotion of the variables in X so they are available to script.py, without spelling out each one in the code by hand.
Things like
```
import __import__(sys.argv[1])
```
or
```
from sys.argv[1] import *
```
don't work. Almost there perhaps... Any ideas? Thanks! | 2013/04/02 | [
"https://Stackoverflow.com/questions/15768136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021819/"
] | here's a one-liner:
```
globals().update(__import__(sys.argv[1]).__dict__)
``` | You can use [`execfile`](http://docs.python.org/2/library/functions.html#execfile):
```
execfile(sys.argv[1])
```
Of course, the usual warnings with `exec` or `eval` apply (Your script has no way of knowing whether it is running trusted or untrusted code).
My suggestion would be to not do what you're doing and instead use `configparser` and handling the configuration though there. |
15,768,136 | In python 2.7, I want to run:
$ ./script.py initparms.py
This is a trick to supply a parameter file to script.py, since initparms.py contains several python variables e.g.
```
Ldir = '/home/marzipan/jelly'
LMaps = True
# etc.
```
script.py contains:
```
X = __import__(sys.argv[1])
Ldir = X.Ldir
LMaps = X.Lmaps
# etc.
```
I want to do a bulk promotion of the variables in X so they are available to script.py, without spelling out each one in the code by hand.
Things like
```
import __import__(sys.argv[1])
```
or
```
from sys.argv[1] import *
```
don't work. Almost there perhaps... Any ideas? Thanks! | 2013/04/02 | [
"https://Stackoverflow.com/questions/15768136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1021819/"
] | here's a one-liner:
```
globals().update(__import__(sys.argv[1]).__dict__)
``` | You could do something like this:
```
import os
import imp
import sys
try:
module_name = sys.argv[1]
module_info = imp.find_module(module_name, [os.path.abspath(os.path.dirname(__file__))] + sys.path)
module_properties = imp.load_module(module_name, *module_info)
except ImportError:
pass
else:
try:
attrlist = module_properties.__all__
except AttributeError:
attrlist = dir(module_properties)
for attr in attrlist:
if attr.startswith('__'):
continue
globals()[attr] = getattr(module_properties, attr)
```
Little complicated, but gets the job done. |
70,668,633 | I am currently on a Discord Bot interacting with the Controlpanel API. (<https://documenter.getpostman.com/view/9044962/TzY69ub2#02b8da43-ab01-487d-b2f5-5f8699b509cd>)
Now, I am getting an KeyError when listing a specific user.
```
headers = {
'Accept': 'application/json',
'Authorization': 'Bearer <censored>'
}
url = "https://<censored>"
endpoint = f"/api/users/{user}"
if __name__ == '__main__':
data = requests.get(f'{url}{endpoint}', headers=headers).text
for user in json.loads(data)['data']:
embed = discord.Embed(title="Users")
embed.add_field(name=user['id'], value=user['name'])
await ctx.send(embed=embed)
```
^That's python.
Error:
```
for user in json.loads(data)['data']:
```
KeyError: 'data'
How can I fix this?
Thank you! | 2022/01/11 | [
"https://Stackoverflow.com/questions/70668633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17903752/"
] | This KeyError happens usually when the Key doesn't exist(not exist or even a typo). in your case I think you dont have the 'data' key in your response and your should use something like:
```
data.json()
```
if you can post the complete response it would be more convinient to give you some hints. | The endpoint you're hitting does not return a list but a single object.
You should use the generic endpoint : `{{url}}/api/users`
Also I don't think you want to recreate your `embed` object for each user.
```py
headers = {
'Authorization': 'Bearer <censored>'
}
url = 'https://<censored>'
endpoint = '/api/users'
if __name__ == '__main__':
embed = discord.Embed(title="Users")
for user in requests.get(
f'{url}{endpoint}', headers=headers
).json()['data']:
embed.add_field(name=user['id'], value=user['name'])
await ctx.send(embed=embed)
```
Also I'm pretty sure you can't just `await` like that in `__main__`. |
41,281,072 | I would like to make a file with 3 main columns but my current file has different number of columns per row.
an example of my file is like this:
```
BPIFB3,chr20;ENST00000375494.3
PXDN,chr2,ENST00000252804.4;ENST00000483018.1
RP11,chr2,ENST00000607956.1
RNF19B,chr1,ENST00000373456.7;ENST00000356990.5;ENST00000235150.4
```
and here is what I want to make:
```
BPIFB3 chr20 ENST00000375494.3
PXDN chr2 ENST00000252804.4
PXDN chr2 ENST00000483018.1
RP11 chr2 ENST00000607956.1
RNF19B chr1 ENST00000373456.7
RNF19B chr1 ENST00000356990.5
RNF19B chr1 ENST00000235150.4
```
in fact if in the 3rd row we have more than 3 columns, per any extra column, I want to make a new row in which the first two columns are the same but the 3rd column is different(which is the extra column in original file).
I tried the following code in python but did not get what I am looking for:
```
from collections import defaultdict
with open('data.tbl') as f, open('out.tbl', 'w') as out:
for line in f.split('\t'):
if len(line) > 2:
d[line[0]] = line[3]
out.write(d.items)
``` | 2016/12/22 | [
"https://Stackoverflow.com/questions/41281072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7310023/"
] | **If** your input is actually well-formed, you can do this:
```
for row in reader:
for thing in row[2].split(';'):
writer.writerow(row[:2]+[thing])
```
But as it exists, your first row has malformed data that doesn't match the rest of your rows. So if that *is* an example of your data, then [you could try replacing](https://stackoverflow.com/a/41264619/344286) `;` with `,` before you feed it to the csv reader, and then you can do:
```
for thing in row[3:]:
```
instead.
---
old answer to your prevous question:
You just want list slicing. Also, if it's a tab separated file you can just use the csv module. And you're importing `defaultdict` that you're not using.
```
import csv
with open('data.tbl') as f, open('out.tbl', 'w') as out:
reader = csv.reader(f, delimiter='\t')
writer = csv.writer(out, delimiter='\t')
for row in reader:
writer.writerow(row[:3])
``` | Try this:
```
import csv
with open('data.tbl') as f, open('out.tbl', 'w') as out:
reader = csv.reader(f, delimiter='\t')
writer = csv.writer(out, delimiter='\t')
for row in reader:
if len(row) == 3:
writer.writerow(row)
else:
n = len(row)
writer.writerow(row[:3])
for j in range(3,n):
writer.writerow([row[0], row[1], row[j]])
``` |
41,281,072 | I would like to make a file with 3 main columns but my current file has different number of columns per row.
an example of my file is like this:
```
BPIFB3,chr20;ENST00000375494.3
PXDN,chr2,ENST00000252804.4;ENST00000483018.1
RP11,chr2,ENST00000607956.1
RNF19B,chr1,ENST00000373456.7;ENST00000356990.5;ENST00000235150.4
```
and here is what I want to make:
```
BPIFB3 chr20 ENST00000375494.3
PXDN chr2 ENST00000252804.4
PXDN chr2 ENST00000483018.1
RP11 chr2 ENST00000607956.1
RNF19B chr1 ENST00000373456.7
RNF19B chr1 ENST00000356990.5
RNF19B chr1 ENST00000235150.4
```
in fact if in the 3rd row we have more than 3 columns, per any extra column, I want to make a new row in which the first two columns are the same but the 3rd column is different(which is the extra column in original file).
I tried the following code in python but did not get what I am looking for:
```
from collections import defaultdict
with open('data.tbl') as f, open('out.tbl', 'w') as out:
for line in f.split('\t'):
if len(line) > 2:
d[line[0]] = line[3]
out.write(d.items)
``` | 2016/12/22 | [
"https://Stackoverflow.com/questions/41281072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7310023/"
] | You don't need dictionary for this problem list is sufficient for this. And delimiter '\t' won't work in your problem coz there are multiple space not tab. so we need to remove multiple space with re. so below program will work for your solution.
```
import re
with open('data.tbl') as f, open('out.tbl', 'w') as out:
for line in f:
line = re.sub('\s+',' ',line)
line = line.strip().split(' ')
if len(line) > 3:
for l in range(2,len(line)):
out.write(str(line[0])+' '+line[1]+ ' '+line[l]+'\n')
else:
out.write(' '.join(line)+'\n')
```
Hope this will help you. | Try this:
```
import csv
with open('data.tbl') as f, open('out.tbl', 'w') as out:
reader = csv.reader(f, delimiter='\t')
writer = csv.writer(out, delimiter='\t')
for row in reader:
if len(row) == 3:
writer.writerow(row)
else:
n = len(row)
writer.writerow(row[:3])
for j in range(3,n):
writer.writerow([row[0], row[1], row[j]])
``` |
41,281,072 | I would like to make a file with 3 main columns but my current file has different number of columns per row.
an example of my file is like this:
```
BPIFB3,chr20;ENST00000375494.3
PXDN,chr2,ENST00000252804.4;ENST00000483018.1
RP11,chr2,ENST00000607956.1
RNF19B,chr1,ENST00000373456.7;ENST00000356990.5;ENST00000235150.4
```
and here is what I want to make:
```
BPIFB3 chr20 ENST00000375494.3
PXDN chr2 ENST00000252804.4
PXDN chr2 ENST00000483018.1
RP11 chr2 ENST00000607956.1
RNF19B chr1 ENST00000373456.7
RNF19B chr1 ENST00000356990.5
RNF19B chr1 ENST00000235150.4
```
in fact if in the 3rd row we have more than 3 columns, per any extra column, I want to make a new row in which the first two columns are the same but the 3rd column is different(which is the extra column in original file).
I tried the following code in python but did not get what I am looking for:
```
from collections import defaultdict
with open('data.tbl') as f, open('out.tbl', 'w') as out:
for line in f.split('\t'):
if len(line) > 2:
d[line[0]] = line[3]
out.write(d.items)
``` | 2016/12/22 | [
"https://Stackoverflow.com/questions/41281072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7310023/"
] | Try splitting on either commas or semicolons with `re`:
```
import re
import csv
with open('data.tbl') as infile, open('out.tbl','w') as outfile:
data = [re.split(",|;",x.strip("\n")) for x in infile]
output = []
for line in data:
if len(line) > 3:
output.append(line[:3])
for elm in line[3:]:
output.append(line[:2]+[elm])
else:
output.append(line)
writer = csv.writer(outfile)
writer.writerows(output)
```
I hope this helps. | Try this:
```
import csv
with open('data.tbl') as f, open('out.tbl', 'w') as out:
reader = csv.reader(f, delimiter='\t')
writer = csv.writer(out, delimiter='\t')
for row in reader:
if len(row) == 3:
writer.writerow(row)
else:
n = len(row)
writer.writerow(row[:3])
for j in range(3,n):
writer.writerow([row[0], row[1], row[j]])
``` |
17,517,718 | I am working on a project which aims to fetch some data from some websites and then stores into database. But these websites contains different charsets such as utf-8, gbk. The fetched data is unicode so i wonder when to convert to string is the right way. I convert to string immediately for now, but it seems that the python suggests to keep unicode as long as possible, i can't figure out why? Because we always don't know the charset of the unicode object. | 2013/07/08 | [
"https://Stackoverflow.com/questions/17517718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674199/"
] | Your `start_time` (`Time.now.in_time.zone`) is populated on the page load/render. Whereas the `updated_at` is re-populated when you save the model. Your times are only off by a few seconds, which indicates that it took the person a few seconds to submit the form.
Based on the updated requirement of it being when a start button is clicked to submit a form, it sounds like you want to populate the time in the controller action.
```
def update
# your code
team.start_time = Time.now.in_time_zone('EST')
# rest of your code saving and processing the return
end
```
As for why the time is different, it should not be, unless you are in a different timezone. However, I did notice there is no timezone in the SQL generated. It is possible that the database is not timezone aware and things are being converted to UTC. What is your DB? | 1 . You set a static time in the view witch gets generated on page load.
2 . Set the time in the controller when you save the object. Basic example:
```
@object = Object.new(params[:object].merge(:start_time => Time.now))
if @object.save
redirect_to 'best side in da world'
else
render :new
end
``` |
8,397,617 | I am trying to get python to emulatue mouse clicks, and then type a phrase into the pop up window that the mouse clicks into or the text box.
1) click a security box "run" link with mouse
2) move inside a pop up and enter different phrases with python
What would be the best way to control the mouse and keyboard in this function. These are based in windows. I just need to click " run " on pop up and then in another pop box in one text line enter a phrase then switch to another text line and enter another. much like a password User Id fields.
Could sommeone point me in the right direction. | 2011/12/06 | [
"https://Stackoverflow.com/questions/8397617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027427/"
] | To trigger an event simply call the relevant event function in jQuery on the element, with no handler function defined, like this:
```
$("#2").click();
```
Or there is also `trigger()`, which accepts the event type as a parameter:
```
$("#2").trigger('click');
```
However it's worth noting that `Id` attributes beginning with numbers are invalid, so you will most likely have to change your Ids for them to work properly.
I've updated your fiddle to fix the IDs and show the above code working [**here**](http://jsfiddle.net/RoryMcCrossan/x9Hfj/1/) | You can use `trigger`:
```
$('#2').trigger('click');
```
<http://api.jquery.com/trigger/> |
8,397,617 | I am trying to get python to emulatue mouse clicks, and then type a phrase into the pop up window that the mouse clicks into or the text box.
1) click a security box "run" link with mouse
2) move inside a pop up and enter different phrases with python
What would be the best way to control the mouse and keyboard in this function. These are based in windows. I just need to click " run " on pop up and then in another pop box in one text line enter a phrase then switch to another text line and enter another. much like a password User Id fields.
Could sommeone point me in the right direction. | 2011/12/06 | [
"https://Stackoverflow.com/questions/8397617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027427/"
] | To trigger an event simply call the relevant event function in jQuery on the element, with no handler function defined, like this:
```
$("#2").click();
```
Or there is also `trigger()`, which accepts the event type as a parameter:
```
$("#2").trigger('click');
```
However it's worth noting that `Id` attributes beginning with numbers are invalid, so you will most likely have to change your Ids for them to work properly.
I've updated your fiddle to fix the IDs and show the above code working [**here**](http://jsfiddle.net/RoryMcCrossan/x9Hfj/1/) | Yes, the `.click()` methods is used also to trigger the `click` event.
```
$('#2').click();
```
This is a shorthand for `$('#2').trigger('click');`.
**Also note that an id cannot start with a digit.**
[jQuery documentation for `click()`](http://api.jquery.com/click/)
[jQuery documentation for `trigger()`](http://api.jquery.com/trigger/) |
8,397,617 | I am trying to get python to emulatue mouse clicks, and then type a phrase into the pop up window that the mouse clicks into or the text box.
1) click a security box "run" link with mouse
2) move inside a pop up and enter different phrases with python
What would be the best way to control the mouse and keyboard in this function. These are based in windows. I just need to click " run " on pop up and then in another pop box in one text line enter a phrase then switch to another text line and enter another. much like a password User Id fields.
Could sommeone point me in the right direction. | 2011/12/06 | [
"https://Stackoverflow.com/questions/8397617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027427/"
] | To trigger an event simply call the relevant event function in jQuery on the element, with no handler function defined, like this:
```
$("#2").click();
```
Or there is also `trigger()`, which accepts the event type as a parameter:
```
$("#2").trigger('click');
```
However it's worth noting that `Id` attributes beginning with numbers are invalid, so you will most likely have to change your Ids for them to work properly.
I've updated your fiddle to fix the IDs and show the above code working [**here**](http://jsfiddle.net/RoryMcCrossan/x9Hfj/1/) | Usually you could just call the same function as the click calls.
Did you need something like the $(this) to be populated? |
8,397,617 | I am trying to get python to emulatue mouse clicks, and then type a phrase into the pop up window that the mouse clicks into or the text box.
1) click a security box "run" link with mouse
2) move inside a pop up and enter different phrases with python
What would be the best way to control the mouse and keyboard in this function. These are based in windows. I just need to click " run " on pop up and then in another pop box in one text line enter a phrase then switch to another text line and enter another. much like a password User Id fields.
Could sommeone point me in the right direction. | 2011/12/06 | [
"https://Stackoverflow.com/questions/8397617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027427/"
] | To trigger an event simply call the relevant event function in jQuery on the element, with no handler function defined, like this:
```
$("#2").click();
```
Or there is also `trigger()`, which accepts the event type as a parameter:
```
$("#2").trigger('click');
```
However it's worth noting that `Id` attributes beginning with numbers are invalid, so you will most likely have to change your Ids for them to work properly.
I've updated your fiddle to fix the IDs and show the above code working [**here**](http://jsfiddle.net/RoryMcCrossan/x9Hfj/1/) | You can use [`triggerHandler`](http://api.jquery.com/triggerHandler/) for this:
```
$("#2").triggerHandler("click");
``` |
51,209,598 | Here is a sample of json data I created from defaultdict in python.
```
[{
"company": [
"ABCD"
],
"fullname": [
"Bruce Lamont",
"Ariel Zilist",
"Bruce Lamont",
"Bobby Ramirez"
],
"position": [
" The Hesh",
" Server",
" HESH",
" Production Assistant"
],
"profile_url": [
"http://www.url1.com",
"http://www.url2.com",
"http://www.url3.com",
"http://www.url4.com",
]
}]
```
I realized I made a mistake creating such list. `json.loads()` gives this error
**Error**
>
> Expecting value: line 1 column 1 (char 0).
>
>
>
I want something like this.
```
[{
"company": [
"name": "THALIA HALL",
"employee": {
fullname: "emp_name",
"position": "position",
profile: "url"
},
{
fullname: "emp_name",
"position": "position",
profile: "url"
}
]
}]
```
How can I solve this problem? I need to do this on python. | 2018/07/06 | [
"https://Stackoverflow.com/questions/51209598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7655640/"
] | you are adding an extra comma in the end for profile\_url array. The proper json should be
```
[{
"company": [
"ABCD"
],
"fullname": [
"Bruce Lamont",
"Ariel Zilist",
"Bruce Lamont",
"Bobby Ramirez"
],
"position": [
" The Hesh",
" Server",
" HESH",
" Production Assistant"
],
"profile_url": [
"http://www.url1.com",
"http://www.url2.com",
"http://www.url3.com",
"http://www.url4.com"
]
}]
```
Use <https://jsonformatter.curiousconcept.com/> to check for JSON formatting errors next time. | ```
import json
j = '[{"company":["ABCD"],"fullname":["Bruce Lamont","Ariel Zilist","Bruce Lamont","Bobby Ramirez"],"position":[" The Hesh"," Server"," HESH"," Production Assistant"],"profile_url":["http://www.url1.com","http://www.url2.com","http://www.url3.com","http://www.url4.com"]}]'
json_obj = json.loads(j)
```
you have your JSON as object and now you can user for making csv |
55,962,661 | I am very new to python and have trouble printing the length of a variable I have created.
I have tried len(), and I have tried converting to lists, arrays and tuples and so on and cannot get it to print the length correctly.
```
print(k1_idx_label0)
len(k1_idx_label0)
```
And the output is ---
```
(array([ 0, 3, 7, 13, 20, 21, 23, 27, 29, 30, 32, 33, 36,
38, 40, 41, 42, 44, 45, 46, 48, 49, 54, 56, 57, 58,
62, 65, 68, 69, 70, 72, 76, 80, 82, 83, 84, 85, 88,
89, 92, 97, 103, 105, 109, 110, 111, 113, 115, 116, 117, 121,
122, 124, 126, 136, 137, 139, 140, 142, 143, 146, 148, 149, 150,
151, 153, 155, 156, 157, 158, 160, 161, 165, 166, 168, 173, 174,
175, 176, 177, 178, 180, 181, 182, 185, 186, 188, 191, 192, 193,
196, 199, 200, 203, 206, 207, 210, 211, 215, 218, 220, 225, 226,
227, 228, 232, 235, 236, 237, 238, 239, 241, 244, 249, 251, 252,
257, 258, 262, 264, 267, 272, 278, 282, 283, 285, 286, 289, 291,
297, 298, 299, 300, 301, 305, 307, 308, 309, 313, 315, 317, 318,
319, 326, 327, 329, 330, 331, 333, 335, 336, 340, 342, 347, 350,
351, 352, 354, 355, 356, 360, 361, 365, 375, 377, 378, 382, 383,
385, 386, 387, 390, 391, 392, 393, 394, 397, 398, 403, 405, 406,
407, 408, 409, 413, 414, 421, 426, 429, 430, 431, 435, 439, 443,
444, 445, 446, 447, 449, 452, 454, 455, 456, 457, 460, 462, 463,
464, 466, 468, 469, 471, 472, 473, 477, 478, 480, 482, 492, 493,
496, 501, 504, 506, 512, 517, 518, 519, 520, 521, 522, 523, 528,
529, 531, 533, 535, 536, 542, 543, 545, 547, 551, 555, 556, 558,
564, 565, 567, 568, 569], dtype=int64),)
1
```
It keeps printing the length as 1 when there is clearly a lot more than that...
any idea? | 2019/05/03 | [
"https://Stackoverflow.com/questions/55962661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11338333/"
] | The tuple has just `1` element, if you want to know the size of that element inside the tuple:
```
len(k1_idx_label0[0])
```
if you want to know the size of **all** elements in the tuple:
```
[len(e) for e in k1_idx_label0]
``` | Try:
```
print(len(k1_idx_label0[0]))
``` |
55,962,661 | I am very new to python and have trouble printing the length of a variable I have created.
I have tried len(), and I have tried converting to lists, arrays and tuples and so on and cannot get it to print the length correctly.
```
print(k1_idx_label0)
len(k1_idx_label0)
```
And the output is ---
```
(array([ 0, 3, 7, 13, 20, 21, 23, 27, 29, 30, 32, 33, 36,
38, 40, 41, 42, 44, 45, 46, 48, 49, 54, 56, 57, 58,
62, 65, 68, 69, 70, 72, 76, 80, 82, 83, 84, 85, 88,
89, 92, 97, 103, 105, 109, 110, 111, 113, 115, 116, 117, 121,
122, 124, 126, 136, 137, 139, 140, 142, 143, 146, 148, 149, 150,
151, 153, 155, 156, 157, 158, 160, 161, 165, 166, 168, 173, 174,
175, 176, 177, 178, 180, 181, 182, 185, 186, 188, 191, 192, 193,
196, 199, 200, 203, 206, 207, 210, 211, 215, 218, 220, 225, 226,
227, 228, 232, 235, 236, 237, 238, 239, 241, 244, 249, 251, 252,
257, 258, 262, 264, 267, 272, 278, 282, 283, 285, 286, 289, 291,
297, 298, 299, 300, 301, 305, 307, 308, 309, 313, 315, 317, 318,
319, 326, 327, 329, 330, 331, 333, 335, 336, 340, 342, 347, 350,
351, 352, 354, 355, 356, 360, 361, 365, 375, 377, 378, 382, 383,
385, 386, 387, 390, 391, 392, 393, 394, 397, 398, 403, 405, 406,
407, 408, 409, 413, 414, 421, 426, 429, 430, 431, 435, 439, 443,
444, 445, 446, 447, 449, 452, 454, 455, 456, 457, 460, 462, 463,
464, 466, 468, 469, 471, 472, 473, 477, 478, 480, 482, 492, 493,
496, 501, 504, 506, 512, 517, 518, 519, 520, 521, 522, 523, 528,
529, 531, 533, 535, 536, 542, 543, 545, 547, 551, 555, 556, 558,
564, 565, 567, 568, 569], dtype=int64),)
1
```
It keeps printing the length as 1 when there is clearly a lot more than that...
any idea? | 2019/05/03 | [
"https://Stackoverflow.com/questions/55962661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11338333/"
] | Your `k1_idx_label0` variable is actually a tuple containing a single item. That item happens to be a `numpy.array`, but `len()` is correctly reporting the length of the object you’re passing to it.
Instead try:
```
len(k1_idx_label0[0])
```
Which should give you what you want: the length of the first element of the 1-element tuple. | Try:
```
print(len(k1_idx_label0[0]))
``` |
55,962,661 | I am very new to python and have trouble printing the length of a variable I have created.
I have tried len(), and I have tried converting to lists, arrays and tuples and so on and cannot get it to print the length correctly.
```
print(k1_idx_label0)
len(k1_idx_label0)
```
And the output is ---
```
(array([ 0, 3, 7, 13, 20, 21, 23, 27, 29, 30, 32, 33, 36,
38, 40, 41, 42, 44, 45, 46, 48, 49, 54, 56, 57, 58,
62, 65, 68, 69, 70, 72, 76, 80, 82, 83, 84, 85, 88,
89, 92, 97, 103, 105, 109, 110, 111, 113, 115, 116, 117, 121,
122, 124, 126, 136, 137, 139, 140, 142, 143, 146, 148, 149, 150,
151, 153, 155, 156, 157, 158, 160, 161, 165, 166, 168, 173, 174,
175, 176, 177, 178, 180, 181, 182, 185, 186, 188, 191, 192, 193,
196, 199, 200, 203, 206, 207, 210, 211, 215, 218, 220, 225, 226,
227, 228, 232, 235, 236, 237, 238, 239, 241, 244, 249, 251, 252,
257, 258, 262, 264, 267, 272, 278, 282, 283, 285, 286, 289, 291,
297, 298, 299, 300, 301, 305, 307, 308, 309, 313, 315, 317, 318,
319, 326, 327, 329, 330, 331, 333, 335, 336, 340, 342, 347, 350,
351, 352, 354, 355, 356, 360, 361, 365, 375, 377, 378, 382, 383,
385, 386, 387, 390, 391, 392, 393, 394, 397, 398, 403, 405, 406,
407, 408, 409, 413, 414, 421, 426, 429, 430, 431, 435, 439, 443,
444, 445, 446, 447, 449, 452, 454, 455, 456, 457, 460, 462, 463,
464, 466, 468, 469, 471, 472, 473, 477, 478, 480, 482, 492, 493,
496, 501, 504, 506, 512, 517, 518, 519, 520, 521, 522, 523, 528,
529, 531, 533, 535, 536, 542, 543, 545, 547, 551, 555, 556, 558,
564, 565, 567, 568, 569], dtype=int64),)
1
```
It keeps printing the length as 1 when there is clearly a lot more than that...
any idea? | 2019/05/03 | [
"https://Stackoverflow.com/questions/55962661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11338333/"
] | Your `k1_idx_label0` variable is actually a tuple containing a single item. That item happens to be a `numpy.array`, but `len()` is correctly reporting the length of the object you’re passing to it.
Instead try:
```
len(k1_idx_label0[0])
```
Which should give you what you want: the length of the first element of the 1-element tuple. | The tuple has just `1` element, if you want to know the size of that element inside the tuple:
```
len(k1_idx_label0[0])
```
if you want to know the size of **all** elements in the tuple:
```
[len(e) for e in k1_idx_label0]
``` |
24,890,259 | **I'm not looking for a solution (I have two ;) ), but on insight to compare the strengths and weaknesses of each solution considering python's internals. Thanks !**
With a coworker, we wish to extract the difference between two successive list elements, for all elements. So, for list :
```
[1,2,4]
```
the expected output is :
```
[1,2]
```
(since 2-1 = 1, and 4-2 = 2).
We came with two solutions and I am not sure how they compare. The first one is very C-like, it considers the list as a table and substracts the difference between two successive list elements.
```
res = []
for i in range(0, len(a)-1):
res.append(a[i+1] - a[i])
```
The second one is (for a list "l"), I think, more pythonic :
```
[j - i for i,j in zip(l[:-1], l[1:])]
```
Though, isn't it far less efficient to build two copies of the list to then extract the differences ? How does Python handle this internally ?
Thanks for your insights ! | 2014/07/22 | [
"https://Stackoverflow.com/questions/24890259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481478/"
] | With a generator:
```
def diff_elements(lst):
"""
>>> list(diff_elements([]))
[]
>>> list(diff_elements([1]))
[]
>>> list(diff_elements([1, 2, 4, 7]))
[1, 2, 3]
"""
as_iter = iter(lst)
last = next(as_iter)
for value in as_iter:
yield value - last
last = value
```
This has the nice properties of:
1. Being readable, and
2. Working on infinitely large data sets. | If I understood your question I suggest you use something like that:
```
diffList = lambda l: [(l[i] - l[i-1]) for i in range(1, len(l))]
answer = diffList( [ 1,2,4] )
```
This function will give you a list with the differences between all consecutive elements in the input list.
This one is similar with your first approach (and still somewhat pythonic) what is more efficient than the second one. |
24,890,259 | **I'm not looking for a solution (I have two ;) ), but on insight to compare the strengths and weaknesses of each solution considering python's internals. Thanks !**
With a coworker, we wish to extract the difference between two successive list elements, for all elements. So, for list :
```
[1,2,4]
```
the expected output is :
```
[1,2]
```
(since 2-1 = 1, and 4-2 = 2).
We came with two solutions and I am not sure how they compare. The first one is very C-like, it considers the list as a table and substracts the difference between two successive list elements.
```
res = []
for i in range(0, len(a)-1):
res.append(a[i+1] - a[i])
```
The second one is (for a list "l"), I think, more pythonic :
```
[j - i for i,j in zip(l[:-1], l[1:])]
```
Though, isn't it far less efficient to build two copies of the list to then extract the differences ? How does Python handle this internally ?
Thanks for your insights ! | 2014/07/22 | [
"https://Stackoverflow.com/questions/24890259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481478/"
] | With a generator:
```
def diff_elements(lst):
"""
>>> list(diff_elements([]))
[]
>>> list(diff_elements([1]))
[]
>>> list(diff_elements([1, 2, 4, 7]))
[1, 2, 3]
"""
as_iter = iter(lst)
last = next(as_iter)
for value in as_iter:
yield value - last
last = value
```
This has the nice properties of:
1. Being readable, and
2. Working on infinitely large data sets. | With no lambdas:
```
[l[i+1] - l[i] for i in range(len(l) - 1)]
```
Eg:
```
>>> l = [1, 4, 8, 15, 16]
>>> [l[i+1] - l[i] for i in range(len(l) - 1)]
[3, 4, 7, 1]
```
A bit faster, as you can see (EDIT: Adding the most voted solution in <https://stackoverflow.com/a/2400875/1171280>):
```
>>> import timeit
>>>
>>> s = """\
... l = [1, 4, 7, 15, 16]
... [l[i+1] - l[i] for i in range(len(l) - 1)]
... """
>>> r = """\
... l = [1, 4, 7, 15, 16]
... [j - i for i,j in zip(l[:-1], l[1:])]
... """
>>> t = """\
... l = [1, 4, 7, 15, 16]
... [j-i for i, j in itertools.izip(l[:-1], l[1:])]
... """
>>> timeit.timeit(stmt=s, number=100000)
0.09615588188171387
>>> timeit.timeit(stmt=s, number=100000)
0.09774398803710938
>>> timeit.timeit(stmt=s, number=100000)
0.09683513641357422
#-------------
>>> timeit.timeit(stmt=r, number=100000)
0.14137601852416992
>>> timeit.timeit(stmt=r, number=100000)
0.12511301040649414
>>> timeit.timeit(stmt=r, number=100000)
0.12285017967224121
#-------------
>>> timeit.timeit(stmt=t, number=100000)
0.11506795883178711
>>> timeit.timeit(stmt=t, number=100000)
0.11677718162536621
>>> timeit.timeit(stmt=t, number=100000)
0.11829996109008789
``` |
12,805,699 | recently i understand the great advantage to use the list comprehension. I am working with several milion of points (x,y,z) stored in a special format \*.las file. In python there are two way to work with this format:
```
Liblas module [http://www.liblas.org/tutorial/python.html][1] (in a C++/Python)
laspy module [http://laspy.readthedocs.org/en/latest/tut_part_1.html][2] (pure Python)
```
I had several problem with liblas and i wish to test laspy.
in liblas i can use list comprehension as:
```
from liblas import file as lasfile
f = lasfile.File(inFile,None,'r') # open LAS
points = [(p.x,p.y) for p in f] # read in list comprehension
```
in laspy i cannot figurate how do the same:
```
from laspy.file import File
f = file.File(inFile, mode='r')
f
<laspy.file.File object at 0x0000000013939080>
(f[0].X,f[0].Y)
(30839973, 696447860)
```
i tryed several combination as:
```
points = [(p.X,p.Y) for p in f]
```
but i get this message
```
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: Point instance has no attribute 'x'
```
I tryed in uppercase and NOT-uppercase because Python is case sensitive:
```
>>> [(p.x,p.y) for p in f]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: Point instance has no attribute 'x'
>>> [(p.X,p.Y) for p in f]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: Point instance has no attribute 'X'
```
this is in interactive prompt:
```
C:\Python27>python.exe
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from laspy.file import File
>>> inFile="C:\\04-las_clip_inside_area\\Ku_018_class.las"
>>> f = File(inFile, None, 'r')
>>> f
<laspy.file.File object at 0x00000000024D5E10>
>>> points = [(p.X,p.Y) for p in f]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Point instance has no attribute 'X'
>>>
```
the print p after the list is:
```
print dir(p)
['__doc__', '__init__', '__module__', 'make_nice', 'pack', 'packer', 'reader', 'unpacked']
```
in a loop format i have always the same error
```
>>> for p in f:
... print dir(p)
... print p.X,p.Y
...
['__doc__', '__init__', '__module__', 'make_nice', 'pack', 'packer', 'reader', 'unpacked']
Traceback (most recent call last):
File "<interactive input>", line 3, in <module>
AttributeError: Point instance has no attribute 'X'
```
using this code suggested by nneonneo
```
import numpy as np
for p in f:
... points = np.array([f.X, f.Y]).T
```
i can store in an array
```
points
array([[ 30839973, 696447860],
[ 30839937, 696447890],
[ 30839842, 696447832],
...,
[ 30943795, 695999984],
[ 30943695, 695999922],
[ 30943960, 695999995]])
```
but miss the way to create a list comprehension
```
points = [np.array(p.X,p.Y).T for p in f]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: Point instance has no attribute 'X'
```
thanks in advance for help.
Gianni | 2012/10/09 | [
"https://Stackoverflow.com/questions/12805699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1493192/"
] | Python is case-sensitive. Too me it looks like you ask for attribute `x`, but it should be an uppercase `X`. | Try
```
import numpy as np
...
points = np.array([f.X, f.Y]).T
``` |
12,805,699 | recently i understand the great advantage to use the list comprehension. I am working with several milion of points (x,y,z) stored in a special format \*.las file. In python there are two way to work with this format:
```
Liblas module [http://www.liblas.org/tutorial/python.html][1] (in a C++/Python)
laspy module [http://laspy.readthedocs.org/en/latest/tut_part_1.html][2] (pure Python)
```
I had several problem with liblas and i wish to test laspy.
in liblas i can use list comprehension as:
```
from liblas import file as lasfile
f = lasfile.File(inFile,None,'r') # open LAS
points = [(p.x,p.y) for p in f] # read in list comprehension
```
in laspy i cannot figurate how do the same:
```
from laspy.file import File
f = file.File(inFile, mode='r')
f
<laspy.file.File object at 0x0000000013939080>
(f[0].X,f[0].Y)
(30839973, 696447860)
```
i tryed several combination as:
```
points = [(p.X,p.Y) for p in f]
```
but i get this message
```
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: Point instance has no attribute 'x'
```
I tryed in uppercase and NOT-uppercase because Python is case sensitive:
```
>>> [(p.x,p.y) for p in f]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: Point instance has no attribute 'x'
>>> [(p.X,p.Y) for p in f]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: Point instance has no attribute 'X'
```
this is in interactive prompt:
```
C:\Python27>python.exe
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from laspy.file import File
>>> inFile="C:\\04-las_clip_inside_area\\Ku_018_class.las"
>>> f = File(inFile, None, 'r')
>>> f
<laspy.file.File object at 0x00000000024D5E10>
>>> points = [(p.X,p.Y) for p in f]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Point instance has no attribute 'X'
>>>
```
the print p after the list is:
```
print dir(p)
['__doc__', '__init__', '__module__', 'make_nice', 'pack', 'packer', 'reader', 'unpacked']
```
in a loop format i have always the same error
```
>>> for p in f:
... print dir(p)
... print p.X,p.Y
...
['__doc__', '__init__', '__module__', 'make_nice', 'pack', 'packer', 'reader', 'unpacked']
Traceback (most recent call last):
File "<interactive input>", line 3, in <module>
AttributeError: Point instance has no attribute 'X'
```
using this code suggested by nneonneo
```
import numpy as np
for p in f:
... points = np.array([f.X, f.Y]).T
```
i can store in an array
```
points
array([[ 30839973, 696447860],
[ 30839937, 696447890],
[ 30839842, 696447832],
...,
[ 30943795, 695999984],
[ 30943695, 695999922],
[ 30943960, 695999995]])
```
but miss the way to create a list comprehension
```
points = [np.array(p.X,p.Y).T for p in f]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: Point instance has no attribute 'X'
```
thanks in advance for help.
Gianni | 2012/10/09 | [
"https://Stackoverflow.com/questions/12805699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1493192/"
] | Python is case-sensitive. Too me it looks like you ask for attribute `x`, but it should be an uppercase `X`. | It looks like `Point` has a `make_nice()` method that makes more attributes show up.
```
for p in f: p.make_nice()
```
Now your list comp should work (with uppercase X and Y--see comments below).
```
[(p.X,p.Y) for p in f]
```
note: This answer is not tested. It is based on reading the source of [`laspy.util.Point`](http://laspy.readthedocs.org/en/latest/_modules/laspy/util.html).
Relevant source:
```
def make_nice(self):
'''Turn a point instance with the bare essentials (an unpacked list of data)
into a fully populated point. Add all the named attributes it possesses,
including binary fields.
'''
i = 0
for dim in self.reader.point_format.specs:
self.__dict__[dim.name] = self.unpacked[i]
i += 1
# rest of method snipped
``` |
39,190,274 | I am currently developing a Python application which I continually performance test, simply by recording the runtime of various parts.
A lot of the code is related only to the testing environment and would not exist in the real world application, I have these separated into functions and at the moment I comment out these calls when testing. This requires me to remember which calls refer to test only components (they are quite interleaved so I cannot group the functionality).
I was wondering if there was a better solution to this, the only idea I have had so far is creation of a 'mode' boolean and insertion of If statements, though this feels needlessly messy. I was hoping there might be some more standardised testing method that I am naive of.
I am new to python so I may have overlooked some simple solutions.
Thank you in advance | 2016/08/28 | [
"https://Stackoverflow.com/questions/39190274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2071737/"
] | That's because of
>
> Let `shiftCount` be the result of masking out all but the least significant 5 bits of `rnum`, that is, compute `rnum & 0x1F`.
>
>
>
of how the `<<` operation is defined. See <http://www.ecma-international.org/ecma-262/6.0/#sec-left-shift-operator-runtime-semantics-evaluation>
So according to it - `32 & 0x1F` equals 0
So `1 << 32` equals to `1 << 0` so is basically no op.
Whereas 2 consecutive shifts by 31 and 1 literally perform calculations | JavaScript defines a left-shift by 32 to do nothing, presumably because it smacks up against the 32-bit boundary. You cannot actually shift anything more than 31 bits across.
Your approach of first shifting 31 bits, then a final bit, works around JavaScript thinking that shifting so much doesn't make sense. Indeed, it's pointless to execute those calculations when you could just write `= 0` in the first place. |
39,190,274 | I am currently developing a Python application which I continually performance test, simply by recording the runtime of various parts.
A lot of the code is related only to the testing environment and would not exist in the real world application, I have these separated into functions and at the moment I comment out these calls when testing. This requires me to remember which calls refer to test only components (they are quite interleaved so I cannot group the functionality).
I was wondering if there was a better solution to this, the only idea I have had so far is creation of a 'mode' boolean and insertion of If statements, though this feels needlessly messy. I was hoping there might be some more standardised testing method that I am naive of.
I am new to python so I may have overlooked some simple solutions.
Thank you in advance | 2016/08/28 | [
"https://Stackoverflow.com/questions/39190274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2071737/"
] | That's because of
>
> Let `shiftCount` be the result of masking out all but the least significant 5 bits of `rnum`, that is, compute `rnum & 0x1F`.
>
>
>
of how the `<<` operation is defined. See <http://www.ecma-international.org/ecma-262/6.0/#sec-left-shift-operator-runtime-semantics-evaluation>
So according to it - `32 & 0x1F` equals 0
So `1 << 32` equals to `1 << 0` so is basically no op.
Whereas 2 consecutive shifts by 31 and 1 literally perform calculations | The reason is that the shift count is considered modulo 32.
This itself happens because (my guess) this is how most common hardware for desktops/laptops works today (x86).
This itself happens because.... well, just because.
These shift limitations are indeed in some cases annoying... for example it would have been better in my opionion to have just one shift operator, working in both directions depending on the sign of the count (like `ASH` works for [Common Lisp](http://www.lispworks.com/documentation/HyperSpec/Body/f_ash.htm)). |
531,487 | I'm looking for a python browser widget (along the lines of pyQT4's [QTextBrowser](http://doc.trolltech.com/3.3/qtextbrowser.html) class or [wxpython's HTML module](http://www.wxpython.org/docs/api/wx.html-module.html)) that has events for interaction with the DOM. For example, if I highlight an h1 node, the widget class should have a method that notifies me something was highlighted and what dom properties that node had (`<h1>`, contents of the tag, sibling and parent tags, etc). Ideally the widget module/class would give access to the DOM tree object itself so I can traverse it, modify it, and re-render the new tree.
Does something like this exist? I've tried looking but I'm unfortunately not able to find it. Thanks in advance! | 2009/02/10 | [
"https://Stackoverflow.com/questions/531487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11110/"
] | It may not be ideal for your purposes, but you might want to take a look at the Python bindings to KHTML that are part of PyKDE. One place to start looking is the KHTMLPart class:
<http://api.kde.org/pykde-4.2-api/khtml/KHTMLPart.html>
Since the API for this class is based on the signals and slots paradigm used in Qt, you will need to connect various signals to slots in your own code to find out when parts of a document have been changed. There's also a DOM API, so it should also be possible to access DOM nodes for selected parts of the document.
More information can be found here:
<http://api.kde.org/pykde-4.2-api/khtml/index.html> | I would also love such a thing. I suspect one with Python bindings does not exist, but would be really happy to be wrong about this.
One option I recently looked at (but never tried) is the [Webkit](http://webkit.org/) browser. Now this has some bindings for Python, and built against different toolkits (I use GTK). However there are available API for the entire Javascript machine for C++, but no Python bindings and I don't see any reason why these can't be bound for Python. It's a fairly huge task, I know, but it would be a universally useful project, so maybe worth the investment. |
531,487 | I'm looking for a python browser widget (along the lines of pyQT4's [QTextBrowser](http://doc.trolltech.com/3.3/qtextbrowser.html) class or [wxpython's HTML module](http://www.wxpython.org/docs/api/wx.html-module.html)) that has events for interaction with the DOM. For example, if I highlight an h1 node, the widget class should have a method that notifies me something was highlighted and what dom properties that node had (`<h1>`, contents of the tag, sibling and parent tags, etc). Ideally the widget module/class would give access to the DOM tree object itself so I can traverse it, modify it, and re-render the new tree.
Does something like this exist? I've tried looking but I'm unfortunately not able to find it. Thanks in advance! | 2009/02/10 | [
"https://Stackoverflow.com/questions/531487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11110/"
] | It may not be ideal for your purposes, but you might want to take a look at the Python bindings to KHTML that are part of PyKDE. One place to start looking is the KHTMLPart class:
<http://api.kde.org/pykde-4.2-api/khtml/KHTMLPart.html>
Since the API for this class is based on the signals and slots paradigm used in Qt, you will need to connect various signals to slots in your own code to find out when parts of a document have been changed. There's also a DOM API, so it should also be possible to access DOM nodes for selected parts of the document.
More information can be found here:
<http://api.kde.org/pykde-4.2-api/khtml/index.html> | If you don't mind being limited to Windows, you can use the IE browser control. From wxPython, it's in wx.lib.iewin.IEHtmlWindow (there's a demo in the wxPython demo). This gives you full access to the DOM and ability to sink events, e.g.
```
ie.document.body.innerHTML = u"<p>Hello, world</p>"
``` |
5,475,549 | In the Ubuntu terminal, how do I loop a command like
```
python myscript.py
```
so that it runs every 15 minutes? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5475549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | you are looking for [crontab](http://en.wikipedia.org/wiki/Crontab) rather than loop. | Sounds like you want to use something like cron instead, but... if you are sure you want something to run in the same terminal-window every N minutes (or seconds, actually), you could use the 'watch' command.
```
watch -n 60 python myscripy.py
``` |
5,475,549 | In the Ubuntu terminal, how do I loop a command like
```
python myscript.py
```
so that it runs every 15 minutes? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5475549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | you are looking for [crontab](http://en.wikipedia.org/wiki/Crontab) rather than loop. | If you really need to schedule something, then you want crontab.
But if this is temporary (i.e. checking to see if a file has appeared or whatever), then here's how you could do this
`while true ; do python myscript.py ; sleep 15m; done`
This will execute forever ("while true") so you'll have to ctrl-c to cancel it when you are done. |
5,475,549 | In the Ubuntu terminal, how do I loop a command like
```
python myscript.py
```
so that it runs every 15 minutes? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5475549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | you are looking for [crontab](http://en.wikipedia.org/wiki/Crontab) rather than loop. | using crontab you can add an entry like `*/15 * * * * python /path/to/myscript.py` |
5,475,549 | In the Ubuntu terminal, how do I loop a command like
```
python myscript.py
```
so that it runs every 15 minutes? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5475549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you really need to schedule something, then you want crontab.
But if this is temporary (i.e. checking to see if a file has appeared or whatever), then here's how you could do this
`while true ; do python myscript.py ; sleep 15m; done`
This will execute forever ("while true") so you'll have to ctrl-c to cancel it when you are done. | Sounds like you want to use something like cron instead, but... if you are sure you want something to run in the same terminal-window every N minutes (or seconds, actually), you could use the 'watch' command.
```
watch -n 60 python myscripy.py
``` |
5,475,549 | In the Ubuntu terminal, how do I loop a command like
```
python myscript.py
```
so that it runs every 15 minutes? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5475549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Sounds like you want to use something like cron instead, but... if you are sure you want something to run in the same terminal-window every N minutes (or seconds, actually), you could use the 'watch' command.
```
watch -n 60 python myscripy.py
``` | using crontab you can add an entry like `*/15 * * * * python /path/to/myscript.py` |
5,475,549 | In the Ubuntu terminal, how do I loop a command like
```
python myscript.py
```
so that it runs every 15 minutes? | 2011/03/29 | [
"https://Stackoverflow.com/questions/5475549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you really need to schedule something, then you want crontab.
But if this is temporary (i.e. checking to see if a file has appeared or whatever), then here's how you could do this
`while true ; do python myscript.py ; sleep 15m; done`
This will execute forever ("while true") so you'll have to ctrl-c to cancel it when you are done. | using crontab you can add an entry like `*/15 * * * * python /path/to/myscript.py` |
50,910,136 | I am new to python and I currently have one text file that I sliced into two columns. I am looking for unique one-to-one relationships in the text file to determine new home buyers:
**Main File**
1234 Address , Billy Joel
Joe Martin, 45 Other Address
63 OtherOther Address, Joe Martin
Billy Joel, 1234 Address
***I am lookng for the unique one-to-one relationship (1234 Address and Billy Joel)***
**Curent Steps/Goals:**
>
> 1. sliced text file into two lists based on the ','
>
>
>
Looking to write something like this (I know this is very horribly laid out, but I am stuck on how to implement this):
```
addressListing= text file that is read
leftLst = addressListing.split(",", 1)[0]
rightLst = addressListing.split(".", 1) [1]
for (x, y) in (leftLst, rightLst):
if x in rightLst and y in leftLst:
return x + y
else:
pass
```
The text file is not neat where there are only addresses on one side and only names on the other. | 2018/06/18 | [
"https://Stackoverflow.com/questions/50910136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9574850/"
] | Everything from the request is just a string. The modelbinder matches up keys in the request body with property names, and then attempts to coerce them to the appropriate type. If the property is not posted or is posted with an empty string, that will obviously fail when trying to convert to an int. As a result, you end up with the default value for the type. In the case of an `int` that's `0`, while the default value of `int?` is `null`.
*Only after this binding process is complete* is the model then validated. Remember you're validating the *model* not the post body. There's no reasonable way to validate the post body, since again, it's just a a bunch of key-value pair strings. Therefore, in the case of an `int` property that's required, but not posted, the value is `0`, which is a perfectly valid value for an int, and the validation is satisfied. In the case of `int?`, the value is `null`, which is *not* a valid int, and thus fails validation. That is why the nullable is required, if you want to require a non-nullable type have a value. It's the only way that an empty value can be differentiated from simply a "default" value.
If you are using view models, as you should be, this should not be an issue. You can bind to a nullable int with a required attribute, and you will be assured that it *will* have a value, despite being nullable, if your model state is valid. Then, you can map that over to a straight int on your entity. That is the correct way to handle things. | >
> non-nullable required types.
>
>
>
You do not. It is either required - then there is no sense in it being nullable - or it is not required, then you nullable makes sense, but it makes no sense to require it.
Attributes are always for the whole request. You are in a logical problem because you try to use them not as intended.
If it is optional, the user should actually submit a patch, not a put/post. |
50,910,136 | I am new to python and I currently have one text file that I sliced into two columns. I am looking for unique one-to-one relationships in the text file to determine new home buyers:
**Main File**
1234 Address , Billy Joel
Joe Martin, 45 Other Address
63 OtherOther Address, Joe Martin
Billy Joel, 1234 Address
***I am lookng for the unique one-to-one relationship (1234 Address and Billy Joel)***
**Curent Steps/Goals:**
>
> 1. sliced text file into two lists based on the ','
>
>
>
Looking to write something like this (I know this is very horribly laid out, but I am stuck on how to implement this):
```
addressListing= text file that is read
leftLst = addressListing.split(",", 1)[0]
rightLst = addressListing.split(".", 1) [1]
for (x, y) in (leftLst, rightLst):
if x in rightLst and y in leftLst:
return x + y
else:
pass
```
The text file is not neat where there are only addresses on one side and only names on the other. | 2018/06/18 | [
"https://Stackoverflow.com/questions/50910136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9574850/"
] | >
> non-nullable required types.
>
>
>
You do not. It is either required - then there is no sense in it being nullable - or it is not required, then you nullable makes sense, but it makes no sense to require it.
Attributes are always for the whole request. You are in a logical problem because you try to use them not as intended.
If it is optional, the user should actually submit a patch, not a put/post. | There was the way to do that, at least it works for me, try `[BindRequired]` for non-nullable types. |
50,910,136 | I am new to python and I currently have one text file that I sliced into two columns. I am looking for unique one-to-one relationships in the text file to determine new home buyers:
**Main File**
1234 Address , Billy Joel
Joe Martin, 45 Other Address
63 OtherOther Address, Joe Martin
Billy Joel, 1234 Address
***I am lookng for the unique one-to-one relationship (1234 Address and Billy Joel)***
**Curent Steps/Goals:**
>
> 1. sliced text file into two lists based on the ','
>
>
>
Looking to write something like this (I know this is very horribly laid out, but I am stuck on how to implement this):
```
addressListing= text file that is read
leftLst = addressListing.split(",", 1)[0]
rightLst = addressListing.split(".", 1) [1]
for (x, y) in (leftLst, rightLst):
if x in rightLst and y in leftLst:
return x + y
else:
pass
```
The text file is not neat where there are only addresses on one side and only names on the other. | 2018/06/18 | [
"https://Stackoverflow.com/questions/50910136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9574850/"
] | Solution working with json requests
-----------------------------------
You **cannot validate an already created model instance**, because a non-nullable property has always a value (no matter whether it was assigned from json or is a default value). The **solution is to report the missing value already during deserialization**.
Create a contract resolver
```
public class RequiredPropertiesContractResolver : DefaultContractResolver
{
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
foreach (var contractProperty in contract.Properties)
{
if (contractProperty.PropertyType.IsValueType
&& contractProperty.AttributeProvider.GetAttributes(typeof(RequiredAttribute), inherit: true).Any())
{
contractProperty.Required = Required.Always;
}
}
return contract;
}
}
```
and then assign it to `SerializerSettings`:
```
services.AddMvc()
.AddJsonOptions(jsonOptions =>
{
jsonOptions.SerializerSettings.ContractResolver = new RequiredPropertiesContractResolver();
});
```
The `ModelState` is then invalid for non-nullable properties with the `[Required]` attribute if the value is missing from json.
---
Example
-------
Json body
```
var jsonBody = @"{ Data2=123 }"
```
is invalid for model
```
class Model
{
[Required]
public int Data { get; set; }
public int Data2 { get; set; }
}
``` | >
> non-nullable required types.
>
>
>
You do not. It is either required - then there is no sense in it being nullable - or it is not required, then you nullable makes sense, but it makes no sense to require it.
Attributes are always for the whole request. You are in a logical problem because you try to use them not as intended.
If it is optional, the user should actually submit a patch, not a put/post. |
50,910,136 | I am new to python and I currently have one text file that I sliced into two columns. I am looking for unique one-to-one relationships in the text file to determine new home buyers:
**Main File**
1234 Address , Billy Joel
Joe Martin, 45 Other Address
63 OtherOther Address, Joe Martin
Billy Joel, 1234 Address
***I am lookng for the unique one-to-one relationship (1234 Address and Billy Joel)***
**Curent Steps/Goals:**
>
> 1. sliced text file into two lists based on the ','
>
>
>
Looking to write something like this (I know this is very horribly laid out, but I am stuck on how to implement this):
```
addressListing= text file that is read
leftLst = addressListing.split(",", 1)[0]
rightLst = addressListing.split(".", 1) [1]
for (x, y) in (leftLst, rightLst):
if x in rightLst and y in leftLst:
return x + y
else:
pass
```
The text file is not neat where there are only addresses on one side and only names on the other. | 2018/06/18 | [
"https://Stackoverflow.com/questions/50910136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9574850/"
] | Everything from the request is just a string. The modelbinder matches up keys in the request body with property names, and then attempts to coerce them to the appropriate type. If the property is not posted or is posted with an empty string, that will obviously fail when trying to convert to an int. As a result, you end up with the default value for the type. In the case of an `int` that's `0`, while the default value of `int?` is `null`.
*Only after this binding process is complete* is the model then validated. Remember you're validating the *model* not the post body. There's no reasonable way to validate the post body, since again, it's just a a bunch of key-value pair strings. Therefore, in the case of an `int` property that's required, but not posted, the value is `0`, which is a perfectly valid value for an int, and the validation is satisfied. In the case of `int?`, the value is `null`, which is *not* a valid int, and thus fails validation. That is why the nullable is required, if you want to require a non-nullable type have a value. It's the only way that an empty value can be differentiated from simply a "default" value.
If you are using view models, as you should be, this should not be an issue. You can bind to a nullable int with a required attribute, and you will be assured that it *will* have a value, despite being nullable, if your model state is valid. Then, you can map that over to a straight int on your entity. That is the correct way to handle things. | There was the way to do that, at least it works for me, try `[BindRequired]` for non-nullable types. |
50,910,136 | I am new to python and I currently have one text file that I sliced into two columns. I am looking for unique one-to-one relationships in the text file to determine new home buyers:
**Main File**
1234 Address , Billy Joel
Joe Martin, 45 Other Address
63 OtherOther Address, Joe Martin
Billy Joel, 1234 Address
***I am lookng for the unique one-to-one relationship (1234 Address and Billy Joel)***
**Curent Steps/Goals:**
>
> 1. sliced text file into two lists based on the ','
>
>
>
Looking to write something like this (I know this is very horribly laid out, but I am stuck on how to implement this):
```
addressListing= text file that is read
leftLst = addressListing.split(",", 1)[0]
rightLst = addressListing.split(".", 1) [1]
for (x, y) in (leftLst, rightLst):
if x in rightLst and y in leftLst:
return x + y
else:
pass
```
The text file is not neat where there are only addresses on one side and only names on the other. | 2018/06/18 | [
"https://Stackoverflow.com/questions/50910136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9574850/"
] | Solution working with json requests
-----------------------------------
You **cannot validate an already created model instance**, because a non-nullable property has always a value (no matter whether it was assigned from json or is a default value). The **solution is to report the missing value already during deserialization**.
Create a contract resolver
```
public class RequiredPropertiesContractResolver : DefaultContractResolver
{
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
foreach (var contractProperty in contract.Properties)
{
if (contractProperty.PropertyType.IsValueType
&& contractProperty.AttributeProvider.GetAttributes(typeof(RequiredAttribute), inherit: true).Any())
{
contractProperty.Required = Required.Always;
}
}
return contract;
}
}
```
and then assign it to `SerializerSettings`:
```
services.AddMvc()
.AddJsonOptions(jsonOptions =>
{
jsonOptions.SerializerSettings.ContractResolver = new RequiredPropertiesContractResolver();
});
```
The `ModelState` is then invalid for non-nullable properties with the `[Required]` attribute if the value is missing from json.
---
Example
-------
Json body
```
var jsonBody = @"{ Data2=123 }"
```
is invalid for model
```
class Model
{
[Required]
public int Data { get; set; }
public int Data2 { get; set; }
}
``` | Everything from the request is just a string. The modelbinder matches up keys in the request body with property names, and then attempts to coerce them to the appropriate type. If the property is not posted or is posted with an empty string, that will obviously fail when trying to convert to an int. As a result, you end up with the default value for the type. In the case of an `int` that's `0`, while the default value of `int?` is `null`.
*Only after this binding process is complete* is the model then validated. Remember you're validating the *model* not the post body. There's no reasonable way to validate the post body, since again, it's just a a bunch of key-value pair strings. Therefore, in the case of an `int` property that's required, but not posted, the value is `0`, which is a perfectly valid value for an int, and the validation is satisfied. In the case of `int?`, the value is `null`, which is *not* a valid int, and thus fails validation. That is why the nullable is required, if you want to require a non-nullable type have a value. It's the only way that an empty value can be differentiated from simply a "default" value.
If you are using view models, as you should be, this should not be an issue. You can bind to a nullable int with a required attribute, and you will be assured that it *will* have a value, despite being nullable, if your model state is valid. Then, you can map that over to a straight int on your entity. That is the correct way to handle things. |
50,910,136 | I am new to python and I currently have one text file that I sliced into two columns. I am looking for unique one-to-one relationships in the text file to determine new home buyers:
**Main File**
1234 Address , Billy Joel
Joe Martin, 45 Other Address
63 OtherOther Address, Joe Martin
Billy Joel, 1234 Address
***I am lookng for the unique one-to-one relationship (1234 Address and Billy Joel)***
**Curent Steps/Goals:**
>
> 1. sliced text file into two lists based on the ','
>
>
>
Looking to write something like this (I know this is very horribly laid out, but I am stuck on how to implement this):
```
addressListing= text file that is read
leftLst = addressListing.split(",", 1)[0]
rightLst = addressListing.split(".", 1) [1]
for (x, y) in (leftLst, rightLst):
if x in rightLst and y in leftLst:
return x + y
else:
pass
```
The text file is not neat where there are only addresses on one side and only names on the other. | 2018/06/18 | [
"https://Stackoverflow.com/questions/50910136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9574850/"
] | Solution working with json requests
-----------------------------------
You **cannot validate an already created model instance**, because a non-nullable property has always a value (no matter whether it was assigned from json or is a default value). The **solution is to report the missing value already during deserialization**.
Create a contract resolver
```
public class RequiredPropertiesContractResolver : DefaultContractResolver
{
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
foreach (var contractProperty in contract.Properties)
{
if (contractProperty.PropertyType.IsValueType
&& contractProperty.AttributeProvider.GetAttributes(typeof(RequiredAttribute), inherit: true).Any())
{
contractProperty.Required = Required.Always;
}
}
return contract;
}
}
```
and then assign it to `SerializerSettings`:
```
services.AddMvc()
.AddJsonOptions(jsonOptions =>
{
jsonOptions.SerializerSettings.ContractResolver = new RequiredPropertiesContractResolver();
});
```
The `ModelState` is then invalid for non-nullable properties with the `[Required]` attribute if the value is missing from json.
---
Example
-------
Json body
```
var jsonBody = @"{ Data2=123 }"
```
is invalid for model
```
class Model
{
[Required]
public int Data { get; set; }
public int Data2 { get; set; }
}
``` | There was the way to do that, at least it works for me, try `[BindRequired]` for non-nullable types. |
1,250,779 | I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?
The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute.
Feel free to comment on how you would handle the following situations:
1. Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization.
2. Default class attribute, that in rare occasions updated for a special instance of the class.
3. Global data structure used to represent an internal state of a class shared between all instances.
4. A class that initializes a number of default attributes, not influenced by constructor arguments.
Some Related Posts:
[Difference Between Class and Instance Attributes](https://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes) | 2009/08/09 | [
"https://Stackoverflow.com/questions/1250779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64313/"
] | Class attributes are often used to allow overriding defaults in subclasses. For example, BaseHTTPRequestHandler has class constants sys\_version and server\_version, the latter defaulting to `"BaseHTTP/" + __version__`. SimpleHTTPRequestHandler overrides server\_version to `"SimpleHTTP/" + __version__`. | Encapsulation is a good principle: when an attribute is inside the class it pertains to instead of being in the global scope, this gives additional information to people reading the code.
In your situations 1-4, I would thus avoid globals as much as I can, and prefer using class attributes, which allow one to benefit from encapsulation. |
1,250,779 | I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?
The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute.
Feel free to comment on how you would handle the following situations:
1. Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization.
2. Default class attribute, that in rare occasions updated for a special instance of the class.
3. Global data structure used to represent an internal state of a class shared between all instances.
4. A class that initializes a number of default attributes, not influenced by constructor arguments.
Some Related Posts:
[Difference Between Class and Instance Attributes](https://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes) | 2009/08/09 | [
"https://Stackoverflow.com/questions/1250779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64313/"
] | #4:
I *never* use class attributes to initialize default instance attributes (the ones you normally put in `__init__`). For example:
```
class Obj(object):
def __init__(self):
self.users = 0
```
and never:
```
class Obj(object):
users = 0
```
Why? Because it's inconsistent: it doesn't do what you want when you assign anything but an invariant object:
```
class Obj(object):
users = []
```
causes the users list to be shared across all objects, which in this case isn't wanted. It's confusing to split these into class attributes and assignments in `__init__` depending on their type, so I always put them all in `__init__`, which I find clearer anyway.
---
As for the rest, I generally put class-specific values inside the class. This isn't so much because globals are "evil"--they're not so big a deal as in some languages, because they're still scoped to the module, unless the module itself is too big--but if external code wants to access them, it's handy to have all of the relevant values in one place. For example, in module.py:
```
class Obj(object):
class Exception(Exception): pass
...
```
and then:
```
from module import Obj
try:
o = Obj()
o.go()
except o.Exception:
print "error"
```
Aside from allowing subclasses to change the value (which isn't always wanted anyway), it means I don't have to laboriously import exception names and a bunch of other stuff needed to use Obj. "from module import Obj, ObjException, ..." gets tiresome quickly. | Class attributes are often used to allow overriding defaults in subclasses. For example, BaseHTTPRequestHandler has class constants sys\_version and server\_version, the latter defaulting to `"BaseHTTP/" + __version__`. SimpleHTTPRequestHandler overrides server\_version to `"SimpleHTTP/" + __version__`. |
1,250,779 | I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?
The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute.
Feel free to comment on how you would handle the following situations:
1. Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization.
2. Default class attribute, that in rare occasions updated for a special instance of the class.
3. Global data structure used to represent an internal state of a class shared between all instances.
4. A class that initializes a number of default attributes, not influenced by constructor arguments.
Some Related Posts:
[Difference Between Class and Instance Attributes](https://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes) | 2009/08/09 | [
"https://Stackoverflow.com/questions/1250779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64313/"
] | #4:
I *never* use class attributes to initialize default instance attributes (the ones you normally put in `__init__`). For example:
```
class Obj(object):
def __init__(self):
self.users = 0
```
and never:
```
class Obj(object):
users = 0
```
Why? Because it's inconsistent: it doesn't do what you want when you assign anything but an invariant object:
```
class Obj(object):
users = []
```
causes the users list to be shared across all objects, which in this case isn't wanted. It's confusing to split these into class attributes and assignments in `__init__` depending on their type, so I always put them all in `__init__`, which I find clearer anyway.
---
As for the rest, I generally put class-specific values inside the class. This isn't so much because globals are "evil"--they're not so big a deal as in some languages, because they're still scoped to the module, unless the module itself is too big--but if external code wants to access them, it's handy to have all of the relevant values in one place. For example, in module.py:
```
class Obj(object):
class Exception(Exception): pass
...
```
and then:
```
from module import Obj
try:
o = Obj()
o.go()
except o.Exception:
print "error"
```
Aside from allowing subclasses to change the value (which isn't always wanted anyway), it means I don't have to laboriously import exception names and a bunch of other stuff needed to use Obj. "from module import Obj, ObjException, ..." gets tiresome quickly. | Encapsulation is a good principle: when an attribute is inside the class it pertains to instead of being in the global scope, this gives additional information to people reading the code.
In your situations 1-4, I would thus avoid globals as much as I can, and prefer using class attributes, which allow one to benefit from encapsulation. |
1,250,779 | I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?
The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute.
Feel free to comment on how you would handle the following situations:
1. Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization.
2. Default class attribute, that in rare occasions updated for a special instance of the class.
3. Global data structure used to represent an internal state of a class shared between all instances.
4. A class that initializes a number of default attributes, not influenced by constructor arguments.
Some Related Posts:
[Difference Between Class and Instance Attributes](https://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes) | 2009/08/09 | [
"https://Stackoverflow.com/questions/1250779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64313/"
] | >
> what is a good use case for class attributes
>
>
>
**Case 0.** Class methods are just class attributes. This is not just a technical similarity - you can access and modify class methods at runtime by assigning callables to them.
**Case 1.** A module can easily define several classes. It's reasonable to encapsulate everything about `class A` into `A...` and everything about `class B` into `B...`. For example,
```
# module xxx
class X:
MAX_THREADS = 100
...
# main program
from xxx import X
if nthreads < X.MAX_THREADS: ...
```
**Case 2.** This class has lots of default attributes which can be modified in an instance. Here the ability to leave attribute to be a 'global default' is a feature, not bug.
```
class NiceDiff:
"""Formats time difference given in seconds into a form '15 minutes ago'."""
magic = .249
pattern = 'in {0}', 'right now', '{0} ago'
divisions = 1
# there are more default attributes
```
One creates instance of NiceDiff to use the existing or slightly modified formatting, but a localizer to a different language subclasses the class to implement some functions in a fundamentally different way **and** redefine constants:
```
class Разница(NiceDiff): # NiceDiff localized to Russian
'''Из разницы во времени, типа -300, делает конкретно '5 минут назад'.'''
pattern = 'через {0}', 'прям щас', '{0} назад'
```
**Your cases**:
* constants -- yes, I put them to class. It's strange to say `self.CONSTANT = ...`, so I don't see a big risk for clobbering them.
* Default attribute -- mixed, as above may go to class, but may also go to `__init__` depending on the semantics.
* Global data structure --- goes to class if used **only** by the class, but may also go to module, in either case must be **very** well-documented. | Encapsulation is a good principle: when an attribute is inside the class it pertains to instead of being in the global scope, this gives additional information to people reading the code.
In your situations 1-4, I would thus avoid globals as much as I can, and prefer using class attributes, which allow one to benefit from encapsulation. |
1,250,779 | I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around?
The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute.
Feel free to comment on how you would handle the following situations:
1. Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization.
2. Default class attribute, that in rare occasions updated for a special instance of the class.
3. Global data structure used to represent an internal state of a class shared between all instances.
4. A class that initializes a number of default attributes, not influenced by constructor arguments.
Some Related Posts:
[Difference Between Class and Instance Attributes](https://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes) | 2009/08/09 | [
"https://Stackoverflow.com/questions/1250779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64313/"
] | #4:
I *never* use class attributes to initialize default instance attributes (the ones you normally put in `__init__`). For example:
```
class Obj(object):
def __init__(self):
self.users = 0
```
and never:
```
class Obj(object):
users = 0
```
Why? Because it's inconsistent: it doesn't do what you want when you assign anything but an invariant object:
```
class Obj(object):
users = []
```
causes the users list to be shared across all objects, which in this case isn't wanted. It's confusing to split these into class attributes and assignments in `__init__` depending on their type, so I always put them all in `__init__`, which I find clearer anyway.
---
As for the rest, I generally put class-specific values inside the class. This isn't so much because globals are "evil"--they're not so big a deal as in some languages, because they're still scoped to the module, unless the module itself is too big--but if external code wants to access them, it's handy to have all of the relevant values in one place. For example, in module.py:
```
class Obj(object):
class Exception(Exception): pass
...
```
and then:
```
from module import Obj
try:
o = Obj()
o.go()
except o.Exception:
print "error"
```
Aside from allowing subclasses to change the value (which isn't always wanted anyway), it means I don't have to laboriously import exception names and a bunch of other stuff needed to use Obj. "from module import Obj, ObjException, ..." gets tiresome quickly. | >
> what is a good use case for class attributes
>
>
>
**Case 0.** Class methods are just class attributes. This is not just a technical similarity - you can access and modify class methods at runtime by assigning callables to them.
**Case 1.** A module can easily define several classes. It's reasonable to encapsulate everything about `class A` into `A...` and everything about `class B` into `B...`. For example,
```
# module xxx
class X:
MAX_THREADS = 100
...
# main program
from xxx import X
if nthreads < X.MAX_THREADS: ...
```
**Case 2.** This class has lots of default attributes which can be modified in an instance. Here the ability to leave attribute to be a 'global default' is a feature, not bug.
```
class NiceDiff:
"""Formats time difference given in seconds into a form '15 minutes ago'."""
magic = .249
pattern = 'in {0}', 'right now', '{0} ago'
divisions = 1
# there are more default attributes
```
One creates instance of NiceDiff to use the existing or slightly modified formatting, but a localizer to a different language subclasses the class to implement some functions in a fundamentally different way **and** redefine constants:
```
class Разница(NiceDiff): # NiceDiff localized to Russian
'''Из разницы во времени, типа -300, делает конкретно '5 минут назад'.'''
pattern = 'через {0}', 'прям щас', '{0} назад'
```
**Your cases**:
* constants -- yes, I put them to class. It's strange to say `self.CONSTANT = ...`, so I don't see a big risk for clobbering them.
* Default attribute -- mixed, as above may go to class, but may also go to `__init__` depending on the semantics.
* Global data structure --- goes to class if used **only** by the class, but may also go to module, in either case must be **very** well-documented. |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | The null filehandle [diamond operator](http://perldoc.perl.org/perlop.html#I%2fO-Operators) `<>` has its place in building command line tools. It acts like `<FH>` to read from a handle, except that it magically selects whichever is found first: command line filenames or STDIN. Taken from perlop:
```
while (<>) {
... # code for each line
}
``` | @Schwern mentioned turning warnings into errors by localizing `$SIG{__WARN__}`. You can do also do this (lexically) with `use warnings FATAL => "all";`. See `perldoc lexwarn`.
On that note, since Perl 5.12, you've been able to say `perldoc foo` instead of the full `perldoc perlfoo`. Finally! :) |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | The operators ++ and unary - don't only work on numbers, but also on strings.
```
my $_ = "a"
print -$_
```
prints *-a*
```
print ++$_
```
prints *b*
```
$_ = 'z'
print ++$_
```
prints *aa* | A bit obscure is the tilde-tilde "operator" which forces scalar context.
```
print ~~ localtime;
```
is the same as
```
print scalar localtime;
```
and different from
```
print localtime;
``` |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | It's simple to quote almost any kind of strange string in Perl.
```
my $url = q{http://my.url.com/any/arbitrary/path/in/the/url.html};
```
In fact, the various quoting mechanisms in Perl are quite interesting. The Perl regex-like quoting mechanisms allow you to quote anything, specifying the delimiters. You can use almost any special character like #, /, or open/close characters like (), [], or {}. Examples:
```
my $var = q#some string where the pound is the final escape.#;
my $var2 = q{A more pleasant way of escaping.};
my $var3 = q(Others prefer parens as the quote mechanism.);
```
Quoting mechanisms:
q : literal quote; only character that needs to be escaped is the end character.
qq : an interpreted quote; processes variables and escape characters. Great for strings that you need to quote:
```
my $var4 = qq{This "$mechanism" is broken. Please inform "$user" at "$email" about it.};
```
qx : Works like qq, but then executes it as a system command, non interactively. Returns all the text generated from the standard out. (Redirection, if supported in the OS, also comes out) Also done with back quotes (the ` character).
```
my $output = qx{type "$path"}; # get just the output
my $moreout = qx{type "$path" 2>&1}; # get stuff on stderr too
```
qr : Interprets like qq, but then compiles it as a regular expression. Works with the various options on the regex as well. You can now pass the regex around as a variable:
```
sub MyRegexCheck {
my ($string, $regex) = @_;
if ($string)
{
return ($string =~ $regex);
}
return; # returns 'null' or 'empty' in every context
}
my $regex = qr{http://[\w]\.com/([\w]+/)+};
@results = MyRegexCheck(q{http://myurl.com/subpath1/subpath2/}, $regex);
```
qw : A very, very useful quote operator. Turns a quoted set of whitespace separated words into a list. Great for filling in data in a unit test.
```
my @allowed = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z { });
my @badwords = qw(WORD1 word2 word3 word4);
my @numbers = qw(one two three four 5 six seven); # works with numbers too
my @list = ('string with space', qw(eight nine), "a $var"); # works in other lists
my $arrayref = [ qw(and it works in arrays too) ];
```
They're great to use them whenever it makes things clearer. For qx, qq, and q, I most likely use the {} operators. The most common habit of people using qw is usually the () operator, but sometimes you also see qw//. | You can expand function calls in a string, for example;
```
print my $foo = "foo @{[scalar(localtime)]} bar";
```
>
> foo Wed May 26 15:50:30 2010 bar
>
>
> |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | Binary "x" is the [repetition operator](http://perldoc.perl.org/perlop.html#Multiplicative-Operators):
```
print '-' x 80; # print row of dashes
```
It also works with lists:
```
print for (1, 4, 9) x 3; # print 149149149
``` | The feature I like the best is statement modifiers.
Don't know how many times I've wanted to do:
```
say 'This will output' if 1;
say 'This will not output' unless 1;
say 'Will say this 3 times. The first Time: '.$_ for 1..3;
```
in other languages.
etc...
The 'etc' reminded me of another 5.12 feature, the Yada Yada operator.
This is great, for the times when you just want a place holder.
```
sub something_really_important_to_implement_later {
...
}
```
Check it out: [Perl Docs on Yada Yada Operator](http://perldoc.perl.org/perlop.html#The-Triple-Dot-Operator). |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | Two things that work well together: IO handles on in-core strings, and using function prototypes to enable you to write your own functions with grep/map-like syntax.
```
sub with_output_to_string(&) { # allows compiler to accept "yoursub {}" syntax.
my $function = shift;
my $string = '';
my $handle = IO::Handle->new();
open($handle, '>', \$string) || die $!; # IO handle on a plain scalar string ref
my $old_handle = select $handle;
eval { $function->() };
select $old_handle;
die $@ if $@;
return $string;
}
my $greeting = with_output_to_string {
print "Hello, world!";
};
print $greeting, "\n";
``` | Next time you're at a geek party pull out this one-liner in a bash shell and the women will swarm you and your friends will worship you:
find . -name "\*.txt"|xargs perl -pi -e 's/1:(\S+)/uc($1)/ge'
Process all \*.txt files and do an in-place find and replace using perl's regex. This one converts text after a '1:' to upper case and removes the '1:'. Uses Perl's 'e' modifier to treat the second part of the find/replace regex as executable code. Instant one-line template system. Using xargs lets you process a huge number of files without running into bash's command line length limit. |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | Let's start easy with the [Spaceship Operator](http://en.wikipedia.org/wiki/Spaceship_operator).
```
$a = 5 <=> 7; # $a is set to -1
$a = 7 <=> 5; # $a is set to 1
$a = 6 <=> 6; # $a is set to 0
``` | How about the ability to use
```
my @symbols = map { +{ 'key' => $_ } } @things;
```
to generate an array of hashrefs from an array -- the + in front of the hashref disambiguates the block so the interpreter knows that it's a hashref and not a code block. Awesome.
(Thanks to Dave Doyle for explaining this to me at the last Toronto Perlmongers meeting.) |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | It's simple to quote almost any kind of strange string in Perl.
```
my $url = q{http://my.url.com/any/arbitrary/path/in/the/url.html};
```
In fact, the various quoting mechanisms in Perl are quite interesting. The Perl regex-like quoting mechanisms allow you to quote anything, specifying the delimiters. You can use almost any special character like #, /, or open/close characters like (), [], or {}. Examples:
```
my $var = q#some string where the pound is the final escape.#;
my $var2 = q{A more pleasant way of escaping.};
my $var3 = q(Others prefer parens as the quote mechanism.);
```
Quoting mechanisms:
q : literal quote; only character that needs to be escaped is the end character.
qq : an interpreted quote; processes variables and escape characters. Great for strings that you need to quote:
```
my $var4 = qq{This "$mechanism" is broken. Please inform "$user" at "$email" about it.};
```
qx : Works like qq, but then executes it as a system command, non interactively. Returns all the text generated from the standard out. (Redirection, if supported in the OS, also comes out) Also done with back quotes (the ` character).
```
my $output = qx{type "$path"}; # get just the output
my $moreout = qx{type "$path" 2>&1}; # get stuff on stderr too
```
qr : Interprets like qq, but then compiles it as a regular expression. Works with the various options on the regex as well. You can now pass the regex around as a variable:
```
sub MyRegexCheck {
my ($string, $regex) = @_;
if ($string)
{
return ($string =~ $regex);
}
return; # returns 'null' or 'empty' in every context
}
my $regex = qr{http://[\w]\.com/([\w]+/)+};
@results = MyRegexCheck(q{http://myurl.com/subpath1/subpath2/}, $regex);
```
qw : A very, very useful quote operator. Turns a quoted set of whitespace separated words into a list. Great for filling in data in a unit test.
```
my @allowed = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z { });
my @badwords = qw(WORD1 word2 word3 word4);
my @numbers = qw(one two three four 5 six seven); # works with numbers too
my @list = ('string with space', qw(eight nine), "a $var"); # works in other lists
my $arrayref = [ qw(and it works in arrays too) ];
```
They're great to use them whenever it makes things clearer. For qx, qq, and q, I most likely use the {} operators. The most common habit of people using qw is usually the () operator, but sometimes you also see qw//. | tie, the variable tying interface. |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | [Autovivification](http://en.wikipedia.org/wiki/Autovivification). AFAIK **no other language has it**. | ```
rename("$_.part", $_) for "data.txt";
```
renames data.txt.part to data.txt without having to repeat myself. |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | My favorite semi-hidden feature of Perl is the `eof` function. Here's an example pretty much directly from `perldoc -f eof` that shows how you can use it to reset the file name and `$.` (the current line number) easily across multiple files loaded up at the command line:
```
while (<>) {
print "$ARGV:$.\t$_";
}
continue {
close ARGV if eof
}
``` | Showing progress in the script by printing on the same line:
```
$| = 1; # flush the buffer on the next output
for $i(1..100) {
print "Progress $i %\r"
}
``` |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work?
Guidelines:
* Try to limit answers to the Perl core and not CPAN
* Please give an example and a short description
---
Hidden Features also found in other languages' Hidden Features:
---------------------------------------------------------------
(These are all from [Corion's answer](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162257))
* [C](https://stackoverflow.com/questions/132241/hidden-features-of-c#)
+ Duff's Device
+ Portability and Standardness
* [C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
+ Quotes for whitespace delimited lists and strings
+ Aliasable namespaces
* [Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
+ Static Initalizers
* [JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
+ Functions are First Class citizens
+ Block scope and closure
+ Calling methods and accessors indirectly through a variable
* [Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
+ Defining methods through code
* [PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
+ Pervasive online documentation
+ Magic methods
+ Symbolic references
* [Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
+ One line value swapping
+ Ability to replace even core functions with your own functionality
Other Hidden Features:
----------------------
Operators:
* [The bool quasi-operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [The flip-flop operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162058)
+ Also used for [list construction](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
* [The `++` and unary `-` operators work on strings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162004)
* [The repetition operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162075)
* [The spaceship operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161943)
* [The || operator (and // operator) to select from a set of choices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162239)
* [The diamond operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162152)
* [Special cases of the `m//` operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162249)
* [The tilde-tilde "operator"](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162060)
Quoting constructs:
* [The qw operator](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Letters can be used as quote delimiters in q{}-like constructs](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Quoting mechanisms](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163374)
Syntax and Names:
* [There can be a space after a sigil](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [You can give subs numeric names with symbolic references](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162094)
* [Legal trailing commas](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163416)
* [Grouped Integer Literals](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [hash slices](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168925)
* [Populating keys of a hash from an array](https://stackoverflow.com/questions/161872/hidden-features-of-perl#195254)
Modules, Pragmas, and command-line options:
* [use strict and use warnings](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Taint checking](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Esoteric use of -n and -p](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162085)
* [CPAN](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163541)
* [`overload::constant`](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [IO::Handle module](https://stackoverflow.com/questions/161872/hidden-features-of-perl#164255)
* [Safe compartments](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163725)
* [Attributes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#310083)
Variables:
* [Autovivification](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162357)
* [The `$[` variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161985)
* [tie](https://stackoverflow.com/questions/161872/hidden-features-of-perl#168947)
* [Dynamic Scoping](https://stackoverflow.com/questions/161872/hidden-features-of-perl#172118)
* [Variable swapping with a single statement](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205627)
Loops and flow control:
* [Magic goto](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [`for` on a single variable](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163481)
* [continue clause](https://stackoverflow.com/questions/161872/hidden-features-of-perl#169592)
* [Desperation mode](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Regular expressions:
* [The `\G` anchor](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162565)
* [`(?{})` and '(??{})` in regexes](https://stackoverflow.com/questions/161872/hidden-features-of-perl#161976)
Other features:
* [The debugger](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163440)
* [Special code blocks such as BEGIN, CHECK, and END](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162206)
* [The `DATA` block](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163700)
* [New Block Operations](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Source Filters](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [Signal Hooks](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162601)
* [map](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167309) ([twice](https://stackoverflow.com/questions/161872/hidden-features-of-perl#167809))
* [Wrapping built-in functions](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162842)
* [The `eof` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl/189883#189883)
* [The `dbmopen` function](https://stackoverflow.com/questions/161872/hidden-features-of-perl#194796)
* [Turning warnings into errors](https://stackoverflow.com/questions/161872/hidden-features-of-perl#205104)
Other tricks, and meta-answers:
* [cat files, decompressing gzips if needed](https://stackoverflow.com/questions/161872/hidden-features-of-perl#163532)
* [Perl Tips](https://stackoverflow.com/questions/161872/hidden-features-of-perl#162271)
---
**See Also:**
* [Hidden features of C](https://stackoverflow.com/questions/132241/hidden-features-of-c)
* [Hidden features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c)
* [Hidden features of C++](https://stackoverflow.com/questions/75538/hidden-features-of-c)
* [Hidden features of Java](https://stackoverflow.com/questions/15496/hidden-features-of-java)
* [Hidden features of JavaScript](https://stackoverflow.com/questions/61088/hidden-features-of-javascript)
* [Hidden features of Ruby](https://stackoverflow.com/questions/63998/hidden-features-of-ruby)
* [Hidden features of PHP](https://stackoverflow.com/questions/61401/hidden-features-of-php)
* [Hidden features of Python](https://stackoverflow.com/questions/101268/hidden-features-of-python)
* [Hidden features of Clojure](https://stackoverflow.com/questions/2493996/hidden-features-of-clojure) | 2008/10/02 | [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | There are many non-obvious features in Perl.
For example, did you know that there can be a space after a sigil?
```
$ perl -wle 'my $x = 3; print $ x'
3
```
Or that you can give subs numeric names if you use symbolic references?
```
$ perl -lwe '*4 = sub { print "yes" }; 4->()'
yes
```
There's also the "bool" quasi operator, that return 1 for true expressions and the empty string for false:
```
$ perl -wle 'print !!4'
1
$ perl -wle 'print !!"0 but true"'
1
$ perl -wle 'print !!0'
(empty line)
```
Other interesting stuff: with `use overload` you can overload string literals and numbers (and for example make them BigInts or whatever).
Many of these things are actually documented somewhere, or follow logically from the documented features, but nonetheless some are not very well known.
*Update*: Another nice one. Below the `q{...}` quoting constructs were mentioned, but did you know that you can use letters as delimiters?
```
$ perl -Mstrict -wle 'print q bJet another perl hacker.b'
Jet another perl hacker.
```
Likewise you can write regular expressions:
```
m xabcx
# same as m/abc/
``` | I personally love the /e modifier to the s/// operation:
```
while(<>) {
s/(\w{0,4})/reverse($1);/e; # reverses all words between 0 and 4 letters
print;
}
```
Input:
```
This is a test of regular expressions
^D
```
Output (I think):
```
sihT si a tset fo regular expressions
``` |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | I found a way to do this. We used GatsbyJS for a project and it relies on a
.env.production file for the env variables. I tried to pass them as
`env:` to the github action, but that didn't work and they were ignored.
Here is what I did. I base 64 encoded the .env.production file:
```
base64 -i .env.production
```
Added the output to an env variable in github action. Then in my action I do:
```
echo ${{ secrets.ENV_PRODUCTION_FILE }} | base64 -d > .env.production
```
This way the contents of my .env.production file ended being written to the machine that executes the github action. | Here is how to solve your actual problem of securely logging into an SSH server using a secret stored in GitHub Actions, named `GITHUB_ACTIONS_DEPLOY`.
Let's call this "beep", because it will cause an audible bell on the server you login to. Maybe you use this literally ping a server in your house when somebody pushes code to your repo.
```yaml
- name: Beep
# if: github.ref == 'refs/heads/XXXX' # Maybe limit only this step to some branches
run: |
eval $(ssh-agent)
ssh-add - <<< "$SSH_KEY"
echo "* ssh-rsa XXX" >> /tmp/known_hosts # Get from your local ~/.ssh/known_hosts or from ssh-keyscan
ssh -o UserKnownHostsFile=/tmp/known_hosts user@example.com "echo '\a'"
env:
SSH_KEY: ${{ secrets.PMT_GITHUB_ACTIONS_DEPLOY }}
```
If, actually you are using SSH as part of a rsync push task, here is how to do that:
```yaml
- name: Publish
if: github.ref == 'refs/heads/XXX'
run: |
eval $(ssh-agent)
ssh-add - <<< "$SSH_KEY"
echo "* ssh-rsa XXX" >> /tmp/known_hosts
rsync $FROM user@server:
env:
SSH_KEY: ${{ secrets.GITHUB_ACTIONS_DEPLOY }}
RSYNC_RSH: "ssh -o UserKnownHostsFile=/tmp/known_hosts"
``` |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | Here is how to solve your actual problem of securely logging into an SSH server using a secret stored in GitHub Actions, named `GITHUB_ACTIONS_DEPLOY`.
Let's call this "beep", because it will cause an audible bell on the server you login to. Maybe you use this literally ping a server in your house when somebody pushes code to your repo.
```yaml
- name: Beep
# if: github.ref == 'refs/heads/XXXX' # Maybe limit only this step to some branches
run: |
eval $(ssh-agent)
ssh-add - <<< "$SSH_KEY"
echo "* ssh-rsa XXX" >> /tmp/known_hosts # Get from your local ~/.ssh/known_hosts or from ssh-keyscan
ssh -o UserKnownHostsFile=/tmp/known_hosts user@example.com "echo '\a'"
env:
SSH_KEY: ${{ secrets.PMT_GITHUB_ACTIONS_DEPLOY }}
```
If, actually you are using SSH as part of a rsync push task, here is how to do that:
```yaml
- name: Publish
if: github.ref == 'refs/heads/XXX'
run: |
eval $(ssh-agent)
ssh-add - <<< "$SSH_KEY"
echo "* ssh-rsa XXX" >> /tmp/known_hosts
rsync $FROM user@server:
env:
SSH_KEY: ${{ secrets.GITHUB_ACTIONS_DEPLOY }}
RSYNC_RSH: "ssh -o UserKnownHostsFile=/tmp/known_hosts"
``` | The good solution is to use gpg for encrypting the key, adding it to a repo and decrypting it on the server using passphrase. The passprase should be stored as github project secret of course.
More info how I did it here: <https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets> |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | I used sed in a GHA to replace a TOKEN in a file like this :
```
run: |-
sed -i "s/TOKEN/${{secrets.MY_SECRET}}/g" "thefile"
```
The file looks like this:
```
credentials "app.terraform.io" {
token = "TOKEN"
}
``` | Here is how to solve your actual problem of securely logging into an SSH server using a secret stored in GitHub Actions, named `GITHUB_ACTIONS_DEPLOY`.
Let's call this "beep", because it will cause an audible bell on the server you login to. Maybe you use this literally ping a server in your house when somebody pushes code to your repo.
```yaml
- name: Beep
# if: github.ref == 'refs/heads/XXXX' # Maybe limit only this step to some branches
run: |
eval $(ssh-agent)
ssh-add - <<< "$SSH_KEY"
echo "* ssh-rsa XXX" >> /tmp/known_hosts # Get from your local ~/.ssh/known_hosts or from ssh-keyscan
ssh -o UserKnownHostsFile=/tmp/known_hosts user@example.com "echo '\a'"
env:
SSH_KEY: ${{ secrets.PMT_GITHUB_ACTIONS_DEPLOY }}
```
If, actually you are using SSH as part of a rsync push task, here is how to do that:
```yaml
- name: Publish
if: github.ref == 'refs/heads/XXX'
run: |
eval $(ssh-agent)
ssh-add - <<< "$SSH_KEY"
echo "* ssh-rsa XXX" >> /tmp/known_hosts
rsync $FROM user@server:
env:
SSH_KEY: ${{ secrets.GITHUB_ACTIONS_DEPLOY }}
RSYNC_RSH: "ssh -o UserKnownHostsFile=/tmp/known_hosts"
``` |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | GitHub Actions should be able to write a secret to a file this way. The reason you see the stars is that the log is filtered, so if a secret would be logged, it's replaced in the log with three asterisks instead. This is a security measure against an accidental disclosure of secrets, since logs are often publicly available.
However, it's a good idea to avoid writing the secret to the log anyway if possible. You can write your command like this so you don't write the secret to the log:
```
- run: 'echo "$SSH_KEY" > key'
shell: bash
env:
SSH_KEY: ${{secrets.SSH_KEY}}
```
All you'll see in the log is `echo "$SSH_KEY" > key`, not the secret or any asterisks.
Note that you do want quotes here, since the `>` character is special to YAML.
If this doesn't work to log into your server, there's likely a different issue; this technique does work for writing secrets in the general case. | I used sed in a GHA to replace a TOKEN in a file like this :
```
run: |-
sed -i "s/TOKEN/${{secrets.MY_SECRET}}/g" "thefile"
```
The file looks like this:
```
credentials "app.terraform.io" {
token = "TOKEN"
}
``` |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | GitHub Actions should be able to write a secret to a file this way. The reason you see the stars is that the log is filtered, so if a secret would be logged, it's replaced in the log with three asterisks instead. This is a security measure against an accidental disclosure of secrets, since logs are often publicly available.
However, it's a good idea to avoid writing the secret to the log anyway if possible. You can write your command like this so you don't write the secret to the log:
```
- run: 'echo "$SSH_KEY" > key'
shell: bash
env:
SSH_KEY: ${{secrets.SSH_KEY}}
```
All you'll see in the log is `echo "$SSH_KEY" > key`, not the secret or any asterisks.
Note that you do want quotes here, since the `>` character is special to YAML.
If this doesn't work to log into your server, there's likely a different issue; this technique does work for writing secrets in the general case. | encode it and decode back
```
- run: 'echo "$SSH_KEY" | base64'
shell: bash
env:
SSH_KEY: ${{ secrets.PRIVATE_KEY }}
```
and decode it back `echo "<encoded string>" | base64 -d` |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | I found a way to do this. We used GatsbyJS for a project and it relies on a
.env.production file for the env variables. I tried to pass them as
`env:` to the github action, but that didn't work and they were ignored.
Here is what I did. I base 64 encoded the .env.production file:
```
base64 -i .env.production
```
Added the output to an env variable in github action. Then in my action I do:
```
echo ${{ secrets.ENV_PRODUCTION_FILE }} | base64 -d > .env.production
```
This way the contents of my .env.production file ended being written to the machine that executes the github action. | I used sed in a GHA to replace a TOKEN in a file like this :
```
run: |-
sed -i "s/TOKEN/${{secrets.MY_SECRET}}/g" "thefile"
```
The file looks like this:
```
credentials "app.terraform.io" {
token = "TOKEN"
}
``` |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | encode it and decode back
```
- run: 'echo "$SSH_KEY" | base64'
shell: bash
env:
SSH_KEY: ${{ secrets.PRIVATE_KEY }}
```
and decode it back `echo "<encoded string>" | base64 -d` | The good solution is to use gpg for encrypting the key, adding it to a repo and decrypting it on the server using passphrase. The passprase should be stored as github project secret of course.
More info how I did it here: <https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets> |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | GitHub Actions should be able to write a secret to a file this way. The reason you see the stars is that the log is filtered, so if a secret would be logged, it's replaced in the log with three asterisks instead. This is a security measure against an accidental disclosure of secrets, since logs are often publicly available.
However, it's a good idea to avoid writing the secret to the log anyway if possible. You can write your command like this so you don't write the secret to the log:
```
- run: 'echo "$SSH_KEY" > key'
shell: bash
env:
SSH_KEY: ${{secrets.SSH_KEY}}
```
All you'll see in the log is `echo "$SSH_KEY" > key`, not the secret or any asterisks.
Note that you do want quotes here, since the `>` character is special to YAML.
If this doesn't work to log into your server, there's likely a different issue; this technique does work for writing secrets in the general case. | The good solution is to use gpg for encrypting the key, adding it to a repo and decrypting it on the server using passphrase. The passprase should be stored as github project secret of course.
More info how I did it here: <https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets> |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | GitHub Actions should be able to write a secret to a file this way. The reason you see the stars is that the log is filtered, so if a secret would be logged, it's replaced in the log with three asterisks instead. This is a security measure against an accidental disclosure of secrets, since logs are often publicly available.
However, it's a good idea to avoid writing the secret to the log anyway if possible. You can write your command like this so you don't write the secret to the log:
```
- run: 'echo "$SSH_KEY" > key'
shell: bash
env:
SSH_KEY: ${{secrets.SSH_KEY}}
```
All you'll see in the log is `echo "$SSH_KEY" > key`, not the secret or any asterisks.
Note that you do want quotes here, since the `>` character is special to YAML.
If this doesn't work to log into your server, there's likely a different issue; this technique does work for writing secrets in the general case. | I found a way to do this. We used GatsbyJS for a project and it relies on a
.env.production file for the env variables. I tried to pass them as
`env:` to the github action, but that didn't work and they were ignored.
Here is what I did. I base 64 encoded the .env.production file:
```
base64 -i .env.production
```
Added the output to an env variable in github action. Then in my action I do:
```
echo ${{ secrets.ENV_PRODUCTION_FILE }} | base64 -d > .env.production
```
This way the contents of my .env.production file ended being written to the machine that executes the github action. |
59,481,941 | I am new to python and I am trying to disable TAB2 from widget notebook tkinter, through the support\_test.py file I have the command of the disable\_tab2 button, which should have the command to disable the option, but I get the error below:
```
Exception in Tkinter callback Traceback (most recent call last): File
"C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.p>y", line 1705, in __call__
return self.func(*args) File "c:\teste\teste_support.py", line 20, in desativa_tab2
w.TNotebook1_t0.configure(state='disabaled') File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw) File "C:\Users\Ryzen\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-state"
```
file teste.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import teste_support
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
teste_support.init(root, top)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
teste_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("600x450+633+190")
top.minsize(120, 1)
top.maxsize(1924, 1061)
top.resizable(1, 1)
top.title("New Toplevel")
top.configure(background="#d9d9d9")
self.Button1 = tk.Button(top)
self.Button1.place(relx=0.417, rely=0.044, height=24, width=47)
self.Button1.configure(activebackground="#ececec")
self.Button1.configure(activeforeground="#000000")
self.Button1.configure(background="#d9d9d9")
self.Button1.configure(command=teste_support.desativa_tab2)
self.Button1.configure(disabledforeground="#a3a3a3")
self.Button1.configure(foreground="#000000")
self.Button1.configure(highlightbackground="#d9d9d9")
self.Button1.configure(highlightcolor="black")
self.Button1.configure(pady="0")
self.Button1.configure(text='''Button''')
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(relx=0.067, rely=0.222, relheight=0.591
, relwidth=0.69)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_t0 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t0, padding=3)
self.TNotebook1.tab(0, text="Page 1",compound="left",underline="-1",)
self.TNotebook1_t0.configure(background="#d9d9d9")
self.TNotebook1_t0.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t0.configure(highlightcolor="black")
self.TNotebook1_t1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1, padding=3)
self.TNotebook1.tab(1, text="Page 2",compound="left",underline="-1",)
self.TNotebook1_t1.configure(background="#d9d9d9")
self.TNotebook1_t1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1.configure(highlightcolor="black")
self.Label1 = tk.Label(self.TNotebook1_t0)
self.Label1.place(relx=0.195, rely=0.333, height=21, width=104)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''TAB 1''')
self.Label1 = tk.Label(self.TNotebook1_t1)
self.Label1.place(relx=0.263, rely=0.258, height=21, width=104)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''TAB 2''')
if __name__ == '__main__':
vp_start_gui()
```
file
teste\_suporte.py
```
# -*- coding: utf-8 -*-
import sys
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
def desativa_tab2():
global w
w.TNotebook1_t0.configure(state='disabaled')
print('teste_support.desativa_tab2')
sys.stdout.flush()
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
# Function which closes the window.
global top_level
top_level.destroy()
top_level = None
if __name__ == '__main__':
import teste
teste.vp_start_gui()
``` | 2019/12/25 | [
"https://Stackoverflow.com/questions/59481941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596546/"
] | I found a way to do this. We used GatsbyJS for a project and it relies on a
.env.production file for the env variables. I tried to pass them as
`env:` to the github action, but that didn't work and they were ignored.
Here is what I did. I base 64 encoded the .env.production file:
```
base64 -i .env.production
```
Added the output to an env variable in github action. Then in my action I do:
```
echo ${{ secrets.ENV_PRODUCTION_FILE }} | base64 -d > .env.production
```
This way the contents of my .env.production file ended being written to the machine that executes the github action. | encode it and decode back
```
- run: 'echo "$SSH_KEY" | base64'
shell: bash
env:
SSH_KEY: ${{ secrets.PRIVATE_KEY }}
```
and decode it back `echo "<encoded string>" | base64 -d` |
44,150,069 | I've implemented the "xor problem" with cntk (python).
Currently it solves the problem only occasionally. How could I implement a more reliable network?
I guess the problem gets solved whenever the starting random weights are near optimal. I have tried `binary_cross_entropy` as the loss function but it didn't improve. I tried `tanh` as the non-linear function but that it didn't work either. I have also tried many different combinations of parameters `learning_rate`, `minibatch_size` and `num_minibatches_to_train`. Please help.
Thanks
```
# -*- coding: utf-8 -*-
import numpy as np
from cntk import *
import random
import pandas as pd
input_dim = 2
output_dim = 1
def generate_random_data_sample(sample_size, feature_dim, num_classes):
Y = []
X = []
for i in range(sample_size):
if i % 4 == 0:
Y.append([0])
X.append([1,1])
if i % 4 == 1:
Y.append([0])
X.append([0,0])
if i % 4 == 2:
Y.append([1])
X.append([1,0])
if i % 4 == 3:
Y.append([1])
X.append([0,1])
return np.array(X,dtype=np.float32), np.array(Y,dtype=np.float32)
def linear_layer(input_var, output_dim,scale=10):
input_dim = input_var.shape[0]
weight = parameter(shape=(input_dim, output_dim),init=uniform(scale=scale))
bias = parameter(shape=(output_dim))
return bias + times(input_var, weight)
def dense_layer(input_var, output_dim, nonlinearity,scale=10):
l = linear_layer(input_var, output_dim,scale=scale)
return nonlinearity(l)
feature = input(input_dim, np.float32)
h1 = dense_layer(feature, 2, sigmoid,scale=10)
z = dense_layer(h1, output_dim, sigmoid,scale=10)
label=input(1,np.float32)
loss = squared_error(z,label)
eval_error = squared_error(z,label)
learning_rate = 0.5
lr_schedule = learning_rate_schedule(learning_rate, UnitType.minibatch)
learner = sgd(z.parameters, lr_schedule)
trainer = Trainer(z, (loss, eval_error), [learner])
def print_training_progress(trainer, mb, frequency, verbose=1):
training_loss, eval_error = "NA", "NA"
if mb % frequency == 0:
training_loss = trainer.previous_minibatch_loss_average
eval_error = trainer.previous_minibatch_evaluation_average
if verbose:
print ("Minibatch: {0}, Loss: {1:.4f}, Error: {2:.2f}".format(mb, training_loss, eval_error))
return mb, training_loss, eval_error
minibatch_size = 800
num_minibatches_to_train = 2000
training_progress_output_freq = 50
for i in range(0, num_minibatches_to_train):
features, labels = generate_random_data_sample(minibatch_size, input_dim, output_dim)
trainer.train_minibatch({feature : features, label : labels})
batchsize, loss, error = print_training_progress(trainer, i, training_progress_output_freq, verbose=1)
out = z
result = out.eval({feature : features})
a = pd.DataFrame(data=dict(
query=[str(int(x[0]))+str(int(x[1])) for x in features],
test=[int(l[0]) for l in labels],
pred=[l[0] for l in result]))
print(pd.DataFrame.drop_duplicates(a[["query","test","pred"]]).sort_values(by="test"))
``` | 2017/05/24 | [
"https://Stackoverflow.com/questions/44150069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635993/"
] | One option is to apply the [`TO_JSON_STRING` function](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#to_json_string) to the results of your query. For example,
```
#standardSQL
SELECT TO_JSON_STRING(t)
FROM (
SELECT x, y
FROM YourTable
WHERE z = 10
) AS t;
```
If you want all of the table's columns as JSON, you can use a simpler form:
```
#standardSQL
SELECT TO_JSON_STRING(t)
FROM YourTable AS t
WHERE z = 10;
``` | I'm using a service account to access the BigQuery REST API to get the response in JSON format.
In order to use a service account, you will have to go to credentials (<https://console.cloud.google.com/apis/credentials>) and choose a project.
[](https://i.stack.imgur.com/qwwRQ.png)
You will get a drop down like this:
[](https://i.stack.imgur.com/gGSlA.png)
Create a Service account for your project and download the secret file in the JSON format. Keep the JSON file in your file system and set the path to it. Check below image to set the file path:
[](https://i.stack.imgur.com/3D5MK.png)
So, now all you have to do in is use JAVA client api to consume the Big Query REST API.
Here's is a simple solution that I've been using for my project.
```
package com.example.bigquery;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import org.apache.log4j.Logger;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.io.CharStreams;
public class BigQueryDemo {
private static final String QUERY_URL_FORMAT = "https://www.googleapis.com/bigquery/v2/projects/%s/queries" + "?access_token=%s";
private static final String QUERY = "query";
private static final String QUERY_HACKER_NEWS_COMMENTS = "SELECT * FROM [bigquery-public-data:hacker_news.comments] LIMIT 1000";
private static final Logger logger = Logger.getLogger(BigQueryDemo.class);
static GoogleCredential credential = null;
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
static {
// Authenticate requests using Google Application Default credentials.
try {
credential = GoogleCredential.getApplicationDefault();
credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));
credential.refreshToken();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void implicit() {
String projectId = credential.getServiceAccountProjectId();
String accessToken = generateAccessToken();
// Set the content of the request.
Dataset dataset = new Dataset().addLabel(QUERY, QUERY_HACKER_NEWS_COMMENTS);
HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset.getLabels());
// Send the request to the BigQuery API.
GenericUrl url = new GenericUrl(String.format(QUERY_URL_FORMAT, projectId, accessToken));
logger.debug("URL: " + url.toString());
String responseJson = getQueryResult(content, url);
logger.debug(responseJson);
}
private static String getQueryResult(HttpContent content, GenericUrl url) {
String responseContent = null;
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
HttpRequest request = null;
try {
request = requestFactory.buildPostRequest(url, content);
request.setParser(JSON_FACTORY.createJsonObjectParser());
request.setHeaders(
new HttpHeaders().set("X-HTTP-Method-Override", "POST").setContentType("application/json"));
HttpResponse response = request.execute();
InputStream is = response.getContent();
responseContent = CharStreams.toString(new InputStreamReader(is));
} catch (IOException e) {
logger.error(e);
}
return responseContent;
}
private static String generateAccessToken() {
String accessToken = null;
if ((System.currentTimeMillis() > credential.getExpirationTimeMilliseconds())) {
accessToken = credential.getRefreshToken();
} else {
accessToken = credential.getAccessToken();
}
System.out.println(accessToken);
return accessToken;
}
}
```
Following is the Github link to the code: <https://github.com/vslala/BigQueryRestSample>
It is just a demo project to fetch JSON data from the BQ REST API. Do not use it in your project directly.
Let me know if you have any questions. |
36,054,382 | I have succeeded ran the code in C++,with the code below:
```
int countOnes(int num) {
int count =0;
while (num) {
count ++;
num = num & (num-1);
}
return count;
}
```
but it didn't work in Python version:
```
def countOnes(num):
count = 0
while(num):
count += 1
num = num&(num-1)
return count
```
It seems blocked when the num = -1(0Xffffffff), why does it work in C++, but not in python? | 2016/03/17 | [
"https://Stackoverflow.com/questions/36054382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6075620/"
] | The reason this function works differently in the two languages is that they have different fundamental number types. In C++, `int` is indeed often a 32 bit integer in two's complement representation, though the language standard allows other representations. In Python, however, the standard number type has arbitrary precision.
The continuation criterion for your loop is that `num` is non-zero. If it doesn't terminate, let's add some debugging to see what happens instead:
```
def countOnes(num):
count = 0
while(num):
count += 1
num = num&(num-1)
print(num) # <-- inspect what happens to num
return count
```
Let's see what we get for different inputs:
```
>>> countOnes(1)
0
1
>>> countOnes(7)
6
4
0
3
```
For `-1`, however, things quickly go out of hand:
```
>>> countOnes(-1)
-2
-4
-8
-16
-32
-64
-128
-256
-512
-1024
-2048
-4096
...
```
`num` keeps decreasing. Since the number type has arbitrary size, the number will only keep growing more negative.
To simulate the fixed precision of the C integer, you can limit `num` to 32 bits:
```
def countOnes(num):
num = num & 0xffffffff # <-- Limit num to 32 bits
count = 0
while(num):
count += 1
num = num&(num-1)
return count
```
With debugging output, the output for `countOnes(-1)` is now:
```
>>> countOnes(-1)
4294967294
4294967292
4294967288
4294967280
4294967264
4294967232
4294967168
4294967040
4294966784
4294966272
4294965248
4294963200
4294959104
4294950912
4294934528
4294901760
4294836224
4294705152
4294443008
4293918720
4292870144
4290772992
4286578688
4278190080
4261412864
4227858432
4160749568
4026531840
3758096384
3221225472
2147483648
0
32
```
as desired :) | Python doesn't have "32-bit integers". Its integers are arbitrary (read:infinite) length. This means that -1 is *not* 0xffffffff, but is instead an infinitely long binary sequence of 1s. |
36,054,382 | I have succeeded ran the code in C++,with the code below:
```
int countOnes(int num) {
int count =0;
while (num) {
count ++;
num = num & (num-1);
}
return count;
}
```
but it didn't work in Python version:
```
def countOnes(num):
count = 0
while(num):
count += 1
num = num&(num-1)
return count
```
It seems blocked when the num = -1(0Xffffffff), why does it work in C++, but not in python? | 2016/03/17 | [
"https://Stackoverflow.com/questions/36054382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6075620/"
] | The reason this function works differently in the two languages is that they have different fundamental number types. In C++, `int` is indeed often a 32 bit integer in two's complement representation, though the language standard allows other representations. In Python, however, the standard number type has arbitrary precision.
The continuation criterion for your loop is that `num` is non-zero. If it doesn't terminate, let's add some debugging to see what happens instead:
```
def countOnes(num):
count = 0
while(num):
count += 1
num = num&(num-1)
print(num) # <-- inspect what happens to num
return count
```
Let's see what we get for different inputs:
```
>>> countOnes(1)
0
1
>>> countOnes(7)
6
4
0
3
```
For `-1`, however, things quickly go out of hand:
```
>>> countOnes(-1)
-2
-4
-8
-16
-32
-64
-128
-256
-512
-1024
-2048
-4096
...
```
`num` keeps decreasing. Since the number type has arbitrary size, the number will only keep growing more negative.
To simulate the fixed precision of the C integer, you can limit `num` to 32 bits:
```
def countOnes(num):
num = num & 0xffffffff # <-- Limit num to 32 bits
count = 0
while(num):
count += 1
num = num&(num-1)
return count
```
With debugging output, the output for `countOnes(-1)` is now:
```
>>> countOnes(-1)
4294967294
4294967292
4294967288
4294967280
4294967264
4294967232
4294967168
4294967040
4294966784
4294966272
4294965248
4294963200
4294959104
4294950912
4294934528
4294901760
4294836224
4294705152
4294443008
4293918720
4292870144
4290772992
4286578688
4278190080
4261412864
4227858432
4160749568
4026531840
3758096384
3221225472
2147483648
0
32
```
as desired :) | You can create the 32bit representation limit
```
def countOnes(num):
num = num % (1 << 32)
count = 0
while(num):
count += 1
num = num&(num-1)
return count
``` |
68,116,542 | I am trying to recode an existing python script to Java.
It includes this following line:
```
r = requests.get('https://{}/redfish/v1/{}'.format(ip, query), auth=('ADMIN', 'ADMIN'), verify=False)
```
I don't have a lot of experience in Python and didn't write the script myself. So far I've only been able to figure out what it does, but not how to replicate it using Java.
If anyone could point me in the right direction that would be awesome.
Thanks! | 2021/06/24 | [
"https://Stackoverflow.com/questions/68116542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8298497/"
] | First, read [this tutorial on the java HTTP client](https://openjdk.java.net/groups/net/httpclient/intro.html). (Note that it requires jdk11 or up).
From there it should be fairly simply; that `.format()` thing is just replacing the `{}` with the provided ip and query parts. The auth part is more interesting. The verify part presumably means 'whatever, forget about SSL'.
Between a password of 'admin' and 'disregard SSL issues', this code screams "You are about 2 weeks away from getting your box p0wned", maybe you should be taking security a bit more seriously than this.
At any rate, the equivalents in the java sphere are more complicated, because java intentionally does not meant 'disable ssl' to be a casual throwaway move, unlike python which just hands you the bazooka no questions asked.
[Here is a tutorial on how to do basic http auth with the http client](https://www.baeldung.com/httpclient-4-basic-authentication).
To shoot your foot off properly and ensure that the foot is fully dead, you need to make an SSL Context that does nothing and silently just accepts all certificates, even ones someone trying to hack your system made. Then pass that for `.sslContext` to `HttpClient.builder()`.
[Here is an example of someone firing this bazooka](https://gist.github.com/mingliangguo/c86e05a0f8a9019b281a63d151965ac7). | At first, you can use `String.format` for the formatting:
```java
String url=String.format("https://%s/redfish/v1/%s",ip,query);
```
You could also use `MessageFormat` if you want to.
For connecting, you can create a `URL`-object and creating a `URLConnection` (in your case `HttpsURLConnection`) and opening an `InputStream` for the response afterwards:
```java
HttpsURLConnectioncon=(HttpsURLConnection)new URL(url).openConnection();
try(BufferedInputStream is=new BufferedInputStream(con.openStream()){
//...
}
```
In order to do the authentication, you can take a look at [this tutorial](https://www.baeldung.com/java-http-url-connection):
```java
String auth = "ADMIN:ADMIN";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
//Get the HttpURLConnection
con.setRequestProperty("Authorization", authHeaderValue);
//Connect/open InputStream
```
If you really want to disable verification, you can create your own `HostnameVerifier` that allows everything but this is strongly discouraged as this **allows man in the middle attacks** as you basically **disable the security of HTTPs**:
```java
con.setHostnameVerifier((hostname,sslSession)->true);
```
All combined, it could look like this:
```java
String url=String.format("https://%s/redfish/v1/%s",ip,query);
String auth = "ADMIN:ADMIN";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
HttpsURLConnection con=(HttpsURLConnection)new URL(url).openConnection();
con.setRequestProperty("Authorization", authHeaderValue);
con.setHostnameVerifier((hostname,sslSession)->true);//vulnerable to man in the middle attacks
try(BufferedInputStream is=new BufferedInputStream(con.openStream()){
//...
}
``` |
44,962,225 | I imported a table with the years that each coach served as the football coach. Some of the years listed look like this: "1903–1910, 1917, 1919"
I am aiming for [1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1917, 1919]
In my original DataFrame this list is an object.
I have tried:
`x = "1903–1910, 1917, 1919"`
`x[0].split('-')`
`re.split(r'\s|-', x[0])`
`x[0].replace('-', ' ').split(' ')`
I keep getting:
`['1903–1910']`
What am I doing wrong? Why isn't python finding the hyphen? | 2017/07/07 | [
"https://Stackoverflow.com/questions/44962225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8268427/"
] | The hyphen you see is not really a hyphen. It could be some other character, like an unicode en-dash which would look very similar.
Try to copy-paste the actual character into the split string.
Looking at the text you posted, here's the difference:
```
➜ ~ echo '1903–1910' | xxd
00000000: 3139 3033 e280 9331 3931 300a 1903...1910.
➜ ~ echo '1903-1910' | xxd
00000000: 3139 3033 2d31 3931 300a 1903-1910.
```
The character in the first case is: <https://unicode-table.com/en/2013/> | Your character is not an hyfen, it's a dash:
```
>>> "–" == "-"
False
>>> x = "1903–1910, 1917, 1919"
>>> x.split("–")
['1903', '1910, 1917, 1919']
``` |
44,962,225 | I imported a table with the years that each coach served as the football coach. Some of the years listed look like this: "1903–1910, 1917, 1919"
I am aiming for [1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1917, 1919]
In my original DataFrame this list is an object.
I have tried:
`x = "1903–1910, 1917, 1919"`
`x[0].split('-')`
`re.split(r'\s|-', x[0])`
`x[0].replace('-', ' ').split(' ')`
I keep getting:
`['1903–1910']`
What am I doing wrong? Why isn't python finding the hyphen? | 2017/07/07 | [
"https://Stackoverflow.com/questions/44962225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8268427/"
] | The hyphen you see is not really a hyphen. It could be some other character, like an unicode en-dash which would look very similar.
Try to copy-paste the actual character into the split string.
Looking at the text you posted, here's the difference:
```
➜ ~ echo '1903–1910' | xxd
00000000: 3139 3033 e280 9331 3931 300a 1903...1910.
➜ ~ echo '1903-1910' | xxd
00000000: 3139 3033 2d31 3931 300a 1903-1910.
```
The character in the first case is: <https://unicode-table.com/en/2013/> | This works but not optimal
```
# -*- coding: utf-8 -*-
x = "1903–1910, 1917, 1919"
endash = '–'
years = x.split(', ')
new_list = []
for year in years:
if endash in year:
start, finish = year.split(endash)
new_list.extend(range(int(start), int(finish)+1))
else:
new_list.append(int(year))
print new_list
```
Output: `[1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1917, 1919]` |
44,962,225 | I imported a table with the years that each coach served as the football coach. Some of the years listed look like this: "1903–1910, 1917, 1919"
I am aiming for [1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1917, 1919]
In my original DataFrame this list is an object.
I have tried:
`x = "1903–1910, 1917, 1919"`
`x[0].split('-')`
`re.split(r'\s|-', x[0])`
`x[0].replace('-', ' ').split(' ')`
I keep getting:
`['1903–1910']`
What am I doing wrong? Why isn't python finding the hyphen? | 2017/07/07 | [
"https://Stackoverflow.com/questions/44962225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8268427/"
] | Your character is not an hyfen, it's a dash:
```
>>> "–" == "-"
False
>>> x = "1903–1910, 1917, 1919"
>>> x.split("–")
['1903', '1910, 1917, 1919']
``` | This works but not optimal
```
# -*- coding: utf-8 -*-
x = "1903–1910, 1917, 1919"
endash = '–'
years = x.split(', ')
new_list = []
for year in years:
if endash in year:
start, finish = year.split(endash)
new_list.extend(range(int(start), int(finish)+1))
else:
new_list.append(int(year))
print new_list
```
Output: `[1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1917, 1919]` |
34,902,486 | There are many posts about 'latin-1' codec , however those answers can't solve my problem, maybe it's my question, I am just a rookie to learn Python, somewhat. When I used `cwd(dirname)` to change directory of FTP site, the unicodeerror occurred. Note that `dirname` included Chinese characters, obviously, those characters caused this error. I made some encoding and decoding according to the suggestions in the past posts, but it didn't work.
Could someone give me some advice how to repair this error and make `cwd` work?
Some codes:
```
file = 'myhongze.jpg'
dirname = './项目成员资料/zgcao/test-python/'
site = '***.***.***.***'
user = ('zhigang',getpass('Input Pwd:'))
ftp = FTP(site)
ftp.login(*user)
ftp.cwd(dirname)# throw exception
```
---
Some tests:
```none
u'./项目成员资料/zgcao/test-python/'.encode('utf-8')
```
Output:
```none
b'./\xe9\xa1\xb9\xe7\x9b\xae\xe6\x88\x90\xe5\x91\x98\xe8\xb5\x84\xe6\x96\x99/zgcao/test-python/'
```
---
```none
u'./项目成员资料/zgcao/test-python/'.encode('utf-8').decode('cp1252')
```
Output:
```none
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 10: character maps to <undefined>
```
---
```none
u'./项目成员资料/zgcao/test-python/'.encode('utf-8').decode('latin-1')
```
Output:
```none
'./项ç\x9b®æ\x88\x90å\x91\x98èµ\x84æ\x96\x99/zgcao/test-python/'
Using the result of decode('latin-1'), the cwd can't still work.
```
---
It is noted that `项目成员资料` is showed as `ÏîÄ¿×é³ÉԱ˽È˿ռä` when I used `retrlines('LIST')`. | 2016/01/20 | [
"https://Stackoverflow.com/questions/34902486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5816236/"
] | No need to edit ftplib source code. Just set `ftp.encoding` property in your code:
```
ftp.encoding = "UTF-8"
ftp.cwd(dirname)
```
A similar question, about FTP output, rather then input:
[List files with UTF-8 characters in the name in Python ftplib](https://stackoverflow.com/q/53091871/850848) | I solved this problem by editing `ftplib.py`. On my machine, it is under `C:\Users\<user>\AppData\Local\Programs\Python\Python36\Lib`.
You just need to replace `encoding = "latin-1"` with `encoding = "utf-8"` |
30,433,983 | This is what I have in my `Procfile`:
```
web: gunicorn --pythonpath meraki meraki.wsgi
```
and when I do `foreman start`, I get this error:
```
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
```
the reason, as far as I can see in the traceback, is:
```
ImportError: No module named wsgi
```
I did `import wsgi` in the shell and the import was successful, no errors.
Why can't I start `foreman`?
**Project Structure:**
```
meraki
meraki
//other apps
meraki
settings
__init__.py
celery.py
views.py
wsgi.py
manage.py
Procfile
requirements
requirements.txt
``` | 2015/05/25 | [
"https://Stackoverflow.com/questions/30433983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4137194/"
] | You've confused yourself by following an unnecessarily complicated structure. You don't need that outer meraki directory, and your Procfile and requirements.txt should be in the same directory as manage.py. Then you can remove the pythonpath parameter and all should be well. | As Roseman said, it is unnecessarily complicated structure.If you want it to do so,Try
```
web: gunicorn --pythonpath /path/to/meraki meraki.wsgi
```
That is `/absolutepath/to/secondmeroki(out of 3)` which contains `apps`. |
71,266,145 | I wrote a python function called `plot_ts_ex` that takes two arguments `ts_file` and `ex_file` (and the file name for this function is `pism_plot_routine`). I want to run this function from a bash script from terminal.
When I don't use variables in the bash script in pass the function arguments (in this case `ts_file = ts_g10km_10ka_hy.nc` and `ex_file = ex_g10km_10ka_hy.nc`) directly, like this:
```
#!/bin/sh
python -c 'import pism_plot_routine; pism_plot_routine.plot_ts_ex("ts_g10km_10ka_hy.nc", "ex_g10km_10ka_hy.nc")'
```
which is similar as in [Run function from the command line](https://stackoverflow.com/questions/3987041/run-function-from-the-command-line), that works.
But when I define variables for the input arguments, it doesn't work:
```
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10km_10ka_hy.nc"
python -c 'import pism_plot_routine; pism_plot_routine.plot_ts_ex("$ts_name", "$ex_name")'
```
It gives the error:
```
FileNotFoundError: [Errno 2] No such file or directory: b'$ts_name'
```
Then I found a similar question [passing an argument to a python function from bash](https://stackoverflow.com/questions/47939713/passing-an-argument-to-a-python-function-from-bash/47943114#47943114?newreg=8641b85190ae44d7ad69a8b2b32f61f8) for a python function with only one argument and I tried
```
#!/bin/sh
python -c 'import sys, pism_plot_routine; pism_plot_routine.plot_ts_ex(sys.argv[1])' "$ts_name" "$ex_name"
```
but that doesn't work.
So how can I pass 2 arguments for a python function in a bash script using variables? | 2022/02/25 | [
"https://Stackoverflow.com/questions/71266145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18308686/"
] | When you use single quotes the variables aren’t going to be expanded, you should use double quotes instead:
```
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10km_10ka_hy.nc"
python -c "import pism_plot_routine; pism_plot_routine.plot_ts_ex('$ts_name', '$ex_name')"
```
---
You can also use sys.argv, arguments are stored in a list, so `ts_name` is `sys.arv[1]` and `ex_name` is `sys.argv[2]`:
```
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10km_10ka_hy.nc"
python -c 'import sys, pism_plot_routine; pism_plot_routine.plot_ts_ex(sys.argv[1], sys.argv[2])' "$ts_name" "$ex_name"
``` | You are giving the value `$ts_name` to python as string, bash does not do anything with it. You need to close the `'`, so that it becomes a string in bash, and then open it again for it to become a string in python.
The result will be something like this:
```
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10km_10ka_hy.nc"
python -c 'import pism_plot_routine; pism_plot_routine.plot_ts_ex("'$ts_name'", "'$ex_name'")'
```
For issues like this it is often nice to use some smaller code to test it, I used `python3 -c 'print("${test}")'` to figure out what it was passing to python, without the bother of the `pism_plot`. |
36,915,188 | I have a large csv file with 25 columns, that I want to read as a pandas dataframe. I am using `pandas.read_csv()`.
The problem is that some rows have extra columns, something like that:
```
col1 col2 stringColumn ... col25
1 12 1 str1 3
...
33657 2 3 str4 6 4 3 #<- that line has a problem
33658 1 32 blbla #<-some columns have missing data too
```
When I try to read it, I get the error
```
CParserError: Error tokenizing data. C error: Expected 25 fields in line 33657, saw 28
```
The problem does not happen if the extra values appear in the first rows. For example if I add values to the third row of the same file it works fine
```
#that example works:
col1 col2 stringColumn ... col25
1 12 1 str1 3
2 12 1 str1 3
3 12 1 str1 3 f 4
...
33657 2 3 str4 6 4 3 #<- that line has a problem
33658 1 32 blbla #<-some columns have missing data too
```
My guess is that pandas checks the first (n) rows to determine the number of columns, and if you have extra columns after that it has a problem parsing it.
Skipping the offending lines like suggested [here](https://stackoverflow.com/questions/18039057/python-pandas-error-tokenizing-data) is not an option, those lines contain valuable information.
Does anybody know a way around this? | 2016/04/28 | [
"https://Stackoverflow.com/questions/36915188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5841927/"
] | If you want Coded UI to launch your forms application on start of a test, use the method
```
ApplicationUnderTest.Launch("FORMS_APP_PATH");
```
You can check the precise method details on MSDN.
Update:
To handle changing paths I created a new Forms solution and called it LabPlus.
I then added a CodedUI test project to it.
Inside the test project I added the reference of the LabPlus assembly.
After that, I wrote following line in my CUI test method:
```
ApplicationUnderTest.Launch(System.Reflection.Assembly.GetAssembly(typeof(LabPlus.Form1)).Location);
```
I hope this answers your question :) | My fix:
1. add reference from test project to WinForm project
2. decorate test class with `[DeploymentItem('your-app.exe')]` attribute
3. add `ApplicationUnderTest.Launch("your-app.exe");` to the test method |
37,009,587 | I'm making a python app to automate some tasks in AutoCAD (drawing specific shapes in specific layers and checking the location of some circles).
For the first part, drawing things, it was easy to use the AutoCAD Interop library, as you could easily put objects in the active document without doing anything on AutoCAD, not even loading any plugin. However i don't find any way of using that same library to check the properties of objects in the document.
What I need is a function that, when passed as argument the layer name, returns a list of the centers of every circle in that layer.
Now, it would be easy to do just by loading a plugin. But i need that info passed to a python program (that loads the AutoCAD Interop library through pythonnet) and i dont know how to do it.
So, summarizing, I need to:
* Learn how to use the AutoCAD Interop library to retrieve drawing's info.
or
* Interface an AutoCAD plugin with an external app writen in python.
Is it possible what i intend to do? What would be the best approach? | 2016/05/03 | [
"https://Stackoverflow.com/questions/37009587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266184/"
] | You can iterate through list of available resources using method of Assembly class:
```
var names = someInstance.GetType()
.GetTypeInfo()
.Assembly
.GetManifestResourceNames();
```
And then load resource by full name from the list above:
```
var stream = someAssembly.GetManifestResourceStream(name);
```
And then do whatever you want with the stream. | You need to get Assembly which you embedded resource then call GetManifestResourceStream.
I have sample with namespace YourProjectNameSpace have MyFolder contain MyFile.json:
```
public class EndpointBuilder
{
private static String _filePath = "YourProjectNameSpace.MyFolder.MyFile.json";
public async Task<Endpoint> Build() {
var assembly = this.GetType().GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream(_filePath);
JsonSerializer jsonSerializer = new JsonSerializer();
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
Endpoint enpoint = serializer.Deserialize<Endpoint>(jsonTextReader);
return enpoint;
}
}
}
``` |
718,040 | <http://pypi.python.org/pypi/simplejson>
I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..
I am on a Windows System | 2009/04/04 | [
"https://Stackoverflow.com/questions/718040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32372/"
] | I would recommend [EasyInstall](http://pypi.python.org/pypi/setuptools#windows), a package management application for Python.
Once you've installed EasyInstall, you should be able to go to a command window and type:
```
easy_install simplejson
```
This may require putting easy\_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like `C:\Python25\Scripts`). | If you have Python 2.6 installed then you already have simplejson - just import `json`; it's the same thing. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.