qid
int64 469
74.7M
| question
stringlengths 36
37.8k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 5
31.5k
| response_k
stringlengths 10
31.6k
|
---|---|---|---|---|---|
164,137 | I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.
I have no knowledge of deploying "real-life" Python applications, though I have used [`py2exe`](http://www.py2exe.org/) in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?
An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?
Thanks. | 2008/10/02 | [
"https://Stackoverflow.com/questions/164137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | Wow, there are a lot of questions in there:
* It is possible to run the bytecode (.pyc) file directly from the Python interpreter, but I haven't seen any bytecode obfuscation tools available.
* I'm not aware of any "all in one" deployment solution, but:
+ For Windows you could use NSIS(<http://nsis.sourceforge.net/Main_Page>). The problem here is that while OSX/\*nix comes with python, Windows doesn't. If you're not willing to build a binary with py2exe, I'm not sure what the licensing issues would be surrounding distribution of the Python runtime environment (not to mention the technical ones).
+ You could package up the OS X distribution using the "bundle" format, and \*NIX has it's own conventions for installing software-- typically a "make install" script.
Hope that was helpful. | I have been using py2exe with good success on Windows. The code needs to be modified a bit so that the code analysis picks up all modules needed, but apart from that, it works.
As for Linux, there are several important distribution formats:
* DEB (Debian, Ubuntu and other derivatives)
* RPM (RedHat, Fedora, openSuSE)
DEBs aren't particularly difficult to make, especially when you're already using distutils/setuptools. Some hints are given in [the policy document](http://wiki.debian.org/DebianPython/NewPolicy), examples for packaging Python applications can be found in the [repository](http://svn.debian.org/wsvn/python-apps/packages/).
I don't have any experience with RPM, but I'm sure there are enough examples to be found. |
164,137 | I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.
I have no knowledge of deploying "real-life" Python applications, though I have used [`py2exe`](http://www.py2exe.org/) in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?
An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?
Thanks. | 2008/10/02 | [
"https://Stackoverflow.com/questions/164137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | Wow, there are a lot of questions in there:
* It is possible to run the bytecode (.pyc) file directly from the Python interpreter, but I haven't seen any bytecode obfuscation tools available.
* I'm not aware of any "all in one" deployment solution, but:
+ For Windows you could use NSIS(<http://nsis.sourceforge.net/Main_Page>). The problem here is that while OSX/\*nix comes with python, Windows doesn't. If you're not willing to build a binary with py2exe, I'm not sure what the licensing issues would be surrounding distribution of the Python runtime environment (not to mention the technical ones).
+ You could package up the OS X distribution using the "bundle" format, and \*NIX has it's own conventions for installing software-- typically a "make install" script.
Hope that was helpful. | Try to use scraZ obfuscator (<http://scraZ.me>).
This is obfuscator for bytecode, not for source code.
Free version have good, but not perfect obfuscation methods.
PRO version have very very strong protection for bytecode.
(after bytecode obfuscation a decompilation is impossible) |
164,137 | I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.
I have no knowledge of deploying "real-life" Python applications, though I have used [`py2exe`](http://www.py2exe.org/) in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?
An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?
Thanks. | 2008/10/02 | [
"https://Stackoverflow.com/questions/164137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | You can distribute the compiled Python bytecode (.pyc files) instead of the source. You can't prevent decompilation in Python (or any other language, really). You could use an obfuscator like [pyobfuscate](http://www.lysator.liu.se/~astrand/projects/pyobfuscate/) to make it more annoying for competitors to decipher your decompiled source.
As Alex Martelli says [in this thread](http://mail.python.org/pipermail/python-list/2006-April/1079623.html), if you want to keep your code a secret, you shouldn't run it on other people's machines.
IIRC, the last time I used [cx\_Freeze](http://python.net/crew/atuining/cx_Freeze/) it created a DLL for Windows that removed the necessity for a native Python installation. This is at least worth checking out. | Maybe IronPython can provide something for you? I bet those .exe/.dll-files can be pretty locked down. Not sure how such features work on mono, thus no idea how this works on Linux/OS X... |
164,137 | I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.
I have no knowledge of deploying "real-life" Python applications, though I have used [`py2exe`](http://www.py2exe.org/) in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?
An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?
Thanks. | 2008/10/02 | [
"https://Stackoverflow.com/questions/164137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | You can distribute the compiled Python bytecode (.pyc files) instead of the source. You can't prevent decompilation in Python (or any other language, really). You could use an obfuscator like [pyobfuscate](http://www.lysator.liu.se/~astrand/projects/pyobfuscate/) to make it more annoying for competitors to decipher your decompiled source.
As Alex Martelli says [in this thread](http://mail.python.org/pipermail/python-list/2006-April/1079623.html), if you want to keep your code a secret, you shouldn't run it on other people's machines.
IIRC, the last time I used [cx\_Freeze](http://python.net/crew/atuining/cx_Freeze/) it created a DLL for Windows that removed the necessity for a native Python installation. This is at least worth checking out. | I have been using py2exe with good success on Windows. The code needs to be modified a bit so that the code analysis picks up all modules needed, but apart from that, it works.
As for Linux, there are several important distribution formats:
* DEB (Debian, Ubuntu and other derivatives)
* RPM (RedHat, Fedora, openSuSE)
DEBs aren't particularly difficult to make, especially when you're already using distutils/setuptools. Some hints are given in [the policy document](http://wiki.debian.org/DebianPython/NewPolicy), examples for packaging Python applications can be found in the [repository](http://svn.debian.org/wsvn/python-apps/packages/).
I don't have any experience with RPM, but I'm sure there are enough examples to be found. |
164,137 | I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.
I have no knowledge of deploying "real-life" Python applications, though I have used [`py2exe`](http://www.py2exe.org/) in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?
An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?
Thanks. | 2008/10/02 | [
"https://Stackoverflow.com/questions/164137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | You can distribute the compiled Python bytecode (.pyc files) instead of the source. You can't prevent decompilation in Python (or any other language, really). You could use an obfuscator like [pyobfuscate](http://www.lysator.liu.se/~astrand/projects/pyobfuscate/) to make it more annoying for competitors to decipher your decompiled source.
As Alex Martelli says [in this thread](http://mail.python.org/pipermail/python-list/2006-April/1079623.html), if you want to keep your code a secret, you shouldn't run it on other people's machines.
IIRC, the last time I used [cx\_Freeze](http://python.net/crew/atuining/cx_Freeze/) it created a DLL for Windows that removed the necessity for a native Python installation. This is at least worth checking out. | Try to use scraZ obfuscator (<http://scraZ.me>).
This is obfuscator for bytecode, not for source code.
Free version have good, but not perfect obfuscation methods.
PRO version have very very strong protection for bytecode.
(after bytecode obfuscation a decompilation is impossible) |
164,137 | I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.
I have no knowledge of deploying "real-life" Python applications, though I have used [`py2exe`](http://www.py2exe.org/) in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?
An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?
Thanks. | 2008/10/02 | [
"https://Stackoverflow.com/questions/164137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | Maybe IronPython can provide something for you? I bet those .exe/.dll-files can be pretty locked down. Not sure how such features work on mono, thus no idea how this works on Linux/OS X... | I have been using py2exe with good success on Windows. The code needs to be modified a bit so that the code analysis picks up all modules needed, but apart from that, it works.
As for Linux, there are several important distribution formats:
* DEB (Debian, Ubuntu and other derivatives)
* RPM (RedHat, Fedora, openSuSE)
DEBs aren't particularly difficult to make, especially when you're already using distutils/setuptools. Some hints are given in [the policy document](http://wiki.debian.org/DebianPython/NewPolicy), examples for packaging Python applications can be found in the [repository](http://svn.debian.org/wsvn/python-apps/packages/).
I don't have any experience with RPM, but I'm sure there are enough examples to be found. |
164,137 | I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.
I have no knowledge of deploying "real-life" Python applications, though I have used [`py2exe`](http://www.py2exe.org/) in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?
An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?
Thanks. | 2008/10/02 | [
"https://Stackoverflow.com/questions/164137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | Maybe IronPython can provide something for you? I bet those .exe/.dll-files can be pretty locked down. Not sure how such features work on mono, thus no idea how this works on Linux/OS X... | Try to use scraZ obfuscator (<http://scraZ.me>).
This is obfuscator for bytecode, not for source code.
Free version have good, but not perfect obfuscation methods.
PRO version have very very strong protection for bytecode.
(after bytecode obfuscation a decompilation is impossible) |
32,527,468 | I have need to take a list of keyword arguments in robot and convert them to a string of the form `key=value` if the keyword is in a certain list and `set key=value` if not. In python, it looks like this:
```
keywords=#list of keywords
def convert(**kwargs):
s = ''
for k,v in kwargs.iteritems():
if k in keywords:
s = s + '-%s=%s ' % (k,v)
else:
s = s + '-set %s=%s ' % (k,v)
return s
```
I know this could be simply written as a python keyword, but I'm trying to figure out if it's possible using Robot. I can iterate using `:For ${arg} in ${kwargs}`, but I'm not sure how it would work to retrieve the keys and values individually. | 2015/09/11 | [
"https://Stackoverflow.com/questions/32527468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/702948/"
] | It's doable in robot, but the code will be really hard to read. This would definitely best be done in python.
Starting in robot framework 2.8, user keywords can accept keyword arguments. The syntax uses `&` rather than `$` or `@`. So, to write a keyword that accepts keyword arguments you would do it like this:
```
*** Keywords ***
| Convert
| [Arguments] | &{args}
```
To iterate over the keys and values you can convert the dictionary to a list, then iterate over the list two at a time. It would look something like this:
```
| | ${result}= | set variable | ${EMPTY}
| | ${items}= | Get Dictionary items | ${args}
| | :FOR | ${key} | ${value} | IN | @{items}
| | | ${result}= | run keyword if | '${key}' in ${keywords}
| | | ... | catenate | ${result} | ${key}=${value}
| | | ... | ELSE
| | | ... | catenate | ${result} | set ${key}=${value}
| | [return] | ${result}
```
You might need to tweak what gets returned. I wasn't sure exactly what you wanted (your example includes dashes, but the description did not) | Here is one simple example. I won't try to re-create your Python function here because doing conditional things in Robot gets convoluted really quickly. There is absolutely nothing wrong with using your own Python library in Robot, so that might be the better path.
That said, you can extract `kwargs` in a Robot keyword:
```
*** Test Cases ***
mytestcase
mykeyword abc=1 def=2
*** Keywords ***
mykeyword
[Arguments] @{kwargs}
:FOR ${arg} IN @{kwargs}
\ ${key} ${value}= Evaluate "${arg}".split("=")
\ Log ${key}, ${value}
```
So in this script each iteration of the loop will extract the `${key}` and ${value}` for each keyword argument supplied to the function.
I haven't used it yet, but the newest version of Robot Framework (2.9) also has dictionary variables, which might make a task like this a little easier, i.e., no loop. You will have to refer to the [Robot Framework Docs](http://robotframework.org/robotframework/#user-guide) for this, though. |
20,357,720 | I've seen passing statements that you can enter complex statements like a for loop in an LLDB command (in the language of the program you're debugging - in this case Objective-C)
I would really like to be able to do this. I've never learned Python, and would prefer not to invest the time to do so in order to use the available python LLDB support - there just aren't enough hours in the day for that. | 2013/12/03 | [
"https://Stackoverflow.com/questions/20357720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205185/"
] | You can enter Objective-C statements using `expr -- ...`, for example:
```
(lldb) po myArray
(
foo,
bar
)
(lldb) expr -- for (NSString *s in myArray) { (void)NSLog(@"%@", s) ; }
2013-12-03 18:29:03.637 myapp[1373:70b] foo
2013-12-03 18:29:03.639 myapp[1373:70b] bar
``` | Based on @"Martin R"'s answer.
At least `NSLog` doesn't seem to print something with Xcode 6.0.1.
```
(lldb) expr -- for(UIWindow *w in [(UIApplication *)[UIApplication sharedApplication] windows]) { (int)printf("%s\n\n", [(NSString *)[w recursiveDescription] UTF8String]); }
``` |
64,231,439 | I have a basic API to reset the password, however, it seems to be throwing this error, despite "values", not appearing in my code altogether:
views.py
```
class PasswordResetNewPasswordAPIView(GenericAPIView):
serializer_class = SetNewPasswordSerializer
def patch(self, request):
user = request.data
serializer = SetNewPasswordSerializer(data=user)
serializer.is_valid(raise_exception=True)
return Response({
"message": "password reset"},
status=status.HTTP_200_OK
)
```
serializers.py
```
class SetNewPasswordSerializer(serializers.Serializer):
password = serializers.CharField(max_length=50, write_only =True)
token = serializers.CharField(write_only =True)
uidb64 = serializers.CharField(max_length = 255, write_only =True)
fields = ("password", "token", "uidb64",)
def validate(self, attrs):
try:
password = attrs.get("password", "")
token = attrs.get("token", "")
uidb64 = attrs.get("uidb64", "")
print(uidb64)
id = force_str(urlsafe_base64_decode(uidb64))
print(id)
user = Author.objects.get(id=id)
if not PasswordResetTokenGenerator().check_token(user, token):
raise AuthenticationFailed("Invalid Reset Parameter", 401)
user.set_password(password)
user.save()
return user
except Exception:
raise AuthenticationFailed("Invalid Reset Parameter", 401)
return super().validate(attrs)
```
urls.py
```
...
path('password-reset-setup/', PasswordResetNewPasswordAPIView.as_view(),name="password-reset-setup"),
```
What could be the possible error? And how to I get around it?
The traceback is:
```
Traceback (most recent call last):
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/django/core/handlers/base.py", line 202, in _get_response
response = response.render()
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/renderers.py", line 724, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/renderers.py", line 657, in get_context
raw_data_patch_form = self.get_raw_data_form(data, view, 'PATCH', request)
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/renderers.py", line 563, in get_raw_data_form
data = serializer.data.copy()
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/serializers.py", line 548, in data
ret = super().data
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/serializers.py", line 250, in data
self._data = self.get_initial()
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/serializers.py", line 398, in get_initial
for field in self.fields.values()
Exception Type: AttributeError at /authors/password-reset-setup/
Exception Value: 'tuple' object has no attribute 'values'
``` | 2020/10/06 | [
"https://Stackoverflow.com/questions/64231439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9871233/"
] | I'm not entirely sure, but it seems like the serializers.py file, you're creating a class that inherits from the `serializers.Serializer` class. You have code that says `fields = ("password", "token", "uidb64",)`, and this seems to be colliding with a field in the parent `serializers.Serializer` class. So one fix is to rename that `field` variable to something like `my_field`.
If you intended to override that variable, then it should be a list, not a tuple. Change it from `fields = ("password", "token", "uidb64",)` to `fields = ["password", "token", "uidb64"]` | The **`fields`** should be inside the **`Meta`** class
```
class SetNewPasswordSerializer(serializers.Serializer):
# rest of your code
**class Meta:
fields = ("password", "token", "uidb64",)**
``` |
64,231,439 | I have a basic API to reset the password, however, it seems to be throwing this error, despite "values", not appearing in my code altogether:
views.py
```
class PasswordResetNewPasswordAPIView(GenericAPIView):
serializer_class = SetNewPasswordSerializer
def patch(self, request):
user = request.data
serializer = SetNewPasswordSerializer(data=user)
serializer.is_valid(raise_exception=True)
return Response({
"message": "password reset"},
status=status.HTTP_200_OK
)
```
serializers.py
```
class SetNewPasswordSerializer(serializers.Serializer):
password = serializers.CharField(max_length=50, write_only =True)
token = serializers.CharField(write_only =True)
uidb64 = serializers.CharField(max_length = 255, write_only =True)
fields = ("password", "token", "uidb64",)
def validate(self, attrs):
try:
password = attrs.get("password", "")
token = attrs.get("token", "")
uidb64 = attrs.get("uidb64", "")
print(uidb64)
id = force_str(urlsafe_base64_decode(uidb64))
print(id)
user = Author.objects.get(id=id)
if not PasswordResetTokenGenerator().check_token(user, token):
raise AuthenticationFailed("Invalid Reset Parameter", 401)
user.set_password(password)
user.save()
return user
except Exception:
raise AuthenticationFailed("Invalid Reset Parameter", 401)
return super().validate(attrs)
```
urls.py
```
...
path('password-reset-setup/', PasswordResetNewPasswordAPIView.as_view(),name="password-reset-setup"),
```
What could be the possible error? And how to I get around it?
The traceback is:
```
Traceback (most recent call last):
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/django/core/handlers/base.py", line 202, in _get_response
response = response.render()
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/renderers.py", line 724, in render
context = self.get_context(data, accepted_media_type, renderer_context)
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/renderers.py", line 657, in get_context
raw_data_patch_form = self.get_raw_data_form(data, view, 'PATCH', request)
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/renderers.py", line 563, in get_raw_data_form
data = serializer.data.copy()
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/serializers.py", line 548, in data
ret = super().data
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/serializers.py", line 250, in data
self._data = self.get_initial()
File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/serializers.py", line 398, in get_initial
for field in self.fields.values()
Exception Type: AttributeError at /authors/password-reset-setup/
Exception Value: 'tuple' object has no attribute 'values'
``` | 2020/10/06 | [
"https://Stackoverflow.com/questions/64231439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9871233/"
] | I'm not entirely sure, but it seems like the serializers.py file, you're creating a class that inherits from the `serializers.Serializer` class. You have code that says `fields = ("password", "token", "uidb64",)`, and this seems to be colliding with a field in the parent `serializers.Serializer` class. So one fix is to rename that `field` variable to something like `my_field`.
If you intended to override that variable, then it should be a list, not a tuple. Change it from `fields = ("password", "token", "uidb64",)` to `fields = ["password", "token", "uidb64"]` | Your serializer needs `Meta` to declare model fields.
Try this:
```
class SetNewPasswordSerializer(serializers.Serializer):
password = serializers.CharField(max_length=50, write_only =True)
token = serializers.CharField(write_only =True)
uidb64 = serializers.CharField(max_length = 255, write_only =True)
class Meta: # you missed meta to declare your model fields
fields = ("password", "token", "uidb64",)
def validate(self, attrs):
try:
password = attrs.get("password", "")
token = attrs.get("token", "")
uidb64 = attrs.get("uidb64", "")
print(uidb64)
id = force_str(urlsafe_base64_decode(uidb64))
print(id)
user = Author.objects.get(id=id)
if not PasswordResetTokenGenerator().check_token(user, token):
raise AuthenticationFailed("Invalid Reset Parameter", 401)
user.set_password(password)
user.save()
return user
except Exception:
raise AuthenticationFailed("Invalid Reset Parameter", 401)
return super().validate(attrs)
``` |
24,806,996 | In python, for example, a function returns two values,
```
def f():
return 1, 2
```
while in some occasions I care about one of output values. In matlab, I can simply do
```
[out1, ~] = f()
```
But in python, how can I do. Thanks for the help! | 2014/07/17 | [
"https://Stackoverflow.com/questions/24806996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3663776/"
] | It's pretty similar in Python:
```
out, _ = f()
```
Note that this will only work with exactly two values. If you have more, you have to add an `_`, for each, unless you're using Python 3.x, which allows you to do this:
```
>>> x, *_ = [1,3,4,5]
>>> print _
[3, 4, 5]
``` | A typical pattern might be something like
```
out, _ = f()
```
This does actually end up declaring a variable called `_`, though it shouldn't really matter.
Or you could do this:
```
out = f()[0]
``` |
38,795,601 | If I have a `classic.css` file that I want to override (in this case it's from the Sphinx documentation used for Python: <https://docs.python.org/2.7/_static/classic.css> ) and essentially "undo" a rule, is there a way to do that?
In this case there are these rules:
```
div.sphinxsidebar h3 {
font-family: 'Trebuchet MS', sans-serif;
color: #ffffff;
font-size: 1.4em;
font-weight: normal;
margin: 0;
padding: 0;
}
div.sphinxsidebar h4 {
font-family: 'Trebuchet MS', sans-serif;
color: #ffffff;
font-size: 1.3em;
font-weight: normal;
margin: 5px 0 0 0;
padding: 0;
}
```
What I want to do is something like
```
div.sphinxsidebar h3,
div.sphinxsidebar h4
{
font-family: [revert-to-auto];
color: [revert-to-auto];
}
```
so I can specify the font-family and color in `body` and have it apply everywhere without having to use `!important`.
Just to clarify: I have my `custom.css` which starts with `@import(classic.css);` as per the Sphinx documentation, rather than the usual use of two `<link rel="stylesheet" type="text/css">` elements in the `<head>` section. | 2016/08/05 | [
"https://Stackoverflow.com/questions/38795601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44330/"
] | Yes, you can use [`initial`](https://www.w3.org/TR/css-cascade-4/#initial) to revert to the [initial value](https://www.w3.org/TR/css-cascade-4/#initial-value) of that property
```css
div.sphinxsidebar h3,
div.sphinxsidebar h4
{
font-family: initial;
color: initial;
}
```
Or Cascade Level 4 introduces [`revert`](https://www.w3.org/TR/css-cascade-4/#valdef-all-revert), which rolls back the cascade to the user level
```css
div.sphinxsidebar h3,
div.sphinxsidebar h4
{
font-family: revert;
color: revert;
}
``` | You want to include both CSS files in your `<head>` tag. The key is that you want your `custom.css` file to go underneath your `classic.css` file, like so:
```
<head>
<link rel="stylesheet" type="text/css" href="classic.css">
<link rel="stylesheet" type="text/css" href="custom.css">
</head>
```
What this does is respect the 'cascading' portion of CSS. It sees the first rule in `classic.css` but then when it gets to `custom.css` it overwrites the rule it previously saw. |
38,795,601 | If I have a `classic.css` file that I want to override (in this case it's from the Sphinx documentation used for Python: <https://docs.python.org/2.7/_static/classic.css> ) and essentially "undo" a rule, is there a way to do that?
In this case there are these rules:
```
div.sphinxsidebar h3 {
font-family: 'Trebuchet MS', sans-serif;
color: #ffffff;
font-size: 1.4em;
font-weight: normal;
margin: 0;
padding: 0;
}
div.sphinxsidebar h4 {
font-family: 'Trebuchet MS', sans-serif;
color: #ffffff;
font-size: 1.3em;
font-weight: normal;
margin: 5px 0 0 0;
padding: 0;
}
```
What I want to do is something like
```
div.sphinxsidebar h3,
div.sphinxsidebar h4
{
font-family: [revert-to-auto];
color: [revert-to-auto];
}
```
so I can specify the font-family and color in `body` and have it apply everywhere without having to use `!important`.
Just to clarify: I have my `custom.css` which starts with `@import(classic.css);` as per the Sphinx documentation, rather than the usual use of two `<link rel="stylesheet" type="text/css">` elements in the `<head>` section. | 2016/08/05 | [
"https://Stackoverflow.com/questions/38795601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44330/"
] | The CSS keyword `inherit` is usable for any property, and its function is to set the property to the value of the parent element. | You want to include both CSS files in your `<head>` tag. The key is that you want your `custom.css` file to go underneath your `classic.css` file, like so:
```
<head>
<link rel="stylesheet" type="text/css" href="classic.css">
<link rel="stylesheet" type="text/css" href="custom.css">
</head>
```
What this does is respect the 'cascading' portion of CSS. It sees the first rule in `classic.css` but then when it gets to `custom.css` it overwrites the rule it previously saw. |
38,795,601 | If I have a `classic.css` file that I want to override (in this case it's from the Sphinx documentation used for Python: <https://docs.python.org/2.7/_static/classic.css> ) and essentially "undo" a rule, is there a way to do that?
In this case there are these rules:
```
div.sphinxsidebar h3 {
font-family: 'Trebuchet MS', sans-serif;
color: #ffffff;
font-size: 1.4em;
font-weight: normal;
margin: 0;
padding: 0;
}
div.sphinxsidebar h4 {
font-family: 'Trebuchet MS', sans-serif;
color: #ffffff;
font-size: 1.3em;
font-weight: normal;
margin: 5px 0 0 0;
padding: 0;
}
```
What I want to do is something like
```
div.sphinxsidebar h3,
div.sphinxsidebar h4
{
font-family: [revert-to-auto];
color: [revert-to-auto];
}
```
so I can specify the font-family and color in `body` and have it apply everywhere without having to use `!important`.
Just to clarify: I have my `custom.css` which starts with `@import(classic.css);` as per the Sphinx documentation, rather than the usual use of two `<link rel="stylesheet" type="text/css">` elements in the `<head>` section. | 2016/08/05 | [
"https://Stackoverflow.com/questions/38795601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44330/"
] | Yes, you can use [`initial`](https://www.w3.org/TR/css-cascade-4/#initial) to revert to the [initial value](https://www.w3.org/TR/css-cascade-4/#initial-value) of that property
```css
div.sphinxsidebar h3,
div.sphinxsidebar h4
{
font-family: initial;
color: initial;
}
```
Or Cascade Level 4 introduces [`revert`](https://www.w3.org/TR/css-cascade-4/#valdef-all-revert), which rolls back the cascade to the user level
```css
div.sphinxsidebar h3,
div.sphinxsidebar h4
{
font-family: revert;
color: revert;
}
``` | The CSS keyword `inherit` is usable for any property, and its function is to set the property to the value of the parent element. |
14,753,844 | I have finally switched from `%` to the `.format()` string formatting operator in my 2.x code in order to make it easier to migrate to 3.x in future. It was a bit surprising to find out that not only the `%`-style formatting remains in Py3, but it is widely used in the standard library code. It seems logical, because writing `'(%s)' % variable` is a bit shorter and maybe easier to comprehend than `'({})'.format(variable)`. But I'm still in doubt. Is it proper (pythonic?) to use both approaches in the code?
Thank you. | 2013/02/07 | [
"https://Stackoverflow.com/questions/14753844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240950/"
] | Python 3.2 documentation said that, `%` will eventually go away.
<http://docs.python.org/3.2/tutorial/inputoutput.html#old-string-formatting>
>
> Since `str.format()` is quite new, a lot of Python code still uses the `%`
> operator. However, because this old style of formatting will
> eventually be removed from the language, `str.format()` should generally
> be used.
>
>
>
But as [@regilero says](https://stackoverflow.com/questions/14753844/python-3-using-s-and-format#comment30714285_14753974), **the sentence is gone from 3.3**, which might suggest it's not actually the case. There are some conversations [here](http://python.6.x6.nabble.com/Status-regarding-Old-vs-Advanced-String-Formating-tp4503327p4504193.html) that suggest the same thing.
As of [Python 3.4 the paragraph 7.1.1](https://docs.python.org/3.4/tutorial/inputoutput.html#old-string-formatting) reads:
>
> The % operator can also be used for string formatting. It interprets
> the left argument much like a sprintf()-style format string to be
> applied to the right argument, and returns the string resulting from
> this formatting operation.
>
>
>
See also [Python 3.4 4.7.2 printf-style String Formatting.](https://docs.python.org/3.4/library/stdtypes.html#old-string-formatting) | "%s" is now "{}", so insted of adding %s replace it with {} where you would want to add the variable into the string.
```
def main():
n="Python 3.+"
l="looks nice"
f="does not look practical."
print("This seems to be the new way {}".format(n)\
+ "will be working, rather than the ' % ',{} but {}".format(l,f))
main()
#In comparison to just injecting the variable
```
Output disregard the quotes they are for illustration reasons
"This seems to be the new way "Python 3.+"
will be working, rather than the '%;, "looks nice" but "does not look practical."" |
36,055,100 | I've a problem using the *yaml* (PyYAML 3.11) library in Python 3.x. When I call `import yaml` I get the following error:
```
Python 3.4.3+ (default, Oct 14 2015, 16:03:50)
[GCC 5.2.1 20151010] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mlohr/python-libs/yaml/__init__.py", line 2, in <module>
from error import *
ImportError: No module named 'error'
```
`error` is a file located in the yaml directory, but the `__init__.py` from yaml does use absolute imports. I guess that's the problem, but I#'m not sure.
In <http://pyyaml.org/wiki/PyYAMLDocumentation#Python3support> is a short path about (supposed) Python 3 support, so I'm not sure if I'm using it the wrong way.
The same issue occurs (that's the way I found the problem) when using Python 3 with python scripts using yaml.
With Python 2.7 and 2.6 it works without problems.
Any idea/suggestion how to get that working? | 2016/03/17 | [
"https://Stackoverflow.com/questions/36055100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2400785/"
] | It would seem that you're either using an old version of `PyYAML` after all or using a Python2 installation of `PyYAML` with Python3 as suggested in an [other answer](https://stackoverflow.com/a/36055462/2681632), because in your traceback we see
```
from error import *
```
which is not an absolute import. You should either upgrade, reinstall `PyYAML` with Python3 sources in your environment, or create a new environment for Python3 packages. | Your environment is polluted. If you create a (temporary) virtualenv this works without a problem:
```
$ mktmpenv -p /opt/python/3.4/bin/python
Running virtualenv with interpreter /opt/python/3.4/bin/python
Using base prefix '/opt/python/3.4'
New python executable in /home/venv/tmp-504ff2573d39ad0c/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-504ff2573d39ad0c) $ pip install pyyaml
Collecting pyyaml
Installing collected packages: pyyaml
Successfully installed pyyaml-3.11
(tmp-504ff2573d39ad0c) $ python
Python 3.4.3 (default, Jun 5 2015, 09:05:22)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import yaml
>>>
```
The most likely cause for this is that you are re-using YAML as installed for Python 2.X. The PyYAML sources are actually different for [2.x](https://bitbucket.org/xi/pyyaml/src/ddf211a41bb231c365fece5599b7e484e6dc33fc/lib/yaml/__init__.py?at=default&fileviewer=file-view-default) and [3.x](https://bitbucket.org/xi/pyyaml/src/ddf211a41bb231c365fece5599b7e484e6dc33fc/lib3/yaml/__init__.py?at=default&fileviewer=file-view-default) installs.
The easiest way around this is to install and use [ruamel.yaml](https://pypi.python.org/pypi/ruamel.yaml) (disclaimer: I am the author of that package), which is an upgrade for PyYAML where the sources are once more recombined. |
47,411,740 | I've had to reinstall a lot of libraries on Windows. When I want to install pycdc from github
Installing pycdc on windows.
pip install git+<https://github.com/zrax/pycdc.git>
I get:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\TT\AppData\Local\Temp\pip-ashu2b4z-build\setup.py
```
C:\Users\TT\unroll>pycdc .py
'pycdc' is not recognized as an internal or external command,
operable program or batch file.
C:\Users\TT\unroll>pip install git+https://github.com/zrax/pycdc.git
Collecting git+https://github.com/zrax/pycdc.git
Cloning https://github.com/zrax/pycdc.git to c:\users\TT\appdata\local\temp\pip-ashu2b4z-build
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\TT\Anaconda3\lib\tokenize.py", line 452, in open
buffer = _builtin_open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\TT\\AppData\\Local\\Temp\\pip-ashu2b4z-build\\setup.py'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\TT\AppData\Local\Temp\pip-ashu2b4z-build\
C:\Users\TT\unroll>pip install git+https://github.com/zrax/pycdc.git
```
I feel like I'm missing some dependency files
Boy do I ever regret doing a re-install. python may be nice to use but a nightmare to setup
Also:
```
C:\Users\TT>pip install git+ssh://git@github.com/BlahCo/search/tree/prod_release_branch/ProductName
Collecting git+ssh://git@github.com/BlahCo/search/tree/prod_release_branch/ProductName
Cloning ssh://git@github.com/BlahCo/search/tree/prod_release_branch/ProductName to c:\users\TT\appdata\local\temp\pip-6x2kywme-build
The authenticity of host 'github.com (192.30.255.113)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)? y
Please type 'yes' or 'no': yes
Warning: Permanently added 'github.com,192.30.255.113' (RSA) to the list of known hosts.
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
Command "git clone -q ssh://git@github.com/BlahCo/search/tree/prod_release_branch/ProductName C:\Users\TT\AppData\Local\Temp\pip-6x2kywme-build" failed with error code 128 in None
``` | 2017/11/21 | [
"https://Stackoverflow.com/questions/47411740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The parameter 'width' specifies the width of the boxes, so a simple solution would be to reduce that value (from 0.5). This would not increase spacing of the boxes, but increase spacing *between* them and therefore make the boxes narrower.
However, it seems to me like your boxplots are well spaced, but your points (jitter) are overlapping, making the graph look messy. A simpler solution would be to remove them, or change them to points instead of jitter. Alternatively you could use a violin plot.
For finer control, 'standard' ggplot2 can be used, perhaps with cowplot which can give you formatting:
```
p <- ggplot(data = flowdata, mapping = aes(x = TP, y = Treg, fill = Haplotype)) +
geom_boxplot(position = position_dodge(0.5)) +
geom_jitter(aes(shape = Treatment)) +
scale_shape_manual(c(21, 23)) +
scale_fill_manual(c("#0092d1","#62b232","#b23a32","#b232a3","#99cccc","#132a64")) +
theme(legend.title = element_blank(), legend.text = element_text(size=8), text = element_text(family = "Calibri"), axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = expression(paste("")), y = expression(paste(CD4^+{}, CD25^+{}, "cells/µL")))
``` | Building on Adams answer, I would furthermore suggest you get the boxplots into several facets, so that the plot is actually readable. I suppose the haplotype might be the interesting facet. Also, you could reduce the `size` of the jitter points or get some transparency `alpha` so that they are less present, but with the facet the boxplots are larger already, so this might solve the problem of readability by itself.
```
p <- ggplot(flowdata, aes(x = TP, y = Treg)) +
geom_boxplot(position = position_dodge(0.5)) +
geom_jitter(aes(shape = Treatment), size = 0.5, alpha = 0.8) +
facet_wrap(~Haplotype, ncol = 3) +
scale_shape_manual(c(21, 23)) +
theme(legend.title = element_blank(),
legend.text = element_text(size=8),
text = element_text(family = "Calibri"),
axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = "",
y = expression(paste(CD4^+{}, CD25^+{}, "cells/µL")))
``` |
30,688,563 | I'm animating a convergence process that I'm simulating in an IPython 3.1 notebook. I'm visualizing the scatter plot result in a matplotlib animation, which I'm writing out to an animated gif via ImageMagick. There are 3000 frames, each with about 5000 points.
I'm not sure exactly how matplotlib creates these animation files, but it appears to cache up a bunch of frames and then write them out all together-- when I look at the CPU usage, it's dominated by python in the beginning and then by convert at the end.
Writing out the gif is happening exceedingly slowly. It's taking more than an hour to write out a 70MB file to an SSD on a modern MacBook Pro. 'convert' is taking the equivalent of 90% of one core on an 4 (8 hyperthread) core machine.
It takes about 15 minutes to write the first 65MB, and over 2 hours to write the last 5MB.
I think the interesting bits of the code follow-- if there's something else that would be helpful, let me know.
```
def updateAnim(i,cg,scat,mags):
if mags[i]==0: return scat,
cg.convergeStep(mags[i])
scat.set_offsets(cg._chrgs[::2,0:2])
return scat,
fig=plt.figure(figsize=(6,10))
plt.axis('equal')
plt.xlim(-1.2,1.2);plt.ylim(-1,3)
c=np.where(co._chrgs[::2,3]>0,'blue','red')
scat=plt.scatter(co._chrgs[::2,0],co._chrgs[::2,1],s=4,color=c,marker='o',alpha=0.25);
ani=animation.FuncAnimation(fig,updateAnim,frames=mags.size,fargs=(co,scat,mags),blit=True);
ani.save('Files/Capacitance/SpherePlateAnimation.gif',writer='imagemagick',fps=30);
```
Any idea what the bottleneck might be or how I might speed it up? I'd prefer the write out time be small compared to simulation time.
Version: ImageMagick 6.9.0-0 Q16 x86\_64 2015-05-30 <http://www.imagemagick.org>
Copyright: Copyright (C) 1999-2014 ImageMagick Studio LLC
Features: DPC Modules
Delegates (built-in): bzlib cairo djvu fftw fontconfig freetype gslib gvc jbig jng jp2 jpeg lcms lqr ltdl lzma openexr pangocairo png ps rsvg tiff webp wmf x xml zlib
`ps -aef` reports:
convert -size 432x720 -depth 8 -delay 3.3333333333333335 -loop 0 rgba:- Files/Capacitance/SpherePlateAnimation.gif | 2015/06/06 | [
"https://Stackoverflow.com/questions/30688563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2571165/"
] | **Update**
Please read the original answer below before doing anything suggested in this update.
If you want to debug this in some depth, you could separate the ImageMagick part out and identify for sure where the issue is. To do that, I would locate your ImageMagick `convert` program like this:
```
which convert # result may be "/usr/local/bin/convert"
```
and then go to the containing directory, e.g.
```
cd /usr/local/bin
```
Now save the original `convert` program as `convert.real` - you can always change it back again later by reversing the last two parameters below:
```
mv convert convert.real
```
Now, save the following file as `convert`
```
#!/bin/bash
dd bs=128k > $HOME/plot.rgba 2> /dev/null
```
and make that executable by doing
```
chmod +x convert
```
Now, when you run `matplotlib` again, it will execute the script above rather than `ImageMagick`, and the script will save the raw RGBA data in your login directory in a file called `plot.rgba`. This will then tell you two things... firstly you will see if `matplotlib` now runs faster as there is no longer any ImageMagick processing, secondly you will see if the filesize is around 4GB like I am guessing.
Now you can use ImageMagick to process the file *after* `matplotlib` is finished using this, with a 10GB memory limit:
```
convert.real -limit memory 10000000 -size 432x720 -depth 8 -delay 3.33 -loop 0 $HOME/plot.rgba Files/Capacitance/SpherePlateAnimation.gif
```
You could also consider splitting the file into 2 (or 4), using `dd` and processing the two halves in parallel and appending them together to see if that helps. Ask, if you want to investigate that option.
**Original Answer**
I am kind of *speaking out loud* here in the hope that it either helps you directly or it jogs someone else's brain into grasping the problem...
It seems from the commandline you have shared that `matplotlib` is writing directly to the `stdin` of ImageMagick's `convert` tool - I can see that from the `RGBA:-` parameter that tells me it is sending RGB plus Alpha transparency as raw values on `stdin`.
That means that there are no intermediate files that I can suggest placing on a RAM-disk, which is where I was heading to with my comment...
The second thing is that, as the raw pixel data is being sent, every single pixel is computed and sent by `matplotlib` so it is invariant with the 5,000 points in your simulation - so no point reducing or optimising the number of points.
Another thing to note is that you are using the 16-bit quantisation version of ImageMagick (Q16 in your version string). That effectively doubles the memory requirement, so if you can easily recompile ImageMagick for an 8-bit quantum depth, that may help.
Now, let's look at that input stream, `RGBA -depth 8` means 4 bytes per pixel and 432x720 pixels per frame, or 1.2MB per frame. Now, you have 3,000 frames, so that makes 3.6GB minimum, plus the output file of 75MB. I suspect that this is just over the limit of ImageMagick's natural memory limit and that is why it slows down at the end, so my suggestion would be to check the memory limits on ImageMagick and consider increasing them to 4GB-6GB or more if you have it.
To check the memory and other resource limits:
```
identify -list resource
Resource limits:
Width: 214.7MP
Height: 214.7MP
Area: 4.295GP
Memory: 2GiB <---
Map: 4GiB
Disk: unlimited
File: 192
Thread: 1
Throttle: 0
Time: unlimited
```
As you cannot raise the memory limits on the commandline that `matplotlib` executes, you could do it via an environment variable that you export prior to starting `matplotlib` like this:
```
export MAGICK_MEMORY_LIMIT=4294967296
identify -list resource
Resource limits:
Width: 214.7MP
Height: 214.7MP
Area: 4.295GP
Memory: 4GiB <---
Map: 4GiB
Disk: unlimited
File: 192
Thread: 1
Throttle: 0
Time: unlimited
```
You can also change it in your `policy.xml` file, but that is more involved, so please try this way initially and ask if you get stuck!
Please pass feedback on this as I may be able to suggest other things depending on whether this works. Please also run `identify -list configure` and edit your question and paste the output there. | [Mark Setchell's answer](https://stackoverflow.com/a/30704560/4576519) provides a good explanation of what goes wrong, but exporting a higher memory limit did not work. I do actually recommend to change *policy.xml* instead, the only trick part is to find where it is saved on your system. [This answer](https://unix.stackexchange.com/a/329561/112686) lists some locations, but it is most probably at
```
/etc/ImageMagick-6/policy.xml
```
Open it, and edit the line that says
```xml
<policy domain="resource" name="memory" value="256MiB"/>
```
to something like
```xml
<policy domain="resource" name="memory" value="4GiB"/>
```
Or any limit that is above the size of the unprocessed gif. If it is not, the `convert` subprocess will be killed. |
15,645,914 | I have some code which I think should return all parts of a python statement that are not in strings. However, I'm not sure that is as rigorous as I would like. Basically, it just finds the next string delimiter and stays in the "string" state until it is closed by the same delimiter. Is there anything wrong with what I have done for some weird case that I have not thought of? Will it be in any way inconsistent with what python does?
```
# String delimiters in order of precedence
string_delims = ["'''",'"""',"'",'"']
# Get non string parts of a statement
def get_non_string(text):
out = ""
state = None
while True:
# not in string
if state == None:
vals = [text.find(s) for s in string_delims]
# None will only be reached if all are -1 (i.e. no substring)
for val,delim in zip(vals+[None], string_delims+[None]):
if val == None:
out += text
return out
if val >= 0:
i = val
state = delim
break
out += text[:i]
text = text[i+len(delim):]
else:
i = text.find(state)
if i < 0:
raise SyntaxError("Symobolic Subsystem: EOL while scanning string literal")
text = text[i+len(delim)]
state = None
```
Example Input:
```
get_non_string("hello'''everyone'''!' :)'''")
```
Example Output:
```
hello!
``` | 2013/03/26 | [
"https://Stackoverflow.com/questions/15645914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/447860/"
] | Python can tokenize Python code:
```
import tokenize
import token
import io
import collections
class Token(collections.namedtuple('Token', 'num val start end line')):
@property
def name(self):
return token.tok_name[self.num]
def get_non_string(text):
result = []
for tok in tokenize.generate_tokens(io.BytesIO(text).readline):
tok = Token(*tok)
# print(tok.name, tok.val)
if tok.name != 'STRING':
result.append(tok.val)
return ''.join(result)
print(get_non_string("hello'''everyone'''!' :)'''"))
```
yields
```
hello!
```
The heavy lifting is done by [tokenize.generate\_tokens](http://docs.python.org/2/library/tokenize.html#tokenize.generate_tokens). | Your own code has problems with several cases, as you don't seem to be making any provisions for escaped quotes (`"\""`, `"""\""""`, etc).
Also:
```
get_on_string('""')
```
throws an error.
I would not describe that as weird cases. |
57,947,879 | When trying to save a new expense on <http://localhost:8000/admin/budget/expense/add/> I recieve a OperationalError message saying:
no such table: budget\_expense
I think it may be something relating to how my models.py file is set up:
```
from django.utils.text import slugify
# Create your models here.
class Project(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True, blank=True)
budget = models.IntegerField()
def save(self, * args, **kwargs):
self.slug = slugify(self.name)
super(Project, self).save(*args, **kwargs)
class Category(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
class Expense(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
amount = models.DecimalField(max_digits=8, decimal_places=2)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
```
For more context this is what the error message looks like:
```
Request Method: POST
Request URL: http://localhost:8000/admin/budget/expense/add/
Django Version: 2.2.5
Exception Type: OperationalError
Exception Value:
no such table: budget_expense
Exception Location: C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383
Python Executable: C:\Python37\python.exe
Python Version: 3.7.4
Python Path:
['C:\\Users\\kobby\\Documents\\financio',
'C:\\Python37\\python37.zip',
'C:\\Python37\\DLLs',
'C:\\Python37\\lib',
'C:\\Python37',
'C:\\Python37\\lib\\site-packages']
Server time: Sun, 15 Sep 2019 20:00:54 +0000
```
I can connect to Django admin just fine and I've been able to add 'projects' however when I want to add 'expenses' that's when the error comes. Any suggestions as to why this may be? | 2019/09/15 | [
"https://Stackoverflow.com/questions/57947879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12058011/"
] | Whenever your `it` reach the `friendlyName_id.end()` the loop is over (by the loop's condition), and you will never reach this part inside your loop.
```
void returnFriendlyName(int input)
{
std::map<std::string, int>::iterator it;
for (it = friendlyName_id.begin(); it != friendlyName_id.end(); it++) {
if (it->second == input) {
std::cout << '\n' << "The Friendly Name for id:" << input << " is " << it->first << '\n' << '\n';
break;
}
}
if (it == friendlyName_id.end()) std::cout << "Sorry, that id does not exist.";
}
```
One more thing, pay attention that your function's name is `returnFriendlyName` which means to return a value you can continue the work with, and here all you do is to print this (probably important) information. To change this, change the function's signature:
```
void returnFriendlyName(int input)
```
To something like:
```
string returnFriendlyName(int input)
```
And add a return statement (or statements):
```
string returnFriendlyName(int input)
{
std::map<std::string, int>::iterator it;
string result = "not-found";
for (it = friendlyName_id.begin(); it != friendlyName_id.end(); it++) {
if (it->second == input) {
std::cout << '\n' << "The Friendly Name for id:" << input << " is " << it->first << '\n' << '\n';
result = it->first;
break; // return result;
}
}
if (it == friendlyName_id.end()) // Unnecessary condition if you used the return statement instead of the `break` inside the loop, because in this case you won't reach this part of the function if the element exists in the list.
std::cout << "Sorry, that id does not exist.";
return result;
}
``` | >
> Is my understanding of this code incorrect? Am I missing something that is causing the else if to not evaluate?
>
>
>
Yes, it is incorrect. The `else` clause is for the `if`, not for the `for`.
You may be confused by the `else` clauses of other languages, like Python's.
If you add braces, you will see it clearly. This is equivalent:
```
void returnFriendlyName(int input)
{
std::map<std::string, int>::iterator it;
for (it = friendlyName_id.begin(); it != friendlyName_id.end(); it++) {
if (it->second == input)
std::cout << '\n' << "The Friendly Name for id:" << input << " is " << it->first << '\n' << '\n';
else if (it == friendlyName_id.end())
std::cout << "Sorry, that id does not exist.";
}
}
```
The order is:
1. **it** is initialized
2. **it** is tested against the loop condition. If false, quit.
3. The body of the loop runs, which includes the `if` and the `else if`.
4. **it** is incremented
5. Jump back to 2 |
37,210,060 | I need to append a list to a 2D list so that I can edit the added list. I have something like this:
```
n = 3
a = [
['a', 2, 3],
['b', 5, 6],
['c', 8, 9]
]
b = [None for _ in range(n)] # [None] * n
print b
a.append(b)
a[3][0] = 'e'
print a
a.append(b)
a[4][0] = 'f'
print a
```
The result I am getting is:
```
[None, None, None]
[['a', 2, 3], ['b', 5, 6], ['c', 8, 9], ['e', None, None]]
[['a', 2, 3], ['b', 5, 6], ['c', 8, 9], ['f', None, None], ['f', None, None]]
```
The `e` in 4th row changes to `f`, which I don't want. With `[None] * 3` I get same result. How do I prevent this from happening? I checked [how to create a fix size list in python](https://stackoverflow.com/questions/10617045/how-to-create-a-fix-size-list-in-python?lq=1) and [python empty list trick](https://stackoverflow.com/questions/9554572/python-empty-list-trick) but it doesn't work. | 2016/05/13 | [
"https://Stackoverflow.com/questions/37210060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2971708/"
] | `b` is "pointing" to the same python object
You should do this instead to create new copies of `b`:
```
a.append(list(b))
``` | Because your shallow copying the list instead of deep copying it (see: [What is the difference between shallow copy, deepcopy and normal assignment operation?](https://stackoverflow.com/questions/17246693/what-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignment-oper) ).
Instead, you can use inbuilt module `copy` do the following:
```
import copy
# replace a.append(b) with the following
a.append(copy.deepcopy(b))
``` |
27,659,563 | I want to read all the wav files using scipy.io.wavfile module in the subdirectories of my main directory.
```
r_dir='/home/deepthought/Music/genres/'
import os
import scipy.io.wavfile
data = []
rate = []
for root,sub,files in os.walk(r_dir):
files = sorted(files)
for f in files:
s_rate, x = scipy.io.wavfile.read(f)
rate.append(s_rate)
data.append(x)
```
Understandably, this code doesn't work as 'files' only has the file name. That is why I am getting the error-
```
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "/usr/lib/python2.7/dist-packages/scipy/io/wavfile.py", line 151, in read
fid = open(filename, 'rb')
IOError: [Errno 2] No such file or directory: 'hiphop.00000.au.wav'
```
How to I get the complete path for each file?? | 2014/12/26 | [
"https://Stackoverflow.com/questions/27659563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3285138/"
] | check this: <http://developer.android.com/guide/practices/screens_support.html>
create
```
layout-mdpi
layout-hdpi
layout-xhdpi
layout-xxhdpi
layout-xxxhdpi
```
folders for different dpi's. For different sizes, you can use
```
layout-small (for small size phones)
layout-normal (for normal size phones)
layout-large (for 7 inch tablets)
layout-xlarge (for 10 inch tablets)
```
and also use like
```
layout-large-hdpi
layout-large-mdpi
layout-xlarge-hdpi
layout-xlarge-mdpi
```
for nexus S you neet to use layout-normal or layout-hdpi | if you have same layout, you don't need to create multiple layout xml.
you can adjust text-size (or various dimension params) by dimens.xml
example
res/layout/your\_activity.xml
```
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/space_large"
android:textSize="@dimen/text_small"/>
```
res/values/dimens.xml
```
<!-- this is common parameter -->
<dimen name="text_small">12sp</dimen>
<dimen name="space_large">8dp</dimen>
```
res/values-large/dimens.xml
```
<!-- for large-size display -->
<dimen name="text_small">14sp</dimen>
<dimen name="space_large">12dp</dimen>
```
this approach sometimes effective.
if your layout change significantly by display size, you should choose multiple layout-xml style, as @oguzhand says. |
3,224,427 | >
> **Possible Duplicate:**
>
> [Python UnicodeDecodeError - Am I misunderstanding encode?](https://stackoverflow.com/questions/368805/python-unicodedecodeerror-am-i-misunderstanding-encode)
>
>
>
I have a string that I'm trying to make safe for the `unicode()` function:
```
>>> s = " foo “bar bar ” weasel"
>>> s.encode('utf-8', 'ignore')
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
s.encode('utf-8', 'ignore')
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 5: ordinal not in range(128)
>>> unicode(s)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
unicode(s)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 5: ordinal not in range(128)
```
I'm mostly flailing around here. What do I need to do to remove the unsafe characters from the string?
Somewhat related to this [question](https://stackoverflow.com/questions/3224268/python-unicode-encode-error), although I was unable to solve my problem from it.
This also fails:
```
>>> s
' foo \x93bar bar \x94 weasel'
>>> s.decode('utf-8')
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
s.decode('utf-8')
File "C:\Python25\254\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x93 in position 5: unexpected code byte
``` | 2010/07/11 | [
"https://Stackoverflow.com/questions/3224427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147601/"
] | Good question. Encoding issues are tricky. Let's start with **"I have a string."** Strings in Python 2 aren't really "strings," they're byte arrays. So your string, where did it come from and what encoding is it in? Your example shows curly quotes in the literal, and I'm not even sure how you did that. I try to paste it into a Python interpreter, or type it on OS X with Option-[, and it doesn't come through.
Looking at your second example though, you have a character of hex 93. That can't be **UTF-8**, because in UTF-8, any byte higher than 127 is part of a multibyte sequence. So I'm guessing it's supposed to be Latin-1. The problem is, x93 isn't a character in the Latin-1 character set. There's this "invalid" range in Latin-1 from x7f to x9f that's considered illegal. However, Microsoft saw that unused range and decided to put "curly quotes" in there. In doing so they created this similar encoding called "windows-1252", which is like Latin-1 with stuff in that invalid range.
So, let's assume it is **windows-1252**. What now? String.decode converts bytes into Unicode, so that's the one you want. Your second example was on the right track, but it failed because the string wasn't UTF-8. Try:
```
>>> uni = 'foo \x93bar bar\x94 weasel'.decode("windows-1252")
u'foo \u201cbar bar\u201d weasel'
>>> print uni
foo “bar bar” weasel
>>> type(uni)
<type 'unicode'>
```
That's correct, because opening curly quote is Unicode U+201C. Now that you have Unicode, you can serialize it to bytes in any encoding you choose (if you need to pass it across the wire) or just keep it as Unicode if it's staying within Python. If you want to convert to UTF-8, use the oppose function, string.encode.
```
>>> uni.encode("utf-8")
'foo \xe2\x80\x9cbar bar \xe2\x80\x9d weasel'
```
Curly quotes take 3 bytes to encode in UTF-8. You could use UTF-16 and they'd only be two bytes. You can't encode as ASCII or Latin-1 though, because those don't have curly quotes. | **EDIT**. Looks like your string is encoded in such a way that `“` (LEFT DOUBLE QUOTATION MARK) becomes `\x93` and `”` (RIGHT DOUBLE QUOTATION MARK) becomes `\x94`. There is a number of codepages with such a mapping, CP1250 is one of them, so you may use this:
```
s = s.decode('cp1250')
```
For all the codepages which map `“` to `\x93` see [here](http://www.fileformat.info/info/unicode/char/201c/codepage_support.htm) (all of them also map `”` to `\x94`, which can be verified [here](http://www.fileformat.info/info/unicode/char/201d/codepage_support.htm)). |
5,370,685 | I have a table in a MySQL Database which has this structure:
```
CREATE TABLE `papers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(1000) COLLATE utf8_bin DEFAULT NULL,
`booktitle` varchar(300) COLLATE utf8_bin DEFAULT NULL,
`journal` varchar(300) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `title_fulltext` (`title`),
FULLTEXT KEY `booktitle_fulltext` (`booktitle`),
FULLTEXT KEY `journal_fulltext` (`journal`)
) ENGINE=MyISAM AUTO_INCREMENT=1601769 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
```
Now I know that in the column title, somewhere within the millions of rows, there is a row which contains the string
```
nFOIL: Integrating Naïve Bayes and FOIL.
```
I want to look for
```
my_string = "nFOIL: integrating Naïve Bayes and FOIL"
```
and find the right row. You see it has to be a case insensitive search and the dot at the end is missing in the query. How do I implement this?
I tried
```
SELECT id FROM papers WHERE UPPER(title) LIKE %s
```
and converted my\_string to upper case in python and put a "%" at the end of my\_string but this doesn't seam a good way of handling this. It did not work too. =)
Thanks for any suggestions! | 2011/03/20 | [
"https://Stackoverflow.com/questions/5370685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641514/"
] | I see you have added FULLTEXT indexes, I though you already knew about MATCH AGAINST syntax of MySQL.
You should try
```
SELECT id FROM papers
WHERE MATCH (title,booktitle,journal) AGAINST ('nFOIL: integrating Naïve Bayes and FOIL' IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION);
``` | Change your collate in utf8\_general\_ci.
In this way your searches will be case insensitive. |
40,762,692 | As I need to proceed many pdfs with different styles, I have an assumptions that the main content will be under the most appeared/common span style.
Is there a way to find the most appeared span style in beautifulsoup python?
This is a command I used to find a specific span style:
```
font-family: CBCDEE+ArialMT;
font-size:12px':
spans = soup.find_all('span',
attrs={'style': 'font-family: CBCDEE+ArialMT; font-size:12px'})`
```
Any ways to find the most appeared/common one? or basically, is there a way to have the span style list and count the appearance of different styles?
Many thanks. | 2016/11/23 | [
"https://Stackoverflow.com/questions/40762692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2546957/"
] | Use a loop to go through the other columns, then divide:
```
awk '{ val = 1; for (i = 2; i <= NF; ++i) val *= $i; print $1 / val }' file
```
Or just do successive divisions, again with a loop:
```
awk '{ for (i = 2; i <= NF; ++i) $1 /= $i; print $1 }' file
```
It's up to you how you want to treat the presence of a `0` in any column - you can add an `if` before performing the division if you like. | With `perl`
```
$ cat ip.txt
0.002 0.2 0.2 0.6
0.03 0.3 0.7
0.004 0.1 0.2 0.005 0.3 0.005
$ perl -lane '$a=$F[0]; $a /= $_ foreach (@F[1..$#F]); print $a' ip.txt
0.0833333333333333
0.142857142857143
26666.6666666667
```
Limiting decimal points:
```
$ perl -lane '$a=$F[0]; $a /= $_ foreach (@F[1..$#F]); printf "%.3f\n", $a' ip.txt
0.083
0.143
26666.667
```
See [Perl flags -pe, -pi, -p, -w, -d, -i, -t?](https://stackoverflow.com/questions/6302025/perl-flags-pe-pi-p-w-d-i-t) for explanation on `perl` command line options |
63,329,657 | I'm trying to restore a pickled config file from RLLib ([json didn't work as shown in this post](https://stackoverflow.com/questions/62908522/error-callbacks-must-be-a-callable-method-that-returns-a-subclass-of-defaultc)), and getting the following error:
```
config = pickle.load(open(f"{path}/params.pkl", "rb"))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-c964561b863c> in <module>
----> 1 config = pickle.load(open(f"{path}/params.pkl", "rb"))
ValueError: unsupported pickle protocol: 5
```
Python Version = 3.7.0
How can I open this file in 3.7? | 2020/08/09 | [
"https://Stackoverflow.com/questions/63329657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183877/"
] | Use [pickle5](https://pypi.org/project/pickle5/) or load it into python 3.8+ and then serialize it to a lower version of it using the protocol parameter. | In the event that you cannot load pickle5 because of its dependencies (mainly Visual Building c++), another solution could be that you change the Python interpreter you're using (to the old one, before the error occured). For me, I was getting this error after I ran a program in IDLE that I had been running in Spyder. When I ran it again within Spyder, it dropped this error.
```
Python Error: Unsupported Pickle Protocol 5
```
To resolve this, within Spyder I changed my Python interpreter to the Python I was using with IDLE (Tools -> Preferences). Once I rebooted Spyder, I had to install the necessary dependencies with command prompt so that within Spyder the console could be used:
```
pip install spyder-kernels
```
Naturally, this may introduce some irregularities within Spyder (namely, packages it's supposed to come with are no longer there because of the different interpreter). These should easily be sussed out when debugging, and resolved using standard pip installs.
Once you recover your (thought to be lost) files, it might be wise to think about reverting back to Spyder's Python interpreter, and updating code to elegantly handle this problem (I would love if somebody could suggest in comments how to do this that didn't require pickle5!) |
63,329,657 | I'm trying to restore a pickled config file from RLLib ([json didn't work as shown in this post](https://stackoverflow.com/questions/62908522/error-callbacks-must-be-a-callable-method-that-returns-a-subclass-of-defaultc)), and getting the following error:
```
config = pickle.load(open(f"{path}/params.pkl", "rb"))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-c964561b863c> in <module>
----> 1 config = pickle.load(open(f"{path}/params.pkl", "rb"))
ValueError: unsupported pickle protocol: 5
```
Python Version = 3.7.0
How can I open this file in 3.7? | 2020/08/09 | [
"https://Stackoverflow.com/questions/63329657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183877/"
] | Use [pickle5](https://pypi.org/project/pickle5/) or load it into python 3.8+ and then serialize it to a lower version of it using the protocol parameter. | If this error is due to **heroku deployment** then check your python version of local setup and heroku setup.
If both are different then it might lead you to this error.
Solution:
* Create a runtime.txt file in your application's base directory
Then inside your runtime.txt mention your local python version so that there are no conflicts.
```
python-3.9.2
``` |
63,329,657 | I'm trying to restore a pickled config file from RLLib ([json didn't work as shown in this post](https://stackoverflow.com/questions/62908522/error-callbacks-must-be-a-callable-method-that-returns-a-subclass-of-defaultc)), and getting the following error:
```
config = pickle.load(open(f"{path}/params.pkl", "rb"))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-c964561b863c> in <module>
----> 1 config = pickle.load(open(f"{path}/params.pkl", "rb"))
ValueError: unsupported pickle protocol: 5
```
Python Version = 3.7.0
How can I open this file in 3.7? | 2020/08/09 | [
"https://Stackoverflow.com/questions/63329657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183877/"
] | For pandas users who saved a dataframe to a pickle file with protocol 5 in python 3.8 and need to load it into python 3.6 which only supports protocol 4 (I'm looking at you **google colab**):
```
!pip3 install pickle5
import pickle5 as pickle
with open(path_to_protocol5, "rb") as fh:
data = pickle.load(fh)
```
Could also save into a protocol-4 pickle from python 3.6
```
data.to_pickle(path_to_protocol4)
```
Update: If facing this when loading a model from stable-baselines3:
```
!pip install --upgrade --quiet cloudpickle pickle5
from stable_baselines3 import PPO
# restart kernel if in jupyter notebook
# Might not need this dict in all cases
custom_objects = {
"lr_schedule": lambda x: .003,
"clip_range": lambda x: .02
}
model = PPO.load("path/to/model.zip", custom_objects=custom_objects)
```
Tested on 2021-05-31 with env:
```
cloudpickle: 1.6.0
pickle5: 0.0.11
stable-baselines3: 1.0
```
Reference: <https://brainsteam.co.uk/2021/01/14/pickle-5-madness-with-mlflow/> | In the event that you cannot load pickle5 because of its dependencies (mainly Visual Building c++), another solution could be that you change the Python interpreter you're using (to the old one, before the error occured). For me, I was getting this error after I ran a program in IDLE that I had been running in Spyder. When I ran it again within Spyder, it dropped this error.
```
Python Error: Unsupported Pickle Protocol 5
```
To resolve this, within Spyder I changed my Python interpreter to the Python I was using with IDLE (Tools -> Preferences). Once I rebooted Spyder, I had to install the necessary dependencies with command prompt so that within Spyder the console could be used:
```
pip install spyder-kernels
```
Naturally, this may introduce some irregularities within Spyder (namely, packages it's supposed to come with are no longer there because of the different interpreter). These should easily be sussed out when debugging, and resolved using standard pip installs.
Once you recover your (thought to be lost) files, it might be wise to think about reverting back to Spyder's Python interpreter, and updating code to elegantly handle this problem (I would love if somebody could suggest in comments how to do this that didn't require pickle5!) |
63,329,657 | I'm trying to restore a pickled config file from RLLib ([json didn't work as shown in this post](https://stackoverflow.com/questions/62908522/error-callbacks-must-be-a-callable-method-that-returns-a-subclass-of-defaultc)), and getting the following error:
```
config = pickle.load(open(f"{path}/params.pkl", "rb"))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-c964561b863c> in <module>
----> 1 config = pickle.load(open(f"{path}/params.pkl", "rb"))
ValueError: unsupported pickle protocol: 5
```
Python Version = 3.7.0
How can I open this file in 3.7? | 2020/08/09 | [
"https://Stackoverflow.com/questions/63329657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4183877/"
] | For pandas users who saved a dataframe to a pickle file with protocol 5 in python 3.8 and need to load it into python 3.6 which only supports protocol 4 (I'm looking at you **google colab**):
```
!pip3 install pickle5
import pickle5 as pickle
with open(path_to_protocol5, "rb") as fh:
data = pickle.load(fh)
```
Could also save into a protocol-4 pickle from python 3.6
```
data.to_pickle(path_to_protocol4)
```
Update: If facing this when loading a model from stable-baselines3:
```
!pip install --upgrade --quiet cloudpickle pickle5
from stable_baselines3 import PPO
# restart kernel if in jupyter notebook
# Might not need this dict in all cases
custom_objects = {
"lr_schedule": lambda x: .003,
"clip_range": lambda x: .02
}
model = PPO.load("path/to/model.zip", custom_objects=custom_objects)
```
Tested on 2021-05-31 with env:
```
cloudpickle: 1.6.0
pickle5: 0.0.11
stable-baselines3: 1.0
```
Reference: <https://brainsteam.co.uk/2021/01/14/pickle-5-madness-with-mlflow/> | If this error is due to **heroku deployment** then check your python version of local setup and heroku setup.
If both are different then it might lead you to this error.
Solution:
* Create a runtime.txt file in your application's base directory
Then inside your runtime.txt mention your local python version so that there are no conflicts.
```
python-3.9.2
``` |
13,797,029 | I am new to Git.I want to clone my remote github repository (git://github.com/eltejaee/BIC2.git) with python script.I know that "dulwich" and "gitpython" are suitable but I couldn't clone or pull with them .What is the best python code to clone my remote github repository? | 2012/12/10 | [
"https://Stackoverflow.com/questions/13797029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1445741/"
] | There are several modules you can use [git-python](https://gitorious.org/git-python) or [pygit](https://gitorious.org/pygit/mainline)
If you just want to clone/pull then you can use system commands:
```
os.system("git clone ...")
os.system("git pull")
```
and if you want the output of the command as well I recommend you to use [subprocesses](http://docs.python.org/2/library/subprocess.html)
For Github you can use [python-github](https://github.com/jmoiron/python-github) | There is a python wrapper for github
<https://github.com/jmoiron/python-github> |
13,797,029 | I am new to Git.I want to clone my remote github repository (git://github.com/eltejaee/BIC2.git) with python script.I know that "dulwich" and "gitpython" are suitable but I couldn't clone or pull with them .What is the best python code to clone my remote github repository? | 2012/12/10 | [
"https://Stackoverflow.com/questions/13797029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1445741/"
] | There are several modules you can use [git-python](https://gitorious.org/git-python) or [pygit](https://gitorious.org/pygit/mainline)
If you just want to clone/pull then you can use system commands:
```
os.system("git clone ...")
os.system("git pull")
```
and if you want the output of the command as well I recommend you to use [subprocesses](http://docs.python.org/2/library/subprocess.html)
For Github you can use [python-github](https://github.com/jmoiron/python-github) | My solution is very simple and straight forward. It doesn't even need the manual entry of paraphrase/password.
Here is my complete code:
```
import os
import sys
path = "/path/to/store/your/cloned/project"
clone = "git://github.com/eltejaee/BIC2.git"
os.system("sshpass -p your_password ssh user_name@your_lhost")
os.chdir(path) # Specifying the path where the cloned project has to be copied
os.system(clone) # Cloning
print "\n CLONED SUCCESSFULLY.! \n"
``` |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | I was trying to do the Windows-based install and kept getting this error.
It turns out you **have to** have Python 3.5.2. Not 2.7, not 3.6.x-- nothing other than 3.5.2.
After installing Python 3.5.2, the `pip install` worked. | I was trying to install CPU TensorFlow on [Ubuntu 18.04](https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_18.04_LTS_.28Bionic_Beaver.29) (Bionic Beaver), and the best way (for me...) I found for it was using it on top of Conda, for that:
1. To create a Conda ‘tensorflow’ environment. Follow *[How to Install Anaconda on Ubuntu 18.04](https://linuxize.com/post/how-to-install-anaconda-on-ubuntu-18-04/)*
2. After all is installed, see *[Getting started with conda](https://conda.io/projects/conda/en/latest/user-guide/getting-started.html)*. And use it according to *[Managing environments](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#managing-environments)*
3. `conda create --name tensorflow`
4. `source activate tenso`rflow
5. `pip install --upgrade pip`
6. `pip uninstall tensorflow`
7. For CPU: `pip install tensorflow-cpu`, for GPU: `pip install tensorflow`
8. `pip install --ignore-installed --upgrade tensorflow`
9. Test TF E.g. on 'Where' with:
>
> python
>
>
>
```
import tensorflow as tf
>>> tf.where([[True, False], [False, True]])
```
Expected result:
```
<tf.Tensor: shape=(2, 2), dtype=int64, numpy=
array([[0, 0],
[1, 1]])>
```
* After the Conda upgrade, I got:
```none
DeprecationWarning: 'source deactivate' is deprecated. Use 'conda deactivate'.
```
So you should use:
```
‘conda activate tensorflow’ / ‘conda deactivate’
``` |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | For Windows 10 64 bit:
I have tried all the suggestions here, but finally I got it running as follows:
1. Uninstall all current versions of Python
2. Remove all Python references in the PATH system and user environment variables
3. Download the latest 64-bit version of Python 3.8: Python 3.8.7 currently, *not* the latest 3.9.x version which is the one I was using, and *not* 32 bit.
4. Install with all options selected, including pip, and including the PATH environment variable
5. `pip install tensorflow` (in an administrator CMD prompt)
6. Upgrade pip if prompted (optional) | I was trying to install from source and got that error. (Why would a wheel built on this machine not be compatible with it?)
For me, the tag `--ignore-installed` made all the difference.
```none
pip install --ignore-installed /tmp/tensorflow_pkg/tensorflow-1.8.0-cp36-cp36m-linux_x86_64.whl
```
worked, while
```none
pip install /tmp/tensorflow_pkg/tensorflow-1.8.0-cp36-cp36m-linux_x86_64.whl
```
threw the abovementioned error.
Context: [Conda](https://en.wikipedia.org/wiki/Conda_(package_manager)) environment; it might have been a problem specific to this |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | It seems that TensorFlow only works on Python 3.5 at the moment. Try to run this command before running the **pip install**
```none
conda create --name tensorflow python=3.5
```
After this, run the following lines:
For **CPU**:
```none
pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.1.0-cp35-cp35m-win_amd64.whl
```
For **GPU**:
```none
pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl
```
It should work like a charm. | For Windows 10 64 bit:
I have tried all the suggestions here, but finally I got it running as follows:
1. Uninstall all current versions of Python
2. Remove all Python references in the PATH system and user environment variables
3. Download the latest 64-bit version of Python 3.8: Python 3.8.7 currently, *not* the latest 3.9.x version which is the one I was using, and *not* 32 bit.
4. Install with all options selected, including pip, and including the PATH environment variable
5. `pip install tensorflow` (in an administrator CMD prompt)
6. Upgrade pip if prompted (optional) |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | Make sure that the wheel is, well, supported by your platform. Pip uses the wheel's filename to determine compatibility. The format is:
```
tensorflow-{version}-{python version}-none-{your platform}.whl
```
I didn't realize that `x86_64` refers to x64, I thought it meant *either* x86 or x64, so I banged my head against this futilely for some time. TensorFlow is not available for 32-bit systems, unless you want to compile it yourself. | Actually, you can use Python 3.5.\*.
I successfully solved this problem with Python 3.5.3. Modify the Python version to 3.5.\* in [Conda](https://en.wikipedia.org/wiki/Conda_(package_manager)). See *[Managing Python](https://conda.io/docs/py2or3.html)*.
Then go to <https://www.tensorflow.org/install/install_windows>, and repeat from "Create a Conda environment named *tensorflow* by invoking the following command" bla, bla... |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | It seems that TensorFlow only works on Python 3.5 at the moment. Try to run this command before running the **pip install**
```none
conda create --name tensorflow python=3.5
```
After this, run the following lines:
For **CPU**:
```none
pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.1.0-cp35-cp35m-win_amd64.whl
```
For **GPU**:
```none
pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl
```
It should work like a charm. | I faced the same issue and tried all the solutions that folks suggested here and other links (like *[Platform not supported for TensorFlow on Ubuntu 14.04.2](https://askubuntu.com/questions/695981/platform-not-supported-for-tensorflow-on-ubuntu-14-04-2)*).
It was so frustrating because using `print(wheel.pep425tags.get_supported())` I could see that my [Ubuntu](https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29) supported ('cp37', 'cp37m', 'linux\_x86\_64') and that was exactly what I was trying to install (from <https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.14.0-cp37-cp37m-linux_x86_64.whl>).
What at the end fixed it was to simply download the package first and then
```none
pip install tensorflow-1.14.0-cp37-cp37m-linux_x86_64.whl
``` |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | Make sure that the wheel is, well, supported by your platform. Pip uses the wheel's filename to determine compatibility. The format is:
```
tensorflow-{version}-{python version}-none-{your platform}.whl
```
I didn't realize that `x86_64` refers to x64, I thought it meant *either* x86 or x64, so I banged my head against this futilely for some time. TensorFlow is not available for 32-bit systems, unless you want to compile it yourself. | I was trying to install from source and got that error. (Why would a wheel built on this machine not be compatible with it?)
For me, the tag `--ignore-installed` made all the difference.
```none
pip install --ignore-installed /tmp/tensorflow_pkg/tensorflow-1.8.0-cp36-cp36m-linux_x86_64.whl
```
worked, while
```none
pip install /tmp/tensorflow_pkg/tensorflow-1.8.0-cp36-cp36m-linux_x86_64.whl
```
threw the abovementioned error.
Context: [Conda](https://en.wikipedia.org/wiki/Conda_(package_manager)) environment; it might have been a problem specific to this |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | The pip wheel file contains the Python version in its name (cp34-cp34m). If you download the .whl file and rename it to say **py3-none** or instead, it should work. Can you try that?
The installation won't work for [Anaconda](https://en.wikipedia.org/wiki/Anaconda_(Python_distribution)) users that choose Python 3 support, because the installation procedure is asking to create a Python 3.5 environment and the file is currently called *cp34-cp34m*. So renaming it would do the job for now.
```
sudo pip3 install --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.7.0-cp34-cp34m-linux_x86_64.whl
```
This will produce the exact error message you got above. However, when you will download the file yourself and rename it to "tensorflow-0.7.0-py3-none-linux\_x86\_64.whl", then execute the command again with the changed filename, it should work fine. | Maybe you are installing the wrong pre-build binary?
Check on <https://github.com/lakshayg/tensorflow-build>
For my [Coffee Lake](https://en.wikipedia.org/wiki/Coffee_Lake) processor on [Ubuntu 18.04](https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_18.04_LTS_.28Bionic_Beaver.29) (Bionic Beaver) the download URL was:
<https://github.com/lakshayg/tensorflow-build/releases/download/tf1.12.0-ubuntu18.04-py2-py3/tensorflow-1.12.0-cp36-cp36m-linux_x86_64.whl>
```
pip install --ignore-installed --upgrade <PATH>
```
resolved the issue for me. |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | I too got the same problem.
I downloaded `get-pip.py` from *<https://bootstrap.pypa.io/get-pip.py>* and then ran `python2.7 get-pip.py` for installing `pip2.7`.
And then ran the `pip install` command with `python2.7` as follows.
**For Ubuntu/Linux:**
```none
python2.7 -m pip install https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl
```
**For Mac OS X:**
```none
python2.7 -m pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
```
This should work just fine as it did for me :)
I followed these instructions from [here](https://askubuntu.com/questions/695981/platform-not-supported-for-tensorflow-on-ubuntu-14-04-2). | I was trying to install from source and got that error. (Why would a wheel built on this machine not be compatible with it?)
For me, the tag `--ignore-installed` made all the difference.
```none
pip install --ignore-installed /tmp/tensorflow_pkg/tensorflow-1.8.0-cp36-cp36m-linux_x86_64.whl
```
worked, while
```none
pip install /tmp/tensorflow_pkg/tensorflow-1.8.0-cp36-cp36m-linux_x86_64.whl
```
threw the abovementioned error.
Context: [Conda](https://en.wikipedia.org/wiki/Conda_(package_manager)) environment; it might have been a problem specific to this |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | Actually, you can use Python 3.5.\*.
I successfully solved this problem with Python 3.5.3. Modify the Python version to 3.5.\* in [Conda](https://en.wikipedia.org/wiki/Conda_(package_manager)). See *[Managing Python](https://conda.io/docs/py2or3.html)*.
Then go to <https://www.tensorflow.org/install/install_windows>, and repeat from "Create a Conda environment named *tensorflow* by invoking the following command" bla, bla... | I was trying to install CPU TensorFlow on [Ubuntu 18.04](https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_18.04_LTS_.28Bionic_Beaver.29) (Bionic Beaver), and the best way (for me...) I found for it was using it on top of Conda, for that:
1. To create a Conda ‘tensorflow’ environment. Follow *[How to Install Anaconda on Ubuntu 18.04](https://linuxize.com/post/how-to-install-anaconda-on-ubuntu-18-04/)*
2. After all is installed, see *[Getting started with conda](https://conda.io/projects/conda/en/latest/user-guide/getting-started.html)*. And use it according to *[Managing environments](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#managing-environments)*
3. `conda create --name tensorflow`
4. `source activate tenso`rflow
5. `pip install --upgrade pip`
6. `pip uninstall tensorflow`
7. For CPU: `pip install tensorflow-cpu`, for GPU: `pip install tensorflow`
8. `pip install --ignore-installed --upgrade tensorflow`
9. Test TF E.g. on 'Where' with:
>
> python
>
>
>
```
import tensorflow as tf
>>> tf.where([[True, False], [False, True]])
```
Expected result:
```
<tf.Tensor: shape=(2, 2), dtype=int64, numpy=
array([[0, 0],
[1, 1]])>
```
* After the Conda upgrade, I got:
```none
DeprecationWarning: 'source deactivate' is deprecated. Use 'conda deactivate'.
```
So you should use:
```
‘conda activate tensorflow’ / ‘conda deactivate’
``` |
33,622,613 | when I try to install TensorFlow by cloning from Git, I run into the error "no module named copyreg," so I tried installing using a [virtualenv](http://pypi.python.org/pypi/virtualenv). However, I then run into this error:
```none
pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl
tensorflow-0.5.0-py2-none-any.whl is not a supported wheel on this platform.
```
I don't see this under the common problems section.
I am using [OS X v10.10.5](https://en.wikipedia.org/wiki/OS_X_Yosemite) (Yosemite) and Python 3.4.3, but I also have Python 2.7 (I am unsure if pip differentiates between these or how to switch between them). | 2015/11/10 | [
"https://Stackoverflow.com/questions/33622613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775886/"
] | I was trying to do the Windows-based install and kept getting this error.
It turns out you **have to** have Python 3.5.2. Not 2.7, not 3.6.x-- nothing other than 3.5.2.
After installing Python 3.5.2, the `pip install` worked. | Maybe you are installing the wrong pre-build binary?
Check on <https://github.com/lakshayg/tensorflow-build>
For my [Coffee Lake](https://en.wikipedia.org/wiki/Coffee_Lake) processor on [Ubuntu 18.04](https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_18.04_LTS_.28Bionic_Beaver.29) (Bionic Beaver) the download URL was:
<https://github.com/lakshayg/tensorflow-build/releases/download/tf1.12.0-ubuntu18.04-py2-py3/tensorflow-1.12.0-cp36-cp36m-linux_x86_64.whl>
```
pip install --ignore-installed --upgrade <PATH>
```
resolved the issue for me. |
51,138,734 | I'm getting stuck when trying to test a router by calling from Postman
```
@http.route('/nails/login', type='json', auth="public")
def api_login(self, csrf=False, **kwargs):
```
and calling in postman with header application/json
```
http://127.0.0.1:8070/nails/login
```
but log always return
```
2018-07-02 14:30:38,123 26497 ERROR ? odoo.http: Exception during JSON request handling.
Traceback (most recent call last):
File "/home/ryu/odoo/odoo-server/odoo/http.py", line 640, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/ryu/odoo/odoo-server/odoo/http.py", line 1453, in _dispatch_nodb
func, arguments = self.nodb_routing_map.bind_to_environ(request.httprequest.environ).match()
File "/usr/local/lib/python2.7/dist-packages/werkzeug/routing.py", line 1573, in match
raise NotFound()
NotFound: 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
2018-07-02 14:30:38,128 26497 INFO ? werkzeug: 127.0.0.1 - - [02/Jul/2018 14:30:38] "POST /nails/login HTTP/1.1" 200 -
``` | 2018/07/02 | [
"https://Stackoverflow.com/questions/51138734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4867974/"
] | Before calling any API, you have to login using `/web/session/authenticate` using post request. The reason for the above error is odoo is not able to find session information, therefore unable to find which database to login.
Sample request type:
```json
{
"params": {
"login": "admin",
"password": "admin",
"db": "odoo10"
}
}
``` | Finally I resolved it by adding this in configuration file, ever try but not sure why it's not working before that..
```
[options]
dbfilter = my_db_name
``` |
7,709,554 | These two are equivalent:
```
let f(x) =
10
let g = fun(x) ->
10
```
I think? They seem to do the same thing, but are there any cases where the behavior of the two would vary? I find the second version useful (even if more verbose) because you can use the `<|` and `<<` operators to implement python-style decorator patterns; is there any case where I *have* to use the first version?
Furthermore, I fully understand how the second one works (the stuff on the right is just a function expression, which I dump into g) but how about the first one? Is there some compiler trick or special case that converts that syntax from a simple assignment statement into a function definition? | 2011/10/10 | [
"https://Stackoverflow.com/questions/7709554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871202/"
] | As Brian already answered, the two are equivalent. Returning `fun` instead of declaring function using `let` makes difference if you want to do something (i.e. some initialization) before returning the function.
For example, if you wanted to create function that adds random number, you could write:
```
let f1 x =
let rnd = new System.Random()
x + rnd.Next()
let f2 =
let rnd = new System.Random()
fun y -> y + rnd.Next()
```
Here, the function `f1` creates new `Random` instance every time it is executed, but `f2` uses the same instance of `rnd` all the time (so `f2` is better way of writing this). But if you return `fun` immediately, then the F# compiler optimizes the code and the two cases are the same. | They are equivalent (modulo the 'value restriction', which allows functions, but not values, to be generic, see e.g. [here](https://stackoverflow.com/questions/1131456/understanding-f-value-restriction-errors)). |
71,143,133 | I have been trying to solve this for quite a while without success.
I have not found (I searched though) theory that could help me on wikipedia.
Here is the problem.
I have a group of n players (more than 7)
I have a game (diplomacy for those who know !) that requires 7 players, one for these roles : E,F,G,I,A,R and T (countries in fact)
I want to set up a tournament (many games).
There will be n games.
(\*) Every player gets into 7 different games, with different role each time
(\*\*) Every game gets 7 different players
=> That is very easy to do.
However, when things get tough, is when you want to limit interactions between players.
What I want is any player to interact (interact = play in same game) at *most* with one other player.
(In other words, I want to prevent players from making such deals : "I help you in game A, you help me in game B")
So:
Question 1 : For which n is this possible ? (obviously at least 50)
Question 2 : When it is possible, how do you do it ?
Question 3 : What is the algo to minimize these interactions when it is not possible ?
For the record, I did implement a try-and-error program in python (using recursion), working quite well, but I never can get maximum intearctions between players limited to 1 (endless calculations)
thanks for any help !
PS This is no homework, it is for actually designing game tournaments :-) | 2022/02/16 | [
"https://Stackoverflow.com/questions/71143133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741820/"
] | The below query should work
```
select u.*
from users u
where u.id not in (select userId from user_project where projectId = 1)
``` | use not exists
```
select u.* from users u
where not exists ( select 1 from user_project up
where up.userid= u.id and up.projectid=1)
``` |
71,143,133 | I have been trying to solve this for quite a while without success.
I have not found (I searched though) theory that could help me on wikipedia.
Here is the problem.
I have a group of n players (more than 7)
I have a game (diplomacy for those who know !) that requires 7 players, one for these roles : E,F,G,I,A,R and T (countries in fact)
I want to set up a tournament (many games).
There will be n games.
(\*) Every player gets into 7 different games, with different role each time
(\*\*) Every game gets 7 different players
=> That is very easy to do.
However, when things get tough, is when you want to limit interactions between players.
What I want is any player to interact (interact = play in same game) at *most* with one other player.
(In other words, I want to prevent players from making such deals : "I help you in game A, you help me in game B")
So:
Question 1 : For which n is this possible ? (obviously at least 50)
Question 2 : When it is possible, how do you do it ?
Question 3 : What is the algo to minimize these interactions when it is not possible ?
For the record, I did implement a try-and-error program in python (using recursion), working quite well, but I never can get maximum intearctions between players limited to 1 (endless calculations)
thanks for any help !
PS This is no homework, it is for actually designing game tournaments :-) | 2022/02/16 | [
"https://Stackoverflow.com/questions/71143133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741820/"
] | use not exists
```
select u.* from users u
where not exists ( select 1 from user_project up
where up.userid= u.id and up.projectid=1)
``` | ```
SELECT u.id, u.username
FROM testdb.user_project up
LEFT JOIN testdb.users u
ON up.userId = u.id
WHERE up.projectId <> 1;
``` |
71,143,133 | I have been trying to solve this for quite a while without success.
I have not found (I searched though) theory that could help me on wikipedia.
Here is the problem.
I have a group of n players (more than 7)
I have a game (diplomacy for those who know !) that requires 7 players, one for these roles : E,F,G,I,A,R and T (countries in fact)
I want to set up a tournament (many games).
There will be n games.
(\*) Every player gets into 7 different games, with different role each time
(\*\*) Every game gets 7 different players
=> That is very easy to do.
However, when things get tough, is when you want to limit interactions between players.
What I want is any player to interact (interact = play in same game) at *most* with one other player.
(In other words, I want to prevent players from making such deals : "I help you in game A, you help me in game B")
So:
Question 1 : For which n is this possible ? (obviously at least 50)
Question 2 : When it is possible, how do you do it ?
Question 3 : What is the algo to minimize these interactions when it is not possible ?
For the record, I did implement a try-and-error program in python (using recursion), working quite well, but I never can get maximum intearctions between players limited to 1 (endless calculations)
thanks for any help !
PS This is no homework, it is for actually designing game tournaments :-) | 2022/02/16 | [
"https://Stackoverflow.com/questions/71143133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741820/"
] | The below query should work
```
select u.*
from users u
where u.id not in (select userId from user_project where projectId = 1)
``` | ```
SELECT u.id, u.username
FROM testdb.user_project up
LEFT JOIN testdb.users u
ON up.userId = u.id
WHERE up.projectId <> 1;
``` |
71,143,133 | I have been trying to solve this for quite a while without success.
I have not found (I searched though) theory that could help me on wikipedia.
Here is the problem.
I have a group of n players (more than 7)
I have a game (diplomacy for those who know !) that requires 7 players, one for these roles : E,F,G,I,A,R and T (countries in fact)
I want to set up a tournament (many games).
There will be n games.
(\*) Every player gets into 7 different games, with different role each time
(\*\*) Every game gets 7 different players
=> That is very easy to do.
However, when things get tough, is when you want to limit interactions between players.
What I want is any player to interact (interact = play in same game) at *most* with one other player.
(In other words, I want to prevent players from making such deals : "I help you in game A, you help me in game B")
So:
Question 1 : For which n is this possible ? (obviously at least 50)
Question 2 : When it is possible, how do you do it ?
Question 3 : What is the algo to minimize these interactions when it is not possible ?
For the record, I did implement a try-and-error program in python (using recursion), working quite well, but I never can get maximum intearctions between players limited to 1 (endless calculations)
thanks for any help !
PS This is no homework, it is for actually designing game tournaments :-) | 2022/02/16 | [
"https://Stackoverflow.com/questions/71143133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741820/"
] | The below query should work
```
select u.*
from users u
where u.id not in (select userId from user_project where projectId = 1)
``` | Basically you want the users that are not associated with Project 1 in the relation table. You can do that using "where not exists".
The solution is better, cause exists removes the need to take care of duplicate values, cause one single occurrence is enough to match (or not match) the definition.
```
select
u.id
, u.username
from users u
where not exists (
select
1
from user_project up
where 1=1
and up.projectID = 1
and up.userId = u.id
)
``` |
71,143,133 | I have been trying to solve this for quite a while without success.
I have not found (I searched though) theory that could help me on wikipedia.
Here is the problem.
I have a group of n players (more than 7)
I have a game (diplomacy for those who know !) that requires 7 players, one for these roles : E,F,G,I,A,R and T (countries in fact)
I want to set up a tournament (many games).
There will be n games.
(\*) Every player gets into 7 different games, with different role each time
(\*\*) Every game gets 7 different players
=> That is very easy to do.
However, when things get tough, is when you want to limit interactions between players.
What I want is any player to interact (interact = play in same game) at *most* with one other player.
(In other words, I want to prevent players from making such deals : "I help you in game A, you help me in game B")
So:
Question 1 : For which n is this possible ? (obviously at least 50)
Question 2 : When it is possible, how do you do it ?
Question 3 : What is the algo to minimize these interactions when it is not possible ?
For the record, I did implement a try-and-error program in python (using recursion), working quite well, but I never can get maximum intearctions between players limited to 1 (endless calculations)
thanks for any help !
PS This is no homework, it is for actually designing game tournaments :-) | 2022/02/16 | [
"https://Stackoverflow.com/questions/71143133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741820/"
] | Basically you want the users that are not associated with Project 1 in the relation table. You can do that using "where not exists".
The solution is better, cause exists removes the need to take care of duplicate values, cause one single occurrence is enough to match (or not match) the definition.
```
select
u.id
, u.username
from users u
where not exists (
select
1
from user_project up
where 1=1
and up.projectID = 1
and up.userId = u.id
)
``` | ```
SELECT u.id, u.username
FROM testdb.user_project up
LEFT JOIN testdb.users u
ON up.userId = u.id
WHERE up.projectId <> 1;
``` |
7,005,732 | I'm writing a calculator in Python (as an exercise), and there's one bit that I'm wondering about.
The program splits up the input into a list of numbers and operators. The result is then computed thusly:
```
import operator
ops = {'+' : operator.add, # operators and corresponding functions
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv,
'%' : operator.mod}
precedence = [['*', '/', '%'], ['+', '-']] # order of precedence for operators
def evaluate(exp):
for oplist in precedence: # search for operators first in order of precedence
for op in exp: # then from left to right
if op in oplist:
index = exp.index(op)
result = ops[op](exp[index - 1], exp[index + 1])
# compute the result of the operation
exp[index - 1:index + 2] = [result]
# replace operation and operands with result
return exp[0]
# for example,
evaluate([2, '+', 3, '+', 4, '+', 5])
# should return 14
```
This function looks through the list for arithmetic operators in order of decreasing precedence and then from left to right, and when it finds such an operator it calls the corresponding function on the neighboring list elements (the operands) and replaces the operator and operands in the list with the result of the operation. Once all of the operations have been executed, the list will contain a single element - the result of the computation.
However, this function doesn't behave the way it is intended to. The problem (I think) is that this function modifies the list (by assigning to slices) while it is iterating over it. I have already found a solution to this problem [here](https://stackoverflow.com/questions/3704918/python-way-to-restart-a-for-loop-similar-to-continue-for-while-loops) (by restarting the inner `for` loop every time the list is modified), but the people who gave the solution seemed to think that there should usually be a better way to accomplish whatever this is needed for.
I was wondering if there is a better way to implement this algorithm that avoids the weird 'restarting the loop' thingy.
Thanks for any ideas! | 2011/08/10 | [
"https://Stackoverflow.com/questions/7005732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/791462/"
] | I think I'd go about it differently, and use a recursive function. Pop off operations and replace them with the result of their evaluation.
```
import operator
ops = {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv,
'%' : operator.mod,
}
precedence = [
set(['*', '/', '%']),
set(['+', '-']),
]
def evaluate(expr):
# if len == 3 then just return result of expression
if len(expr) == 3:
l, op, r = expr
return ops[op](l, r)
else:
for op_list in precedence:
for op in expr:
if op in op_list:
# find index of first operation
idx = expr.index(op)-1
# pop off and evaluate first matching operation in expr
result = evaluate([expr.pop(idx) for i in range(3)])
# insert result back into expr
expr.insert(idx, result)
return evaluate(expr)
``` | You can manipulate the index if you use a `while` loop instead
```
def evaluate(exp):
for oplist in precedence: # search for operators first in order of precedence
idx = 0
while idx < len(exp):
op = exp[idx]
if op in oplist:
result = ops[op](exp[idx - 1], exp[idx + 1])
exp[idx - 1:idx + 2] = [result]
idx -= 1 # move index back since list is shortened by 2
else:
idx += 1
return exp[0]
``` |
7,005,732 | I'm writing a calculator in Python (as an exercise), and there's one bit that I'm wondering about.
The program splits up the input into a list of numbers and operators. The result is then computed thusly:
```
import operator
ops = {'+' : operator.add, # operators and corresponding functions
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv,
'%' : operator.mod}
precedence = [['*', '/', '%'], ['+', '-']] # order of precedence for operators
def evaluate(exp):
for oplist in precedence: # search for operators first in order of precedence
for op in exp: # then from left to right
if op in oplist:
index = exp.index(op)
result = ops[op](exp[index - 1], exp[index + 1])
# compute the result of the operation
exp[index - 1:index + 2] = [result]
# replace operation and operands with result
return exp[0]
# for example,
evaluate([2, '+', 3, '+', 4, '+', 5])
# should return 14
```
This function looks through the list for arithmetic operators in order of decreasing precedence and then from left to right, and when it finds such an operator it calls the corresponding function on the neighboring list elements (the operands) and replaces the operator and operands in the list with the result of the operation. Once all of the operations have been executed, the list will contain a single element - the result of the computation.
However, this function doesn't behave the way it is intended to. The problem (I think) is that this function modifies the list (by assigning to slices) while it is iterating over it. I have already found a solution to this problem [here](https://stackoverflow.com/questions/3704918/python-way-to-restart-a-for-loop-similar-to-continue-for-while-loops) (by restarting the inner `for` loop every time the list is modified), but the people who gave the solution seemed to think that there should usually be a better way to accomplish whatever this is needed for.
I was wondering if there is a better way to implement this algorithm that avoids the weird 'restarting the loop' thingy.
Thanks for any ideas! | 2011/08/10 | [
"https://Stackoverflow.com/questions/7005732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/791462/"
] | I think I'd go about it differently, and use a recursive function. Pop off operations and replace them with the result of their evaluation.
```
import operator
ops = {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.truediv,
'%' : operator.mod,
}
precedence = [
set(['*', '/', '%']),
set(['+', '-']),
]
def evaluate(expr):
# if len == 3 then just return result of expression
if len(expr) == 3:
l, op, r = expr
return ops[op](l, r)
else:
for op_list in precedence:
for op in expr:
if op in op_list:
# find index of first operation
idx = expr.index(op)-1
# pop off and evaluate first matching operation in expr
result = evaluate([expr.pop(idx) for i in range(3)])
# insert result back into expr
expr.insert(idx, result)
return evaluate(expr)
``` | I'm not sure what you mean by "restarting the loop" thingy. In this particular case, it seems to me that you should simply apply a function repeatedly to the expression until it has been reduced to a value. This is less efficient than it could be, but it works and is clear. So...
```
def find_op(tokens, oplist):
for i, token in enumerate(tokens):
if token in oplist:
return i
else:
return -1
def reduce_binary_infix(tokens, i, ops):
op = ops[tokens[i]]
tokens[i - 1: i + 2] = [op(tokens[i - 1], tokens[i + 1])]
return tokens
def evaluate(tokens, ops, precedence):
for prec in precedence:
index = find_op(tokens, prec)
while index >= 0:
tokens = reduce_binary_infix(tokens, index, ops)
index = find_op(tokens, prec)
return tokens
print evaluate([2, '+', 3, '+', 4, '+', 5], ops, precedence)
```
Tested:
```
>>> print evaluate([2, '+', 3, '+', 4, '+', 5], ops, precedence)
[14]
```
This could be made more efficient by not searching through the whole string repeatedly. That could be done by having a `start_index` parameter in `find_op`, and by having `reduce_binary_infix` return a new current index along with the reduced list.
This is also a bit more verbose than what you have, but I think it helps the code's readability -- not to mention its reusability. |
23,092,756 | Basically, I am looking for a way to rewrite the following in a simpler, more pythonic fashion:
```
for key, value in dictionary.items():
function(key, value)
```
Is there a way to achieve this? | 2014/04/15 | [
"https://Stackoverflow.com/questions/23092756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433940/"
] | You can also do
```
from itertools import starmap
from collections import deque
exhaust_iterable = deque(maxlen=0).extend
exhaust_iterable(starmap(function, dictionary.items()))
```
if you *really* want to... | There's nothing much to factor out, but may be something that could be useful is
```
def dictmap(f, d):
return {k: f(k, v) for k, v in d.items()}
```
then you can write
```
result = dictmap(function, dictionary)
```
(given that keys are enumerated in a random order returning a list with the result doesn't make much sense and dictionary seems more appropriate).
Note however that for reasons that are not so clear to me `map` and functional reasoning is sort of considered bad in the Python community (for example anonymous functions are second-class citizens and they got quite close to be completely removed from Python 3). |
23,092,756 | Basically, I am looking for a way to rewrite the following in a simpler, more pythonic fashion:
```
for key, value in dictionary.items():
function(key, value)
```
Is there a way to achieve this? | 2014/04/15 | [
"https://Stackoverflow.com/questions/23092756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433940/"
] | There's nothing much to factor out, but may be something that could be useful is
```
def dictmap(f, d):
return {k: f(k, v) for k, v in d.items()}
```
then you can write
```
result = dictmap(function, dictionary)
```
(given that keys are enumerated in a random order returning a list with the result doesn't make much sense and dictionary seems more appropriate).
Note however that for reasons that are not so clear to me `map` and functional reasoning is sort of considered bad in the Python community (for example anonymous functions are second-class citizens and they got quite close to be completely removed from Python 3). | ```
[function(x, y) for x, y in d.items()]
``` |
23,092,756 | Basically, I am looking for a way to rewrite the following in a simpler, more pythonic fashion:
```
for key, value in dictionary.items():
function(key, value)
```
Is there a way to achieve this? | 2014/04/15 | [
"https://Stackoverflow.com/questions/23092756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433940/"
] | This is a one-liner. Not sure I'd consider it "more pythonic", though
```
map(function, *zip(*d.iteritems()))
``` | There's nothing much to factor out, but may be something that could be useful is
```
def dictmap(f, d):
return {k: f(k, v) for k, v in d.items()}
```
then you can write
```
result = dictmap(function, dictionary)
```
(given that keys are enumerated in a random order returning a list with the result doesn't make much sense and dictionary seems more appropriate).
Note however that for reasons that are not so clear to me `map` and functional reasoning is sort of considered bad in the Python community (for example anonymous functions are second-class citizens and they got quite close to be completely removed from Python 3). |
23,092,756 | Basically, I am looking for a way to rewrite the following in a simpler, more pythonic fashion:
```
for key, value in dictionary.items():
function(key, value)
```
Is there a way to achieve this? | 2014/04/15 | [
"https://Stackoverflow.com/questions/23092756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433940/"
] | You can also do
```
from itertools import starmap
from collections import deque
exhaust_iterable = deque(maxlen=0).extend
exhaust_iterable(starmap(function, dictionary.items()))
```
if you *really* want to... | ```
[function(x, y) for x, y in d.items()]
``` |
23,092,756 | Basically, I am looking for a way to rewrite the following in a simpler, more pythonic fashion:
```
for key, value in dictionary.items():
function(key, value)
```
Is there a way to achieve this? | 2014/04/15 | [
"https://Stackoverflow.com/questions/23092756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433940/"
] | You can also do
```
from itertools import starmap
from collections import deque
exhaust_iterable = deque(maxlen=0).extend
exhaust_iterable(starmap(function, dictionary.items()))
```
if you *really* want to... | This is a one-liner. Not sure I'd consider it "more pythonic", though
```
map(function, *zip(*d.iteritems()))
``` |
23,092,756 | Basically, I am looking for a way to rewrite the following in a simpler, more pythonic fashion:
```
for key, value in dictionary.items():
function(key, value)
```
Is there a way to achieve this? | 2014/04/15 | [
"https://Stackoverflow.com/questions/23092756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433940/"
] | This is a one-liner. Not sure I'd consider it "more pythonic", though
```
map(function, *zip(*d.iteritems()))
``` | ```
[function(x, y) for x, y in d.items()]
``` |
63,433,654 | I have this test snippet
```
while True:
input("prompt> ")
```
On Windows, when I run this script with "py", I can use the arrow keys as expected. But when I try doing this in my ubuntu command line, it will show the following output:
[](https://i.stack.imgur.com/EtWY6.png)
How do I make it such that this code snippet is interactive for any python3 installation on any OS? Why is it only working on Windows now? | 2020/08/16 | [
"https://Stackoverflow.com/questions/63433654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7579456/"
] | it's about OS -
windows os is working differently from a based Linux-OS like ubuntu.
you can try this:
<https://stackoverflow.com/a/893200/9350669>
by the way, I just install python3 in my VM-ubuntu and run your script and the arrow keys work well, so you can try reinstall python or update the os. [](https://i.stack.imgur.com/2dEW1.png) | ```
python3 -i script.py
```
Apparently this solves the problem and makes the session interactive. Lol okay. |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | I managed to find out what the problem was (no thanks to the error message). As it turns out, I needed to set up my e-mail server:
>
> Note that in order to send e-mail using send\_mail(), your server must be configured to send mail, and Django must be told about your outbound e-mail server. See <http://docs.djangoproject.com/en/dev/topics/email/> for the specifics.
>
>
>
I guess I thought little of what was meant by it, but I was pointed in the direction of [this](http://sontek.net/using-gmail-to-send-e-mails-from-django) guide, and things eventually started to click.
Thanks to *everyone* for chiming in with their advice. That is one useless error message, and I can only assume the people who helped me out only knew the answer because they had experienced the exact same thing. | The code tries to connect to <http://127.0.0.1:8000/contact/> - the port 8000 is not reachable (firewall) or there is no server running. |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | In settings.py, For console output, you need
```
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
```
For smtp
```
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
```
Also refer this doc here
<https://docs.djangoproject.com/en/1.6/topics/email/> | I've never used DJango myself but judging by the error, there is no server listening at port 8000 (or some firewall/server restriction is blocking port 8000 on localhost) |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | 10061 isn't the port number, that's the error number. You want to open port 8000.
See this answer for someone who was having the same problem because they were using the wrong port: [No connection could be made because the target machine actively refused it](https://stackoverflow.com/questions/4532335/errno-10061-no-connection-could-be-made-because-the-target-machine-actively-ref) | >
> If you are using gmail, you have to unlock Captcha to enable
> Django to send it for you.`https://accounts.google.com/displayunlockcaptcha`
>
>
>
I could solve my issue of this type by unlocking Captcha for the gmail account I used in the app.You can go to this [link](https://accounts.google.com/displayunlockcaptcha) in other to unlock Captcha.
I hope this's gonn'be useful :) |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | 10061 isn't the port number, that's the error number. You want to open port 8000.
See this answer for someone who was having the same problem because they were using the wrong port: [No connection could be made because the target machine actively refused it](https://stackoverflow.com/questions/4532335/errno-10061-no-connection-could-be-made-because-the-target-machine-actively-ref) | I've never used DJango myself but judging by the error, there is no server listening at port 8000 (or some firewall/server restriction is blocking port 8000 on localhost) |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | 10061 isn't the port number, that's the error number. You want to open port 8000.
See this answer for someone who was having the same problem because they were using the wrong port: [No connection could be made because the target machine actively refused it](https://stackoverflow.com/questions/4532335/errno-10061-no-connection-could-be-made-because-the-target-machine-actively-ref) | This is probably a noob mistake but I hit this error because I was trying to call as\_view() on a [Function-Based View](https://docs.djangoproject.com/en/4.0/topics/http/views/).
**Error case**:
```
urlpatterns = [
path('scratch/echo/', views.scratch_echo.as_view()),
]
```
**Working case**:
```
urlpatterns = [
path('scratch/echo/', views.scratch_echo),
]
```
I think I just copy-pasted the setup for a Class-Based View from a different tutorial and my server stopped running. |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | I managed to find out what the problem was (no thanks to the error message). As it turns out, I needed to set up my e-mail server:
>
> Note that in order to send e-mail using send\_mail(), your server must be configured to send mail, and Django must be told about your outbound e-mail server. See <http://docs.djangoproject.com/en/dev/topics/email/> for the specifics.
>
>
>
I guess I thought little of what was meant by it, but I was pointed in the direction of [this](http://sontek.net/using-gmail-to-send-e-mails-from-django) guide, and things eventually started to click.
Thanks to *everyone* for chiming in with their advice. That is one useless error message, and I can only assume the people who helped me out only knew the answer because they had experienced the exact same thing. | I've never used DJango myself but judging by the error, there is no server listening at port 8000 (or some firewall/server restriction is blocking port 8000 on localhost) |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | I managed to find out what the problem was (no thanks to the error message). As it turns out, I needed to set up my e-mail server:
>
> Note that in order to send e-mail using send\_mail(), your server must be configured to send mail, and Django must be told about your outbound e-mail server. See <http://docs.djangoproject.com/en/dev/topics/email/> for the specifics.
>
>
>
I guess I thought little of what was meant by it, but I was pointed in the direction of [this](http://sontek.net/using-gmail-to-send-e-mails-from-django) guide, and things eventually started to click.
Thanks to *everyone* for chiming in with their advice. That is one useless error message, and I can only assume the people who helped me out only knew the answer because they had experienced the exact same thing. | In settings.py, For console output, you need
```
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
```
For smtp
```
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
```
Also refer this doc here
<https://docs.djangoproject.com/en/1.6/topics/email/> |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | I managed to find out what the problem was (no thanks to the error message). As it turns out, I needed to set up my e-mail server:
>
> Note that in order to send e-mail using send\_mail(), your server must be configured to send mail, and Django must be told about your outbound e-mail server. See <http://docs.djangoproject.com/en/dev/topics/email/> for the specifics.
>
>
>
I guess I thought little of what was meant by it, but I was pointed in the direction of [this](http://sontek.net/using-gmail-to-send-e-mails-from-django) guide, and things eventually started to click.
Thanks to *everyone* for chiming in with their advice. That is one useless error message, and I can only assume the people who helped me out only knew the answer because they had experienced the exact same thing. | I got this error attempting to use `django.core.mail.send_mail`. I only need this for running through some tutorials. I don't need it to actually send mail.
The solution for me was to add this single variable to `settings.py`:
```
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
```
It sends the content of the email to *console output*, which is perfect given what I'm doing.
Docs: [`https://docs.djangoproject.com/en/1.7/topics/email/#django.core.mail.backends.smtp.EmailBackend`](https://docs.djangoproject.com/en/1.7/topics/email/#django.core.mail.backends.smtp.EmailBackend) |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | I managed to find out what the problem was (no thanks to the error message). As it turns out, I needed to set up my e-mail server:
>
> Note that in order to send e-mail using send\_mail(), your server must be configured to send mail, and Django must be told about your outbound e-mail server. See <http://docs.djangoproject.com/en/dev/topics/email/> for the specifics.
>
>
>
I guess I thought little of what was meant by it, but I was pointed in the direction of [this](http://sontek.net/using-gmail-to-send-e-mails-from-django) guide, and things eventually started to click.
Thanks to *everyone* for chiming in with their advice. That is one useless error message, and I can only assume the people who helped me out only knew the answer because they had experienced the exact same thing. | 10061 isn't the port number, that's the error number. You want to open port 8000.
See this answer for someone who was having the same problem because they were using the wrong port: [No connection could be made because the target machine actively refused it](https://stackoverflow.com/questions/4532335/errno-10061-no-connection-could-be-made-because-the-target-machine-actively-ref) |
6,782,732 | I have followed the [Django Book](http://www.djangobook.com) up until chapter seven, and I am currently messing around with forms, GET, POST and all that goodness. At one point, the guide made me figure out the reaction, after a form is filled out and sent, but when I send the form data, I get this error:
```
error at /contact/
[Errno 10061] No connection could be made because the target machine actively refused itRequest Method: POST
Request URL: http://127.0.0.1:8000/contact/
Django Version: 1.3
Exception Type: error
Exception Value: [Errno 10061] No connection could be made because the target machine actively refused it
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
```
In other words, I haven’t had any port problems up until this point. I just opened port 10061 explicitly in Windows Firewall but to no avail by the look of it. (I closed and opened the `runserver`, after I had changed the rules.)
I am running Windows 7, and the gist of my question is what exactly this error message means more so than how to deal with it (both are preferable, of course).
**EDIT:** I have also forwarded port 8000 in Windows Firewall (apply to all profiles, TCP), but I still get what looks like the same error. | 2011/07/21 | [
"https://Stackoverflow.com/questions/6782732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419005/"
] | In settings.py, For console output, you need
```
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
```
For smtp
```
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
```
Also refer this doc here
<https://docs.djangoproject.com/en/1.6/topics/email/> | The code tries to connect to <http://127.0.0.1:8000/contact/> - the port 8000 is not reachable (firewall) or there is no server running. |
56,085,331 | I am trying to download a file from a azure storage blob. I am getting below error. I am using python 2.7.5 and azure-cli: 2.0.64. But when I use sudo its working fine. can some one please help me fixing this issue ?.
Thanks in advance !!
cannot import name 'AzureException' | 2019/05/10 | [
"https://Stackoverflow.com/questions/56085331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8821850/"
] | You can use [`count()`](https://www.php.net/manual/en/function.count.php) and [`array_fill()`](https://php.net/manual/en/function.array-fill.php) to generate a "blank array" and then overlay that array with the `+` operator.
See: [Array Operators](https://www.php.net/manual/en/language.operators.array.php)
```
$num = array(1, 2, 3, 4, 5);
$let = array('a', 'b', 'c');
$overlay = array_fill(0, count($num), NULL);
$sample = array_combine($num, $let + $overlay);
var_dump($sample);
```
**Output:**
```
array(5) {
[1]=>
string(1) "a"
[2]=>
string(1) "b"
[3]=>
string(1) "c"
[4]=>
NULL
[5]=>
NULL
}
``` | ```
function custom_arr_combine($numbers, $letters) {
$lengthMax = count($numbers);
if ($lengthMax < count($letters))
$lengthMax = count($letters);
$new_arr = [];
for($i = 0; $i < $lengthMax; $i++) {
$key = "";
if (isset($numbers[$i]))
$key = $numbers[$i];
$value = "";
if (isset($letters[$i]))
$value = $letters[$i];
$new_arr[$key] = $value;
}
return $new_arr;
}
// test
$numbers = array(1, 2,3,4,5,6);
$letters = array('q', 'w', 'e', 'r');
$arr = custom_arr_combine($numbers, $letters);
foreach($arr as $nbr => $letter)
echo $nbr. " ". $letter. "\n";
```
Can this custom function help you in this [link](https://repl.it/@AbdellatifDerbe/ConcernedTautQuotient)
[](https://i.stack.imgur.com/T20Sv.png) |
57,493,434 | I'm getting used to VSCode in my daily Data Science remote workflow due to LiveShare feature.
So, upon executing functions it just executes the first line of code; if I mark the whole region then it does work, but it's cumbersome way of dealing with the issue.
I tried number of extensions, but none of them seem to solve the problem.
```py
def gini_normalized(test, pred):
"""Simple normalized Gini based on Scikit-Learn's roc_auc_score"""
gini = lambda a, p: 2 * roc_auc_score(a, p) - 1
return gini(test, pred)
```
Executing the beginning of the function results in error:
```
def gini_normalized(test, pred):...
File "", line 1
def gini_normalized(test, pred):
^
SyntaxError: unexpected EOF while parsing
```
There's a solution for PyCharm: Python Smart Execute - <https://plugins.jetbrains.com/plugin/11945-python-smart-execute>. Also Atom's Hydrogen doesn't have such issue either.
Any ideas regarding VSCode?
Thanks! | 2019/08/14 | [
"https://Stackoverflow.com/questions/57493434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8491272/"
] | I'm a developer on the VSCode DataScience features. Just to make sure that I'm understanding correctly. You would like the shift-enter command to send the entire function to the Interactive Window if you run it on the definition of the function?
If so, then yes, we don't currently support that. Shift-enter can run line by line or run a section of code that you manually highlight. If you want, you can use #%% lines in your code to put functions into code cells. Then when you are in a cell shift-enter will run that entire cell, might be the best current approach for you.
That smart execute does look interesting, if you would like to file that as a suggestion you can use our GitHub here to get it on our backlog to look at.
<https://github.com/Microsoft/vscode-python> | Hi you could click the symbol before each line and turn it into > (the indented codes of the function was hidden now). Then if you select the whole line and the next line, shift+enter could run them together.
[enter image description here](https://i.stack.imgur.com/RAvui.png) |
29,672,793 | I have two `models`:
```
class Organization(models.Model):
title = models.CharField(max_length=100)
class Folder(models.Model):
organization = models.ForeignKey("Organization",related_name='folders')
title = models.CharField(max_length=50)
```
Now I want to filter the `folder` by `organization id`. so I tried:
* `Folder.objects.filter(organization= 1)`
* `Folder.objects.filter(organization_id= 1)`
* `Folder.objects.filter(organization__id= 1)`
* `Folder.objects.filter(organization__pk= 1)`
* `Folder.objects.filter(organization= Organization.objects.get(id=1))`
Believe it or not everything returns the same.
So anybody know what is the correct way to query by foreign key field's id?
update
------
but when try to create `folder` by:
```
Folder.objects.create(organization__id=1,title='hello')
```
got error:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/suhail/.virtualenvs/heybadges/local/lib/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/suhail/.virtualenvs/heybadges/local/lib/python2.7/site-packages/django/db/models/query.py", line 370, in create
obj = self.model(**kwargs)
File "/home/suhail/.virtualenvs/heybadges/local/lib/python2.7/site-packages/django/db/models/base.py", line 452, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'organization__id' is an invalid keyword argument for this function
```
but `Folder.objects.create(organization_id=1,title='hello')` works fine. | 2015/04/16 | [
"https://Stackoverflow.com/questions/29672793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351696/"
] | [Django docs](https://docs.djangoproject.com/en/1.8/topics/db/queries/#the-pk-lookup-shortcut) say that you should use `Folder.objects.filter(organization__pk=1)` in most cases. | Answer to the update:
Probably `Folder.objects.create(organization_id=1,title='hello')` works because [Django appends "\_id" to the field name to create its database column name](https://docs.djangoproject.com/en/1.8/ref/models/fields/#database-representation). |
59,571,620 | I am making a small text rpg game to practice python and realise things i need to work on. This is my first problem and i do not yet have strong fundamentals on python.
I have a nested dictionary and i would like to print a value from the dictionary but i get a completely different value. Why couls this be?
```
ZONENAME = ""
DESCRIPTION = "description"
EXAMINATION = "info"
ANSWER = ""
SOLVED = False
UP = "up", "north"
DOWN = "down", "south"
LEFT = "left", "west"
RIGHT = "right", "east"
zonemap = {
"a1": {
ZONENAME: "Hometown",
DESCRIPTION : "ioioi",
EXAMINATION : "---",
SOLVED : False,
ANSWER : "",
UP : "i",
DOWN : "i",
LEFT : "i",
RIGHT : "a2",
},
"a2": {
ZONENAME : "ii",
DESCRIPTION : "....",
EXAMINATION : "....",
ANSWER : "your name",
SOLVED : False,
UP : "i",
DOWN : "i",
LEFT : "i",
RIGHT : "a3",
}
}
print(zonemap["a2"][ZONENAME])
``` | 2020/01/03 | [
"https://Stackoverflow.com/questions/59571620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8893037/"
] | To expound on Andrej's comment:
`ZONENAME` and `ANSWER` are both empty strings. When you use these as keys in `zonemap["a2"]`, the key is `""` (an empty string), **not** `"ZONENAME"` or `"ANSWER"`. So you first assign the value `"ii"` to the key `""`, then you assign the value `"your name"` to the key `""`. When you try to access the zone name through `zonemap["a2"][ZONENAME]`, you're actually accessing `zonemap["a2"][""]`, which holds the value `"your name"`. | Lets delve a little deeper into your issue here, so you can get a better understanding of what is happening.
At the start of your code, you're setting the following variables;
```
ZONENAME = ""
DESCRIPTION = "description"
EXAMINATION = "info"
ANSWER = ""
SOLVED = False
UP = "up", "north"
DOWN = "down", "south"
LEFT = "left", "west"
RIGHT = "right", "east"
```
The result of this, is when you call `ZONENAME` you get the response;
```
>>> ZONENAME
''
```
Now, lets have a look at your print statement, `print(zonemap["a2"][ZONENAME])`. Here you are calling, `dictonary["name of dictonary"][variable]` Since you have not enclosed your key name in quotes `''` you are directly referencing the variable itself, which as seen earlier is `''`.
So when you call `print(zonemap["a2"][ZONENAME])` you're actually saying; `print(zonemap["a2"][''])` which matches a key in your dictionary, which you set twice overriding the first value you set to that key.
What you have essentially done, it set the key names in the dictionary to the values of the variables you set prior to creating the dictionary.
You can see this by trying to access the key `ZONENAME`;
```
print(zonemap["a2"]['ZONENAME'])
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
print(zonemap["a2"]['ZONENAME'])
KeyError: 'ZONENAME'
```
The key does not exist, as it was never defined as `ZONENAME`. If you want to define the keys as the names you specified, you have to enclosed them in quotations.
```
zonemap = {
"a1": {
'ZONENAME': "Hometown",
'DESCRIPTION': "ioioi",
'EXAMINATION': "---",
'SOLVED': False,
'ANSWER': "",
'UP': "i",
'DOWN' : "i",
'LEFT' : "i",
'RIGHT' : "a2",
},
"a2": {
'ZONENAME' : "ii",
'DESCRIPTION' : "....",
'EXAMINATION' : "....",
'ANSWER' : "your name",
'SOLVED' : False,
'UP' : "i",
'DOWN' : "i",
'LEFT' : "i",
'RIGHT' : "a3",
}
}
```
This would now give you an accurate response when you call the key value in the dictionary.
```
>>> print(zonemap["a2"]['ZONENAME'])
ii
```
It would be a good opportunity for you to read up on dictionary's and how they work more in-depth.
[Dictonaries](https://www.w3schools.com/python/python_dictionaries.asp) |
62,296,850 | I'm using
- RaspberryPi4
- Raspberry camera ver2.1
- Python3
- OpenCV3
trying to catch a color from movie and success-ed with like [this](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html),
But because of AWB/AE, sometime misses the target.
I tryed to stop them
1. OpenCVs ".set" [command](https://stackoverflow.com/questions/11420748/setting-camera-parameters-in-opencv-python)
--> not supported
2. "raspivid" command
--> not correct
3. picamera.camera() module
--> cv2.cvtColor(frame, cv2.COLOR\_BGR2HSV)
is error.
I couldn't find out the right way.
Hope to help, thank you. | 2020/06/10 | [
"https://Stackoverflow.com/questions/62296850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13718320/"
] | Solve it myself
```
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import picamera
import time
from picamera.array import PiRGBArray
from picamera import PiCamera
def detect(img):
hsv_min = np.array([20,100,80])
hsv_max = np.array([27,255,255])
masked = cv2.inRange(img, hsv_min, hsv_max)
return masked
def main():
#camera mode
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 20
camera.awb_mode = 'fluorescent'
camera.awb_gains = 4
camera.exposure_mode = 'off'
capture = PiRGBArray(camera, size=(640, 480))
# allow the camera to warmup
time.sleep(0.1)
for frame in camera.capture_continuous(capture, format="bgr", use_video_port=True):
image = frame.array
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = detect(hsv)
label = cv2.connectedComponentsWithStats(mask)
cv2.imshow("Image", image)
cv2.imshow("Mask", mask)
key = cv2.waitKey(1) & 0xFF
capture.truncate(0)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
if __name__ == '__main__':
main()
```
thank you for cooperation! | There are properties to control auto white balance ([CAP\_PROP\_AUTO\_WB](https://docs.opencv.org/4.3.0/d4/d15/group__videoio__flags__base.html#ggaeb8dd9c89c10a5c63c139bf7c4f5704da762391cbaa101c4015e6a935aa0cfc95)) and auto exposure ([CAP\_PROP\_AUTO\_EXPOSURE](https://docs.opencv.org/4.3.0/d4/d15/group__videoio__flags__base.html#ggaeb8dd9c89c10a5c63c139bf7c4f5704da5c790a640b290f73fcd279e8bbaf0f13)).
As far as I know, you can use them in python (instead of raw integer value like in the code you linked to) :
```
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
cap.set(cv2.CAP_PROP_AUTO_EXPOSURE,0)
cap.set(cv2.CAP_PROP_AUTO_WB,0)
```
But be aware that this doesn't work with all backends, at least GStreamer doesn't provide a way to control camera parameter, with V4L2 it depends on the camera driver.
You can force the API to use by passing it at a second argument to [`VideoCapture`](https://docs.opencv.org/4.3.0/d8/dfe/classcv_1_1VideoCapture.html) constructor. |
12,910,270 | I am using ncclient to connect to the netconf. However when ever i try to connect through python
**"ncclient.transport.errors.SessionCloseError: Unexpected session close"** error is thrown. the code snippet that i am using is given below
```
manager.connect('<servername>',22,username='<username>')
```
Any help on this is much appriciated. I am able to connect to the remote server by using public key, hence i didnt provide passwordk in connect
And in the netconf server logs i am able to see access-denied error. (I got the same prob even when i tried with username and pwd) | 2012/10/16 | [
"https://Stackoverflow.com/questions/12910270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581175/"
] | You haven't given a lot of information.
1. Which version of `ncclient` are you using?
2. Which version of Python are you using?
3. Which NETCONF implementation are you trying to connect to? Is this to an actual switch or router, or something like a Linux server running `libnetconf` or `yuma`?
Based on the info here, I could imagine a couple of things being wrong:
* `paramiko` isn't using the right key to establish SSH transport.
* You're attempting to establish a NETCONF session with an SSH server rather than a NETCONF server.
In your script, create some logs with something like `manager.logging.basicConfig(filename='ncclient.log', level=manager.logging.DEBUG)` and then re-run your script - do you get anything more informative?
This is an old question, but I hope I can point you in the right direction at least. | its possible that your machines don't know each other (like when you connect via normal ssh and get the "unknown key, really connect (y/n)?" error. In that case, by default the session will not connect. To change this behavior use the "unknown\_host\_cb" parameter:
```
def allowUnknownHosts(host,fingerprint):
return True
self.manager = manager.connect(host=host, port=port, username=user,password=password, unknown_host_cb=allowUnknownHosts)
``` |
72,247,999 | I tried program to delete node from linked list recursively. My program is given below
```
class node:
def __init__(self, data=None):
self.data = data
self.next = None
class linkedList:
def __init__(self):
self.head=None
def printList(self):
cur = self.head
while(cur != None):
print(cur.data,end="->")
cur=cur.next
print("null")
def push(self,dat):
newNode = node(dat)
temp = self.head
self.head = newNode
newNode.next = temp
@staticmethod
def dnr(head, key):
if head is not None:
if head.data == key:
head=head.next
return head
if head is not None:
head.next = linkedList.dnr(head.next, key)
return head
return head
if __name__ == '__main__':
ll=linkedList()
ll.push(3)
ll.push(6)
ll.push(9)
ll.push(12)
ll.push(15)
ll.printList()
print("*******")
# ll.head = linkedList.dnr(ll.head,2)
linkedList.dnr(ll.head,9)
ll.printList()
```
The problem with this is that this does not work for first element.To make it work for first element I have to call the function like this
`ll.head = linkedList.dnr(ll.head,2)`
second thing is that I wanted my function to call this way
`ll.dnr(2)`
please tell me how to create a recursive function to delete node in linked list in python | 2022/05/15 | [
"https://Stackoverflow.com/questions/72247999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | `DXGI_SAMPLE_DESC` as you surmised is for specifying Multi-Sample Anti-Aliasing ([MSAA](https://en.wikipedia.org/wiki/Multisample_anti-aliasing)).
That said, you should be aware that the SwapChain support for MSAA is not something you should use anymore. As such, just always set `DXGI_SWAP_CHAIN_DESC.SampleDesc.Count = 1;` and `DXGI_SWAP_CHAIN_DESC.SampleDesc.Quality = 0;`.
Instead, to use MSAA you should explicitly create your own MSAA render target and explicitly resolve the result yourself as part of your presentation of the results to the single-sample SwapChain. For details on why and how, see [this blog post series](https://walbourn.github.io/care-and-feeding-of-modern-swapchains/).
Note that you *can* use MSAA SwapChains for DirectX 11 with the older `DXGI_SWAP_EFFECT_DISCARD` and `DXGI_SWAP_EFFECT_SEQUENTIAL` flip-effects, and the DirectX 11 runtime will do the resolve automatically. Per the blog post, this is NOT supported for DirectX 12 or the use of modern `DXGI_SWAP_EFFECT_FLIP_DISCARD` or `DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL` swap effects. This is really a 'toy' setup as any production rendering will do additional processing after the resolve from multi-sample to single-sample before putting it into the swapchain for display.
>
> As you are likely new to DirectX 11, you may want to look at [DirectX Tool Kit](https://github.com/microsoft/DirectXTK/wiki/Getting-Started). I have a tutorial that covers MSAA.
>
>
> | ok it is `anti-aliasing` (my bad i didn't know that)
>
> Anti-aliasing is a technique used by users to get rid of jaggies that form on the screen. Since pixels are rectangular, they form small jagged edges when used to display round edges. Anti-aliasing tries to smooth out the shape and produce perfect round edges.
>
>
> |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | If you want to share you f variable, you should put it in the global scope
```
var f = 200; //moved
function startgame(){
var intervalID = window.setInterval (foodcountdown(), 20000);
document.getElementById("hunger").innerHTML = f; //corrected
}
function foodcountdown() {
f=f-5; //corrected
document.getElementById("hunger").innerHTML = f; //added
}
``` | Move the bulk of the logic inside the `setInterval` function and make sure to `return` the function if the timer reaches 0:
```js
function startgame() {
let f = 200;
document.getElementById("hunger").innerHTML = f;
const intervalID = window.setInterval(() => {
if (f === 0) return;
f -= 5;
document.getElementById("hunger").innerHTML = f;
}, 500);
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
```
(Shortened the time for demonstration.) |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | 1. `setinterval(foodcountdown, 20000);` - There should not be `()`, you need to pass the function to the interval to let it execute it, not execute it yourself
2. `getElementById('hunger').innerHTML` - You need a `.` in front of `innerHTML`, not a `;` as you currently have
3. By using the keyword `var` in `var f = ...` inside your `foodcountdown` function, you are creating a local variable, and thus not affecting the one you want, declared in `startGame`. `f` needs to be accessible by both functions, make it global, or at least in the same upper scope
4. Your `intervalID` also needs to be accessible if you ever want to clear it
5. You're displaying the food count at the start of the game, but never again
Here is a fixed demo:
```js
var f, intervalID;
function startgame() {
f = 200; // Allows you to restart a game from the start
clearInterval(intervalID); // In case a game was already started
intervalID = setInterval(foodcountdown, 200); // changed to 200ms for the demo
displayFoodCount();
}
function foodcountdown() {
f -= 5;
displayFoodCount();
if (f <= 0) {
clearInterval(intervalID);
console.log('Game over!');
}
}
function displayFoodCount() {
document.getElementById("hunger").innerHTML = f;
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
``` | The main problem is that you are invoking your foodcountdown function instead of passing it in. Also you need to make sure that the startgame function is called when the DOM is loaded (maybe call it in the onload of the body).
```
var f = 200;
var interval;
function startgame() {
interval = setInterval(foodcountdown, 20000);
}
function foodcountdown() {
console.log(f);
if (f <= 0) {
clearInterval(interval);
}
document.getElementById("hunger").innerHTML = f;
f -= 5;
}
```
```
<!DOCTYPE html>
<html>
<script src="main.js"></script>
<body onload="startgame()">
<div id="hunger"></div>
</body>
</html>
``` |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | 1. `setinterval(foodcountdown, 20000);` - There should not be `()`, you need to pass the function to the interval to let it execute it, not execute it yourself
2. `getElementById('hunger').innerHTML` - You need a `.` in front of `innerHTML`, not a `;` as you currently have
3. By using the keyword `var` in `var f = ...` inside your `foodcountdown` function, you are creating a local variable, and thus not affecting the one you want, declared in `startGame`. `f` needs to be accessible by both functions, make it global, or at least in the same upper scope
4. Your `intervalID` also needs to be accessible if you ever want to clear it
5. You're displaying the food count at the start of the game, but never again
Here is a fixed demo:
```js
var f, intervalID;
function startgame() {
f = 200; // Allows you to restart a game from the start
clearInterval(intervalID); // In case a game was already started
intervalID = setInterval(foodcountdown, 200); // changed to 200ms for the demo
displayFoodCount();
}
function foodcountdown() {
f -= 5;
displayFoodCount();
if (f <= 0) {
clearInterval(intervalID);
console.log('Game over!');
}
}
function displayFoodCount() {
document.getElementById("hunger").innerHTML = f;
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
``` | Here is working example. Move your *variables* and *DOM Selections* to the the top. And also you can use `innerText` instead of innerHTML if you don't going to insert HTML.
```
const hunger = document.getElementById("hunger");
const f = 200;
hunger.innerText = f;
function foodCountDown() {
setInterval(function() {
f -= 5
hunger.innerText = f
}, 20000)
}
``` |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | 1. `setinterval(foodcountdown, 20000);` - There should not be `()`, you need to pass the function to the interval to let it execute it, not execute it yourself
2. `getElementById('hunger').innerHTML` - You need a `.` in front of `innerHTML`, not a `;` as you currently have
3. By using the keyword `var` in `var f = ...` inside your `foodcountdown` function, you are creating a local variable, and thus not affecting the one you want, declared in `startGame`. `f` needs to be accessible by both functions, make it global, or at least in the same upper scope
4. Your `intervalID` also needs to be accessible if you ever want to clear it
5. You're displaying the food count at the start of the game, but never again
Here is a fixed demo:
```js
var f, intervalID;
function startgame() {
f = 200; // Allows you to restart a game from the start
clearInterval(intervalID); // In case a game was already started
intervalID = setInterval(foodcountdown, 200); // changed to 200ms for the demo
displayFoodCount();
}
function foodcountdown() {
f -= 5;
displayFoodCount();
if (f <= 0) {
clearInterval(intervalID);
console.log('Game over!');
}
}
function displayFoodCount() {
document.getElementById("hunger").innerHTML = f;
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
``` | 1. You should declare `f` as a global variable, outside the functions.
2. You should update the HTML element every time you decrease the value.
3. You should pass the function to `setInterval`, and not the result of the function.
4. You have a `;` before `innerHTML` instead of `.`.
So (I decreased the interval for the sample):
```js
var f, intervalID;
function startgame() {
f = 200;
intervalID = window.setInterval(foodcountdown, 2000);
}
function foodcountdown() {
f = f - 5;
document.getElementById("hunger").innerHTML = f;
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
``` |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | If you want to share you f variable, you should put it in the global scope
```
var f = 200; //moved
function startgame(){
var intervalID = window.setInterval (foodcountdown(), 20000);
document.getElementById("hunger").innerHTML = f; //corrected
}
function foodcountdown() {
f=f-5; //corrected
document.getElementById("hunger").innerHTML = f; //added
}
``` | The main problem is that you are invoking your foodcountdown function instead of passing it in. Also you need to make sure that the startgame function is called when the DOM is loaded (maybe call it in the onload of the body).
```
var f = 200;
var interval;
function startgame() {
interval = setInterval(foodcountdown, 20000);
}
function foodcountdown() {
console.log(f);
if (f <= 0) {
clearInterval(interval);
}
document.getElementById("hunger").innerHTML = f;
f -= 5;
}
```
```
<!DOCTYPE html>
<html>
<script src="main.js"></script>
<body onload="startgame()">
<div id="hunger"></div>
</body>
</html>
``` |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | 1. You should declare `f` as a global variable, outside the functions.
2. You should update the HTML element every time you decrease the value.
3. You should pass the function to `setInterval`, and not the result of the function.
4. You have a `;` before `innerHTML` instead of `.`.
So (I decreased the interval for the sample):
```js
var f, intervalID;
function startgame() {
f = 200;
intervalID = window.setInterval(foodcountdown, 2000);
}
function foodcountdown() {
f = f - 5;
document.getElementById("hunger").innerHTML = f;
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
``` | Move the bulk of the logic inside the `setInterval` function and make sure to `return` the function if the timer reaches 0:
```js
function startgame() {
let f = 200;
document.getElementById("hunger").innerHTML = f;
const intervalID = window.setInterval(() => {
if (f === 0) return;
f -= 5;
document.getElementById("hunger").innerHTML = f;
}, 500);
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
```
(Shortened the time for demonstration.) |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | If you want to share you f variable, you should put it in the global scope
```
var f = 200; //moved
function startgame(){
var intervalID = window.setInterval (foodcountdown(), 20000);
document.getElementById("hunger").innerHTML = f; //corrected
}
function foodcountdown() {
f=f-5; //corrected
document.getElementById("hunger").innerHTML = f; //added
}
``` | 1. You should declare `f` as a global variable, outside the functions.
2. You should update the HTML element every time you decrease the value.
3. You should pass the function to `setInterval`, and not the result of the function.
4. You have a `;` before `innerHTML` instead of `.`.
So (I decreased the interval for the sample):
```js
var f, intervalID;
function startgame() {
f = 200;
intervalID = window.setInterval(foodcountdown, 2000);
}
function foodcountdown() {
f = f - 5;
document.getElementById("hunger").innerHTML = f;
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
``` |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | The main problem is that you are invoking your foodcountdown function instead of passing it in. Also you need to make sure that the startgame function is called when the DOM is loaded (maybe call it in the onload of the body).
```
var f = 200;
var interval;
function startgame() {
interval = setInterval(foodcountdown, 20000);
}
function foodcountdown() {
console.log(f);
if (f <= 0) {
clearInterval(interval);
}
document.getElementById("hunger").innerHTML = f;
f -= 5;
}
```
```
<!DOCTYPE html>
<html>
<script src="main.js"></script>
<body onload="startgame()">
<div id="hunger"></div>
</body>
</html>
``` | Move the bulk of the logic inside the `setInterval` function and make sure to `return` the function if the timer reaches 0:
```js
function startgame() {
let f = 200;
document.getElementById("hunger").innerHTML = f;
const intervalID = window.setInterval(() => {
if (f === 0) return;
f -= 5;
document.getElementById("hunger").innerHTML = f;
}, 500);
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
```
(Shortened the time for demonstration.) |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | If you want to share you f variable, you should put it in the global scope
```
var f = 200; //moved
function startgame(){
var intervalID = window.setInterval (foodcountdown(), 20000);
document.getElementById("hunger").innerHTML = f; //corrected
}
function foodcountdown() {
f=f-5; //corrected
document.getElementById("hunger").innerHTML = f; //added
}
``` | 1. `setinterval(foodcountdown, 20000);` - There should not be `()`, you need to pass the function to the interval to let it execute it, not execute it yourself
2. `getElementById('hunger').innerHTML` - You need a `.` in front of `innerHTML`, not a `;` as you currently have
3. By using the keyword `var` in `var f = ...` inside your `foodcountdown` function, you are creating a local variable, and thus not affecting the one you want, declared in `startGame`. `f` needs to be accessible by both functions, make it global, or at least in the same upper scope
4. Your `intervalID` also needs to be accessible if you ever want to clear it
5. You're displaying the food count at the start of the game, but never again
Here is a fixed demo:
```js
var f, intervalID;
function startgame() {
f = 200; // Allows you to restart a game from the start
clearInterval(intervalID); // In case a game was already started
intervalID = setInterval(foodcountdown, 200); // changed to 200ms for the demo
displayFoodCount();
}
function foodcountdown() {
f -= 5;
displayFoodCount();
if (f <= 0) {
clearInterval(intervalID);
console.log('Game over!');
}
}
function displayFoodCount() {
document.getElementById("hunger").innerHTML = f;
}
```
```html
<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>
``` |
62,611,133 | I have checked lots of websites and almost all questions related to the same on Stackoverflow. I cant find the solution to this problem. Its very important for a project. Please help. I want to use the variable self.email in Class A in the function email(self) in Class B. I've tried several things, but its not working. Inheritance wont work because its a kivy-python code and its already inheriting classes like GridLayout().
```
Class A:
def __init__(self):
---some code---
def email_id(self):
self.email = x
Class B:
def __init__(self):
print(A().email)
``` | 2020/06/27 | [
"https://Stackoverflow.com/questions/62611133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13589445/"
] | If you want to share you f variable, you should put it in the global scope
```
var f = 200; //moved
function startgame(){
var intervalID = window.setInterval (foodcountdown(), 20000);
document.getElementById("hunger").innerHTML = f; //corrected
}
function foodcountdown() {
f=f-5; //corrected
document.getElementById("hunger").innerHTML = f; //added
}
``` | Here is working example. Move your *variables* and *DOM Selections* to the the top. And also you can use `innerText` instead of innerHTML if you don't going to insert HTML.
```
const hunger = document.getElementById("hunger");
const f = 200;
hunger.innerText = f;
function foodCountDown() {
setInterval(function() {
f -= 5
hunger.innerText = f
}, 20000)
}
``` |
12,423,592 | To start vlc using python, I've done that :
```
import subprocess
p = subprocess.Popen(["C:\Program Files(x86)\VideoLAN\VLC\vlc.exe","C:\Users\Kamilos\Desktop\TBT\Tbt_S01E17.avi"])
```
But it doesn't work, why ? :p
(tested in python 2.7.3 and 3)
EDIT SOLVED : like Drake said, just replace back-slash with blash
```
subprocess.Popen(["C:/Program Files(x86)/VideoLAN/VLC/vlc.exe","C:/Users/Kamilos/Desktop/TBT/Tbt_S01E17.avi"])
``` | 2012/09/14 | [
"https://Stackoverflow.com/questions/12423592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1617507/"
] | You are effectively escaping every character after the path separator. In the same way that `"\n"` means a new line, `"\P"`, `"\V"` also mean something other than just a 2-character string.
You could just use `"\\"` (or `"/"`, can't remember which Windows uses) for the path separator, but the proper way is to get Python to join the path together for you using [`os.path.join`](http://docs.python.org/library/os.path.html#os.path.join).
Try:
```
import subprocess
import os
p = subprocess.Popen([os.path.join("C:/", "Program Files(x86)", "VideoLAN", "VLC", "vlc.exe"),os.path.join("C:/", "Users", "Kamilos", "Desktop", "TBT", "Tbt_S01E17.avi")])
``` | Verify that the path exists:
```
import os
print os.path.exists("C:\Users\Kamilos\Desktop\TBT\Tbt_S01E17.avi")
``` |
12,423,592 | To start vlc using python, I've done that :
```
import subprocess
p = subprocess.Popen(["C:\Program Files(x86)\VideoLAN\VLC\vlc.exe","C:\Users\Kamilos\Desktop\TBT\Tbt_S01E17.avi"])
```
But it doesn't work, why ? :p
(tested in python 2.7.3 and 3)
EDIT SOLVED : like Drake said, just replace back-slash with blash
```
subprocess.Popen(["C:/Program Files(x86)/VideoLAN/VLC/vlc.exe","C:/Users/Kamilos/Desktop/TBT/Tbt_S01E17.avi"])
``` | 2012/09/14 | [
"https://Stackoverflow.com/questions/12423592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1617507/"
] | You are effectively escaping every character after the path separator. In the same way that `"\n"` means a new line, `"\P"`, `"\V"` also mean something other than just a 2-character string.
You could just use `"\\"` (or `"/"`, can't remember which Windows uses) for the path separator, but the proper way is to get Python to join the path together for you using [`os.path.join`](http://docs.python.org/library/os.path.html#os.path.join).
Try:
```
import subprocess
import os
p = subprocess.Popen([os.path.join("C:/", "Program Files(x86)", "VideoLAN", "VLC", "vlc.exe"),os.path.join("C:/", "Users", "Kamilos", "Desktop", "TBT", "Tbt_S01E17.avi")])
``` | It worked this way for me:
```
os.system(''start vlc C:\\local\\file\\name.mp4")
```
or:
```
subprocess.Popen(["C:/Program Files (x86)/VideoLAN/VLC/vlc.exe","C:\\Users\\USERNAME\\Desktop\\videos\\example.mp4"])
```
-the difference is in the way to put the: ' \ ' , ' // ' |
6,181,532 | What is the Pythonic way to do this?
```
value = (mydict.has_key('index') and mydict['index']) or 1024
```
Initialize from a dict's value, if present, otherwise use default value.
Got some answers on LBYL and EAFP, but too verbose code :p
I want some one-line-initialize.
PS: python-2.4 only (running CentOS5) | 2011/05/30 | [
"https://Stackoverflow.com/questions/6181532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561948/"
] | ```
value = mydict.get('index', 1024)
```
(Note that this is not exactly equivalent to your code, since it will use `1024` only if the key `index` is not present, while your code also uses `1024` when the value corresponding to key `index` is falsy. From your explanation I infer the former is what you actually want.) | Alternatively use `setdefault()` - like `get()`, but it inserts the key before returning the value:
```
value = mydict.setdefault('index', 1024)
``` |
6,181,532 | What is the Pythonic way to do this?
```
value = (mydict.has_key('index') and mydict['index']) or 1024
```
Initialize from a dict's value, if present, otherwise use default value.
Got some answers on LBYL and EAFP, but too verbose code :p
I want some one-line-initialize.
PS: python-2.4 only (running CentOS5) | 2011/05/30 | [
"https://Stackoverflow.com/questions/6181532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561948/"
] | ```
value = mydict.get('index', 1024)
```
(Note that this is not exactly equivalent to your code, since it will use `1024` only if the key `index` is not present, while your code also uses `1024` when the value corresponding to key `index` is falsy. From your explanation I infer the former is what you actually want.) | The `get` and `setdefault` methods are important to know, they should be in any Python programmer's toolbox.
Another important way of doing this is to use `collections.defaultdict`, because then you can define your "default" in a single place without having to scatter it throughout your code wherever the dictionary is used, i.e. Don't Repeat Yourself. Then if you change the default you don't need to hunt through your code finding all those gets and setdefaults. For example
```
>>> import collections
>>> myDict = collections.defaultdict
>>> myDict = collections.defaultdict(lambda : 1024)
>>> myDict[0] += 1
>>> print myDict[0], myDict[100]
1025 1024
```
Because you get to set the function call, you can do whatever you like for your default value. How about assigning a random value between 1 and 10 for every new key?
```
>>> import collections
>>> import random
>>> myDict = collections.defaultdict(lambda : random.randint(1,10))
>>> print myDict[0], myDict[100]
1 5
>>> print myDict[0], myDict[100], myDict[2]
1 5 6
```
OK, that example's a little contrived, but I'm sure you can think of better uses. Say you have an expensive class to construct - the instance is only created if the key is not actually present, unlike when calling `get` and `setdefault`, e.g.
```
>>> class ExpensiveClass(object):
>>> numObjects = 0
>>> def __init__(self):
>>> ExpensiveClass.numObjects += 1
>>>
>>> print ExpensiveClass.numObjects
0
>>> x = {}
>>> x[0] = ExpensiveClass()
>>> print ExpensiveClass.numObjects
1
>>> print x.get(0, ExpensiveClass())
<__main__.ExpensiveClass object at 0x025665B0>
>>> print ExpensiveClass.numObjects
2
>>> ExpensiveClass.numObjects = 0
>>> z = collections.defaultdict(ExpensiveClass)
>>> print ExpensiveClass.numObjects
0
>>> print z[0]
>>> <__main__.ExpensiveClass object at 0x02566510>
>>> print ExpensiveClass.numObjects
1
```
Note that the call to `x.get` constructs a new `ExpensiveClass` instance, even though we don't ever use that instance because `x[0]` already exists. This could cause problems if you were indeed trying to count the number of `ExpensiveClass` objects, or if they were very slow to create. These problems don't occur for `collections.defaultdict`. |
6,181,532 | What is the Pythonic way to do this?
```
value = (mydict.has_key('index') and mydict['index']) or 1024
```
Initialize from a dict's value, if present, otherwise use default value.
Got some answers on LBYL and EAFP, but too verbose code :p
I want some one-line-initialize.
PS: python-2.4 only (running CentOS5) | 2011/05/30 | [
"https://Stackoverflow.com/questions/6181532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561948/"
] | ```
value = mydict.get('index', 1024)
```
(Note that this is not exactly equivalent to your code, since it will use `1024` only if the key `index` is not present, while your code also uses `1024` when the value corresponding to key `index` is falsy. From your explanation I infer the former is what you actually want.) | The `collections` module `defaultdict` class might be of help. Unfortunately it wasn't introduced until Python 2.5 and it doesn't do *exactly* what your code does. Here's a few differences:
* It only supplies a value when a key is missing, not when it is there but has a value considered `False`.
* If the looked-up key is missing it will add it to the dictionary with a default value as well as return the default value.
* All missing values get the same default value.
If that's OK you can emulate the essence of one in older Pythons with something like this:
```
try:
from collections import defaultdict
except ImportError:
class defaultdict(dict):
def __init__(self, default_factory=None, *a, **kw):
dict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
self[key] = value = self.default_factory()
return value
```
A recipe for a more complete emulation is available on [ActiveState](http://code.activestate.com/recipes/523034/). Even if you had Python 2.5+, you might want to derive your own class to customize to have the exact behavior you wanted. Besides checking for "False" truth values and perhaps not adding any missing ones to the dictionary, you could also provide it with a separate dictionary of multiple default values corresponding to different keys instead of "one size fits all". For ways to do that see [*Is there a way to set multiple defaults on a Python dict using another dict?*](https://stackoverflow.com/questions/849806/is-there-a-way-to-set-multiple-defaults-on-a-python-dict-using-another-dict/850402#850402). |
6,181,532 | What is the Pythonic way to do this?
```
value = (mydict.has_key('index') and mydict['index']) or 1024
```
Initialize from a dict's value, if present, otherwise use default value.
Got some answers on LBYL and EAFP, but too verbose code :p
I want some one-line-initialize.
PS: python-2.4 only (running CentOS5) | 2011/05/30 | [
"https://Stackoverflow.com/questions/6181532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561948/"
] | Alternatively use `setdefault()` - like `get()`, but it inserts the key before returning the value:
```
value = mydict.setdefault('index', 1024)
``` | The `get` and `setdefault` methods are important to know, they should be in any Python programmer's toolbox.
Another important way of doing this is to use `collections.defaultdict`, because then you can define your "default" in a single place without having to scatter it throughout your code wherever the dictionary is used, i.e. Don't Repeat Yourself. Then if you change the default you don't need to hunt through your code finding all those gets and setdefaults. For example
```
>>> import collections
>>> myDict = collections.defaultdict
>>> myDict = collections.defaultdict(lambda : 1024)
>>> myDict[0] += 1
>>> print myDict[0], myDict[100]
1025 1024
```
Because you get to set the function call, you can do whatever you like for your default value. How about assigning a random value between 1 and 10 for every new key?
```
>>> import collections
>>> import random
>>> myDict = collections.defaultdict(lambda : random.randint(1,10))
>>> print myDict[0], myDict[100]
1 5
>>> print myDict[0], myDict[100], myDict[2]
1 5 6
```
OK, that example's a little contrived, but I'm sure you can think of better uses. Say you have an expensive class to construct - the instance is only created if the key is not actually present, unlike when calling `get` and `setdefault`, e.g.
```
>>> class ExpensiveClass(object):
>>> numObjects = 0
>>> def __init__(self):
>>> ExpensiveClass.numObjects += 1
>>>
>>> print ExpensiveClass.numObjects
0
>>> x = {}
>>> x[0] = ExpensiveClass()
>>> print ExpensiveClass.numObjects
1
>>> print x.get(0, ExpensiveClass())
<__main__.ExpensiveClass object at 0x025665B0>
>>> print ExpensiveClass.numObjects
2
>>> ExpensiveClass.numObjects = 0
>>> z = collections.defaultdict(ExpensiveClass)
>>> print ExpensiveClass.numObjects
0
>>> print z[0]
>>> <__main__.ExpensiveClass object at 0x02566510>
>>> print ExpensiveClass.numObjects
1
```
Note that the call to `x.get` constructs a new `ExpensiveClass` instance, even though we don't ever use that instance because `x[0]` already exists. This could cause problems if you were indeed trying to count the number of `ExpensiveClass` objects, or if they were very slow to create. These problems don't occur for `collections.defaultdict`. |
6,181,532 | What is the Pythonic way to do this?
```
value = (mydict.has_key('index') and mydict['index']) or 1024
```
Initialize from a dict's value, if present, otherwise use default value.
Got some answers on LBYL and EAFP, but too verbose code :p
I want some one-line-initialize.
PS: python-2.4 only (running CentOS5) | 2011/05/30 | [
"https://Stackoverflow.com/questions/6181532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561948/"
] | Alternatively use `setdefault()` - like `get()`, but it inserts the key before returning the value:
```
value = mydict.setdefault('index', 1024)
``` | The `collections` module `defaultdict` class might be of help. Unfortunately it wasn't introduced until Python 2.5 and it doesn't do *exactly* what your code does. Here's a few differences:
* It only supplies a value when a key is missing, not when it is there but has a value considered `False`.
* If the looked-up key is missing it will add it to the dictionary with a default value as well as return the default value.
* All missing values get the same default value.
If that's OK you can emulate the essence of one in older Pythons with something like this:
```
try:
from collections import defaultdict
except ImportError:
class defaultdict(dict):
def __init__(self, default_factory=None, *a, **kw):
dict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
self[key] = value = self.default_factory()
return value
```
A recipe for a more complete emulation is available on [ActiveState](http://code.activestate.com/recipes/523034/). Even if you had Python 2.5+, you might want to derive your own class to customize to have the exact behavior you wanted. Besides checking for "False" truth values and perhaps not adding any missing ones to the dictionary, you could also provide it with a separate dictionary of multiple default values corresponding to different keys instead of "one size fits all". For ways to do that see [*Is there a way to set multiple defaults on a Python dict using another dict?*](https://stackoverflow.com/questions/849806/is-there-a-way-to-set-multiple-defaults-on-a-python-dict-using-another-dict/850402#850402). |
72,778,496 | I am new bee on python selenium environment. I am trying to get the SQL version table from [enter link description here](https://sqlserverbuilds.blogspot.com/)
```
from selenium.webdriver.common.by import By
from selenium import webdriver
# define the website to scrape and path where the chromediver is located
website = "https://www.sqlserverversions.com"
driver = webdriver.Chrome(executable_path='/Users//Downloads/chromedriver/chromedriver.exe')
# define 'driver' variable
# open Google Chrome with chromedriver
driver.get(website)
matches = driver.find_elements(By.TAG_NAME, 'tr')
for match in matches:
b=match.find_elements(By.XPATH,"./td[1]")
print(b.text)
```
it says AttributeError: 'list' object has no attribute 'text'. Am i choosing the write syntax and right parameters to grab the data?
Below is the table which i am trying to get data.
[enter image description here](https://i.stack.imgur.com/wkBHX.png)
Below are the parameters which i am trying to put in code.
[enter image description here](https://i.stack.imgur.com/RlXsq.png)
Please advise what is required to modify in the code to obtain the data in table format.
Thanks,
Arun | 2022/06/27 | [
"https://Stackoverflow.com/questions/72778496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7747401/"
] | Check out the below snippet. i have updated theFoodImg variable to theFoodImgs and leveraged querySelectorAll to get a node list of all the .food-img class elements.
Then use a foreach loop on the nodelist to loop it and add your listeners.
You may want to update more of your variables from querySelector to querySelectorAll. I have done this one to get you headed down the correct path.
\*\*Edit added a recipeLink class. cant key off of a class in the selector that is being added and removed. The snippet should be in full working order now.
```js
const theFoodImgs = document.querySelectorAll('.food-img'),
pinTopBar = document.querySelector('.fa-thumbtack'),
topBar = document.querySelector('#top-bar'),
pinColor = document.querySelector('.fa-thumbtack');
let recipeLink, linkIcon;
theFoodImgs.forEach(function (el) {
el.addEventListener('click', function() {
recipeLink = this.parentNode.parentNode.querySelector('.recipeLink');
linkIcon = this.parentNode.parentNode.querySelector('.fa-link');
if(this.classList.contains('active')){
this.classList.remove('active');
this.classList.remove('food-hover');
this.classList.add('food-img');
recipeLink.classList.add('recipe-link');
recipeLink.classList.remove('click');
linkIcon.classList.add('white-link')
linkIcon.classList.remove('blue-link')
} else {
this.classList.remove('food-img');
this.classList.add('active');
recipeLink.classList.remove('recipe-link');
recipeLink.classList.add('click');
linkIcon.classList.remove('white-link')
linkIcon.classList.add('blue-link')
}
});
el.addEventListener('mouseenter', function(){
if (el.classList.contains('active') !== true) {
el.classList.add('food-hover');
}
})
});
if(topBar.classList.contains('fix')) {
pinColor.style.color = 'goldenrod';
}
pinTopBar.addEventListener('click', function() {
if(topBar.classList.contains('fix') !== true) {
topBar.classList.add('fix');
pinColor.style.color = 'goldenrod';
}
else {
topBar.classList.remove('fix');
pinColor.style.color = 'black';
}
})
```
```css
/* css reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
text-decoration: none;
}
body {
margin: 0;
padding: 0;
}
a {
color: black;
text-decoration: none;
}
hr {
width: 80%;
margin: 0 auto;
background-color: black;
box-shadow: 0 0 15px gold;
}
/* banner and title styles */
div#banner {
background: url(https://i.ibb.co/MgBrNdY/background-img.jpg);
box-shadow: inset 0 0 0 9000em rgba(68, 68, 68, 0.5);
background-size: cover;
height: 50vh; /* change later for media queries */
}
/* title style */
h1#large-screen-title {
color: goldenrod;
text-align: center;
padding: 0.5em;
font-size: 4em;
}
div#top-bar {
background-color: rgb(255, 250, 234);
height: min-content;
}
.fix {
position: fixed;
height: 15%;
right: 0;
left: 0;
top: 0;
box-shadow: 0 0 20px goldenrod;
}
img#odin-logo {
height: 5em;
}
i.fa-thumbtack {
float: right;
padding: 1em;
}
i.fa-thumbtack:hover {
cursor: pointer;
}
@media only screen and (min-width: 700px) {
div#banner {
height: 80vh;
}
h1#title-index {
height: 60vh;
color: transparent;
border: 0px solid white;
}
div#top-bar {
text-align: center;
}
}
/* recipe card styles */
div#recipe-card-container {
padding-top: 5em;
padding-left: 0.5em;
padding-right: 0.5em;
display: grid;
grid-template-columns: 1fr;
justify-content: center;
align-items: center;
gap: 2em;
}
/*each recipe card */
div#recipe-card-container > div.each-recipe {
display: grid;
gap: 2em;
margin-bottom: 5em;
justify-content: center;
}
div#recipe-card-container div.recipe-img {
/* background-color: red; */
width: 100%;
height: 50vh;
border-radius: 3px;
transition: 450ms;
}
/*recipe link within each card */
div.recipe-link {
background-color: lightgray;
text-align: center;
padding-top: 1em;
padding: 0.5em;
transition: 450ms;
border-radius: 0.3em;
}
div.recipe-link:hover {
background-color: #eece1a;
transition: 450ms;
}
/* when clicked add this style */
.click {
background-color: #eece1a;
text-align: center;
padding-top: 1em;
padding: 0.5em;
border-radius: 0.3em;
transition: 450ms;
width: 100%;
margin: 0 auto;
}
/**/
i.fa-link {
float: left;
}
div.recipe-link:hover > i.fa-link {
color: rgb(0, 0, 255, 0.5);
}
/*when clicked, target i.fa-link color */
.white-link {
color: white;
}
.blue-link {
color: rgb(0, 0, 255, 0.5);
}
/* food image style on card */
.food-img {
height: 100%;
border-radius: 50%;
border: 4px solid rgba(189, 80, 12, 0.637);
transition: 450ms;
cursor: pointer;
}
img.food-img {
width: 100%;
}
img.food-hover:hover,
.active {
box-shadow: 0 0 20px rgb(189, 80, 12);
height: 105%;
object-fit: cover;
border-radius: 50%;
border: 4px solid rgba(189, 80, 12, 0.637);
transition: 450ms;
cursor: pointer;
}
/*grey bar with copyright*/
div.copy {
background-color: rgba(0, 0, 0, 0.54);
margin-top: 2em;
padding: 2em;
color: white;
text-align: center;
}
@media only screen and (min-width: 1020px) {
div#recipe-card-container {
padding-left: 0;
padding-right: 0;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
gap: 2em;
margin-top: 2em;
box-shadow: inset 0 500px rgb(85, 63, 63);
}
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../style.css" />
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Odin Recipes</title>
</head>
<body>
<div id="banner">
<div id="top-bar" class="fix">
<a href="https://www.theodinproject.com/"
><img src="https://i.ibb.co/7nhgfNJ/odin-logo.png" alt="" id="odin-logo"
/></a>
<i class="fa-solid fa-thumbtack"></i>
</div>
</div>
<br />
<br />
<hr />
<h1 id="large-screen-title">Odin Recipes</h1>
<br /><br />
<hr />
<div id="recipe-card-container">
<div class="each-recipe">
<div class="recipe-img">
<img
src="https://i.ibb.co/mDCCZTW/pizza.jpg"
alt=""
class="food-img food-hover"
/>
</div>
<a href="/recipes/pizza.html">
<div class="recipe-link recipeLink">
<i class="fa-solid fa-link white-link"></i>Click here for Pizza
Recipe
</div>
</a>
</div>
<div class="each-recipe">
<div class="recipe-img">
<img src="https://i.ibb.co/5cQCFWP/pavlova.png" alt="" class="food-img food-hover"/>
</div>
<a href="/recipes/pavlova.html">
<div class="recipe-link recipeLink">
<i class="fa-solid fa-link white-link"></i>Click here for Pavlova Recipe
</div>
</a>
</div>
<div class="each-recipe">
<div class="recipe-img">
<img
src="/recipes/images/"
alt=""
class="food-img food-hover"
/>
</div>
<a href="/recipes/">
<div class="recipe-link recipeLink">
<i class="fa-solid fa-link white-link"></i>Click here for Pavlova
Recipe
</div>
</a>
</div>
</div>
<div class="copy">Copyright © 2022</div>
<script
src="https://kit.fontawesome.com/fb94170dc7.js"
crossorigin="anonymous"
></script>
<script src="app.js"></script>
</body>
</html>
``` | I simplified the process to not query ANY loops. Instead I'm assigning the event handler to the parent of the recipes. Then I look for the active element and REMOVE the active class from the recipe itself. Instead of adding/removing classes from each element, I simply add an active class to the recipe parent and use CSS to modify the children of the active class.
```js
const recipes = document.querySelector("#recipe-card-container")
recipes.addEventListener("click", function(el) {
let target = el.target;
if (target.className.indexOf("food-img") > -1) {
let active = document.querySelector(".each-recipe.active");
if (active) {
active.classList.remove("active");
}
target.parentNode.parentNode.classList.add("active");
}
});
```
```css
/* css reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
text-decoration: none;
}
body {
margin: 0;
padding: 0;
}
a {
color: black;
text-decoration: none;
}
hr {
width: 80%;
margin: 0 auto;
background-color: black;
box-shadow: 0 0 15px gold;
}
/* banner and title styles */
div#banner {
background: url(https://i.ibb.co/MgBrNdY/background-img.jpg);
box-shadow: inset 0 0 0 9000em rgba(68, 68, 68, 0.5);
background-size: cover;
height: 50vh;
/* change later for media queries */
}
/* title style */
h1#large-screen-title {
color: goldenrod;
text-align: center;
padding: 0.5em;
font-size: 4em;
}
div#top-bar {
background-color: rgb(255, 250, 234);
height: min-content;
}
.fix {
position: fixed;
height: 15%;
right: 0;
left: 0;
top: 0;
box-shadow: 0 0 20px goldenrod;
}
img#odin-logo {
height: 5em;
}
i.fa-thumbtack {
float: right;
padding: 1em;
}
i.fa-thumbtack:hover {
cursor: pointer;
}
@media only screen and (min-width: 700px) {
div#banner {
height: 80vh;
}
h1#title-index {
height: 60vh;
color: transparent;
border: 0px solid white;
}
div#top-bar {
text-align: center;
}
}
/* recipe card styles */
div#recipe-card-container {
padding-top: 5em;
padding-left: 0.5em;
padding-right: 0.5em;
display: grid;
grid-template-columns: 1fr;
justify-content: center;
align-items: center;
gap: 2em;
}
/*each recipe card */
div#recipe-card-container>div.each-recipe {
display: grid;
gap: 2em;
margin-bottom: 5em;
justify-content: center;
}
div#recipe-card-container div.recipe-img {
/* background-color: red; */
width: 100%;
height: 50vh;
border-radius: 3px;
transition: 450ms;
}
/*recipe link within each card */
div.recipe-link {
background-color: lightgray;
text-align: center;
padding-top: 1em;
padding: 0.5em;
transition: 450ms;
border-radius: 0.3em;
}
div.recipe-link:hover {
background-color: #eece1a;
transition: 450ms;
}
/* when clicked add this style */
.active .recipe-link {
background-color: #eece1a;
text-align: center;
padding-top: 1em;
padding: 0.5em;
border-radius: 0.3em;
transition: 450ms;
width: 100%;
margin: 0 auto;
}
/**/
i.fa-link {
float: left;
}
div.recipe-link:hover>i.fa-link {
color: rgb(0, 0, 255, 0.5);
}
/*when clicked, target i.fa-link color */
.recipe-link i {
color: white;
}
.each-recipe.active i {
color: rgb(0, 0, 255, 0.5);
}
/* food image style on card */
.food-img {
height: 100%;
border-radius: 50%;
border: 4px solid rgba(189, 80, 12, 0.637);
transition: 450ms;
cursor: pointer;
}
img.food-img {
width: 100%;
}
img.food-hover:hover,
.each-recipe.active img {
box-shadow: 0 0 20px rgb(189, 80, 12);
height: 105%;
object-fit: cover;
border-radius: 50%;
border: 4px solid rgba(189, 80, 12, 0.637);
transition: 450ms;
cursor: pointer;
}
/*grey bar with copyright*/
div.copy {
background-color: rgba(0, 0, 0, 0.54);
margin-top: 2em;
padding: 2em;
color: white;
text-align: center;
}
@media only screen and (min-width: 1020px) {
div#recipe-card-container {
padding-left: 0;
padding-right: 0;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
gap: 2em;
margin-top: 2em;
box-shadow: inset 0 500px rgb(85, 63, 63);
}
}
```
```html
<div id="recipe-card-container">
<div class="each-recipe">
<div class="recipe-img">
<img src="https://i.ibb.co/mDCCZTW/pizza.jpg" alt="" class="food-img food-hover" />
</div>
<a href="/recipes/pizza.html">
<div class="recipe-link">
<i class="fa-solid fa-link"></i>Click here for Pizza Recipe
</div>
</a>
</div>
<div class="each-recipe">
<div class="recipe-img">
<img src="https://i.ibb.co/5cQCFWP/pavlova.png" alt="" class="food-img food-hover" />
</div>
<a href="/recipes/pavlova.html">
<div class="recipe-link">
<i class="fa-solid fa-link"></i>Click here for Pavlova Recipe
</div>
</a>
</div>
<div class="each-recipe">
<div class="recipe-img">
<img src="/recipes/images/" alt="" class="food-img food-hover" />
</div>
<a href="/recipes/">
<div class="recipe-link">
<i class="fa-solid fa-link"></i>Click here for Pavlova Recipe
</div>
</a>
</div>
</div>
<div class="copy">Copyright © 2022</div>
<script src="https://kit.fontawesome.com/fb94170dc7.js" crossorigin="anonymous"></script>
``` |
72,778,496 | I am new bee on python selenium environment. I am trying to get the SQL version table from [enter link description here](https://sqlserverbuilds.blogspot.com/)
```
from selenium.webdriver.common.by import By
from selenium import webdriver
# define the website to scrape and path where the chromediver is located
website = "https://www.sqlserverversions.com"
driver = webdriver.Chrome(executable_path='/Users//Downloads/chromedriver/chromedriver.exe')
# define 'driver' variable
# open Google Chrome with chromedriver
driver.get(website)
matches = driver.find_elements(By.TAG_NAME, 'tr')
for match in matches:
b=match.find_elements(By.XPATH,"./td[1]")
print(b.text)
```
it says AttributeError: 'list' object has no attribute 'text'. Am i choosing the write syntax and right parameters to grab the data?
Below is the table which i am trying to get data.
[enter image description here](https://i.stack.imgur.com/wkBHX.png)
Below are the parameters which i am trying to put in code.
[enter image description here](https://i.stack.imgur.com/RlXsq.png)
Please advise what is required to modify in the code to obtain the data in table format.
Thanks,
Arun | 2022/06/27 | [
"https://Stackoverflow.com/questions/72778496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7747401/"
] | Check out the below snippet. i have updated theFoodImg variable to theFoodImgs and leveraged querySelectorAll to get a node list of all the .food-img class elements.
Then use a foreach loop on the nodelist to loop it and add your listeners.
You may want to update more of your variables from querySelector to querySelectorAll. I have done this one to get you headed down the correct path.
\*\*Edit added a recipeLink class. cant key off of a class in the selector that is being added and removed. The snippet should be in full working order now.
```js
const theFoodImgs = document.querySelectorAll('.food-img'),
pinTopBar = document.querySelector('.fa-thumbtack'),
topBar = document.querySelector('#top-bar'),
pinColor = document.querySelector('.fa-thumbtack');
let recipeLink, linkIcon;
theFoodImgs.forEach(function (el) {
el.addEventListener('click', function() {
recipeLink = this.parentNode.parentNode.querySelector('.recipeLink');
linkIcon = this.parentNode.parentNode.querySelector('.fa-link');
if(this.classList.contains('active')){
this.classList.remove('active');
this.classList.remove('food-hover');
this.classList.add('food-img');
recipeLink.classList.add('recipe-link');
recipeLink.classList.remove('click');
linkIcon.classList.add('white-link')
linkIcon.classList.remove('blue-link')
} else {
this.classList.remove('food-img');
this.classList.add('active');
recipeLink.classList.remove('recipe-link');
recipeLink.classList.add('click');
linkIcon.classList.remove('white-link')
linkIcon.classList.add('blue-link')
}
});
el.addEventListener('mouseenter', function(){
if (el.classList.contains('active') !== true) {
el.classList.add('food-hover');
}
})
});
if(topBar.classList.contains('fix')) {
pinColor.style.color = 'goldenrod';
}
pinTopBar.addEventListener('click', function() {
if(topBar.classList.contains('fix') !== true) {
topBar.classList.add('fix');
pinColor.style.color = 'goldenrod';
}
else {
topBar.classList.remove('fix');
pinColor.style.color = 'black';
}
})
```
```css
/* css reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
text-decoration: none;
}
body {
margin: 0;
padding: 0;
}
a {
color: black;
text-decoration: none;
}
hr {
width: 80%;
margin: 0 auto;
background-color: black;
box-shadow: 0 0 15px gold;
}
/* banner and title styles */
div#banner {
background: url(https://i.ibb.co/MgBrNdY/background-img.jpg);
box-shadow: inset 0 0 0 9000em rgba(68, 68, 68, 0.5);
background-size: cover;
height: 50vh; /* change later for media queries */
}
/* title style */
h1#large-screen-title {
color: goldenrod;
text-align: center;
padding: 0.5em;
font-size: 4em;
}
div#top-bar {
background-color: rgb(255, 250, 234);
height: min-content;
}
.fix {
position: fixed;
height: 15%;
right: 0;
left: 0;
top: 0;
box-shadow: 0 0 20px goldenrod;
}
img#odin-logo {
height: 5em;
}
i.fa-thumbtack {
float: right;
padding: 1em;
}
i.fa-thumbtack:hover {
cursor: pointer;
}
@media only screen and (min-width: 700px) {
div#banner {
height: 80vh;
}
h1#title-index {
height: 60vh;
color: transparent;
border: 0px solid white;
}
div#top-bar {
text-align: center;
}
}
/* recipe card styles */
div#recipe-card-container {
padding-top: 5em;
padding-left: 0.5em;
padding-right: 0.5em;
display: grid;
grid-template-columns: 1fr;
justify-content: center;
align-items: center;
gap: 2em;
}
/*each recipe card */
div#recipe-card-container > div.each-recipe {
display: grid;
gap: 2em;
margin-bottom: 5em;
justify-content: center;
}
div#recipe-card-container div.recipe-img {
/* background-color: red; */
width: 100%;
height: 50vh;
border-radius: 3px;
transition: 450ms;
}
/*recipe link within each card */
div.recipe-link {
background-color: lightgray;
text-align: center;
padding-top: 1em;
padding: 0.5em;
transition: 450ms;
border-radius: 0.3em;
}
div.recipe-link:hover {
background-color: #eece1a;
transition: 450ms;
}
/* when clicked add this style */
.click {
background-color: #eece1a;
text-align: center;
padding-top: 1em;
padding: 0.5em;
border-radius: 0.3em;
transition: 450ms;
width: 100%;
margin: 0 auto;
}
/**/
i.fa-link {
float: left;
}
div.recipe-link:hover > i.fa-link {
color: rgb(0, 0, 255, 0.5);
}
/*when clicked, target i.fa-link color */
.white-link {
color: white;
}
.blue-link {
color: rgb(0, 0, 255, 0.5);
}
/* food image style on card */
.food-img {
height: 100%;
border-radius: 50%;
border: 4px solid rgba(189, 80, 12, 0.637);
transition: 450ms;
cursor: pointer;
}
img.food-img {
width: 100%;
}
img.food-hover:hover,
.active {
box-shadow: 0 0 20px rgb(189, 80, 12);
height: 105%;
object-fit: cover;
border-radius: 50%;
border: 4px solid rgba(189, 80, 12, 0.637);
transition: 450ms;
cursor: pointer;
}
/*grey bar with copyright*/
div.copy {
background-color: rgba(0, 0, 0, 0.54);
margin-top: 2em;
padding: 2em;
color: white;
text-align: center;
}
@media only screen and (min-width: 1020px) {
div#recipe-card-container {
padding-left: 0;
padding-right: 0;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
gap: 2em;
margin-top: 2em;
box-shadow: inset 0 500px rgb(85, 63, 63);
}
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../style.css" />
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Odin Recipes</title>
</head>
<body>
<div id="banner">
<div id="top-bar" class="fix">
<a href="https://www.theodinproject.com/"
><img src="https://i.ibb.co/7nhgfNJ/odin-logo.png" alt="" id="odin-logo"
/></a>
<i class="fa-solid fa-thumbtack"></i>
</div>
</div>
<br />
<br />
<hr />
<h1 id="large-screen-title">Odin Recipes</h1>
<br /><br />
<hr />
<div id="recipe-card-container">
<div class="each-recipe">
<div class="recipe-img">
<img
src="https://i.ibb.co/mDCCZTW/pizza.jpg"
alt=""
class="food-img food-hover"
/>
</div>
<a href="/recipes/pizza.html">
<div class="recipe-link recipeLink">
<i class="fa-solid fa-link white-link"></i>Click here for Pizza
Recipe
</div>
</a>
</div>
<div class="each-recipe">
<div class="recipe-img">
<img src="https://i.ibb.co/5cQCFWP/pavlova.png" alt="" class="food-img food-hover"/>
</div>
<a href="/recipes/pavlova.html">
<div class="recipe-link recipeLink">
<i class="fa-solid fa-link white-link"></i>Click here for Pavlova Recipe
</div>
</a>
</div>
<div class="each-recipe">
<div class="recipe-img">
<img
src="/recipes/images/"
alt=""
class="food-img food-hover"
/>
</div>
<a href="/recipes/">
<div class="recipe-link recipeLink">
<i class="fa-solid fa-link white-link"></i>Click here for Pavlova
Recipe
</div>
</a>
</div>
</div>
<div class="copy">Copyright © 2022</div>
<script
src="https://kit.fontawesome.com/fb94170dc7.js"
crossorigin="anonymous"
></script>
<script src="app.js"></script>
</body>
</html>
``` | It finally worked!
```js
// const theFoodImg = document.querySelector('.food-img');
// const recipeLink = document.querySelector('.recipe-link');
// const linkIcon = document.querySelector('.fa-link');
const pinTopBar = document.querySelector('.fa-thumbtack');
const topBar = document.querySelector('#top-bar');
const pinColor = document.querySelector('.fa-thumbtack');
// theFoodImg.addEventListener('click', function() {
// if(theFoodImg.classList.contains('active')){
// theFoodImg.classList.remove('active');
// theFoodImg.classList.remove('food-hover');
// theFoodImg.classList.add('food-img');
// recipeLink.classList.add('recipe-link');
// recipeLink.classList.remove('click');
// linkIcon.classList.add('white-link')
// linkIcon.classList.remove('blue-link')
// } else {
// theFoodImg.classList.remove('food-img');
// theFoodImg.classList.add('active');
// recipeLink.classList.remove('recipe-link');
// recipeLink.classList.add('click');
// linkIcon.classList.remove('white-link');
// linkIcon.classList.add('blue-link');
// }
// })
// theFoodImg.addEventListener('mouseenter', function(){
// if (theFoodImg.classList.contains('active') !== true) {
// theFoodImg.classList.add('food-hover');
// }
// })
if(topBar.classList.contains('fix')) {
pinColor.style.color = 'goldenrod';
}
pinTopBar.addEventListener('click', function() {
if(topBar.classList.contains('fix') !== true) {
topBar.classList.add('fix');
pinColor.style.color = 'goldenrod';
}
else {
topBar.classList.remove('fix');
pinColor.style.color = 'black';
}
})
const recipeContainer = document.querySelector('div#recipe-card-container');
const linkIcon = document.querySelectorAll('.fa-link');
recipeContainer.addEventListener('click',function(event){
if(event.target.classList.contains('food-img') || event.target.classList.contains('food-hover')){
if(event.target.classList.contains('active')==false) {
event.target.classList.remove('food-img');
event.target.classList.add('active');
const recipeImg = event.target.parentElement;
const aTag = recipeImg.nextElementSibling;
const recipeLink = aTag.firstElementChild;
const linkIcon = recipeLink.firstElementChild;
recipeLink.classList.remove('recipe-link');
recipeLink.classList.add('click');
linkIcon.classList.remove('white-link');
linkIcon.classList.add('blue-link');
if(!event.target.classList.contains('food-hover')){
event.target.classList.add('food-hover');
}
} else {
event.target.classList.remove('active');
event.target.classList.remove('food-hover');
event.target.classList.add('food-img');
const recipeImg = event.target.parentElement;
const aTag = recipeImg.nextElementSibling;
const recipeLink = aTag.firstElementChild;
const linkIcon = recipeLink.firstElementChild;
linkIcon.classList.add('white-link');
linkIcon.classList.remove('blue-link');
recipeLink.classList.add('recipe-link');
recipeLink.classList.remove('click');
}
}
})
```
```css
/* css reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
text-decoration: none;
}
body {
margin: 0;
padding: 0;
}
a {
color: black;
text-decoration: none;
}
hr {
width: 80%;
margin: 0 auto;
background-color: black;
box-shadow: 0 0 15px gold;
}
/* banner and title styles */
div#banner {
background: url(https://i.ibb.co/MgBrNdY/background-img.jpg);
box-shadow: inset 0 0 0 9000em rgba(68, 68, 68, 0.5);
background-size: cover;
height: 50vh; /* change later for media queries */
}
/* title style */
h1#large-screen-title {
color: goldenrod;
text-align: center;
padding: 0.5em;
font-size: 4em;
}
div#top-bar {
background-color: rgb(255, 250, 234);
height: min-content;
}
.fix {
position: fixed;
height: 15%;
right: 0;
left: 0;
top: 0;
box-shadow: 0 0 20px goldenrod;
}
img#odin-logo {
height: 5em;
}
i.fa-thumbtack {
float: right;
padding: 1em;
}
i.fa-thumbtack:hover {
cursor: pointer;
}
@media only screen and (min-width: 700px) {
div#banner {
height: 80vh;
}
h1#title-index {
height: 60vh;
color: transparent;
border: 0px solid white;
}
div#top-bar {
text-align: center;
}
}
/* recipe card styles */
div#recipe-card-container {
padding-top: 5em;
padding-left: 0.5em;
padding-right: 0.5em;
display: grid;
grid-template-columns: 1fr;
justify-content: center;
align-items: center;
gap: 2em;
}
/*each recipe card */
div#recipe-card-container > div.each-recipe {
display: grid;
gap: 2em;
margin-bottom: 5em;
justify-content: center;
}
div#recipe-card-container div.recipe-img {
/* background-color: red; */
width: 100%;
height: 45vh;
border-radius: 3px;
transition: 450ms;
}
/*recipe link within each card */
div.recipe-link {
background-color: lightgray;
text-align: center;
padding-top: 1em;
padding: 0.5em;
transition: 450ms;
border-radius: 0.3em;
width: 100%;
margin: 0 auto;
}
div.recipe-link:hover {
background-color: #eece1a;
transition: 450ms;
}
/* when clicked add this style */
.click {
background-color: #eece1a;
text-align: center;
padding-top: 1em;
padding: 0.5em;
border-radius: 0.3em;
transition: 450ms;
width: 100%;
margin: 0 auto;
}
/**/
i.fa-link {
float: left;
}
div.recipe-link:hover > i.fa-link {
color: rgb(0, 0, 255, 0.5);
}
/*when clicked, target i.fa-link color */
.white-link {
color: white;
}
.blue-link {
color: rgb(0, 0, 255, 0.5);
}
/* food image style on card */
.food-img {
height: 100%;
border-radius: 50%;
border: 4px solid rgba(189, 80, 12, 0.637);
transition: 450ms;
cursor: pointer;
}
img.food-img {
width: 100%;
}
img.food-hover {
box-shadow: 0 0 20px #eee;
}
img.food-img:hover,
.active {
box-shadow: 0 0 20px rgb(189, 80, 12);
height: 105%;
object-fit: cover;
border-radius: 50%;
border: 4px solid rgba(189, 80, 12, 0.637);
transition: 450ms;
cursor: pointer;
}
/*grey bar with copyright*/
div.copy {
background-color: rgba(0, 0, 0, 0.54);
margin-top: 30vh;
padding: 2em;
color: white;
text-align: center;
}
@media only screen and (min-width: 1020px) {
div#recipe-card-container {
padding-left: 0;
padding-right: 0;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
gap: 2em;
margin-top: 2em;
box-shadow: inset 0 700px rgb(85, 63, 63);
}
}
@media only screen and (max-width: 720px) {
div#recipe-card-container div.recipe-img {
width: 100%;
height: 30vh;
border-radius: 3px;
object-fit: cover;
}
.food-img {
height: 30vh;
border-radius: 20px;
border: 4px solid rgba(189, 80, 12, 0.637);
cursor: pointer;
object-fit: cover;
}
img.food-hover:hover,
.active {
box-shadow: 0 0 20px rgb(189, 80, 12);
height: 32vh;
object-fit: cover;
border-radius: 20px;
border: 4px solid rgba(189, 80, 12, 0.637);
cursor: pointer;
}
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../style.css" />
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Odin Recipes</title>
</head>
<body>
<div id="banner">
<div id="top-bar" class="fix">
<a href="https://www.theodinproject.com/"
><img src="https://i.ibb.co/7nhgfNJ/odin-logo.png" alt="" id="odin-logo"
/></a>
<i class="fa-solid fa-thumbtack"></i>
</div>
</div>
<br />
<br />
<hr />
<h1 id="large-screen-title">Odin Recipes</h1>
<br /><br />
<hr />
<div id="recipe-card-container">
<div class="each-recipe">
<div class="recipe-img">
<img src="https://i.ibb.co/mDCCZTW/pizza.jpg" alt="" class="food-img" />
</div>
<a href="/recipes/pizza.html">
<div class="recipe-link">
<i class="fa-solid fa-link white-link"></i>Click here for Pizza
Recipe
</div>
</a>
</div>
<div class="each-recipe">
<div class="recipe-img">
<img src="https://i.ibb.co/5cQCFWP/pavlova.png" alt="" class="food-img" />
</div>
<a href="/recipes/pavlova.html">
<div class="recipe-link">
<i class="fa-solid fa-link white-link"></i>Click here for Pavlova
Recipe
</div>
</a>
</div>
<div class="each-recipe">
<div class="recipe-img">
<img src="/recipes/images/" alt="" class="food-img" />
</div>
<a href="/recipes/">
<div class="recipe-link">
<i class="fa-solid fa-link white-link"></i>Click here for Pavlova
Recipe
</div>
</a>
</div>
</div>
<div class="copy">Copyright © 2022</div>
<script
src="https://kit.fontawesome.com/fb94170dc7.js"
crossorigin="anonymous"
></script>
<script src="app.js"></script>
</body>
</html>
``` |
3,720,428 | I use the built in `json` for python 2.6. I'm having tons of trouble parsing jsons like this:
```
{
name: 'some name'
value: 'some value'
}
```
I found two reasons -
1. `'` doesn't work. You need `"`
2. the keys of the dictionary need to be strings. I.e `"name"`/`"value"`
Am I missing something? Is there a way to parse this kind of dictionary using the `json` package? Is there any other python package that can parse this?
Thanks | 2010/09/15 | [
"https://Stackoverflow.com/questions/3720428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170713/"
] | I think that what you want is not a "stronger" parser but a broken parser that will parse broken code. See [the standard](http://www.json.org/)
specifically,
* The keys of an object are defined to be strings
* Strings are defined to be "" or "chars" where chars has the pretty much obvious meaning
There's someplace on the internet where you can watch Douglass Crockford make semi-witty remarks about why this is the case. It has to do with compatibility with non-javascript languages though. Specifically, you could not have
```
{name :'some name', value: 'some value'}
```
as a dict in python unless `name` and `some value` where preexisting, hashable variables;
Broken parsers in general are bad. Just look at the mess that broken HTML parsers in browsers have created where any idiot can make a web site. That dude that wrote all those RFC's had it wrong: It's better to be strict in what you emit **and** what you accept. | There are:
* [simplejson](http://pypi.python.org/pypi/simplejson/), which is "is the externally maintained development version of the json library included with Python 2.6 and Python 3.0, but maintains backwards compatibility with Python 2.5."
* [cjson](http://pypi.python.org/pypi/python-cjson)
(Not sure if they'll parse broken JSON.) |
3,720,428 | I use the built in `json` for python 2.6. I'm having tons of trouble parsing jsons like this:
```
{
name: 'some name'
value: 'some value'
}
```
I found two reasons -
1. `'` doesn't work. You need `"`
2. the keys of the dictionary need to be strings. I.e `"name"`/`"value"`
Am I missing something? Is there a way to parse this kind of dictionary using the `json` package? Is there any other python package that can parse this?
Thanks | 2010/09/15 | [
"https://Stackoverflow.com/questions/3720428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170713/"
] | I think that what you want is not a "stronger" parser but a broken parser that will parse broken code. See [the standard](http://www.json.org/)
specifically,
* The keys of an object are defined to be strings
* Strings are defined to be "" or "chars" where chars has the pretty much obvious meaning
There's someplace on the internet where you can watch Douglass Crockford make semi-witty remarks about why this is the case. It has to do with compatibility with non-javascript languages though. Specifically, you could not have
```
{name :'some name', value: 'some value'}
```
as a dict in python unless `name` and `some value` where preexisting, hashable variables;
Broken parsers in general are bad. Just look at the mess that broken HTML parsers in browsers have created where any idiot can make a web site. That dude that wrote all those RFC's had it wrong: It's better to be strict in what you emit **and** what you accept. | The problem is not with the Python module, the problem is with your string, which could be whatever you say, but not JSON, so it cannot be parsed by a JSON parser.
If it were JSON it would look like:
```
{"name":"some name", "value":"some value"}
```
So, it is not a problem with the Python module. It is like asking for a "stronger python compiler" because C-Python cannot parse:
```
using json
json.loads(my_string)
```
Obviously the first line is simply **not Python**, so we cannot ask Python to interpret it.
Now if you want to parse that string I recommend that you either: make it a JSON string OR use [Pyparsing](http://pyparsing.wikispaces.com/) for writing a quick and dirty parser (I guarantee it will work great in less than, say, 50 lines).
Cheers,
Juan. |
3,720,428 | I use the built in `json` for python 2.6. I'm having tons of trouble parsing jsons like this:
```
{
name: 'some name'
value: 'some value'
}
```
I found two reasons -
1. `'` doesn't work. You need `"`
2. the keys of the dictionary need to be strings. I.e `"name"`/`"value"`
Am I missing something? Is there a way to parse this kind of dictionary using the `json` package? Is there any other python package that can parse this?
Thanks | 2010/09/15 | [
"https://Stackoverflow.com/questions/3720428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170713/"
] | The problem is not with the Python module, the problem is with your string, which could be whatever you say, but not JSON, so it cannot be parsed by a JSON parser.
If it were JSON it would look like:
```
{"name":"some name", "value":"some value"}
```
So, it is not a problem with the Python module. It is like asking for a "stronger python compiler" because C-Python cannot parse:
```
using json
json.loads(my_string)
```
Obviously the first line is simply **not Python**, so we cannot ask Python to interpret it.
Now if you want to parse that string I recommend that you either: make it a JSON string OR use [Pyparsing](http://pyparsing.wikispaces.com/) for writing a quick and dirty parser (I guarantee it will work great in less than, say, 50 lines).
Cheers,
Juan. | There are:
* [simplejson](http://pypi.python.org/pypi/simplejson/), which is "is the externally maintained development version of the json library included with Python 2.6 and Python 3.0, but maintains backwards compatibility with Python 2.5."
* [cjson](http://pypi.python.org/pypi/python-cjson)
(Not sure if they'll parse broken JSON.) |
72,284,019 | I need to make a presentation with Python3. I know the basics of Kivy and I am pretty good with Python. I just wanted know how to put lots of text in one label, for example: a whole paragraph of text. I have tried it by just putting the text in the label But this happens.
[THIS](https://i.stack.imgur.com/C1wrT.png)
It just becomes one line along the whole window. So I wanted to make it appear in a paragraph. Also, if the code that is needed to fill my requirements in .kv file format, it will be very much appreciated. If thats not possible, its also okay in the .py file format.
I will add the code here:
***.py file:***
```
#!/usr/bin/env python3
import sys
from kivy.app import App
from kivy.metrics import dp
from kivy.properties import StringProperty
from kivy.uix.widget import Widget
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button
import kivy.resources
if getattr(sys, 'frozen', False):
kivy.resources.resource_add_path(sys._MEIPASS)
class TaneMahuta(App):
pass
TaneMahuta().run()
```
***.kv file:***
```
Box:
<Box@BoxLayout>:
Label:
text: "Tāne Mahuta is one of the six kids that were born to Papatūānuku and Ranginui. Tāne is an vital character in the Māori culture because his job is to maintain the greenery and life on the earth. The forests he looks after are essential sources of food, places to live, and much more. He is the god of most natural creatures. In stories, he is very confident, persistent and resilient. He is also the one that separated Ranginui and Papatūānuku to let in light. Even the largest tree in NZ is named after him = Tāne Mahuta. The tree, Tāne Mahuta, has some of the attributes of Tāne Mahuta (atua). It is a symbol of strength and stature."
``` | 2022/05/18 | [
"https://Stackoverflow.com/questions/72284019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17671039/"
] | Try for testing
```
if: steps.projectcheck.outputs.central == 'true'
```
Ìf `steps.projectcheck.outputs.central` is a [string literal](https://docs.github.com/en/actions/learn-github-actions/expressions#literals), you should not need `${{ }}` | I recommend to look into [expressions in GitHub actions](https://docs.github.com/en/actions/learn-github-actions/expressions)
`if` conditional is treated as an expression, hence no explicit `${{ <expression> }}` is needed and you can write it like [VonC](https://stackoverflow.com/users/6309/vonc) mentioned.
But it's a good rule of thumb to use expressions everywhere, I'd recommend writing it like this:
```yaml
if: ${{ steps.projectcheck.outputs.central == "true" }}
``` |
70,364,727 | hopefully i can explain right what i am trying to do. I want to check if variables giving from a list, exists in OS, if so, use the same OS variable name and value in python.
This is how am i doing it right now but i think it is a lot of code and if want more os variables i would be bigger. So what could be a good starting to do this smarter and more efficient?
OS (linux) variables
```sh
export WEB_URL="https://google.com"
export WEB_USERNAME="Foo"
export WEB_PASSWORD="Bar"
```
```py
# Check os env variables
if "WEB_URL" in os.environ:
web_url = os.environ.get("WEB_URL")
else:
logger.error("No URL os env find please check")
if "WEB_USERNAME" in os.environ:
web_username = os.environ.get("WEB_USERNAME")
else:
logger.error("No USERNAME os env find please check")
if "WEB_PASSWORD" in os.environ:
web_password = os.environ.get("WEB_PASSWORD")
else:
logger.error("No PASSWORD os env find please check")
```
must be somthing like this to start with?
```py
os_variables = ["WEB_URL", "WEB_USERNAME", "WEB_PASSWORD"]
for var in os_variables:
if var in os.environ:
print(var.lower(), "=", os.environ.get(f"{var}"))
```
result:
```
web_url = https://google.com
web_username = Foo
web_password = Bar
```
so what is printed here above should literally be the variable, just to show what i mean | 2021/12/15 | [
"https://Stackoverflow.com/questions/70364727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14923537/"
] | as a compromise I finally came up with this as a solution
```py
env_variables = ('WEB_URL', 'WEB_USERNAME', 'WEB_PASSWORD')
def check_env(var):
for var in env_variables:
if var in os.environ:
if os.environ[var] == "":
logging.error(f'{var} is empty, please set a value')
sys.exit()
else:
logging.error(
f'{var} does not exist, please setup this env variable')
sys.exit()
check_env(env_variables)
``` | If I understand your problem correctly you will need to make use of [eval()](https://realpython.com/python-eval-function/) and [exec()](https://docs.python.org/3/library/functions.html#exec). Maybe something along those lines:
```
exec(str(eval(var.lower(), "=", "'", os.environ.get(f"{var}")"'")))
```
Evaluating first should give you something like `web_url = 'https://google.com'`. If this is turned into a string it can be executed, but be careful with global and local variables in this case. |
31,471,751 | I would like to install netcdf4-python to my Ubuntu14.04. The libhdf5-dev\_1.8.11\_5ubuntu7\_amd64.deb and libnetcdf-4.1.3-7ubuntu2\_amd64.deb are installed. I downloaded netcdf4-1.1.8.tar.gz from <https://pypi.python.org/pypi/netCDF4#downloads>
I tried configure it by
```
./configure --enable-netcdf-4 –with-hdf5=/usr/include/ --enable-share –prefix=/usr
```
but I got the following message:
```
bash: ./configure: No such file or directory
```
I do not know how I can install netcdf4-python.
I would appreciated if someone helped me. | 2015/07/17 | [
"https://Stackoverflow.com/questions/31471751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4265720/"
] | The instructions for Ubuntu are [here](https://code.google.com/p/netcdf4-python/wiki/UbuntuInstall) which are basically:
**HDF5**
Download the current HDF5 source release.
Unpack, go into the directory and execute:
```
./configure --prefix=/usr/local --enable-shared --enable-hl
make
sudo make install
```
To speed things up, compile on more than one processor using
```
make -j n
```
where n is the number of processes to be launched.
**netCDF4**
e
Download the current netCDF4 source release.
Unpack, go into the directory and execute:
```
LDFLAGS=-L/usr/local/lib CPPFLAGS=-I/usr/local/include ./configure --enable-netcdf-4 --enable-dap --enable-shared --prefix=/usr/local
make
make install
```
Installing netcdf4-python
When both HDF5 and netCDF4 are in /usr/local, make sure the linker will be able to find those libraries by executing
```
sudo ldconfig
```
then installing netcdf4-python is just a matter of doing
```
python setup.py install
```
Make sure you actually **untar** the files and **cd** to the correct directories. | The netCDF4 python module documentation can be found [here](http://unidata.github.io/netcdf4-python/ "here"). Check out the "Install" section; it'll have what you're looking for. But, if you satisfy all of the pre-requisites you can simply do the following:
```
python setup.py build && python setup.py install
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.