qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
13,455,143
|
Having a class
```
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
```
Both methods (`Func1` and `Func2`) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address `z`.
The result of `Func*` would only differ if an instance would shadow `z` with something like `self.z = None`.
What is the proper python way to access the class variable `z` using the syntax of `Func1` or `Func2`?
|
2012/11/19
|
[
"https://Stackoverflow.com/questions/13455143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572616/"
] |
I would say that the proper way to get access to the variable is simply:
```
a_instance.z #instance variable 'z'
A.z #class variable 'z'
```
No need for `Func1` and `Func2` here.
---
As a side note, if you *must* write `Func2`, it seems like a `classmethod` might be appropriate:
```
@classmethod
def Func2(cls):
return cls.z
```
---
As a final note, which version you use within methods (`self.z` vs. `A.z` vs. `cls.z` with `classmethod`) really depends on how you want your API to behave. Do you want the user to be able to shadow `A.z` by setting an instance attribute `z`? If so, then use `self.z`. If you don't want that shadowing, you can use `A.z`. Does the method need `self`? If not, then it's probably a classmethod, etc.
|
I would usually use `self.z`, because in case there are subclasses with different values for `z` it will choose the "right" one. The only reason not to do that is if you know you will always want the `A` version notwithstanding.
Accessing via self or via a classmethod (see mgilson's answer) also facilitates the creating of mixin classes.
|
13,455,143
|
Having a class
```
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
```
Both methods (`Func1` and `Func2`) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address `z`.
The result of `Func*` would only differ if an instance would shadow `z` with something like `self.z = None`.
What is the proper python way to access the class variable `z` using the syntax of `Func1` or `Func2`?
|
2012/11/19
|
[
"https://Stackoverflow.com/questions/13455143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572616/"
] |
I would say that the proper way to get access to the variable is simply:
```
a_instance.z #instance variable 'z'
A.z #class variable 'z'
```
No need for `Func1` and `Func2` here.
---
As a side note, if you *must* write `Func2`, it seems like a `classmethod` might be appropriate:
```
@classmethod
def Func2(cls):
return cls.z
```
---
As a final note, which version you use within methods (`self.z` vs. `A.z` vs. `cls.z` with `classmethod`) really depends on how you want your API to behave. Do you want the user to be able to shadow `A.z` by setting an instance attribute `z`? If so, then use `self.z`. If you don't want that shadowing, you can use `A.z`. Does the method need `self`? If not, then it's probably a classmethod, etc.
|
If you don't care about value clobbering and things like that, you're fine with `self.z`. Otherwise, `A.z` will undoubtedly evaluate to the class variable. Beware, though, about what would happen if a subclass `B` redefines `z` but **not** `Func2`:
```
class B(A):
z = 7
b = B()
b.Func2() # Returns 0, not 7
```
Which is quite logical, after all. So, if you want to access a class variable in a, somehow, *polymorphic* way, you can just do one of the following:
```
self.__class__.z
type(self).z
```
[According to the documentation](http://docs.python.org/release/2.7.3/reference/datamodel.html#new-style-and-classic-classes), the second form does not work with old-style classes, so the first form is usually more comptaible across Python 2.x versions. However, the second form is the safest one for new-style classes and, thus, for Python 3.x, as classes may redefine the `__class__` attribute.
|
13,455,143
|
Having a class
```
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
```
Both methods (`Func1` and `Func2`) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address `z`.
The result of `Func*` would only differ if an instance would shadow `z` with something like `self.z = None`.
What is the proper python way to access the class variable `z` using the syntax of `Func1` or `Func2`?
|
2012/11/19
|
[
"https://Stackoverflow.com/questions/13455143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572616/"
] |
I would usually use `self.z`, because in case there are subclasses with different values for `z` it will choose the "right" one. The only reason not to do that is if you know you will always want the `A` version notwithstanding.
Accessing via self or via a classmethod (see mgilson's answer) also facilitates the creating of mixin classes.
|
If you don't care about value clobbering and things like that, you're fine with `self.z`. Otherwise, `A.z` will undoubtedly evaluate to the class variable. Beware, though, about what would happen if a subclass `B` redefines `z` but **not** `Func2`:
```
class B(A):
z = 7
b = B()
b.Func2() # Returns 0, not 7
```
Which is quite logical, after all. So, if you want to access a class variable in a, somehow, *polymorphic* way, you can just do one of the following:
```
self.__class__.z
type(self).z
```
[According to the documentation](http://docs.python.org/release/2.7.3/reference/datamodel.html#new-style-and-classic-classes), the second form does not work with old-style classes, so the first form is usually more comptaible across Python 2.x versions. However, the second form is the safest one for new-style classes and, thus, for Python 3.x, as classes may redefine the `__class__` attribute.
|
64,996,663
|
I was testing this function on some sample text file to make sure it is working as expected.
```
#include <stdio.h>
#include <time.h>
#define BUF 100
int main(){
FILE *fp = fopen("my_huge_file.txt","r");
char str[BUF];
int count=0;
while( (fgets(str, BUF, fp)) != NULL ){
for (int i = 0; i<BUF;i++){
if (str[i] == 'A')
count++;
}
}
printf("We had %d \'A\'s\n",count);
}
```
Running this using `time ./a.out` prints:
>
>
> ```
> We had 420538682 'A's
>
> real 0m31.267s
> user 0m28.590s
> sys 0m2.531s
>
> ```
>
>
I then used `time tr -cd A < my_huge_file.txt | wc -c` and got back:
>
>
> ```
> 420538233
>
> real 0m13.611s
> user 0m10.688s
> sys 0m3.297s
>
> ```
>
>
I also used python's count method `time count.py`:
```
c = 0
with open("my_huge_file.txt", 'r') as fp:
for line in fp:
c += line.count('A')
print(c)
```
>
>
> ```
> 420538233
>
> real 0m33.073s
> user 0m30.232s
> sys 0m2.650s
>
> ```
>
>
I am not sure how to investigate this discrepancy. tr and python's count are returning 420538233. The C function returns 420538682.
|
2020/11/25
|
[
"https://Stackoverflow.com/questions/64996663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549160/"
] |
This issue is because your pipeline agent does not have Java 11 pre-installed in it.
You have two options to solve this issue.
**Option 1:** Change the pipeline agent to an agent which does have Java 11 pre-installed.
If you are using Microsoft-hosted pipeline agents, you can use this link to check which all agents have Java 11 pre-installed: [Microsoft-hosted agents](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops&tabs=yaml)
**Option 2:** Install the Java 11 JDK in your existing pipeline agent.
You can use the [Java Tool Installer](https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/tool/java-tool-installer?view=azure-devops) task to install any Java version on your existing pipeline.
|
Perhaps the JDK running in your pipeline is, say, version 8. In that case, the Java compiler that is executed doesn't understand what version 11 means. Perhaps your local environment is using Java 11 where this problem would therefore not happen.
|
64,996,663
|
I was testing this function on some sample text file to make sure it is working as expected.
```
#include <stdio.h>
#include <time.h>
#define BUF 100
int main(){
FILE *fp = fopen("my_huge_file.txt","r");
char str[BUF];
int count=0;
while( (fgets(str, BUF, fp)) != NULL ){
for (int i = 0; i<BUF;i++){
if (str[i] == 'A')
count++;
}
}
printf("We had %d \'A\'s\n",count);
}
```
Running this using `time ./a.out` prints:
>
>
> ```
> We had 420538682 'A's
>
> real 0m31.267s
> user 0m28.590s
> sys 0m2.531s
>
> ```
>
>
I then used `time tr -cd A < my_huge_file.txt | wc -c` and got back:
>
>
> ```
> 420538233
>
> real 0m13.611s
> user 0m10.688s
> sys 0m3.297s
>
> ```
>
>
I also used python's count method `time count.py`:
```
c = 0
with open("my_huge_file.txt", 'r') as fp:
for line in fp:
c += line.count('A')
print(c)
```
>
>
> ```
> 420538233
>
> real 0m33.073s
> user 0m30.232s
> sys 0m2.650s
>
> ```
>
>
I am not sure how to investigate this discrepancy. tr and python's count are returning 420538233. The C function returns 420538682.
|
2020/11/25
|
[
"https://Stackoverflow.com/questions/64996663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549160/"
] |
This issue is because your pipeline agent does not have Java 11 pre-installed in it.
You have two options to solve this issue.
**Option 1:** Change the pipeline agent to an agent which does have Java 11 pre-installed.
If you are using Microsoft-hosted pipeline agents, you can use this link to check which all agents have Java 11 pre-installed: [Microsoft-hosted agents](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops&tabs=yaml)
**Option 2:** Install the Java 11 JDK in your existing pipeline agent.
You can use the [Java Tool Installer](https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/tool/java-tool-installer?view=azure-devops) task to install any Java version on your existing pipeline.
|
I had the same problem. You need to specify the jdk version in the pipeline .yaml-file:
>
> To build with Maven, add the following snippet to your
> azure-pipelines.yml file. Change values, such as the path to your
> pom.xml file, to match your project configuration. See the Maven task
> for more about these options.
>
>
>
```
steps:
- task: Maven@3 inputs:
mavenPomFile: 'pom.xml'
mavenOptions: '-Xmx3072m'
javaHomeOption: 'JDKVersion'
jdkVersionOption: '1.11'
jdkArchitectureOption: 'x64'
publishJUnitResults: false
testResultsFiles: '**/TEST-*.xml'
goals: 'package'
```
<https://learn.microsoft.com/en-us/azure/devops/pipelines/ecosystems/java?view=azure-devops#maven>
|
64,996,663
|
I was testing this function on some sample text file to make sure it is working as expected.
```
#include <stdio.h>
#include <time.h>
#define BUF 100
int main(){
FILE *fp = fopen("my_huge_file.txt","r");
char str[BUF];
int count=0;
while( (fgets(str, BUF, fp)) != NULL ){
for (int i = 0; i<BUF;i++){
if (str[i] == 'A')
count++;
}
}
printf("We had %d \'A\'s\n",count);
}
```
Running this using `time ./a.out` prints:
>
>
> ```
> We had 420538682 'A's
>
> real 0m31.267s
> user 0m28.590s
> sys 0m2.531s
>
> ```
>
>
I then used `time tr -cd A < my_huge_file.txt | wc -c` and got back:
>
>
> ```
> 420538233
>
> real 0m13.611s
> user 0m10.688s
> sys 0m3.297s
>
> ```
>
>
I also used python's count method `time count.py`:
```
c = 0
with open("my_huge_file.txt", 'r') as fp:
for line in fp:
c += line.count('A')
print(c)
```
>
>
> ```
> 420538233
>
> real 0m33.073s
> user 0m30.232s
> sys 0m2.650s
>
> ```
>
>
I am not sure how to investigate this discrepancy. tr and python's count are returning 420538233. The C function returns 420538682.
|
2020/11/25
|
[
"https://Stackoverflow.com/questions/64996663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549160/"
] |
This issue is because your pipeline agent does not have Java 11 pre-installed in it.
You have two options to solve this issue.
**Option 1:** Change the pipeline agent to an agent which does have Java 11 pre-installed.
If you are using Microsoft-hosted pipeline agents, you can use this link to check which all agents have Java 11 pre-installed: [Microsoft-hosted agents](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops&tabs=yaml)
**Option 2:** Install the Java 11 JDK in your existing pipeline agent.
You can use the [Java Tool Installer](https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/tool/java-tool-installer?view=azure-devops) task to install any Java version on your existing pipeline.
|
I solved this problem by adding a new file **system.properties** and the content added to the file is **java.runtime.version=11**.
```
java.runtime.version=11
```
|
58,167,766
|
I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*?
|
2019/09/30
|
[
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] |
It just means when the match is “” or an empty string, that it is included in the list of results.
|
If a subject is an empty string then fullmatch() evaluates to True for any regex that can find a ... The overall regex match is not included in the tuple, unless you place the entire ... appear in the regular expression, as raw strings do not offer a means to escape it.
|
58,167,766
|
I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*?
|
2019/09/30
|
[
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] |
This happen when you use groups that matches empty string , example:
```
print(re.findall(r'(\w)(\d?)(\w)', "bc"))
```
OUPUT:
```
[('b', '', 'c')]
```
Here group `(\d?)` matches `''` and is included in the result.
|
It just means when the match is “” or an empty string, that it is included in the list of results.
|
58,167,766
|
I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*?
|
2019/09/30
|
[
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] |
This happen when you use groups that matches empty string , example:
```
print(re.findall(r'(\w)(\d?)(\w)', "bc"))
```
OUPUT:
```
[('b', '', 'c')]
```
Here group `(\d?)` matches `''` and is included in the result.
|
If a subject is an empty string then fullmatch() evaluates to True for any regex that can find a ... The overall regex match is not included in the tuple, unless you place the entire ... appear in the regular expression, as raw strings do not offer a means to escape it.
|
58,167,766
|
I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*?
|
2019/09/30
|
[
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] |
Zero-length matches, or empty matches.
A Regular Expression is made of boundaries definitions, or anchors, for instance the operator `^`. Once the anchor is hit, you have a match, which can be "empty", that is immediately followed by another anchor.
|
If a subject is an empty string then fullmatch() evaluates to True for any regex that can find a ... The overall regex match is not included in the tuple, unless you place the entire ... appear in the regular expression, as raw strings do not offer a means to escape it.
|
58,167,766
|
I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*?
|
2019/09/30
|
[
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] |
This happen when you use groups that matches empty string , example:
```
print(re.findall(r'(\w)(\d?)(\w)', "bc"))
```
OUPUT:
```
[('b', '', 'c')]
```
Here group `(\d?)` matches `''` and is included in the result.
|
Zero-length matches, or empty matches.
A Regular Expression is made of boundaries definitions, or anchors, for instance the operator `^`. Once the anchor is hit, you have a match, which can be "empty", that is immediately followed by another anchor.
|
62,684,468
|
I'm working on an automated web scraper for a Restaurant website, but I'm having an issue. The said website uses Cloudflare's anti-bot security, which I would like to bypass, not the Under-Attack-Mode but a captcha test that only triggers when it detects a non-American IP or a bot. I'm trying to bypass it as Cloudflare's security doesn't trigger when I clear cookies, disable javascript or when I use an American proxy.
Knowing this, I tried using python's requests library as such:
```
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'}
response = requests.get("https://grimaldis.myguestaccount.com/guest/accountlogin", headers=headers).text
print(response)
```
But this ends up triggering Cloudflare, no matter the proxy I use.
**HOWEVER** when using urllib.request with the same headers as such:
```
import urllib.request
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'}
request = urllib.request.Request("https://grimaldis.myguestaccount.com/guest/accountlogin", headers=headers)
r = urllib.request.urlopen(request).read()
print(r.decode('utf-8'))
```
When run with the same American IP, this time it does not trigger Cloudflare's security, even though it uses the same headers and IP used with the requests library.
So I'm trying to figure out what exactly is triggering Cloudflare in the requests library that isn't in the urllib library.
While the typical answer would be "Just use urllib then", I'd like to figure out what exactly is different with requests, and how I could fix it, first off to understand how requests works and Cloudflare detects bots, but also so that I may apply any fix I can find to other httplibs (notably asynchronous ones)
**EDIT N°2: Progress so far:**
Thanks to @TuanGeek we can now bypass the Cloudflare block using requests as long as we connect directly to the host IP rather than the domain name (for some reason, the DNS redirection with requests triggers Cloudflare, but urllib doesn't):
```
import requests
from collections import OrderedDict
import socket
# grab the address using socket.getaddrinfo
answers = socket.getaddrinfo('grimaldis.myguestaccount.com', 443)
(family, type, proto, canonname, (address, port)) = answers[0]
headers = OrderedDict({
'Host': "grimaldis.myguestaccount.com",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
})
s = requests.Session()
s.headers = headers
response = s.get(f"https://{address}/guest/accountlogin", verify=False).text
```
To note: trying to access via HTTP (rather than HTTPS with the verify variable set to False) will trigger Cloudflare's block
Now this is great, but unfortunately, my final goal of making this work asynchronously with the httplib HTTPX still isn't met, as using the following code, the Cloudflare block is still triggered even though we're connecting directly through the Host IP, with proper headers, and with verifying set to False:
```
import trio
import httpx
import socket
from collections import OrderedDict
answers = socket.getaddrinfo('grimaldis.myguestaccount.com', 443)
(family, type, proto, canonname, (address, port)) = answers[0]
headers = OrderedDict({
'Host': "grimaldis.myguestaccount.com",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
})
async def asks_worker():
async with httpx.AsyncClient(headers=headers, verify=False) as s:
r = await s.get(f'https://{address}/guest/accountlogin')
print(r.text)
async def run_task():
async with trio.open_nursery() as nursery:
nursery.start_soon(asks_worker)
trio.run(run_task)
```
**EDIT N°1: For additional details, here's the raw HTTP request from urllib and requests**
REQUESTS:
```
send: b'GET /guest/nologin/account-balance HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: grimaldis.myguestaccount.com\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0\r\nConnection: close\r\n\r\n'
reply: 'HTTP/1.1 403 Forbidden\r\n'
header: Date: Thu, 02 Jul 2020 20:20:06 GMT
header: Content-Type: text/html; charset=UTF-8
header: Transfer-Encoding: chunked
header: Connection: close
header: CF-Chl-Bypass: 1
header: Set-Cookie: __cfduid=df8902e0b19c21b364f3bf33e0b1ce1981593721256; expires=Sat, 01-Aug-20 20:20:06 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Cache-Control: private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0
header: Expires: Thu, 01 Jan 1970 00:00:01 GMT
header: X-Frame-Options: SAMEORIGIN
header: cf-request-id: 03b2c8d09300000ca181928200000001
header: Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
header: Set-Cookie: __cfduid=df8962e1b27c25b364f3bf66e8b1ce1981593723206; expires=Sat, 01-Aug-20 20:20:06 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Vary: Accept-Encoding
header: Server: cloudflare
header: CF-RAY: 5acb25c75c981ca1-EWR
```
URLLIB:
```
send: b'GET /guest/nologin/account-balance HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: grimaldis.myguestaccount.com\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0\r\nConnection: close\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Thu, 02 Jul 2020 20:20:01 GMT
header: Content-Type: text/html;charset=utf-8
header: Transfer-Encoding: chunked
header: Connection: close
header: Set-Cookie: __cfduid=db9de9687b6c22e6c12b33250a0ded3251292457801; expires=Sat, 01-Aug-20 20:20:01 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Expires: Thu, 2 Jul 2020 20:20:01 GMT
header: Cache-Control: no-cache, private, no-store
header: X-Powered-By: Undertow/1
header: Pragma: no-cache
header: X-Frame-Options: SAMEORIGIN
header: Content-Security-Policy: script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.google-analytics.com https://www.google-analytics.com/analytics.js https://use.typekit.net connect.facebook.net/ https://googleads.g.doubleclick.net/ app.pendo.io cdn.pendo.io pendo-static-6351154740266000.storage.googleapis.com pendo-io-static.storage.googleapis.com https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/ https://www.google.com/recaptcha/api.js apis.google.com https://www.googletagmanager.com api.instagram.com https://app-rsrc.getbee.io/plugin/BeePlugin.js https://loader.getbee.io api.instagram.com https://bat.bing.com/bat.js https://www.googleadservices.com/pagead/conversion.js https://connect.facebook.net/en_US/fbevents.js https://connect.facebook.net/ https://fonts.googleapis.com/ https://ssl.gstatic.com/ https://tagmanager.google.com/;style-src 'unsafe-inline' *;img-src * data:;connect-src 'self' app.pendo.io api.feedback.us.pendo.io; frame-ancestors 'self' app.pendo.io pxsweb.com *.pxsweb.com;frame-src 'self' *.myguestaccount.com https://app.getbee.io/ *;
header: X-Lift-Version: Unknown Lift Version
header: CF-Cache-Status: DYNAMIC
header: cf-request-id: 01b2c5b1fa00002654a25485710000001
header: Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
header: Set-Cookie: __cfduid=db9de811004e591f9a12b66980a5dde331592650101; expires=Sat, 01-Aug-20 20:20:01 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Set-Cookie: __cfduid=db9de811004e591f9a12b66980a5dde331592650101; expires=Sat, 01-Aug-20 20:20:01 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Set-Cookie: __cfduid=db9de811004e591f9a12b66980a5dde331592650101; expires=Sat, 01-Aug-20 20:20:01 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Server: cloudflare
header: CF-RAY: 5acb58a62c5b5144-EWR
```
|
2020/07/01
|
[
"https://Stackoverflow.com/questions/62684468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7032457/"
] |
This really piqued my interests. The `requests` solution that I was able to get working.
Solution
--------
Finally narrow down the problem. When you use requests it uses urllib3 connection pool. There seems to be some inconsistency between a regular urllib3 connection and a connection pool. A working solution:
```py
import requests
from collections import OrderedDict
from requests import Session
import socket
# grab the address using socket.getaddrinfo
answers = socket.getaddrinfo('grimaldis.myguestaccount.com', 443)
(family, type, proto, canonname, (address, port)) = answers[0]
s = Session()
headers = OrderedDict({
'Accept-Encoding': 'gzip, deflate, br',
'Host': "grimaldis.myguestaccount.com",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'
})
s.headers = headers
response = s.get(f"https://{address}/guest/accountlogin", headers=headers, verify=False).text
print(response)
```
Technical Background
--------------------
So I ran both method through Burp Suite to compare the requests. Below are the raw dumps of the requests
### using requests
```
GET /guest/accountlogin HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Connection: close
Host: grimaldis.myguestaccount.com
Accept-Language: en-GB,en;q=0.5
Upgrade-Insecure-Requests: 1
dnt: 1
```
### using urllib
```
GET /guest/accountlogin HTTP/1.1
Host: grimaldis.myguestaccount.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Dnt: 1
```
**The difference is the ordering of the headers.** The difference in the `dnt` capitalization is not actually the problem.
So I was able to make a successful request with the following raw request:
```
GET /guest/accountlogin HTTP/1.1
Host: grimaldis.myguestaccount.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0
```
So the `Host` header has be sent above `User-Agent`. So if you want to continue to to use requests. Consider using a OrderedDict to ensure the ordering of the headers.
|
After some debugging, and thanks to the answers of @TuanGeek, we've found out the issue with the requests library seems to come from a DNS issue on requests' part when dealing with cloudflare, a simple fix to this issue is connecting directly to the host IP as such:
```
import requests
from collections import OrderedDict
from requests import Session
import socket
# grab the address using socket.getaddrinfo
answers = socket.getaddrinfo('grimaldis.myguestaccount.com', 443)
(family, type, proto, canonname, (address, port)) = answers[0]
s = Session()
headers = OrderedDict({
'Accept-Encoding': 'gzip, deflate, br',
'Host': "grimaldis.myguestaccount.com",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'
})
s.headers = headers
response = s.get(f"https://{address}/guest/accountlogin", headers=headers, verify=False).text
print(response)
```
Now, this fix didn't work when working with the httplib HTTPX, However I've found where the issue stems from.
The issue comes from the h11 library (used by HTTPX to handle HTTP/1.1 requests), while urllib would automatically fix the letter case of headers, h11 took a different approach by lowercasing every header. While in theory this shouldn't cause any issues, as servers should handle headers in a case-insensitive manner (and in a lot of cases they do), the reality is that HTTP is Hard™️ and services such as Cloudflare don't respect RFC2616 and requires headers to be properly capitalized.
Discussions about capitalization have been going for a while over at h11:
<https://github.com/python-hyper/h11/issues/31>
And have "recently" started to pop up over on HTTPX's repo as well:
<https://github.com/encode/httpx/issues/538>
<https://github.com/encode/httpx/issues/728>
Now the unsatisfactory answer to the issue between Cloudflare and HTTPX is that until something is done over on h11's side (or until Cloudflare miraculously starts respecting RFC2616), not much can be changed to how HTTPX and Cloudflare handle header capitalization.
Either use a different HTTPLIB such as aiohttp or requests-futures, try forking and patching the header capitalization with h11 yourself, or wait and hope for the issue to be dealt with properly by the h11 team.
|
52,608,420
|
I am using a language I made with a similar syntax to python, and I wanted to use python syntax highlighting for my language as well.
The only problem is that my language uses curly brackets rather then : and indents.
So some times when I type return for example it highlights the return in red.
Is there any way I can disable error highlights?
Here is an Example:
[](https://i.stack.imgur.com/iIiS8.png)
|
2018/10/02
|
[
"https://Stackoverflow.com/questions/52608420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6516763/"
] |
I'm surprised that someone is still using jQuery Mobile but I think I have most of the code you need.
Several years ago I wrote an article covering a complex jQuery Mobile authorization tutorial: <https://www.gajotres.net/complex-jquery-mobile-authorization-example/>
The main idea is to post your authorization information from jQM client:
```
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).on("mobileinit", function () {
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
$.mobile.changePage.defaults.changeHash = false;
});
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<a href="#login" class="ui-btn-left ui-btn ui-btn-inline ui-mini ui-corner-all ui-btn-icon-left ui-icon-delete" id="back-btn">Back</a>
<h3>Welcome Page</h3>
</div>
<div data-role="content">
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
</body>
</html>
```
Forward this information to server side PHP. Of course you will need to handle DB read/write; my example use some kind of ORM, for example Propel as it has a large number of available tutorials.
```
<?php
function authorize()
{
//normally this info would be pulled from a database.
//build JSON array
$status = array("status" => "success");
return $status;
}
$possible_params = array("authorization", "test");
$value = "An error has occurred";
if (isset($_POST["action"]) && in_array($_POST["action"], $possible_params))
{
switch ($_POST["action"])
{
case "authorization":
$value = authorize();
break;
}
}
//return JSON array
exit(json_encode($value));
?>
```
Get response back to jQuery Mobile and depending on a page type, open appropriate page using:
```
$.mobile.changePage("#second");
```
Here's a whole jQM example from my tutorial:
```
var userHandler = {
username : '',
status : ''
}
$(document).on('pagecontainershow', function (e, ui) {
var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage');
if(activePage.attr('id') === 'login') {
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
userHandler.username = $('#username').val();
// Send data to server through the Ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'auth.php',
data: {action : 'authorization', formData : $('#check-user').serialize()},
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show'); // This will show Ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide'); // This will hide Ajax spinner
},
success: function (result) {
// Check if authorization process was successful
if(result.status == 'success') {
userHandler.status = result.status;
$.mobile.changePage("#second");
} else {
alert('Logon unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
} else if(activePage.attr('id') === 'second') {
activePage.find('.ui-content').text('Wellcome ' + userHandler.username);
}
});
$(document).on('pagecontainerbeforechange', function (e, ui) {
var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage');
if(activePage.attr('id') === 'second') {
var to = ui.toPage;
if (typeof to === 'string') {
var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname.substring(1);
if (to === '#login' && userHandler.status === 'success') {
alert('You cant open a login page while youre still logged on!');
e.preventDefault();
e.stopPropagation();
// remove active status on a button if a transition was triggered with a button
$('#back-btn').removeClass('ui-btn-active ui-shadow').css({'box-shadow':'0 0 0 #3388CC'});
}
}
}
});
```
Above tutorial is written in jQuery Mobile 1.4.5. While there's already a version 1.5 it is still an alpha version and there's a good chance we will never see a RC version of 1.5, so stick to 1.4.5.
Again you only need to write PHP DB handling implementation and that should not take you that much time if you stick to Propel ORM.
|
I'm not sure what your php file looks like as you have not provided the code...
But here is a mockup example of the front-end js and html.
Place js in between head tags.
```
<script type="text/javascript">
$(document).ready(function () {
$("#insert").click(function () {
var email = $("#email").val();
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
alert("Not a valid e-mail address");
return false;
}
var password = $("#password").val();
if(password.length < 5){
alert("Please ensure password is longer than 5 characters");
return false;
}
var dataString =
"email=" + email
+ "&password=" + password
+ "&insert=";
$.ajax({
type: "POST",
url: "#yoururl...",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function () {
$("#insert").val('Connecting...');
},
success: function(data){
if(data=="teacher")
{
window.location='teacher.html'
}
else if(data=="student")
{
window.location='student.html'
}
else {
alert("Failed to login");
}
}
});
});
});
</script>
```
html:
```
<input id="email" type="text" class="form-control" name="email"
placeholder="Email">
<input id="password" type="password" class="form-control" name="password"
placeholder="Password">
<button type="submit" id="insert" value="Insert" class="btn btn-primary btn-
block" >Login</button>
```
Hope that helps.
|
58,100,383
|
I have been experimenting to create a docker image with python3.6 based on amazonlinux.
So far, I have not been very successful. I use
```
docker run -it amazonlinux
```
to start an interactive docker terminal. Inside the terminal, I run "yum install python36" and see the following error message. Note that I copied this step was from an old amazonlinux based Dockerfile. This Dockerfile used to work. So I suspend the error I see below is due to amazon updated their docker linux image
```
bash-4.2# yum install python36
Loaded plugins: ovl, priorities
amzn2-core | 2.4 kB 00:00:00
No package python36 available.
Error: Nothing to do
```
I have tried to add a python3.6 repo by following this post
<https://janikarhunen.fi/how-to-install-python-3-6-1-on-centos-7> however, it still gives the same error when I run
```
yum install python36u
```
Is there any way to add python3.6 to amazonlinux base layer? Thanks in advance.
|
2019/09/25
|
[
"https://Stackoverflow.com/questions/58100383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1947254/"
] |
You can check this [Dockerfile](https://github.com/RealSalmon/docker-amazonlinux-python/blob/master/Dockerfile) based on amazon Linux and having python version is `PYTHON_VERSION=3.6.4`.
Or you can work with your existing one like
```
ARG PYTHON_VERSION=3.6.4
ARG BOTO3_VERSION=1.6.3
ARG BOTOCORE_VERSION=1.9.3
ARG APPUSER=app
RUN yum -y update &&\
yum install -y shadow-utils findutils gcc sqlite-devel zlib-devel \
bzip2-devel openssl-devel readline-devel libffi-devel && \
groupadd ${APPUSER} && useradd ${APPUSER} -g ${APPUSER} && \
cd /usr/local/src && \
curl -O https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz && \
tar -xzf Python-${PYTHON_VERSION}.tgz && \
cd Python-${PYTHON_VERSION} && \
./configure --enable-optimizations && make && make altinstall && \
rm -rf /usr/local/src/Python-${PYTHON_VERSION}* && \
yum remove -y shadow-utils audit-libs libcap-ng && yum -y autoremove && \
yum clean all
```
But better to clone the repo and make your own image form that.
|
I too had similiar issue for docker.
yum install docker
Loaded plugins: ovl, priorities
amzn2-core | 3.7 kB 00:00:00
No package docker available.
Error: Nothing to do
instead yum I used amazon-linux-extras, it worked
amazon-linux-extras install docker
==================================
|
58,100,383
|
I have been experimenting to create a docker image with python3.6 based on amazonlinux.
So far, I have not been very successful. I use
```
docker run -it amazonlinux
```
to start an interactive docker terminal. Inside the terminal, I run "yum install python36" and see the following error message. Note that I copied this step was from an old amazonlinux based Dockerfile. This Dockerfile used to work. So I suspend the error I see below is due to amazon updated their docker linux image
```
bash-4.2# yum install python36
Loaded plugins: ovl, priorities
amzn2-core | 2.4 kB 00:00:00
No package python36 available.
Error: Nothing to do
```
I have tried to add a python3.6 repo by following this post
<https://janikarhunen.fi/how-to-install-python-3-6-1-on-centos-7> however, it still gives the same error when I run
```
yum install python36u
```
Is there any way to add python3.6 to amazonlinux base layer? Thanks in advance.
|
2019/09/25
|
[
"https://Stackoverflow.com/questions/58100383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1947254/"
] |
There is now a far easier answer to this question thanks to aws 'extras'. Now this will work:
```
amazon-linux-extras install python3
```
|
I too had similiar issue for docker.
yum install docker
Loaded plugins: ovl, priorities
amzn2-core | 3.7 kB 00:00:00
No package docker available.
Error: Nothing to do
instead yum I used amazon-linux-extras, it worked
amazon-linux-extras install docker
==================================
|
53,296,469
|
below is the python code
```
def load_scan(path):
print(path)
slices = [dicom.read_file(path + '/' + s) for s in os.listdir(path)]
slices.sort(key = lambda x: int(x.InstanceNumber))
try:
slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
except:
slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)
for s in slices:
s.SliceThickness = slice_thickness
return slices
patient = load_scan(filepath)
```
i downloaded the sample dicom files from [link](https://wiki.cancerimagingarchive.net/display/Public/LIDC-IDRI)
any help would be great... how to read dicom files and then process them.
|
2018/11/14
|
[
"https://Stackoverflow.com/questions/53296469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207817/"
] |
Find where filereader.py is. You can see the directory from the traceback itself.
Replace `raise StopIteration` with `return` and you are set to go.
Your filereader.py directory will look like this : `/usr/local/lib/python3.7/site-packages/dicom/filereader.py`
|
I believe dicom is no longer supported, Use [pydicom](https://pypi.org/project/pydicom/) instead of dicom.
|
24,255,734
|
I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(element)
```
EDIT: This code works but feels very unclean. I feel like python has a better way to do this:
```
counter = 0
while counter < 3:
if counter >= len(my_list):
break
do_stuff(my_list[counter])
counter += 1
```
|
2014/06/17
|
[
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] |
You could use `itertools.islice`:
```
for element in itertools.islice(my_list, 0, 3):
do_stuff(element)
```
Of course, if it actually *is* a list, then you could just use a regular slice:
```
for element in my_list[:3]:
do_stuff(element)
```
Regular slices on normal sequences are "forgiving" in that if you ask for more elements than are there, no exception will be raised.
|
```
for element in my_list[:3]:
do_stuff(element)
```
|
24,255,734
|
I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(element)
```
EDIT: This code works but feels very unclean. I feel like python has a better way to do this:
```
counter = 0
while counter < 3:
if counter >= len(my_list):
break
do_stuff(my_list[counter])
counter += 1
```
|
2014/06/17
|
[
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] |
You could use `itertools.islice`:
```
for element in itertools.islice(my_list, 0, 3):
do_stuff(element)
```
Of course, if it actually *is* a list, then you could just use a regular slice:
```
for element in my_list[:3]:
do_stuff(element)
```
Regular slices on normal sequences are "forgiving" in that if you ask for more elements than are there, no exception will be raised.
|
@mhawke's answer is perfect if it's actually a `list` or something else that supports the slice interface.
For a more general iterable type, try the ever-handy [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate):
```
for ii, element in enumerate(my_list):
if ii>=3:
break
do_stuff(element)
```
|
24,255,734
|
I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(element)
```
EDIT: This code works but feels very unclean. I feel like python has a better way to do this:
```
counter = 0
while counter < 3:
if counter >= len(my_list):
break
do_stuff(my_list[counter])
counter += 1
```
|
2014/06/17
|
[
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] |
Slice the list:
```
for element in my_list[:3]:
do_stuff(element)
```
[Documentation](https://docs.python.org/2/reference/expressions.html#slicings) says that there won't be any errors if the list doesn't have elements on those indices, thus you can safely use that on lists containing less than 3 elements. List slicing returns a new list.
The *slightly* more efficient way (for big slices) would be to use [`itertools.islice`](https://docs.python.org/3.3/library/itertools.html#itertools.islice):
```
for element in islice(my_list, 0, 3): # or islice(my_list, 3)
do_stuff(element)
```
|
```
for element in my_list[:3]:
do_stuff(element)
```
|
24,255,734
|
I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(element)
```
EDIT: This code works but feels very unclean. I feel like python has a better way to do this:
```
counter = 0
while counter < 3:
if counter >= len(my_list):
break
do_stuff(my_list[counter])
counter += 1
```
|
2014/06/17
|
[
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] |
Slice the list:
```
for element in my_list[:3]:
do_stuff(element)
```
[Documentation](https://docs.python.org/2/reference/expressions.html#slicings) says that there won't be any errors if the list doesn't have elements on those indices, thus you can safely use that on lists containing less than 3 elements. List slicing returns a new list.
The *slightly* more efficient way (for big slices) would be to use [`itertools.islice`](https://docs.python.org/3.3/library/itertools.html#itertools.islice):
```
for element in islice(my_list, 0, 3): # or islice(my_list, 3)
do_stuff(element)
```
|
@mhawke's answer is perfect if it's actually a `list` or something else that supports the slice interface.
For a more general iterable type, try the ever-handy [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate):
```
for ii, element in enumerate(my_list):
if ii>=3:
break
do_stuff(element)
```
|
24,255,734
|
I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(element)
```
EDIT: This code works but feels very unclean. I feel like python has a better way to do this:
```
counter = 0
while counter < 3:
if counter >= len(my_list):
break
do_stuff(my_list[counter])
counter += 1
```
|
2014/06/17
|
[
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] |
```
for element in my_list[:3]:
do_stuff(element)
```
|
@mhawke's answer is perfect if it's actually a `list` or something else that supports the slice interface.
For a more general iterable type, try the ever-handy [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate):
```
for ii, element in enumerate(my_list):
if ii>=3:
break
do_stuff(element)
```
|
69,979,902
|
I am doing this assignment for a python course but I am nowhere near the solution.
Let's say if I enter x = 4, this is what I am supposed to get:
```
"pyramid(0) =>" [ ]
"pyramid(1) =>" [ [1] ]
"pyramid(2) =>" [ [1], [1, 1] ]
"pyramid(3) =>" [ [1], [1, 1], [1, 1, 1] ]
```
I believe the logic is similar when making triangle's right side, right?
this is my code, but I am missing something, hope you guys could point me to the right direction and the task's logic.
Thank you!
```
x = 4
list1 = []
line = 0
while line < x:
one = line + 1
while one > 0:
list1.append(1)
one -= 1
line += 1
print(list1)
```
|
2021/11/15
|
[
"https://Stackoverflow.com/questions/69979902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15572613/"
] |
You can do:
```
def pyramid(n):
result = []
for i in range(n):
result.append([1] * (i+1))
return result
>>> pyramid(0)
[]
>>> pyramid(1)
[[1]]
>>> pyramid(2)
[[1], [1, 1]]
```
|
I tried to come up with words to guide you to this solution, but it just wasn't possible. You need a 'for' loop to count to 4, and you need `[1]*i` to create a list with a certain number of 1s.
```
x = 4
list1 = []
print("pyramid(0) =>", list1)
for i in range(x):
list1.append( [1] * i )
print("pyramid(%d) =>" % (i+1), list1)
```
|
69,979,902
|
I am doing this assignment for a python course but I am nowhere near the solution.
Let's say if I enter x = 4, this is what I am supposed to get:
```
"pyramid(0) =>" [ ]
"pyramid(1) =>" [ [1] ]
"pyramid(2) =>" [ [1], [1, 1] ]
"pyramid(3) =>" [ [1], [1, 1], [1, 1, 1] ]
```
I believe the logic is similar when making triangle's right side, right?
this is my code, but I am missing something, hope you guys could point me to the right direction and the task's logic.
Thank you!
```
x = 4
list1 = []
line = 0
while line < x:
one = line + 1
while one > 0:
list1.append(1)
one -= 1
line += 1
print(list1)
```
|
2021/11/15
|
[
"https://Stackoverflow.com/questions/69979902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15572613/"
] |
You can do:
```
def pyramid(n):
result = []
for i in range(n):
result.append([1] * (i+1))
return result
>>> pyramid(0)
[]
>>> pyramid(1)
[[1]]
>>> pyramid(2)
[[1], [1, 1]]
```
|
As @mkrieger1 stated, you need more lists. Create the sublist in you for loop, then add to that sublist instead of adding to `list`. Then you can add the sublist to `list1`. This can keep your structure intact.
```py
x = 4
list1 = []
line = 0
while line < x:
one = line + 1
sublist = [] # create the sublist to be added
while one > 0:
sublist.append(1) # grow the sublist to the right size
one -= 1
list1.append(sublist) # add the sublist into the printed list
line += 1
print(list1)
```
|
44,311,287
|
I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail. I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application. Any help on this would be greatly appreciated.
```
# -*- coding: utf-8 -*-
import paramiko
import time,sys
from datetime import datetime
from time import sleep
prompt = "#"
datetime = datetime.now()
ssh_pre = paramiko.SSHClient()
ssh_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_pre.connect("192.168.0.1",22, "admin", "admin")
output=""
ssh = ssh_pre.invoke_shell()
sys.stdout=open("ssh_session_dump.txt","w")
print("Script Start Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))
model="XV4-17034"
ssh.send("more off\n")
if ssh.recv_ready():
output = ssh.recv(1000)
ssh.send("show system-info\n")
sleep(5)
output = ssh.recv(5000)
output=output.decode('utf-8')
lines=output.split("\n")
for item in lines:
if "Model:" in item:
line=item.split()
if line[1]==model+',':
print("Test Case 1.1 - PASS - Model is an " + model)
else:
print("Test Case 1.1 - FAIL - Model is not an " + model)
ssh.send( "quit\n" )
ssh.close()
datetime = datetime.now()
print("")
print("Script End Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))
print("")
sys.stdout.close()
```
|
2017/06/01
|
[
"https://Stackoverflow.com/questions/44311287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8055089/"
] |
If this were my project, I would convert the code to a function and then create a keyword library that includes that function.
For example, you could create a file named CustomLibrary.py with a function defined like this:
```
def verify_model(model):
prompt = "#"
datetime = datetime.now()
ssh_pre = paramiko.SSHClient()
...
for item in lines:
if "Model:" in item:
line=item.split()
if line[1]==model+',':
return True
else:
raise Exception("Model was %s, expected %s" % (line[1], model))
...
```
Then, you could create a robot test like this:
```
*** Settings ***
Library CustomLibrary
*** Test cases ***
Verify model is Foo
verify model foo
```
Of course, it's a tiny bit more complicated than that. For example, you would probably need to change the logic in the function to guarantee that you close the connection before returning. Overall, though, that's the general approach: create one or more functions, import them as a library, and then call the functions from a robot test.
|
To call Python code from Robot Framework, you need to use the same syntax as a Robot Framework Library, but once you do, it's very simple. Here's an example, in a file called CustomLibrary.py located in the same folder as the test:
```
from robot.libraries.BuiltIn import BuiltIn
# Do any other imports you want here.
class CustomLibrary(object):
def __init__(self):
self.selenium_lib = BuiltIn().get_library_instance('ExtendedSelenium2Library')
# This is where you initialize any other global variables you might want to use in the code.
# I import BuiltIn and Extended Selenium2 Library to gain access to their keywords.
def run_my_code(self):
# Place the rest of your code here
```
I've used this a lot in my testing. In order to call it, you need something similar to this:
```
*** Settings ***
Library ExtendedSelenium2Library
Library CustomLibrary
*** Test Cases ***
Test My Code
Run My Code
```
This will run whatever code you place in the Python file. Robot Framework does not directly implement Python, as far as I know, but it is written in Python. So, as long as you feed it Python in a form that it can recognize, it'll run it just like any other keyword from BuiltIn or Selenium2Library.
Please note that ExtendedSelenium2Library is exactly the same as Selenium2Library except that it includes code to deal with Angular websites. Same keywords, so I just use it as a strict upgrade. If you want to use the old Selenium2Library, just swap out all instances of the text "ExtendedSelenium2Library" for "Selenium2Library".
Please note that in order to use any keywords from BuiltIn or ExtendedSelenium2Library you will need to use the syntax `BuiltIn().the_keyword_name(arg1, arg2, *args)` or `selenium_lib().the_keyword_name(arg1, arg2, *args)`, respectively.
|
44,311,287
|
I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail. I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application. Any help on this would be greatly appreciated.
```
# -*- coding: utf-8 -*-
import paramiko
import time,sys
from datetime import datetime
from time import sleep
prompt = "#"
datetime = datetime.now()
ssh_pre = paramiko.SSHClient()
ssh_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_pre.connect("192.168.0.1",22, "admin", "admin")
output=""
ssh = ssh_pre.invoke_shell()
sys.stdout=open("ssh_session_dump.txt","w")
print("Script Start Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))
model="XV4-17034"
ssh.send("more off\n")
if ssh.recv_ready():
output = ssh.recv(1000)
ssh.send("show system-info\n")
sleep(5)
output = ssh.recv(5000)
output=output.decode('utf-8')
lines=output.split("\n")
for item in lines:
if "Model:" in item:
line=item.split()
if line[1]==model+',':
print("Test Case 1.1 - PASS - Model is an " + model)
else:
print("Test Case 1.1 - FAIL - Model is not an " + model)
ssh.send( "quit\n" )
ssh.close()
datetime = datetime.now()
print("")
print("Script End Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))
print("")
sys.stdout.close()
```
|
2017/06/01
|
[
"https://Stackoverflow.com/questions/44311287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8055089/"
] |
If this were my project, I would convert the code to a function and then create a keyword library that includes that function.
For example, you could create a file named CustomLibrary.py with a function defined like this:
```
def verify_model(model):
prompt = "#"
datetime = datetime.now()
ssh_pre = paramiko.SSHClient()
...
for item in lines:
if "Model:" in item:
line=item.split()
if line[1]==model+',':
return True
else:
raise Exception("Model was %s, expected %s" % (line[1], model))
...
```
Then, you could create a robot test like this:
```
*** Settings ***
Library CustomLibrary
*** Test cases ***
Verify model is Foo
verify model foo
```
Of course, it's a tiny bit more complicated than that. For example, you would probably need to change the logic in the function to guarantee that you close the connection before returning. Overall, though, that's the general approach: create one or more functions, import them as a library, and then call the functions from a robot test.
|
The easiest way is importing a `.py` file into your testsuite using relative path approach, like `./my_lib.py` (assume that your python file is in the same folder with your TC file)
In your `.py` file, simply define a function, for example:
```
def get_date(date_string, date_format='%Y-%m-%d'):
return datetime.strptime(date_string, date_format)
```
And then in your TC file:
```
*** Settings ***
Library ./my_lib.py
*** Test Cases ***
TEST CASE 1
Get Date | ${some_variable}
```
|
44,311,287
|
I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail. I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application. Any help on this would be greatly appreciated.
```
# -*- coding: utf-8 -*-
import paramiko
import time,sys
from datetime import datetime
from time import sleep
prompt = "#"
datetime = datetime.now()
ssh_pre = paramiko.SSHClient()
ssh_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_pre.connect("192.168.0.1",22, "admin", "admin")
output=""
ssh = ssh_pre.invoke_shell()
sys.stdout=open("ssh_session_dump.txt","w")
print("Script Start Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))
model="XV4-17034"
ssh.send("more off\n")
if ssh.recv_ready():
output = ssh.recv(1000)
ssh.send("show system-info\n")
sleep(5)
output = ssh.recv(5000)
output=output.decode('utf-8')
lines=output.split("\n")
for item in lines:
if "Model:" in item:
line=item.split()
if line[1]==model+',':
print("Test Case 1.1 - PASS - Model is an " + model)
else:
print("Test Case 1.1 - FAIL - Model is not an " + model)
ssh.send( "quit\n" )
ssh.close()
datetime = datetime.now()
print("")
print("Script End Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))
print("")
sys.stdout.close()
```
|
2017/06/01
|
[
"https://Stackoverflow.com/questions/44311287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8055089/"
] |
To call Python code from Robot Framework, you need to use the same syntax as a Robot Framework Library, but once you do, it's very simple. Here's an example, in a file called CustomLibrary.py located in the same folder as the test:
```
from robot.libraries.BuiltIn import BuiltIn
# Do any other imports you want here.
class CustomLibrary(object):
def __init__(self):
self.selenium_lib = BuiltIn().get_library_instance('ExtendedSelenium2Library')
# This is where you initialize any other global variables you might want to use in the code.
# I import BuiltIn and Extended Selenium2 Library to gain access to their keywords.
def run_my_code(self):
# Place the rest of your code here
```
I've used this a lot in my testing. In order to call it, you need something similar to this:
```
*** Settings ***
Library ExtendedSelenium2Library
Library CustomLibrary
*** Test Cases ***
Test My Code
Run My Code
```
This will run whatever code you place in the Python file. Robot Framework does not directly implement Python, as far as I know, but it is written in Python. So, as long as you feed it Python in a form that it can recognize, it'll run it just like any other keyword from BuiltIn or Selenium2Library.
Please note that ExtendedSelenium2Library is exactly the same as Selenium2Library except that it includes code to deal with Angular websites. Same keywords, so I just use it as a strict upgrade. If you want to use the old Selenium2Library, just swap out all instances of the text "ExtendedSelenium2Library" for "Selenium2Library".
Please note that in order to use any keywords from BuiltIn or ExtendedSelenium2Library you will need to use the syntax `BuiltIn().the_keyword_name(arg1, arg2, *args)` or `selenium_lib().the_keyword_name(arg1, arg2, *args)`, respectively.
|
The easiest way is importing a `.py` file into your testsuite using relative path approach, like `./my_lib.py` (assume that your python file is in the same folder with your TC file)
In your `.py` file, simply define a function, for example:
```
def get_date(date_string, date_format='%Y-%m-%d'):
return datetime.strptime(date_string, date_format)
```
And then in your TC file:
```
*** Settings ***
Library ./my_lib.py
*** Test Cases ***
TEST CASE 1
Get Date | ${some_variable}
```
|
46,418,397
|
This may appear like a very trivial question but I have just started learning python classes and objects. I have a code like below.
```
class Point(object):
def __init__(self,x,y):
self.x = float(x)
self.y = float(y)
def __str__(self):
return '('+str(self.x)+','+str(self.y)+')'
def main():
p1 = Point(pt1,pt2)
p2 = Point(pt3,pt4)
p3 = Point(pt5,pt6)
p4 = Point(pt7,pt8)
parray = [p1,p2,p3,p4]
print " Points are", p1,p2,p3,p4
print "parray",parray
```
I m getting the below Output :
Points are (4.0,2.0) (4.0,8.0) (4.0,-1.0) (100.0,1.0)
parray - intersection.Point object at 0x7ff09f00a550, intersection.Point object at 0x7ff09f00a410, intersection.Point object at 0x7ff09f00a590
My question is why are the addresses of objects assigned to array while I get the values while printing the objects?
Can someone suggest a way to get the values returned by class in array in main function?
|
2017/09/26
|
[
"https://Stackoverflow.com/questions/46418397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8629294/"
] |
I would use Repeat to add one element and implement the interpolation as a new lambda layer. I don't think there's an existing layer for this in keras.
|
Surprisingly there is no existing layer/function in keras that does such an interpolation of a tensor (as pointed out by xtof54). So, I implemented it using a lambda layer, and it worked fine.
```
def resize_like(input_tensor, ref_tensor): # resizes input tensor wrt. ref_tensor
H, W = ref_tensor.get_shape()[1], ref_tensor.get_shape()[2]
return tf.image.resize_nearest_neighbor(input_tensor, [H.value, W.value])
```
The problem, in the first place, was due to the use of a tensor directly from tensorflow in a Keras layer, as a few additional attributes (required for a keras tensor) that are missing. In addition, though Lambda layer is quite easy to use, it would be really convenient if keras allows the use of tensors (if possible) from tensorflow directly in keras layers, in the future.
|
66,742,855
|
I am working in selenium with python.
I used the code that worked, one hour ago, but now it returns me that
```
no such element: Unable to lacate element:...
```
The same code worked maximum one hour ago.
Where is the problem? I checked the source code, but it still the same
Here is my code:
```
import selenium
from selenium import webdriver
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
PATH="C:\Program Files (x86)\chromedriver"
driver=webdriver.Chrome(PATH)
driver.get("https://moitane.ge/shop/5-gudvili/43-axali-xorci-da-xorcproduqti")
time.sleep(3)
#el = driver.find_element(By.XPATH, "//div[@class='style__ShopProductSubCategoryChip-sc-1bc3ssb-2 iKSeHs']")
el = driver.find_element(By.XPATH, "//li[@class='style__CategoryItem-sc-8ncu0g-2 tZtCz']//span[text()='ახალი ხილი']")
time.sleep(3)
el.click()
time.sleep(5)
ell = driver.find_element(By.XPATH, "//*[@id='main-layout']/div[5]/div[4]/div/div[1]/div/div/div/div[1]/div")
```
It gives me error:
```
NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='main-layout']/div[5]/div[4]/div/div[1]/div/div/div/div[1]/div"}
(Session info: chrome=89.0.4389.90)
```
Here is copied element:
`'<div class="style__ProductItemWrapper-nvyr2y-0 cbyRwl product-item-wrapper"><img class="style__ProductItemImage-nvyr2y-2 gfMqx product-image" src="https://static.moitane.ge/Moitane_files/093c2492-ccf3-4515-adcf-2f610a09e473_Thumb.jpeg" style="width: 166px; height: 132.8px; cursor: pointer;"><p class="style__ProductItemText-nvyr2y-3 ebZGDv" style="cursor: pointer; height: 40px;">ბანანი (წონის) (იმპ) </p><div style="display: flex; margin-top: auto; width: 100%; align-items: flex-start;"><span class="style__ProductItemDesc-nvyr2y-4 cIkCnK" style="margin-left: auto;">1 კგ</span></div><div class="style__ProductItemActionsWrapper-nvyr2y-5 kQtpVm" style="cursor: pointer; position: relative;"><span class="style__ProductItemPrice-nvyr2y-6 hLsuWS"><span>4.10 ₾</span> </span><div style="position: absolute; top: 0px; right: 0px; height: 100%; width: 50%;"></div><span class="style__ProductItemActionButton-nvyr2y-7 bieLnj"><i class="icon-plus" style="color: rgb(146, 146, 157);"></i></span></div></div>`'
|
2021/03/22
|
[
"https://Stackoverflow.com/questions/66742855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15446325/"
] |
You could also use a capture group without a global flag to match for only a single match, and match all lines that do not start with 10 hyphens using a negative lookahead.
```
^(?:(?!----------).*\n)+(?=----------$)
```
[regex demo](https://regex101.com/r/h0BlCk/1)
Or you can match as least as possible lines, until you encounter a line that starts with 10 hyphens.
```
^(?:.*\n)+?(?=----------$)
```
[Regex demo](https://regex101.com/r/UNXrcr/1)
|
You may try matching on the following pattern, with DOT ALL mode enabled:
```regex
^.*?(?=----------|$)
```
[Demo
----](https://regex101.com/r/mvZxBD/1)
This will match all content up to, but including, the first set of dashes. Note that for inputs not having any dash separators, it would return all content.
If your regex engine does not support DOT ALL mode, then use this version:
```regex
^[\S\s]*?(?=----------|$)
```
|
64,812,794
|
The following code appears when I am running a cell on Google Colab:
```
NameError Traceback (most recent call last)
<ipython-input-36-5f325bc0550d in <module>()
4
5 TAGGER_PATH = "crf_nlu.tagger" # path to the tagger- it will save/access the model from here
----> 6 ct = CRFTagger(feature_func=get_features) # initialize tagger with get_features function
7
8 print("training tagger...")
/usr/local/lib/python3.6/dist-packages/nltk/tag/crf.py in __init__(self, feature_func, verbose, training_opt)
81
82 self._model_file = ''
---> 83 self._tagger = pycrfsuite.Tagger()
84
85 if feature_func is None:
NameError: name 'pycrfsuite' is not defined
```
This is the code from the cell:
```
# Train the CRF BIO-tag tagger
import pycrfsuite
TAGGER_PATH = "crf_nlu.tagger" # path to the tagger- it will save/access the model from here
ct = CRFTagger(feature_func=get_features) # initialize tagger with get_features function
print("training tagger...")
ct.train(training_data, TAGGER_PATH)
print("done")
```
What causes this issue?
I have an import for the *CRFTagger* which is:
>
> from nltk.tag import CRFTagger
>
>
>
|
2020/11/12
|
[
"https://Stackoverflow.com/questions/64812794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14597269/"
] |
I just sorted it out. For the google colab, I had to add the following line:
>
> pip install sklearn-pycrfsuite
>
>
>
|
Use:
>
> pip install python-crfsuite
>
>
>
Scikit-crfsuite provides API similar to scikit-learn library.
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
You can execute your file by using this:
```
python /Users/luca/Documents/python/gameover.py
```
You can also run the file by moving to the path of the file you want to run and typing:
```
python gameover.py
```
|
Let's say your script is called `my_script.py` and you have put it in your Downloads folder.
There are many ways of installing Python, but [Homebrew](https://brew.sh/) is the easiest.
0. Open [Terminal.app](https://en.wikipedia.org/wiki/Terminal_(macOS)) (press ⌘+Space and type "Terminal" and press the [Enter key](https://en.wikipedia.org/wiki/Enter_key))
1. Install Homebrew (by pasting the following text into Terminal.app and pressing the [Enter key](https://en.wikipedia.org/wiki/Enter_key))
```
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
2. Install Python using Homebrew
```
brew install python
```
3. [`cd`](https://en.wikipedia.org/wiki/Cd_(command)) into the directory that contains your Python script (as an example I'm using the Downloads (`Downloads`) folder in your home ([`~`](https://en.wikipedia.org/wiki/Tilde#Directories_and_URLs)) folder):
```
cd ~/Downloads
```
4. Run the script using the `python3` executable
```
python3 my_script.py
```
You can also skip step 3 and give `python3` an [absolute path](https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths) instead
```
python3 ~/Downloads/my_script.py
```
---
Instead of typing out that whole thing (`~/Downloads/my_script.py`), you can find the `.py` file in Finder.app and just drag it into the Terminal.app window which should type out the absolute path for you.
If you have spaces or certain other symbols somewhere in your filename you need to enclose the file name in quotes:
```
python3 "~/Downloads/some directory with spaces/and a filename with a | character.py"
```
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
If you are working with Ubuntu, sometimes you need to run as `sudo`:
For Python2:
```
sudo python gameover.py
```
For Python3:
```
sudo python3 gameover.py
```
|
Open the directory where you have saved your python program
```
cd desktop/home/file.....
```
type the command
```
python3 filename.py
```
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial:
<http://docs.python-guide.org/en/latest/starting/install3/osx/>.
To run the program you can then copy and paste in this code:
```
python /Users/luca/Documents/python/gameover.py
```
Or you can go to the directory of the file with `cd` followed by the folder. When you are in the folder you can then `python YourFile.py`.
|
First of all, you need to move to the location of the file you are trying to execute, so in a Terminal:
```
cd ~/Documents/python
```
Now, you should be able to execute your file:
```
python gameover.py
```
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
You need [*python*](http://www.python.org/) installed on your system. Then you can run this in the terminal in the correct directory:
```
python gameover.py
```
|
Open the directory where you have saved your python program
```
cd desktop/home/file.....
```
type the command
```
python3 filename.py
```
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
If you are working with Ubuntu, sometimes you need to run as `sudo`:
For Python2:
```
sudo python gameover.py
```
For Python3:
```
sudo python3 gameover.py
```
|
For OS Monterrey
```
/usr/local/bin/python3
```
or o Open the search bar on your mac and enter python a window will open with the address of the directory copy the directory and paste it into the terminal
enjoy
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial:
<http://docs.python-guide.org/en/latest/starting/install3/osx/>.
To run the program you can then copy and paste in this code:
```
python /Users/luca/Documents/python/gameover.py
```
Or you can go to the directory of the file with `cd` followed by the folder. When you are in the folder you can then `python YourFile.py`.
|
For OS Monterrey
```
/usr/local/bin/python3
```
or o Open the search bar on your mac and enter python a window will open with the address of the directory copy the directory and paste it into the terminal
enjoy
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial:
<http://docs.python-guide.org/en/latest/starting/install3/osx/>.
To run the program you can then copy and paste in this code:
```
python /Users/luca/Documents/python/gameover.py
```
Or you can go to the directory of the file with `cd` followed by the folder. When you are in the folder you can then `python YourFile.py`.
|
Open the directory where you have saved your python program
```
cd desktop/home/file.....
```
type the command
```
python3 filename.py
```
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
First of all, you need to move to the location of the file you are trying to execute, so in a Terminal:
```
cd ~/Documents/python
```
Now, you should be able to execute your file:
```
python gameover.py
```
|
Open the directory where you have saved your python program
```
cd desktop/home/file.....
```
type the command
```
python3 filename.py
```
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
You can execute your file by using this:
```
python /Users/luca/Documents/python/gameover.py
```
You can also run the file by moving to the path of the file you want to run and typing:
```
python gameover.py
```
|
This Depends on what version of python is installed on you system. See below.
If You have Python 2.\* version you have to run this command
```
python gameover.py
```
But if you have Python 3.\* version you have to run this command
```
python3 gameover.py
```
Because for MAC with Python version 3.\* you will get command not found error
if you run "python gameover.py"
|
21,492,214
|
I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python".
|
2014/01/31
|
[
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] |
This Depends on what version of python is installed on you system. See below.
If You have Python 2.\* version you have to run this command
```
python gameover.py
```
But if you have Python 3.\* version you have to run this command
```
python3 gameover.py
```
Because for MAC with Python version 3.\* you will get command not found error
if you run "python gameover.py"
|
If you are working with Ubuntu, sometimes you need to run as `sudo`:
For Python2:
```
sudo python gameover.py
```
For Python3:
```
sudo python3 gameover.py
```
|
42,165,925
|
I have .txt file that has 6 lines on it.
```
Line 1 name
Line 2 eamil address
line 4 phone number
line 5 sensor name
line 6 link .
```
I want to read those 6 lines in python and forward an email to the email address listed in the second line. I have a script that does this . But I don't know how to do this from .txt file .
Thanks.
|
2017/02/10
|
[
"https://Stackoverflow.com/questions/42165925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7449247/"
] |
```
with open("filename", "r") as f:
for l in f:
// do your processing, maybe keep track of how many lines you see since you need to do something different on each line
```
|
Have a look at this question: [How do I read a text file into a string variable in Python](https://stackoverflow.com/q/8369219/2519977)
It shows you how to read a file line per line into an array.
So you can do:
```
with open('data.txt', 'r') as myfile:
data=myfile.read().replace('\n', '')
```
`data[1]` would then be the email address.
Please do proper research before asking.
|
42,165,925
|
I have .txt file that has 6 lines on it.
```
Line 1 name
Line 2 eamil address
line 4 phone number
line 5 sensor name
line 6 link .
```
I want to read those 6 lines in python and forward an email to the email address listed in the second line. I have a script that does this . But I don't know how to do this from .txt file .
Thanks.
|
2017/02/10
|
[
"https://Stackoverflow.com/questions/42165925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7449247/"
] |
You said email lies in the second line of the file?
you can manipulate txt files by line using the readline() function.
usage example:
text file:
```
John Smith
john@smith.tld
line3
1-800-smth-here
sensorname
link
file = open(“testfile.txt”, “r”)
client_email = file.readline(1)
print client_email
```
would result in
```
john@smith.tld
```
|
Have a look at this question: [How do I read a text file into a string variable in Python](https://stackoverflow.com/q/8369219/2519977)
It shows you how to read a file line per line into an array.
So you can do:
```
with open('data.txt', 'r') as myfile:
data=myfile.read().replace('\n', '')
```
`data[1]` would then be the email address.
Please do proper research before asking.
|
65,912,670
|
I have .csv file with only 2 columns. ("left" and "right")
The file size is less than 200 MB
I use the following code on **dev server** and it works as expected:
```
import pandas as pd
df = pd.read_csv('en_bigram.csv')
st = df[df["right"] == "some_text"]["left"]
st[st.str.startswith("My")].to_list()
```
"pandas" module is not installed on **production server**. I will like to know if
*I should install pandas*
or
*I should rewrite the code in pure python*
Is there any overhead (like memory/ cpu) in using pandas in production?
Can the 4 lines pandas code written using python's built in modules like csv in 4 or 5 lines?
|
2021/01/27
|
[
"https://Stackoverflow.com/questions/65912670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] |
I ran the following experiments on my machine (Intel 9th Gen i7) with a test data file of ~535 MB:
### Pandas version
```py
# import measurement dependencies
import time
import psutil
p = psutil.Process()
start = time.process_time()
import pandas as pd
df = pd.read_csv('test.csv')
st = df[df["right"] == "some_text"]["left"]
res = st[st.str.startswith("My")].to_list()
print(time.process_time() - start)
print(p.memory_percent())
```
### Pure Python Version
```py
# import measurement dependencies
import time
import psutil
p = psutil.Process()
start = time.process_time()
import csv
with open('test.csv', 'r') as f:
r = csv.reader(f)
headers = next(r, None)
left = headers.index("left")
right = headers.index("right")
res = [line for line in r if line[right] == "some_text" and line[left].startswith('My')]
print(time.process_time() - start)
print(p.memory_percent())
```
Please let me know if there are any efficiencies I am missing with the Python version of the code (or pandas, for that matter), but after several trials, the results were far enough for me to be convinced they are statistically significant:
| | Process Time (lower is better) | Memory (lower is better) |
| --- | --- | --- |
| Pandas | ~11s | 4.5% |
| Python | ~14s | 3.1% |
Unless there is some major issue with how I wrote the Python version, it seems to me that Pandas does seem to be more efficient in CPU time, but less efficient in memory.
While the `pandas` library is more memory than the `csv` module, by about a factor of 4, both were significantly less than 50 MB of memory.
|
>
> Is there any overhead (like memory/ cpu) in using pandas in production? Can the 4 lines pandas code written using python's built in modules like csv in 4 or 5 lines?
>
>
>
I'm going to say go with pandas. Once you start slicing and dicing large datasets, numpy arrays are much more efficient than python lists.
|
67,172,207
|
I've seen a couple of questions similar to this but none in python. Basically, I want to check if certain words are in a list. Though the words I want to compare might have a ',' which I want to ignore. I have tried this, though it does not ignore the ','.
```py
x = ['hello','there,','person']
y = ['there','person']
similar = [words for words in x if words in y ]
print(similar)
```
**Output**
```
['person']
```
**But I want**
```
['there','person']
```
Does anyone know the simplest way of implementing this?
|
2021/04/20
|
[
"https://Stackoverflow.com/questions/67172207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14222251/"
] |
Check out this code use `any function` along with `map` to map containing conditon.
```
x = ['hello','there,','person']
y = ['there','person'] # or take this for more intuation ['there','person','bro']
similar = [words for words in y if any(map(lambda i: i.count(words), x))]
print(similar)
```
**OUTPUT:**
```
['there', 'person']
```
|
Just compare the strings without any comma:
```py
similar = [words for words in x if words.replace(',', '') in y ]
```
**Output**:
```py
>>similar
['there,', 'person']
```
|
67,172,207
|
I've seen a couple of questions similar to this but none in python. Basically, I want to check if certain words are in a list. Though the words I want to compare might have a ',' which I want to ignore. I have tried this, though it does not ignore the ','.
```py
x = ['hello','there,','person']
y = ['there','person']
similar = [words for words in x if words in y ]
print(similar)
```
**Output**
```
['person']
```
**But I want**
```
['there','person']
```
Does anyone know the simplest way of implementing this?
|
2021/04/20
|
[
"https://Stackoverflow.com/questions/67172207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14222251/"
] |
Just compare the strings without any comma:
```py
similar = [words for words in x if words.replace(',', '') in y ]
```
**Output**:
```py
>>similar
['there,', 'person']
```
|
The other two answers so far require a quadratic time complexity of *O(n x m)*, where *n* and *m* are the lengths of `x` and `y`, respectively.
For a solution that requires just a linear time complexity of *O(n + m)*, you can normalize the strings in `x` to ones without commas and store them as a set, so that you can use set intersection to find common strings with `y`:
```
similar = {word.replace(',' ,'') for word in x}.intersection(y)
```
|
67,172,207
|
I've seen a couple of questions similar to this but none in python. Basically, I want to check if certain words are in a list. Though the words I want to compare might have a ',' which I want to ignore. I have tried this, though it does not ignore the ','.
```py
x = ['hello','there,','person']
y = ['there','person']
similar = [words for words in x if words in y ]
print(similar)
```
**Output**
```
['person']
```
**But I want**
```
['there','person']
```
Does anyone know the simplest way of implementing this?
|
2021/04/20
|
[
"https://Stackoverflow.com/questions/67172207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14222251/"
] |
Check out this code use `any function` along with `map` to map containing conditon.
```
x = ['hello','there,','person']
y = ['there','person'] # or take this for more intuation ['there','person','bro']
similar = [words for words in y if any(map(lambda i: i.count(words), x))]
print(similar)
```
**OUTPUT:**
```
['there', 'person']
```
|
The other two answers so far require a quadratic time complexity of *O(n x m)*, where *n* and *m* are the lengths of `x` and `y`, respectively.
For a solution that requires just a linear time complexity of *O(n + m)*, you can normalize the strings in `x` to ones without commas and store them as a set, so that you can use set intersection to find common strings with `y`:
```
similar = {word.replace(',' ,'') for word in x}.intersection(y)
```
|
24,807,434
|
I've run into a problem with having imports in `__init__.py` and using `import as` with absolute imports in modules of the package.
My project has a subpackage and in its `__init__.py` I "lift" one of the classes from a module to the subpackage level with `from import as` statement. The module imports other modules from that subpackage with absolute imports. I get this error `AttributeError: 'module' object has no attribute 'subpkg'`.
Example
=======
**Structure**:
```
pkg/
├── __init__.py
├── subpkg
│ ├── __init__.py
│ ├── one.py
│ └── two_longname.py
└── tst.py
```
**pkg/**init**.py** is empty.
**pkg/subpkg/**init**.py**:
```
from pkg.subpkg.one import One
```
**pkg/subpkg/one.py**:
```
import pkg.subpkg.two_longname as two
class One(two.Two):
pass
```
**pkg/subpkg/two\_longname.py**:
```
class Two:
pass
```
**pkg/tst.py**:
```
from pkg.subpkg import One
print(One)
```
**Output**:
```
$ python3.4 -m pkg.tst
Traceback (most recent call last):
File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/and/dev/test/python/imptest2/pkg/tst.py", line 1, in <module>
from pkg.subpkg import One
File "/home/and/dev/test/python/imptest2/pkg/subpkg/__init__.py", line 1, in <module>
from pkg.subpkg.one import One
File "/home/and/dev/test/python/imptest2/pkg/subpkg/one.py", line 1, in <module>
import pkg.subpkg.two_longname as two
AttributeError: 'module' object has no attribute 'subpkg'
```
Workarounds
-----------
There are changes that make it work:
1. Empty `pkg/subpkg/__init__.py` and importing directly from `pkg.subpkg.one`.
I don't consider this as an option because AFAIK "lifting" things to the package level is ok. Here is quote from [an article](http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html):
>
> One common thing to do in your `__init__.py` is to import selected
> Classes, functions, etc into the package level so they can be
> conveniently imported from the package.
>
>
>
2. Changing `import as` to `from import` in `one.py`:
```
from pkg.subpkg import two_longname
class One(two_longname.Two):
pass
```
The only con here is that I can't create a short alias for module. I got that idea from @begueradj's answer.
It is also possible to use a relative import in `one.py` to fix the problem. But I think it's just a variation of workaround #2.
Questions
=========
1. Can someone explain what is actually going on here? Why a combination of imports in `__init__.py` and usage of `import as` leads to such problems?
2. Are there any better workarounds?
---
Original example
================
This is my original example. It's not very realistic but I'm not deleting it so @begueradj's answer still makes sense.
**pkg/**init**.py** is empty.
**pkg/subpkg/**init**.py**:
```
from pkg.subpkg.one import ONE
```
**pkg/subpkg/one.py**:
```
import pkg.subpkg.two
ONE = pkg.subpkg.two.TWO
```
**pkg/subpkg/two.py**:
```
TWO = 2
```
**pkg/tst.py**:
```
from pkg.subpkg import ONE
```
**Output**:
```
$ python3.4 -m pkg.tst
Traceback (most recent call last):
File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/and/dev/test/python/imptest/pkg/tst.py", line 1, in <module>
from pkg.subpkg import ONE
File "/home/and/dev/test/python/imptest/pkg/subpkg/__init__.py", line 2, in <module>
from pkg.subpkg.one import ONE
File "/home/and/dev/test/python/imptest/pkg/subpkg/one.py", line 6, in <module>
ONE = pkg.subpkg.two.TWO
AttributeError: 'module' object has no attribute 'subpkg'
```
Initially I had this in **one.py**:
```
import pkg.subpkg.two as two
ONE = two.TWO
```
In that case I get error on import (just like in my original project which uses `import as` too).
|
2014/07/17
|
[
"https://Stackoverflow.com/questions/24807434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3227133/"
] |
You incorrectly assume that one cannot have an alias with `from ... import`, as `from ... import ... as` has been there since Python 2.0. The `import ... as` is the obscure syntax that not many know about, but which you use by accident in your code.
[PEP 0221](http://legacy.python.org/dev/peps/pep-0221/) claims that the following 2 are "effectively" the same:
1. `import foo.bar.bazaar as baz`
2. `from foo.bar import bazaar as baz`
The statement is not quite true in **Python versions up to and including 3.6.x** as evidenced by the corner case you met, namely if the required modules already exist in `sys.modules` but are yet uninitialized. The `import ... as` requires that the module `foo.bar` is injected in `foo` namespace as the attribute `bar`, in addition to being in `sys.modules`, whereas the `from ... import ... as` looks for `foo.bar` in `sys.modules`.
(Do note also that `import foo.bar` only ensures that the module `foo.bar` is in `sys.modules` and accessible as `foo.bar`, but might not be fully initialized yet.)
Changing the code as follows did the trick for me:
```
# import pkg.subpkg.two_longname as two
from pkg.subpkg import two_longname as two
```
And code runs perfectly on both Python 2 and Python 3.
Also, in `one.py` you cannot do `from pkg import subpkg`, for the same reason.
---
To demonstrate this bug further, fix your `one.py` as above, and add the following code in `tst.py`:
```
import pkg
import pkg.subpkg.two_longname as two
del pkg.subpkg
from pkg.subpkg import two_longname as two
import pkg.subpkg.two_longname as two
```
Only the last line crashes, because `from ... import` consults the `sys.modules` for `pkg.subpkg` and finds it there, whereas `import ... as` consults `sys.modules` for `pkg` and tries to find `subpkg` as an attribute in the `pkg` module. As we just had deleted that attribute, the last line fails with `AttributeError: 'module' object has no attribute 'subpkg'`.
---
As the `import foo.bar as baz` syntax is a bit obscure and adds more corner cases, and I have rarely if ever seen it being used, I would recommend avoiding it completely and favouring `from .. import ... as`.
|
Your project structure regarding the way you call modules, must be like this:
```
pkg/
├── __init__.py
├── subpkg
│ ├── __init__.py
│ ├── one.py
│ └── two.py
tst.py
```
Define your **two.py** like this:
```
class TWO:
def functionTwo(self):
print("2")
```
Define your **one.py** like this :
```
from pkg.subpkg import two
class ONE:
def functionOne(self):
print("1")
self.T=two.TWO()
print("Calling TWO from ONE: ")
self.T.functionTwo()
```
Define your **test.py** like this
```
from pkg.subpkg import one
class TEST:
def functionTest(self):
O=one.ONE()
O.functionOne()
if __name__=='__main__':
T=TEST()
T.functionTest()
```
When you execute, you will get this:
```
1
Calling TWO from ONE:
2
```
Hope this helps.
|
24,807,434
|
I've run into a problem with having imports in `__init__.py` and using `import as` with absolute imports in modules of the package.
My project has a subpackage and in its `__init__.py` I "lift" one of the classes from a module to the subpackage level with `from import as` statement. The module imports other modules from that subpackage with absolute imports. I get this error `AttributeError: 'module' object has no attribute 'subpkg'`.
Example
=======
**Structure**:
```
pkg/
├── __init__.py
├── subpkg
│ ├── __init__.py
│ ├── one.py
│ └── two_longname.py
└── tst.py
```
**pkg/**init**.py** is empty.
**pkg/subpkg/**init**.py**:
```
from pkg.subpkg.one import One
```
**pkg/subpkg/one.py**:
```
import pkg.subpkg.two_longname as two
class One(two.Two):
pass
```
**pkg/subpkg/two\_longname.py**:
```
class Two:
pass
```
**pkg/tst.py**:
```
from pkg.subpkg import One
print(One)
```
**Output**:
```
$ python3.4 -m pkg.tst
Traceback (most recent call last):
File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/and/dev/test/python/imptest2/pkg/tst.py", line 1, in <module>
from pkg.subpkg import One
File "/home/and/dev/test/python/imptest2/pkg/subpkg/__init__.py", line 1, in <module>
from pkg.subpkg.one import One
File "/home/and/dev/test/python/imptest2/pkg/subpkg/one.py", line 1, in <module>
import pkg.subpkg.two_longname as two
AttributeError: 'module' object has no attribute 'subpkg'
```
Workarounds
-----------
There are changes that make it work:
1. Empty `pkg/subpkg/__init__.py` and importing directly from `pkg.subpkg.one`.
I don't consider this as an option because AFAIK "lifting" things to the package level is ok. Here is quote from [an article](http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html):
>
> One common thing to do in your `__init__.py` is to import selected
> Classes, functions, etc into the package level so they can be
> conveniently imported from the package.
>
>
>
2. Changing `import as` to `from import` in `one.py`:
```
from pkg.subpkg import two_longname
class One(two_longname.Two):
pass
```
The only con here is that I can't create a short alias for module. I got that idea from @begueradj's answer.
It is also possible to use a relative import in `one.py` to fix the problem. But I think it's just a variation of workaround #2.
Questions
=========
1. Can someone explain what is actually going on here? Why a combination of imports in `__init__.py` and usage of `import as` leads to such problems?
2. Are there any better workarounds?
---
Original example
================
This is my original example. It's not very realistic but I'm not deleting it so @begueradj's answer still makes sense.
**pkg/**init**.py** is empty.
**pkg/subpkg/**init**.py**:
```
from pkg.subpkg.one import ONE
```
**pkg/subpkg/one.py**:
```
import pkg.subpkg.two
ONE = pkg.subpkg.two.TWO
```
**pkg/subpkg/two.py**:
```
TWO = 2
```
**pkg/tst.py**:
```
from pkg.subpkg import ONE
```
**Output**:
```
$ python3.4 -m pkg.tst
Traceback (most recent call last):
File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/and/dev/test/python/imptest/pkg/tst.py", line 1, in <module>
from pkg.subpkg import ONE
File "/home/and/dev/test/python/imptest/pkg/subpkg/__init__.py", line 2, in <module>
from pkg.subpkg.one import ONE
File "/home/and/dev/test/python/imptest/pkg/subpkg/one.py", line 6, in <module>
ONE = pkg.subpkg.two.TWO
AttributeError: 'module' object has no attribute 'subpkg'
```
Initially I had this in **one.py**:
```
import pkg.subpkg.two as two
ONE = two.TWO
```
In that case I get error on import (just like in my original project which uses `import as` too).
|
2014/07/17
|
[
"https://Stackoverflow.com/questions/24807434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3227133/"
] |
You incorrectly assume that one cannot have an alias with `from ... import`, as `from ... import ... as` has been there since Python 2.0. The `import ... as` is the obscure syntax that not many know about, but which you use by accident in your code.
[PEP 0221](http://legacy.python.org/dev/peps/pep-0221/) claims that the following 2 are "effectively" the same:
1. `import foo.bar.bazaar as baz`
2. `from foo.bar import bazaar as baz`
The statement is not quite true in **Python versions up to and including 3.6.x** as evidenced by the corner case you met, namely if the required modules already exist in `sys.modules` but are yet uninitialized. The `import ... as` requires that the module `foo.bar` is injected in `foo` namespace as the attribute `bar`, in addition to being in `sys.modules`, whereas the `from ... import ... as` looks for `foo.bar` in `sys.modules`.
(Do note also that `import foo.bar` only ensures that the module `foo.bar` is in `sys.modules` and accessible as `foo.bar`, but might not be fully initialized yet.)
Changing the code as follows did the trick for me:
```
# import pkg.subpkg.two_longname as two
from pkg.subpkg import two_longname as two
```
And code runs perfectly on both Python 2 and Python 3.
Also, in `one.py` you cannot do `from pkg import subpkg`, for the same reason.
---
To demonstrate this bug further, fix your `one.py` as above, and add the following code in `tst.py`:
```
import pkg
import pkg.subpkg.two_longname as two
del pkg.subpkg
from pkg.subpkg import two_longname as two
import pkg.subpkg.two_longname as two
```
Only the last line crashes, because `from ... import` consults the `sys.modules` for `pkg.subpkg` and finds it there, whereas `import ... as` consults `sys.modules` for `pkg` and tries to find `subpkg` as an attribute in the `pkg` module. As we just had deleted that attribute, the last line fails with `AttributeError: 'module' object has no attribute 'subpkg'`.
---
As the `import foo.bar as baz` syntax is a bit obscure and adds more corner cases, and I have rarely if ever seen it being used, I would recommend avoiding it completely and favouring `from .. import ... as`.
|
Here is a theory on what's going on.
When you use the `as` reserved word, for instance:
```
import pkg.subpkg.two_longname as two
```
Python must to completely initialize and resolve all dependences that has to do with `pkg.subpkg`. But there is a problem, to completely load `subpkg` you need to completely load `one.py` as well right? wich at the same time imports `two_longname.py` using the `as` keyword ... Can you see the recursion here? That's why at the moment of doing:
```
import pkg.subpkg.two_longname as two
```
you get an error claiming `subpkg` does not exist.
To perform a test, go to one.py and change it to this:
```
#import pkg.subpkg.two_longname as two
from pkg.subpkg import two_longname
#class One(two.Two):
class One(two_longname.Two):
pass
```
I suppose this is all about performance, Python loads a module partially whenever is possible. And the `as` keyword is one of the exceptions. I don't know if there are others, but it would be interesting know about them.
|
24,807,434
|
I've run into a problem with having imports in `__init__.py` and using `import as` with absolute imports in modules of the package.
My project has a subpackage and in its `__init__.py` I "lift" one of the classes from a module to the subpackage level with `from import as` statement. The module imports other modules from that subpackage with absolute imports. I get this error `AttributeError: 'module' object has no attribute 'subpkg'`.
Example
=======
**Structure**:
```
pkg/
├── __init__.py
├── subpkg
│ ├── __init__.py
│ ├── one.py
│ └── two_longname.py
└── tst.py
```
**pkg/**init**.py** is empty.
**pkg/subpkg/**init**.py**:
```
from pkg.subpkg.one import One
```
**pkg/subpkg/one.py**:
```
import pkg.subpkg.two_longname as two
class One(two.Two):
pass
```
**pkg/subpkg/two\_longname.py**:
```
class Two:
pass
```
**pkg/tst.py**:
```
from pkg.subpkg import One
print(One)
```
**Output**:
```
$ python3.4 -m pkg.tst
Traceback (most recent call last):
File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/and/dev/test/python/imptest2/pkg/tst.py", line 1, in <module>
from pkg.subpkg import One
File "/home/and/dev/test/python/imptest2/pkg/subpkg/__init__.py", line 1, in <module>
from pkg.subpkg.one import One
File "/home/and/dev/test/python/imptest2/pkg/subpkg/one.py", line 1, in <module>
import pkg.subpkg.two_longname as two
AttributeError: 'module' object has no attribute 'subpkg'
```
Workarounds
-----------
There are changes that make it work:
1. Empty `pkg/subpkg/__init__.py` and importing directly from `pkg.subpkg.one`.
I don't consider this as an option because AFAIK "lifting" things to the package level is ok. Here is quote from [an article](http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html):
>
> One common thing to do in your `__init__.py` is to import selected
> Classes, functions, etc into the package level so they can be
> conveniently imported from the package.
>
>
>
2. Changing `import as` to `from import` in `one.py`:
```
from pkg.subpkg import two_longname
class One(two_longname.Two):
pass
```
The only con here is that I can't create a short alias for module. I got that idea from @begueradj's answer.
It is also possible to use a relative import in `one.py` to fix the problem. But I think it's just a variation of workaround #2.
Questions
=========
1. Can someone explain what is actually going on here? Why a combination of imports in `__init__.py` and usage of `import as` leads to such problems?
2. Are there any better workarounds?
---
Original example
================
This is my original example. It's not very realistic but I'm not deleting it so @begueradj's answer still makes sense.
**pkg/**init**.py** is empty.
**pkg/subpkg/**init**.py**:
```
from pkg.subpkg.one import ONE
```
**pkg/subpkg/one.py**:
```
import pkg.subpkg.two
ONE = pkg.subpkg.two.TWO
```
**pkg/subpkg/two.py**:
```
TWO = 2
```
**pkg/tst.py**:
```
from pkg.subpkg import ONE
```
**Output**:
```
$ python3.4 -m pkg.tst
Traceback (most recent call last):
File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/and/dev/test/python/imptest/pkg/tst.py", line 1, in <module>
from pkg.subpkg import ONE
File "/home/and/dev/test/python/imptest/pkg/subpkg/__init__.py", line 2, in <module>
from pkg.subpkg.one import ONE
File "/home/and/dev/test/python/imptest/pkg/subpkg/one.py", line 6, in <module>
ONE = pkg.subpkg.two.TWO
AttributeError: 'module' object has no attribute 'subpkg'
```
Initially I had this in **one.py**:
```
import pkg.subpkg.two as two
ONE = two.TWO
```
In that case I get error on import (just like in my original project which uses `import as` too).
|
2014/07/17
|
[
"https://Stackoverflow.com/questions/24807434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3227133/"
] |
You incorrectly assume that one cannot have an alias with `from ... import`, as `from ... import ... as` has been there since Python 2.0. The `import ... as` is the obscure syntax that not many know about, but which you use by accident in your code.
[PEP 0221](http://legacy.python.org/dev/peps/pep-0221/) claims that the following 2 are "effectively" the same:
1. `import foo.bar.bazaar as baz`
2. `from foo.bar import bazaar as baz`
The statement is not quite true in **Python versions up to and including 3.6.x** as evidenced by the corner case you met, namely if the required modules already exist in `sys.modules` but are yet uninitialized. The `import ... as` requires that the module `foo.bar` is injected in `foo` namespace as the attribute `bar`, in addition to being in `sys.modules`, whereas the `from ... import ... as` looks for `foo.bar` in `sys.modules`.
(Do note also that `import foo.bar` only ensures that the module `foo.bar` is in `sys.modules` and accessible as `foo.bar`, but might not be fully initialized yet.)
Changing the code as follows did the trick for me:
```
# import pkg.subpkg.two_longname as two
from pkg.subpkg import two_longname as two
```
And code runs perfectly on both Python 2 and Python 3.
Also, in `one.py` you cannot do `from pkg import subpkg`, for the same reason.
---
To demonstrate this bug further, fix your `one.py` as above, and add the following code in `tst.py`:
```
import pkg
import pkg.subpkg.two_longname as two
del pkg.subpkg
from pkg.subpkg import two_longname as two
import pkg.subpkg.two_longname as two
```
Only the last line crashes, because `from ... import` consults the `sys.modules` for `pkg.subpkg` and finds it there, whereas `import ... as` consults `sys.modules` for `pkg` and tries to find `subpkg` as an attribute in the `pkg` module. As we just had deleted that attribute, the last line fails with `AttributeError: 'module' object has no attribute 'subpkg'`.
---
As the `import foo.bar as baz` syntax is a bit obscure and adds more corner cases, and I have rarely if ever seen it being used, I would recommend avoiding it completely and favouring `from .. import ... as`.
|
As the accepted answer states this is an issue with Python's behavior.
I've filed a bug: <http://bugs.python.org/issue30024>
The fix by Serhiy Storchaka was merged and expected in Python 3.7
|
73,404,980
|
I need to include a directory containing a python script and binaries that need to be executed by the script based on the parsed arguments in the JavaFX application.
The project is modular and built using Maven (although the modular part is not such an important piece of information).
When built using the maven run configuration, application works properly but for the purpose of creating a runtime image I stumble upon the problem of not having the script executed when I run the generated launcher .bat script in the "bin" folder of the "target".
For the purpose of generating the runtime, I have put the script directory in the project "resources" folder. The script is executed from the Java code using the Java Runtime.
Let's say the code looks like this:
```
pyPath = Paths.get("src/main/resources/script/main.py").toAbsolutePath().toString();
command = "python"+pyPath+args;
runtime = Runtime.getRuntime();
process = runtime.exec(command);
```
And ***pom.xml*** file looks like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>gui</artifactId>
<version>1.0-SNAPSHOT</version>
<name>gui</name>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.8.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>18</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>18</version>
</dependency>
<dependency>
<groupId>org.controlsfx</groupId>
<artifactId>controlsfx</artifactId>
<version>11.1.1</version>
</dependency>
<dependency>
<groupId>com.dlsc.formsfx</groupId>
<artifactId>formsfx-core</artifactId>
<version>11.3.2</version>
<exclusions>
<exclusion>
<groupId>org.openjfx</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.kordamp.ikonli</groupId>
<artifactId>ikonli-javafx</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jfoenix</groupId>
<artifactId>jfoenix</artifactId>
<version>9.0.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.panteleyev</groupId>
<artifactId>jpackage-maven-plugin</artifactId>
<version>1.5.2</version>
<configuration>
<name>gui</name>
<appVersion>1.0.0</appVersion>
<vendor>1234</vendor>
<destination>target/dist</destination>
<module>com.example.gui/com.example.gui.Application</module>
<runtimeImage>target/example-gui</runtimeImage>
<winDirChooser>true</winDirChooser>
<winPerUserInstall>true</winPerUserInstall>
<winShortcut>true</winShortcut>
<winMenuGroup>Applications</winMenuGroup>
<icon>${project.basedir}/main/resources/img/icon.ico</icon>
<javaOptions>
<option>-Dfile.encoding=UTF-8</option>
</javaOptions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>18</source>
<target>18</target>
</configuration>
</plugin>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.8</version>
<executions>
<execution>
<id>default-cli</id>
<configuration>
<mainClass>com.example.gui/com.example.gui.Application</mainClass>
<launcher>gui-launcher</launcher>
<jlinkZipName>gui</jlinkZipName>
<jlinkImageName>gui</jlinkImageName>
<jlinkVerbose>true</jlinkVerbose>
<noManPages>true</noManPages>
<stripDebug>true</stripDebug>
<noHeaderFiles>true</noHeaderFiles>
<options>
<option>--add-opens</option><option>javafx.graphics/com.sun.javafx.scene=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.base/com.sun.javafx.binding=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.base/com.sun.javafx.event=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.base/com.sun.javafx.binding=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.graphics/com.sun.javafx.scene=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.base/com.sun.javafx.event=ALL-UNNAMED</option>
</options>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
```
\***Note: additional options for the javafx-maven-plugin are added for the jfoenix package compatibility**
Also **module-info.java**
```
module com.example.gui {
requires javafx.controls;
requires javafx.fxml;
requires org.controlsfx.controls;
requires com.dlsc.formsfx;
requires org.kordamp.ikonli.javafx;
requires com.jfoenix;
opens com.example.gui to javafx.fxml;
exports com.example.gui;
}
```
Now the question is how do I include the script in the application runtime image, have it executed when I call the generated .bat for the application and finally packed using the jpackage?
|
2022/08/18
|
[
"https://Stackoverflow.com/questions/73404980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19794251/"
] |
Problems
========
The `src/main/resources` directory only exists in your project sources. It does not exist in the build output, and it definitely does not exist in your deployment location. In other words, using:
```java
var pyPath = Paths.get("src/main/resources/script/main.py").toAbsolutePath().toString();
```
Will only work when your working directory is your project directory. It's also reading the "wrong" `main.py` resource, as the "correct" one will be in your `target` directory. Additionally, resources are **not** files. You must access resources using the resource-lookup API. For example:
```java
var pyPath = getClass().getResource("/script/main.py").toString();
```
And note `src/main/resources` is not included in the resource name.
Executing the Script
--------------------
But even after you correctly access the resource you still have a problem. Your script is a resource, which means it will be embedded in a JAR file or custom run-time image when deployed. I strongly doubt Python will know how to read and execute such a resource. This means you need to find a way to make the Python script a regular file on the host computer.
---
Potential Solutions
===================
I can think of at least three approaches that may solve the problems described above. As I only have Windows, I can't promise the below examples will work on other platforms, or otherwise be easily translated for other platforms.
My examples don't include JavaFX, as I don't believe that's necessary to demonstrate how to include a Python script that is executed at runtime.
Here are some common aspects between all solutions.
**module-info.java:**
```java
module com.example {}
```
**main.py:**
```python
print("Hello from Python!")
```
1. Extract the Script at Runtime
--------------------------------
One approach is to extract the Python script to a known location on the host computer at runtime. This is likely the most versatile solution, as it doesn't depend much on the way you deploy your application (jar, jlink, jpackage, etc.).
This example extracts the script to a temporary file, but you can use another location, such as an application-specific directory under the user's home directory. You can also code it to extract only if not already extracted, or only once per application instance.
I think this is the solution I would use, at least to start with.
**Project structure:**
```none
| pom.xml
|
\---src
\---main
+---java
| | module-info.java
| |
| \---com
| \---example
| \---app
| Main.java
|
\---resources
\---scripts
main.py
```
**Main.java:**
```java
package com.example.app;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
Path target = Files.createTempDirectory("sample-1.0").resolve("main.py");
try {
// extract resource to temp file
try (InputStream in = Main.class.getResourceAsStream("/scripts/main.py")) {
Files.copy(in, target);
}
String executable = "python";
String script = target.toString();
System.out.printf("COMMAND: %s %s%n", executable, script); // log command
new ProcessBuilder(executable, script).inheritIO().start().waitFor();
} finally {
// cleanup for demo
Files.deleteIfExists(target);
Files.deleteIfExists(target.getParent());
}
}
}
```
**pom.xml:**
```xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>sample</artifactId>
<version>1.0</version>
<name>sample</name>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>18</maven.compiler.release>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<archive>
<manifest>
<mainClass>com.example.app.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jlink-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>default-cli</id>
<phase>package</phase>
<goals>
<goal>jlink</goal>
</goals>
</execution>
</executions>
<configuration>
<classifier>win</classifier>
</configuration>
</plugin>
<plugin>
<groupId>org.panteleyev</groupId>
<artifactId>jpackage-maven-plugin</artifactId>
<version>1.5.2</version>
<executions>
<execution>
<id>default-cli</id>
<phase>package</phase>
<goals>
<goal>jpackage</goal>
</goals>
</execution>
</executions>
<configuration>
<type>APP_IMAGE</type>
<runtimeImage>${project.build.directory}/maven-jlink/classifiers/win</runtimeImage>
<module>com.example/com.example.app.Main</module>
<destination>${project.build.directory}/image</destination>
<winConsole>true</winConsole>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
Build the project with:
```none
mvn package
```
And then execute the built application image:
```none
> .\target\image\sample\sample.exe
COMMAND: python C:\Users\***\AppData\Local\Temp\sample-1.015076039373849618085\main.py
Hello from Python!
```
2. Place the Script in the "Application Directory"
--------------------------------------------------
*Disclaimer: I don't know if doing this is a smart or even supported approach.*
This solution makes use of `--input` to place the script in the "application directory" of the application image. You can then get a reference to this directory by setting a system property via `--java-options` and `$APPDIR`. Note I tried to get this to work with the class-path, so as to not need the `$APPDIR` system property, but everything I tried resulted in `Class#getResource(String)` returning `null`.
The application directory is the `app` directory shown in [this documentation](https://docs.oracle.com/en/java/javase/18/jpackage/packaging-overview.html#GUID-DAE6A497-6E6F-4895-90CA-3C71AF052271).
As this solution places the Python script with the rest of the application image, which means it's placed in the installation location, you may be more likely to run into file permission issues.
Given the way I coded `Main.java`, this demo *must* be executed only after packaging with `jpackage`. I suspect there's a more robust way to implement this solution.
**Project structure:**
```none
| pom.xml
|
+---lib
| \---scripts
| main.py
|
\---src
\---main
\---java
| module-info.java
|
\---com
\---example
\---app
Main.java
```
**Main.java:**
```java
package com.example.app;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
String executable = "python";
String script = Path.of(System.getProperty("app.dir"), "scripts", "main.py").toString();
System.out.printf("COMMAND: %s %s%n", executable, script); // log command
new ProcessBuilder(executable, script).inheritIO().start().waitFor();
}
}
```
**pom.xml:**
(this is only the `<configuration>` of the `org.panteleyev:jpackage-maven-plugin` plugin, as everything else in the POM is unchanged from the first solution)
```xml
<configuration>
<type>APP_IMAGE</type>
<runtimeImage>${project.build.directory}/maven-jlink/classifiers/win</runtimeImage>
<input>lib</input>
<javaOptions>
<javaOption>-Dapp.dir=$APPDIR</javaOption>
</javaOptions>
<module>com.example/com.example.app.Main</module>
<destination>${project.build.directory}/image</destination>
<winConsole>true</winConsole>
</configuration>
```
Build the project with:
```none
mvn package
```
And then execute the built application image:
```none
> .\target\image\sample\sample.exe
COMMAND: python C:\Users\***\Desktop\sample\target\image\sample\app\scripts\main.py
Hello from Python!
```
3. Add the Script as Additional "App Content"
---------------------------------------------
*Disclaimer: Same as the disclaimer for the second solution.*
This would make use of the `--app-content` argument when invoking `jpackage`. Unfortunately, I could not figure out how to configure this using Maven, at least not with the `org.panteleyev:jpackage-maven-plugin` plugin. But essentially this solution would have been the same as the second solution above, but with `--input` removed and `--app-content lib/scripts` added. And a slight change to how the script `Path` is resolved in code.
The `--app-content` argument seems to put whatever directories/files are specified in the root of the generated application image. I'm not sure of a nice convenient way to get this directory, as the application image structure is slightly different depending on the platform. And as far as I can tell, there's no equivalent `$APPDIR` for the image's root directory.
|
I managed to create the artifacts using the [Java Packager](https://github.com/fvarrui/JavaPackager) plugin for Maven which made the deployment a much easier task.
|
19,795,357
|
I need to run some python files over and over with different settings and different file names.
Here is an example of a task I need to do. This is for Linux, but I need to do the same thing in Windows. Is there a way to use python to be the caller and run other python scripts which are already set to work on STD I/O? Does python have a shell like this? I would rather do this than switch over to maintaining batch code on both Linux and Windows.
```
#!/bin/bash
#run scripts to generate and manipulate data
for ((i=1; i<=3 ; i++))
do
randfuncgen.py -k 12 > randomvalues_$i.fitdata
probe.py -k 12 < randomvalues_$i.fitdata > randomvalues_$i.walshdata
std.py -m s < randomvalue_$i.walshdata > randomvalues_separate_std_$i.walshdata
std.py -m a < randomvalue_$i.walshdata > randomvalues_all_std_$i.walshdata
done
```
|
2013/11/05
|
[
"https://Stackoverflow.com/questions/19795357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] |
Don't think you can work around using `require`, but you can specifically check for `MODULE_NOT_FOUND` errors:
```
function moduleExists(mod) {
try {
require(mod);
} catch(e) {
if (e.code === 'MODULE_NOT_FOUND')
return false;
throw e;
};
return true;
}
```
|
I'm showing with the "swig" module. There might be better ways, but this works for me.
```
var swig;
try {
swig = require('swig');
} catch (err) {
console.log(" [FAIL]\t Cannot load swig.\n\t Have you tried installing it? npm install swig");
}
if (swig != undefined) {
console.log(" [ OK ]\t Module: swig");
}
```
|
19,795,357
|
I need to run some python files over and over with different settings and different file names.
Here is an example of a task I need to do. This is for Linux, but I need to do the same thing in Windows. Is there a way to use python to be the caller and run other python scripts which are already set to work on STD I/O? Does python have a shell like this? I would rather do this than switch over to maintaining batch code on both Linux and Windows.
```
#!/bin/bash
#run scripts to generate and manipulate data
for ((i=1; i<=3 ; i++))
do
randfuncgen.py -k 12 > randomvalues_$i.fitdata
probe.py -k 12 < randomvalues_$i.fitdata > randomvalues_$i.walshdata
std.py -m s < randomvalue_$i.walshdata > randomvalues_separate_std_$i.walshdata
std.py -m a < randomvalue_$i.walshdata > randomvalues_all_std_$i.walshdata
done
```
|
2013/11/05
|
[
"https://Stackoverflow.com/questions/19795357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] |
The best way is to use [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve), since it does not actually run any code contained in the module.
>
> Use the internal `require()` machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.
>
>
>
Just like `require`, `resolve` throws if the module is not found, so it needs to be wrapped in `try`/`catch`.
|
I'm showing with the "swig" module. There might be better ways, but this works for me.
```
var swig;
try {
swig = require('swig');
} catch (err) {
console.log(" [FAIL]\t Cannot load swig.\n\t Have you tried installing it? npm install swig");
}
if (swig != undefined) {
console.log(" [ OK ]\t Module: swig");
}
```
|
19,795,357
|
I need to run some python files over and over with different settings and different file names.
Here is an example of a task I need to do. This is for Linux, but I need to do the same thing in Windows. Is there a way to use python to be the caller and run other python scripts which are already set to work on STD I/O? Does python have a shell like this? I would rather do this than switch over to maintaining batch code on both Linux and Windows.
```
#!/bin/bash
#run scripts to generate and manipulate data
for ((i=1; i<=3 ; i++))
do
randfuncgen.py -k 12 > randomvalues_$i.fitdata
probe.py -k 12 < randomvalues_$i.fitdata > randomvalues_$i.walshdata
std.py -m s < randomvalue_$i.walshdata > randomvalues_separate_std_$i.walshdata
std.py -m a < randomvalue_$i.walshdata > randomvalues_all_std_$i.walshdata
done
```
|
2013/11/05
|
[
"https://Stackoverflow.com/questions/19795357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] |
The best way is to use [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve), since it does not actually run any code contained in the module.
>
> Use the internal `require()` machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.
>
>
>
Just like `require`, `resolve` throws if the module is not found, so it needs to be wrapped in `try`/`catch`.
|
Don't think you can work around using `require`, but you can specifically check for `MODULE_NOT_FOUND` errors:
```
function moduleExists(mod) {
try {
require(mod);
} catch(e) {
if (e.code === 'MODULE_NOT_FOUND')
return false;
throw e;
};
return true;
}
```
|
55,602,574
|
I am attempting to programmatically put data into a locally running DynamoDB Container by triggering a Python lambda expression.
I'm trying to follow the template provided here: <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.03.html>
I am using the amazon/dynamodb-local you can download here: <https://hub.docker.com/r/amazon/dynamodb-local>
Using Ubuntu 18.04.2 LTS to run the container and lambda server
AWS Sam CLI to run my Lambda api
Docker Version 18.09.4
Python 3.6 (You can see this in sam logs below)
Startup command for python lambda is just "sam local start-api"
First my Lambda Code
```
import json
import boto3
def lambda_handler(event, context):
print("before grabbing dynamodb")
# dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000",region_name='us-west-2',AWS_ACCESS_KEY_ID='RANDOM',AWS_SECRET_ACCESS_KEY='RANDOM')
dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")
table = dynamodb.Table('ContactRequests')
try:
response = table.put_item(
Item={
'id': "1234",
'name': "test user",
'email': "testEmail@gmail.com"
}
)
print("response: " + str(response))
return {
"statusCode": 200,
"body": json.dumps({
"message": "hello world"
}),
}
```
I know that I should have this table ContactRequests available at localhost:8000, because I can run this script to view my docker container dynamodb tables
I have tested this with a variety of values in the boto.resource call to include the access keys, region names, and secret keys, with no improvement to result
```
dev@ubuntu:~/Projects$ aws dynamodb list-tables --endpoint-url http://localhost:8000
{
"TableNames": [
"ContactRequests"
]
}
```
I am also able to successfully hit the localhost:8000/shell that dynamodb offers
Unfortunately while running, if I hit the endpoint that triggers this method, I get a timeout that logs like so
```
Fetching lambci/lambda:python3.6 Docker container image......
2019-04-09 15:52:08 Mounting /home/dev/Projects/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro inside runtime container
2019-04-09 15:52:12 Function 'HelloWorldFunction' timed out after 3 seconds
2019-04-09 15:52:13 Function returned an invalid response (must include one of: body, headers or statusCode in the response object). Response received:
2019-04-09 15:52:13 127.0.0.1 - - [09/Apr/2019 15:52:13] "GET /hello HTTP/1.1" 502 -
```
Notice that none of my print methods are being triggered, if I remove the call to table.put, then the print methods are successfully called.
I've seen similar questions on Stack Overflow such as this [lambda python dynamodb write gets timeout error](https://stackoverflow.com/questions/44034289/lambda-python-dynamodb-write-gets-timeout-error) that state that the problem is I am using a local db, but shouldn't I still be able to write to a local db with boto3, if I point it to my locally running dynamodb instance?
|
2019/04/09
|
[
"https://Stackoverflow.com/questions/55602574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740463/"
] |
As per [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters) suggests, the `monthIndex` would start at 0, rather than 1. So you need to manually subtract 1.
```
data.forEach((item) => {
item.date.pop()
item.date[1]--
item.date = new Date(...item.date).toLocaleString('en-US')
});
```
|
The month is represented by a value from 0 to 11, 4 is the fifth month, it corresponds to May, you just need to decrease it by 1.
|
60,654,425
|
I am making a lot of plots and saving them to a file, it all works, but during the compilation I get the following message:
```
RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
fig = self.plt.figure(figsize=self.figsize)
```
So I think I could improve the code by closing the figures, I googled it and found that I should use `fig.close()`. However I get the following error `'Figure' object has no attribute 'close'`. How should I make it work?
This is the loop in which I create plots:
```
for i in years:
ax = newdf.plot.barh(y=str(i), rot=0)
fig = ax.get_figure()
fig.savefig('C:\\Users\\rysza\\Desktop\\python data analysis\\zajecia3\\figure'+str(i)+'.jpeg',bbox_inches='tight')
fig.close()
```
|
2020/03/12
|
[
"https://Stackoverflow.com/questions/60654425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11085398/"
] |
Replace `fig.close()` with `plt.close(fig)`, [`close`](https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html) is a function defined directly in the module.
|
Try this, matplotlib.pyplot.close(fig) , for more information refer this website
<https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html>
|
14,082,909
|
I'm creating a simple script for blender and i need a little help with get some data from file i've created before via python.
That file got structure like below:
```
name first morph
values -1.0000 1.0000
data 35 0.026703 0.115768 -0.068769
data 36 -0.049349 0.015188 -0.029470
data 37 -0.042880 -0.045805 -0.039931
data 38 0.000000 0.115775 -0.068780
name second morph
values -0.6000 1.2000
data 03 0.037259 -0.046251 -0.020062
data 04 -0.010330 -0.046106 -0.019890
…
```
etc more 2k lines ;p
What i need is to create a loop that read for me those data line by line and put values into three different arrays: names[] values[] and data[] depending on first word of file line.
```
Manualy it should be like that:
names.append('first morph')
values.append( (-1.0000,1.0000))
data.append((35, 0.026703, 0.115768, -0.068769))
data.append((36, -0.049349, 0.015188, -0.029470))
data.append((37, -0.042880, -0.045805, -0.039931))
data.append((38, 0.000000, 0.115775, -0.068780))
names.append('second morph')
values.append( (-0.6000,1.2000))
…
```
I dont know why my atempts of creating that kind of 'for line in file:' loop creating more errors than complete data, i dont know why is going out of range, or not getting proper data
Please help how to automate that process instead of writing manualy each line since i already exported needed parameters into a file.
|
2012/12/29
|
[
"https://Stackoverflow.com/questions/14082909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1936580/"
] |
```
names = []
values = []
data = []
with open('yourfile') as lines:
for line in lines:
first, rest = line.split(' ', 1)
if first == 'name':
names.append(rest)
elif first == 'values':
floats = map(float, rest.split())
values.append(tuple(floats))
elif first == 'data':
int_str, floats_str = rest.split(' ', 1)
floats = map(float, floats_str.split())
data.append( (int(int_str),) + tuple(floats) )
```
Why do you need it like this? How will you know where the next name starts in your data and values lists?
|
Here is a simple python "for line in" solution... you can just call `processed.py`...
```
fp = open("data1.txt", "r")
data = fp.readlines()
fp1 = open("processed.py", "w")
fp1.write("names = []\nvalues=[]\ndata=[]\n")
for line in data:
s = ""
if "name" in line:
s = "names.append('" + line[5:].strip() + "')"
elif "values" in line:
s = "values.append((" + ", ".join(line[7:].strip().split(" ")) + "))"
elif "data" in line:
s = "data.append((" + ", ".join(line[5:].strip().split(" ")) + "))"
fp1.write(s + "\n");
fp1.close()
fp.close()
```
|
33,936,017
|
I learn how to remove items from a list while iterating from [here](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) by:
```
somelist = [x for x in somelist if determine(x)]
```
Further, how do I remove a specific index from a list while iterating? For instance,
```
lists = list() # a list of lists
for idx, line in enumerate(lists):
if idx > 0:
cur_val = line[0] # value of current line
prev_val = lists[idx-1][0] # value of previous line
if prev_val == cur_val :
del lists[idex-1] # IndexError: list index out of range
```
|
2015/11/26
|
[
"https://Stackoverflow.com/questions/33936017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3067748/"
] |
Basically your attempt is not supported according to any documentation. In general you should not modify a container while iterating unless the documentation explicitly says that you can. It doesn't help if it "seems to work" since you then just exploiting some behavior in the version of the implementation you're using, but that behavior can change without prior notice (breaking your program).
What you need to do is making the modification separate from the iteration. Using list comprehension is one way to achieve this, but basically you're doing the same thing.
There's a few variants, either you make a copy of the data and iterate through that and modify the original. Or you make a copy before iterating the original and modify the copy and then updates the original. There's also the variant where you build the copy during iteration and then update the original.
In addition your example is flawed because you don't take into account that modification affects the proper index in the modified `list`. For example if you have the list `[1, 1, 2, 2, 3, 3]`, then when you've removed the duplicates `1`s and `2`s and detect duplicate `3`s you have the list `[1, 2, 3, 3]`, but when you find the duplicate `3`s you find these at index `4` and `5`, but after the deletion they are at index `2` and `3` instead.
```
lists = list() # a list of lists
cur = 0 # index in the modified list
for idx, line in list(enumerate(lists)): # make a copy of the original
if idx > 0:
cur_val = line[0] # value of current line
prev_val = lists[idx-1][0] # value of previous line
if prev_val == cur_val:
del lists[cur-1] # IndexError: list index out of range
else:
cur += 1
else:
cur += 1
```
The solution where you modify a copy instead is basically the same, but the solution where you build the copy during iteration is a bit different.
```
lists = list() # a list of lists
tmp = []
for idx, line in enumerate(lists): # make a copy of the original
if idx > 0:
cur_val = line[0] # value of current line
prev_val = lists[idx-1][0] # value of previous line
if prev_val != cur_val:
tmp.append(line)
else:
tmp.append( line )
lists[:] = tmp
```
The last line is where the origin is updated, otherwise the loop works by appending those elements that are to be kept to `tmp` (instead of copying all and then remove those that's not to be kept).
|
You can produce the same thing using list comprehension:
```
somelist = [i for idx, i in enumerate(lists) if i[0] != lists[idx][0]]
```
|
13,033,820
|
I have a question about while loops in python.
I want to make a program that performs a while loop in a certain time.I want to add the extra feature that while the program us running,a certain variable can be changed by pressing a random key.
```
from time import sleep
import time
i=0
a=0
while i<10:
i=i+1
i=i+a
a=a+1
time.sleep(1)
print i
```
I want to do it that the variable a can be reset to 0 by pressing any key.The loop should continue unchanged if no button is pressed.What command should i add?
Thanks
Edit: I tried:
```
import pygame
from pygame.locals import *
import time
i=0
a=0
pygame.init()
while i<10:
pygame.event.get()
i=i+a
print i
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
i=0
i=i+1
time.sleep(1)
pygame.quit()
```
But now nothing happens when I press a button.What did i miss?
|
2012/10/23
|
[
"https://Stackoverflow.com/questions/13033820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714419/"
] |
This might be happening because you render the *header*, *menu* and *body* inside a `<table>`. At least the *body* seems to be missing the row and cell tags (`<tr><td>...</td></tr>`). Therefore there are no rows and cells in your table which can lead to all sorts of rendering problems.
It would probably help if you didn't render into a table and use CSS for layout purposes instead.
|
This looks to be nothing to do with the MVC side of what you are doing - that looks perfectly fine.
The issue will be with your HTML. I would suggest having a look at the site using one of the browser developer tools (e.g. in Chrome or IE open your site and press F12) - you can use the features of these to examine how the visual elements on your page relate to the HTML. These tools are invaluable as an MVC programmer.
Using tables to control the layout of a web-page is discouraged in favour of using css for layout. You can find some basic css layout templates via Google to get started.
|
59,407,592
|
Below code has a call to a method called **lago**.
```
#!/usr/bin/env python
#
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
#
import sys
class InstallTest():
"""Ru Ovirt System Tests"""
def run_command_checking_exit_code(command):
""" Runs a command"""
print("Command is " + str(command))
print(command.read())
print(command.close())
def lago():
"""run the conductor profiles required to install OLVM """
Log.test_objective('TODO')
run_command_checking_exit_code('ls -al')
"""
yum_list = ["epel-release", "centos-release-qemu-ev", "python-devel", "libvirt", "libvirt-devel", "libguestfs-tools", "libguestfs-devel", "gcc", "libffi-devel", "openssl-devel", "qemu-kvm-ev"]
for yum in yum_list
ret, msg, tup = self.client.run('/qa/conductor/tests/' + OSSE_OLV_VERSION + '/installer/installerfactory.py -s ' + OSSE_OLV_ENGINE_HOST + ' -t OS_OL7U6_X86_64_PVHVM_30GB -c 10.1.0.10 -o ' + self.log_jobdir_cc +'/vm_install_ol7.6', timeout=1000000)
if ret:
self.tc_fail('Creation of OLV Engine VM failed')
ret, msg, tup = self.client.run('/qa/conductor/tests/' + OSSE_OLV_VERSION + '/installer/installerfactory.py -s ' + OSSE_OLV_ENGINE_HOST +' -p ovirt-engine -c 10.1.0.10 -o ' + self.log_jobdir_cc + '/engine_deploy', timeout=1000000)
if ret:
self.tc_fail('Install of OLV Engine Host failed')
self.tc_pass('OLV Engine Host installed')
"""
def main():
lago()
main()
```
However, it is shown to not exist in the output
```
Traceback (most recent call last):
File "C:/Users/rafranci/Downloads/ovirt_st_setup.py", line 20, in <module>
class InstallTest():
File "C:/Users/rafranci/Downloads/ovirt_st_setup.py", line 65, in InstallTest
main()
File "C:/Users/rafranci/Downloads/ovirt_st_setup.py", line 63, in main
lago()
NameError: name 'lago' is not defined
```
As far as I can see, there is no reason for this - ideas?
|
2019/12/19
|
[
"https://Stackoverflow.com/questions/59407592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12342391/"
] |
Try this :
```js
var value1="4111111111111111"
var pattern = new RegExp('^4[0-9]{12}(?:[0-9]{3})?$}');
var result=pattern.test(value1);
console.log(result);
```
This will return either `True` or `False`
|
If you pattern is somthimg like that: `4111111111111111` or `4111111111111111`
then use this code:
```
const str="^4[0-9]{12}([0-9]{3})?$";
'4111111111111'.match(str)
'4111111111111111'.match(str)
```
|
56,750,400
|
Is there any library implementation for the `label2idx()` function in python?
I wish to extract superpixels from the label representation to the format exactly returned by the `label2idx()` function.
label2idx function: <https://in.mathworks.com/help/images/ref/label2idx.html>
|
2019/06/25
|
[
"https://Stackoverflow.com/questions/56750400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9215748/"
] |
Given an array of labels `label_arr` containing all labels from `1` to `max(label_arr)`, you can do:
```
def label2idx(label_arr):
return [
np.where(label_arr.ravel() == i)[0]
for i in range(1, np.max(label_arr) + 1)]
```
---
If you want to relax the requirement of all labels being contained you can add a simple `if`, i.e.:
```
def label2idx(label_arr):
return [
np.where(label_arr.ravel() == i)[0]
if i in label_arr else np.array([], dtype=int)
for i in range(1, np.max(label_arr) + 1)]
```
---
Just to replicate the example in the MATLAB docs:
```
import numpy as np
import scipy as sp
import scipy.ndimage
struct_arr = np.array(
[[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 1, 1, 0],
[1, 1, 1, 0, 0, 0, 0, 0]])
label_arr, num_labels = sp.ndimage.label(struct_arr)
# label_arr:
# [[1 1 1 0 0 0 0 0]
# [1 1 1 0 2 2 0 0]
# [1 1 1 0 2 2 0 0]
# [1 1 1 0 0 0 0 0]
# [1 1 1 0 0 0 3 0]
# [1 1 1 0 0 0 3 0]
# [1 1 1 0 0 3 3 0]
# [1 1 1 0 0 0 0 0]]
def label2idx(label_arr):
return [
np.where(label_arr.ravel() == i)[0]
for i in range(1, np.max(label_arr) + 1)]
pixel_idxs = label2idx(label_arr)
for pixel_idx in pixel_idxs:
print(pixel_idx)
# [ 0 1 2 8 9 10 16 17 18 24 25 26 32 33 34 40 41 42 48 49 50 56 57 58]
# [12 13 20 21]
# [38 46 53 54]
```
Note, however that you do not get the very same results because of the differences between MATLAB and NumPy, notably:
* MATLAB: FORTRAN-style matrix indexing and 1-based indexing
* Python+NumPy: C-style matrix indexing and 0-based indexing
and if you want to get the very same numbers you get in MATLAB you may use this instead (note the extra `.T` and the `+ 1`):
```
def label2idx_MATLAB(label_arr):
return [
np.where(label_arr.T.ravel() == i)[0] + 1
for i in range(1, np.max(label_arr) + 1)]
```
|
MATLAB's [`label2idx`](https://www.mathworks.com/help/images/ref/label2idx.html) outputs the flattened indices (column-major ordered) given the labeled image.
We can use `scikit-image's` built-in [`regionprops`](https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops) to get those indices from the labeled image. `Scikit-image` also provides for us a built-in to get the labeled image, so it all works out with that same package. The implementation would look something like this -
```
from skimage.measure import label,regionprops
def label2idx(L):
# Get region-properties for all labels
props = regionprops(L)
# Get XY coordinates/indices for each label
indices = [p.coords for p in props]
# Get flattened-indices for each label, similar to MATLAB version
# Note that this is row-major ordered.
flattened_indices = [np.ravel_multi_index(idx.T,L.shape) for idx in indices]
return indices, flattened_indices
```
Sample run -
```
# Input array
In [62]: a
Out[62]:
array([[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 1, 1, 0],
[1, 1, 1, 0, 0, 0, 0, 0]])
# Get labeled image
In [63]: L = label(a)
In [64]: idx,flat_idx = label2idx(L)
In [65]: flat_idx
Out[65]:
[array([ 0, 1, 2, 8, 9, 10, 16, 17, 18, 24, 25, 26, 32, 33, 34, 40, 41,
42, 48, 49, 50, 56, 57, 58]),
array([12, 13, 20, 21]),
array([38, 46, 53, 54])]
```
If you need the indices in column-major order like in MATLAB, simply transpose the image and then feed in -
```
In [5]: idx,flat_idx = label2idx(L.T)
In [6]: flat_idx
Out[6]:
[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23]),
array([33, 34, 41, 42]),
array([46, 52, 53, 54])]
```
Note that the indexing still starts from `0`, unlike in MATLAB where it's from `1`.
**Alternative to getting labeled image with SciPy**
SciPy also has a built-in to get labeled-image : [`scipy.ndimage.label`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.label.html) -
```
from scipy.ndimage import label
L = label(a)[0]
```
|
37,662,732
|
I'm looking for an XPATH to extract 'sets' as separate sequences. It has to be interpreted by python `lxml` (which is a wrapper around `libxml2`).
For example, given the following:
```
<root>
<sub1>
<sub2>
<Container>
<item>1 - My laptop has exploded again</item>
<item>2 - This is an issue which needs to be fixed.</item>
</Container>
</sub2>
<sub2>
<Container>
<item>3 - It's still not working</item>
<item>4 - do we have a working IT department or what?</item>
</Container>
</sub2>
<sub2>
<Container>
<item>5 - Never mind - I got my 8 year old niece to fix it</item>
</Container>
</sub2>
</sub1>
</root>
```
I want to be able to 'isolate' each group or sequence, e.g. sequence 1 being:
```
1 - My laptop has exploded again
2 - This is an issue which needs to be fixed.
```
Second sequence:
```
3 - It's still not working
4 - do we have a working IT department or what?
```
Third sequence:
```
5 - Never mind - I got my 8 year old niece to fix it
```
Where 'sequence' would be, translated in pseudocode/python:
```
seq1 = ['1 - My laptop has exploded again', '2 - This is an issue which needs to be fixed.']
seq2 = ['3 - It's still not working', '4 - do we have a working IT department or what?']
seq 3 = ['5 - Never mind - I got my 8 year old niece to fix it']
```
From some preliminary research it seems like [sequences can't be nested](https://stackoverflow.com/questions/32732003/in-xpath-how-can-i-select-groups-of-following-sibling-nodes-before-and-after-an) but I'm wondering if there's some black magic doable with [these operators](http://zvon.org/comp/r/tut-XPath_1.html#Pages~List_of_XPaths).
|
2016/06/06
|
[
"https://Stackoverflow.com/questions/37662732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204634/"
] |
1. Evaluate this XPath expression:
`count(/*/*/*)`
This finds the number of `<sub2>` elements (equivalent and more readable, but longer, is:
```
count(/*/sub1/sub2))
```
2. For each `$n` in 1 to `count(/*/*/*)` evaluate the following XPath expression:
`/*/*/*[$n]/*/item/text()`
Again, this is equivalent to the longer and more readable:
```
/*/sub1/sub2[$n]/Container/item/text()
```
Before evaluating the above expressions replace `$n` with the actual value of `$n` (for example using the `format()` method for strings.
For the provided XML document `$n` is 3, therefore the actual XPath expressions that are evaluated are:
```
/*/*/*[1]/*/item/text()
```
,
```
/*/*/*[2]/*/item/text()
```
,
```
/*/*/*[3]/*/item/text()
```
And they produce the following results each:
A collection (language - dependent -- array, sequence, collection, `IEnumerable<string>`, ... etc.):
```
"1 - My laptop has exploded again", "2 - This is an issue which needs to be fixed."
```
,
```
"3 - It's still not working", "4 - do we have a working IT department or what?"
```
,
```
"5 - Never mind - I got my 8 year old niece to fix it"
```
|
```
from lxml import etree
doc=etree.parse("data.xml");
v = doc.findall('sub1/sub2/Container')
finalResult = list()
for vv in v:
sequence = list()
for item in vv.findall('item'):
sequence.append(item.text)
finalResult.append(sequence)
print finalResult
```
And this is the result:
```
[['1 - My laptop has exploded again', '2 - This is an issue which needs to be fixed.'], ["3 - It's still not working", '4 - do we have a working IT department or what?'], ['5 - Never mind - I got my 8 year old niece to fix it']]
```
### Note
I assumed that the data is in a file named 'data.xml' in the same directory as the script that contains the above code.
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.html#locale.getpreferredencoding):
>
> Return the encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.
>
>
>
[Here](https://stackoverflow.com/a/34345136/645146) I found "hacky" but working method to overwrite these settings:
In file `settings.py` of your django project add these lines:
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
|
Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.
[djangoproject.com](https://code.djangoproject.com/ticket/32439)
the settings box looks like this. Enable the check and restart your system
[](https://i.stack.imgur.com/dv0tU.png)
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
One solution is to use `./manage.py dumpdata -o data.json` instead of `./manage.py dumpdata > data.json`.
Another solution is to use [Python's UTF-8 mode](https://docs.python.org/3/using/cmdline.html?highlight=utf%20mode#id5), run:
```
python -Xutf8 ./manage.py dumpdata > data.json
```
|
To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.html#locale.getpreferredencoding):
>
> Return the encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.
>
>
>
[Here](https://stackoverflow.com/a/34345136/645146) I found "hacky" but working method to overwrite these settings:
In file `settings.py` of your django project add these lines:
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.html#locale.getpreferredencoding):
>
> Return the encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.
>
>
>
[Here](https://stackoverflow.com/a/34345136/645146) I found "hacky" but working method to overwrite these settings:
In file `settings.py` of your django project add these lines:
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
|
If you have multiple Python environments, before applying workarounds, it's worth checking that you issue `python manage.py` against the correct environment. That was my case where I met the same error: the database was created under containerized environment on Linux, with a higher Python version, but Django and other packages were present also in the legacy local environment on Windows. As well, the project directory was attached to the container as a volume, and the content was identical locally and in the container. So, I just mix up and ran `manage.py` locally instead of being attached to the container.
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.html#locale.getpreferredencoding):
>
> Return the encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.
>
>
>
[Here](https://stackoverflow.com/a/34345136/645146) I found "hacky" but working method to overwrite these settings:
In file `settings.py` of your django project add these lines:
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
|
On windows the way i solved mine was
Add to your settings
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
run this on shell only on windows
```
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
```
I actually did this it worked
```
python -Xutf8 manage.py dumpdata -o data.json
```
But wasnt showing data from my installed apps
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
One solution is to use `./manage.py dumpdata -o data.json` instead of `./manage.py dumpdata > data.json`.
Another solution is to use [Python's UTF-8 mode](https://docs.python.org/3/using/cmdline.html?highlight=utf%20mode#id5), run:
```
python -Xutf8 ./manage.py dumpdata > data.json
```
|
Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.
[djangoproject.com](https://code.djangoproject.com/ticket/32439)
the settings box looks like this. Enable the check and restart your system
[](https://i.stack.imgur.com/dv0tU.png)
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.
[djangoproject.com](https://code.djangoproject.com/ticket/32439)
the settings box looks like this. Enable the check and restart your system
[](https://i.stack.imgur.com/dv0tU.png)
|
If you have multiple Python environments, before applying workarounds, it's worth checking that you issue `python manage.py` against the correct environment. That was my case where I met the same error: the database was created under containerized environment on Linux, with a higher Python version, but Django and other packages were present also in the legacy local environment on Windows. As well, the project directory was attached to the container as a volume, and the content was identical locally and in the container. So, I just mix up and ran `manage.py` locally instead of being attached to the container.
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.
[djangoproject.com](https://code.djangoproject.com/ticket/32439)
the settings box looks like this. Enable the check and restart your system
[](https://i.stack.imgur.com/dv0tU.png)
|
On windows the way i solved mine was
Add to your settings
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
run this on shell only on windows
```
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
```
I actually did this it worked
```
python -Xutf8 manage.py dumpdata -o data.json
```
But wasnt showing data from my installed apps
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
One solution is to use `./manage.py dumpdata -o data.json` instead of `./manage.py dumpdata > data.json`.
Another solution is to use [Python's UTF-8 mode](https://docs.python.org/3/using/cmdline.html?highlight=utf%20mode#id5), run:
```
python -Xutf8 ./manage.py dumpdata > data.json
```
|
If you have multiple Python environments, before applying workarounds, it's worth checking that you issue `python manage.py` against the correct environment. That was my case where I met the same error: the database was created under containerized environment on Linux, with a higher Python version, but Django and other packages were present also in the legacy local environment on Windows. As well, the project directory was attached to the container as a volume, and the content was identical locally and in the container. So, I just mix up and ran `manage.py` locally instead of being attached to the container.
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
One solution is to use `./manage.py dumpdata -o data.json` instead of `./manage.py dumpdata > data.json`.
Another solution is to use [Python's UTF-8 mode](https://docs.python.org/3/using/cmdline.html?highlight=utf%20mode#id5), run:
```
python -Xutf8 ./manage.py dumpdata > data.json
```
|
On windows the way i solved mine was
Add to your settings
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
run this on shell only on windows
```
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
```
I actually did this it worked
```
python -Xutf8 manage.py dumpdata -o data.json
```
But wasnt showing data from my installed apps
|
64,457,733
|
I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine
|
2020/10/21
|
[
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] |
On windows the way i solved mine was
Add to your settings
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
run this on shell only on windows
```
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
```
I actually did this it worked
```
python -Xutf8 manage.py dumpdata -o data.json
```
But wasnt showing data from my installed apps
|
If you have multiple Python environments, before applying workarounds, it's worth checking that you issue `python manage.py` against the correct environment. That was my case where I met the same error: the database was created under containerized environment on Linux, with a higher Python version, but Django and other packages were present also in the legacy local environment on Windows. As well, the project directory was attached to the container as a volume, and the content was identical locally and in the container. So, I just mix up and ran `manage.py` locally instead of being attached to the container.
|
56,460,723
|
I am working with Django and currently try to move my local dev. to Docker. I managed to run my web server. However, what I didn't to yet was `npm install`. That's where I got stuck and I couldn't find documentation or good examples. Anyone who has done that before?
**Dockerfile**:
```
# Pull base image
FROM python:3.7
# Define environment variable
ENV PYTHONUNBUFFERED 1
RUN apt-get update && apt-get install -y \
# Language dependencies
gettext \
# In addition, when you clean up the apt cache by removing /var/lib/apt/lists
# it reduces the image size, since the apt cache is not stored in a layer.
&& rm -rf /var/lib/apt/lists/*
# Copy the current directory contents into the container at /app
COPY . /app
# Set the working directory to /app
WORKDIR /app
# Install Python dependencies
RUN pip install pipenv
RUN pipenv install --system --deploy --dev
COPY ./docker-entrypoint.sh /
RUN chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]
```
**docker-compose:**
```
version: '3'
services:
db:
image: postgres
ports:
- "5432:5432"
environment:
# Password will be required if connecting from a different host
- POSTGRES_PASSWORD=django
web:
build: .
env_file: .env
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
container_name: django
```
**docker-entrypoint.sh**
```
#!/bin/bash
# Apply database migrations
echo "Apply database migrations"
python manage.py migrate
# Run tests (In progress)
# echo "Running tests"
# pytest
# Start server
echo "Starting server"
python manage.py runserver 0.0.0.0:8000
```
|
2019/06/05
|
[
"https://Stackoverflow.com/questions/56460723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10419791/"
] |
It is simple, you should just follow this instruction:
```
npm install
//or
yarn install
```
This will install all node\_modules, when it is not found in the current directory, it will search for the **node\_modules** on directory up.
Hope this answers your question.
|
In the Dockerfile just add:
RUN npm install
This will look if there is a package.json in the current directory and if it does, it will install all dependencies.
|
12,091,009
|
I'm trying to get this [nodetime](http://nodetime.com/docs) running, but seems there's some prblems I can't figur out. I did exactly as the guide say, So i supposed to get following:
>
> After your start your application, a link of the form https://nodetime.com/[session\_id] will be printed to the console, where the session will be your unique id for accessing the profiler server
>
>
>
It end the console didn't display any session id link, only this:
`23 Aug 13:32:23 - Nodetime: profiler resumed for 180 seconds`
Maybe any of you guys has experienced same issue? Looking for fixes! Thanks, in advance!
Below is what i got after nodetime installation, i got some Python error, but still seems lika a successful installation...
```
npm WARN package.json application-name@0.0.1 No README.md file found!
npm WARN package.json jade@0.26.3 No README.md file found!
npm http GET http://registry.npmjs.org/nodetime
npm http 200 http://registry.npmjs.org/nodetime
npm http GET http://registry.npmjs.org/nodetime/-/nodetime-0.4.5.tgz
npm http 200 http://registry.npmjs.org/nodetime/-/nodetime-0.4.5.tgz
npm http GET http://registry.npmjs.org/request/2.10.0
npm http GET http://registry.npmjs.org/v8tools
npm http GET http://registry.npmjs.org/timekit
npm http 200 http://registry.npmjs.org/request/2.10.0
npm http GET http://registry.npmjs.org/request/-/request-2.10.0.tgz
npm http 200 http://registry.npmjs.org/v8tools
npm http GET http://registry.npmjs.org/v8tools/-/v8tools-0.1.1.tgz
npm http 200 http://registry.npmjs.org/timekit
npm http GET http://registry.npmjs.org/timekit/-/timekit-0.1.9.tgz
npm http 200 http://registry.npmjs.org/v8tools/-/v8tools-0.1.1.tgz
npm http 200 http://registry.npmjs.org/request/-/request-2.10.0.tgz
npm http 200 http://registry.npmjs.org/timekit/-/timekit-0.1.9.tgz
npm http GET http://registry.npmjs.org/bindings
npm http 200 http://registry.npmjs.org/bindings
> timekit@0.1.9 install C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\nod
e_modules\nodetime\node_modules\timekit
> node-gyp rebuild
> v8tools@0.1.1 install C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\nod
e_modules\nodetime\node_modules\v8tools
> node-gyp rebuild
C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\node_modules\nodetime\node_
modules\timekit>node "C:\Program Files (x86)\nodejs\node_modules\npm\bin\node-gy
p-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild
C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\node_modules\nodetime\node_
modules\v8tools>node "C:\Program Files (x86)\nodejs\node_modules\npm\bin\node-gy
p-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT
HON env variable.
gyp ERR! stack at failNoPython (C:\Program Files (x86)\nodejs\node_modules\n
pm\node_modules\node-gyp\lib\configure.js:110:14)
gyp ERR! stack at C:\Program Files (x86)\nodejs\node_modules\npm\node_module
s\node-gyp\lib\configure.js:74:11
gyp ERR! stack at Object.oncomplete (fs.js:297:15)
gyp gypERR! System Windows_NT 6.1.7601
ERR! gyp configure errorERR!
command "node" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\node_module
s\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\node_modules\n
odetime\node_modules\timekit
gypgyp ERR! node -v v0.8.5
gyp ERR! node-gyp -v v0.6.3
gyp ERR! not ok
ERR! stack Error: Can't find Python executable "python", you can set the PYTHON
env variable.
gyp ERR! stack at failNoPython (C:\Program Files (x86)\nodejs\node_modules\n
pm\node_modules\node-gyp\lib\configure.js:110:14)
gyp ERR! stack at C:\Program Files (x86)\nodejs\node_modules\npm\node_module
s\node-gyp\lib\configure.js:74:11
gyp ERR! stack at Object.oncomplete (fs.js:297:15)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "node" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\nod
e_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\node_modules\n
odetime\node_modules\v8tools
gyp ERR! node -v v0.8.5
gyp ERR! node-gyp -v v0.6.3
gyp ERR! not ok
npm WARN optional dep failed, continuing timekit@0.1.9
npm WARN optional dep failed, continuing v8tools@0.1.1
nodetime@0.4.5 node_modules\nodetime
+-- request@2.10.0
```
|
2012/08/23
|
[
"https://Stackoverflow.com/questions/12091009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326868/"
] |
No. You cannot embed an Apps Script web app in an external site. You can only do it on a Google Site.
|
Yes it is possible I have installed google comments and google follower on my tumblr blog.
|
44,093,441
|
In C++, how are the local class variables declared? I'm new to C++ but have some python experience. I'm wondering if C++ classes have a way of identifying their local variables, for example, in python your class' local variables are marked with a self. so they would be like:
```
self.variable_name
```
Does C++ have something similar to this for local variables or does it have something completely different? In pseudocode, I think the class' variables would look something like this:
```
class Code:
public:
<some code>
private:
int self.variable
double self.other_variable
<more code>
```
but then, I could be completely wrong. Thanks in advance.
|
2017/05/21
|
[
"https://Stackoverflow.com/questions/44093441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8034222/"
] |
That's pretty close! Within the class, however, one would mention the class variables simply using their own name, therefore as `variable` as opposed to `class.variable`.
(Also, note that your functions need to have a semicolon following them, and by convention these functions tend to be defined under the class itself, or in separate files)
```
class Circle {
public:
Circle(double var, bool otherVar); //constructor
double getVariable(); //getter
void setVariable(double var); //setter
// you can put more functions here
private:
double variable;
bool otherVariable;
//you can put more functions here
};
Circle::Circle(double var, bool otherVar){
variable = var;
otherVariable = otherVar;
}
Circle::getVariable(){
return variable;
}
Circle::setVariable(double var){
variable = var
}
```
For a better look at this topic, please look at this [similar question/answer.](https://stackoverflow.com/questions/865922/how-to-write-a-simple-class-in-c), or as noted in a comment, consider reading a textbook on C++...
EDIT: I wrote this answer based on the question title of "identifying" variables, by noting that the problem was likely that code couldn't compile because `class.variable` is not how things are referred to in C++. However, I'm unsure if the question refers to initializing, declaring, etc.
|
When you read Effective C++ (written by Scott Meyers), member variables are init when ctor initializer. After ctor, all assignment is assignment, not init. You can write ctor like this.
```
Circle(double value, bool isTrueFalse, <More Variables>) : class.variable(value), class.othervariable(isTrueFalse), ..<More Variables> //this is init.
{
class.variable = value; //this is assignment. not init.
}
```
C++ init orders is up-side-down, not ctor initializer order.
```
private:
double class.variable; //First init;
bool class.variables;//Second init;
```
If you want local variables init, you pass value to ctor.
in C++. assignment and init is diffrent. class local members only init at ctor Initializer. init is faster than assignment. because init is just one call ctor, and end. but assignment is call ctor, and assignment Operator one more. you should to use ctor Initializer, for performece.
|
63,147,540
|
This is my first time using Python and I'm tasked with the following: print a list of cities from this JSON: <http://jsonplaceholder.typicode.com/users>
I'm trying to print out a list that should read:
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
etc.
This is the code I have so far:
```
import json
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users")
users = json.loads(response.text)
print(users)
```
When I run `$python3 -i api.py` (file is named api.py) I'm able to print the list from the JSON file in my terminal. However I have been stuck trying to figure out how to print the cities only. I'm assuming it would look something like `users.address.city` but any attempt at figuring out the code has resulted in the following error: `AttributeError: 'list' object has no attribute 'address'`.
Any help you could provide would be greatly appreciated. Thanks!
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63147540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13488080/"
] |
As `users` is a list, it should be:
```
print(users[0]['address']['city'])
```
This is how you can access nested properties in JSON response.
You can also loop over the users and print their city in the same format.
```
for user in users:
print(user['address']['city'])
```
|
You can get city name with user['address']['city']
and use loop to get all city names
like this
```
for user in users:
print(user['address']['city'])
```
output :
```
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
Roscoeview
South Christy
Howemouth
Aliyaview
Bartholomebury
Lebsackbury
[Program finished]
```
|
63,147,540
|
This is my first time using Python and I'm tasked with the following: print a list of cities from this JSON: <http://jsonplaceholder.typicode.com/users>
I'm trying to print out a list that should read:
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
etc.
This is the code I have so far:
```
import json
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users")
users = json.loads(response.text)
print(users)
```
When I run `$python3 -i api.py` (file is named api.py) I'm able to print the list from the JSON file in my terminal. However I have been stuck trying to figure out how to print the cities only. I'm assuming it would look something like `users.address.city` but any attempt at figuring out the code has resulted in the following error: `AttributeError: 'list' object has no attribute 'address'`.
Any help you could provide would be greatly appreciated. Thanks!
|
2020/07/29
|
[
"https://Stackoverflow.com/questions/63147540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13488080/"
] |
As `users` is a list, it should be:
```
print(users[0]['address']['city'])
```
This is how you can access nested properties in JSON response.
You can also loop over the users and print their city in the same format.
```
for user in users:
print(user['address']['city'])
```
|
```
first of all i get this, why your loading(response.text) , instead requests package has a built in .json() method which is what you want to access nested data . so you could do something like this
response = requests.get("https://jsonplaceholder.typicode.com/users")
data = response.json()
# optional
print(data)
* loop through the addresses to get all the cities
for dt in data['address']:
# do what you want with the data returned
```
|
7,196,148
|
I know there is not much on stackoverflow on dojango, but I thought I'd ask anyway.
Dojango describes RegexField as follows:
```
class RegexField(DojoFieldMixin, fields.RegexField):
widget = widgets.ValidationTextInput
js_regex = None # we additionally have to define a custom javascript regexp, because the python one is not compatible to javascript
def __init__(self, js_regex=None, *args, **kwargs):
self.js_regex = js_regex
super(RegexField, self).__init__(*args, **kwargs)
```
And I am using it as so in my forms.py:
```
post_code = RegexField(js_regex = '[A-Z]{1,2}\d[A-Z\d]? \d[ABD-HJLNP-UW-Z]{2}')
# &
post_code = RegexField(attrs={'js_regex': '[A-Z]{1,2}\d[A-Z\d]? \d[ABD-HJLNP-UW-Z]{2}'})
```
Unfortunately these both give me:
```
TypeError: __init__() takes at least 2 arguments (1 given)
```
If I use the following:
```
post_code = RegexField(regex = '[A-Z]{1,2}\d[A-Z\d]? \d[ABD-HJLNP-UW-Z]{2}')
```
I get the following HTML:
```
<input name="post_code" required="true" promptMessage="" type="text" id="id_post_code" dojoType="dijit.form.ValidationTextBox" />
```
Can anyone tell me what I might be doing wrong?
|
2011/08/25
|
[
"https://Stackoverflow.com/questions/7196148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563247/"
] |
After three days of beavering away I fould that you need to send `regex` and `js_regex`, though `regex` is not used:
```
post_code = RegexField(
regex='',
required = True,
widget=ValidationTextInput(
attrs={
'invalid': 'Post Code in incorrect format',
'regExp': '[A-Z]{1,2}\d[A-Z\d]? \d[ABD-HJLNP-UW-Z]{2}'
}
)
)
```
[Oh yeah! and you also need to declare the widget as a `ValidationTextInput`]
|
The error is related to `super().__init__` call. If `fields.RegexField` is standard Django `RegexField`, then it requires `regex` keyword argument, as documented. Since you don't pass it, you get `TypeError`. If it's supposed to be the same as `js_regex`, then pass it along in the super call.
```
def __init__(self, js_regex, *args, **kwargs):
self.js_regex = js_regex
super(RegexField, self).__init__(regex, *args, **kwargs)
```
|
46,327,700
|
I have this `list` in `python` which can have `n` elements. Now what I am trying to do is show `4` elements from this `list` at a time with an added option 'next' to show next set of 4 elements. So if my list is something like this:
```
['room 11','room 22','room 33','room 44','room 55','room 65','room 77']
```
then display it to users like this:
```
1. Room Number : room 11
2. Room Number : room 22
3. Room Number : room 33
4. Room Number : room 44
5. Next
```
if user selects `1`(user selects the number corresponding to the room in the list) then print `Room selected: room 11` or if user selects `2` then print `Room selected: room 22`. If user selects `5` then show next set of 4 elements from the list(if less then 4 left than just show whats left).
I wrote this code which is only partial as I am having difficulty in implementing this functionality completely:
```
room_list_num = 0
room_list_slot = 0
def room_try():
room_list = ['room 11','room 22','room 33','room 44','room 55','room 66','room 77','room 88','room 99','room 110','room 111','room 112']
inner_list_str = ["%d. Room number: %s" % (i, x)
for i, x in enumerate(room_list, 1)]
global room_list_slot
while room_list_slot < len(room_list):
room_list_num = input('Following are the available rooms. Please select the corresponding number of the room you want: \n {}'.format( '\n '.join(inner_list_str[room_list_slot:(room_list_slot+4)])))
room_list_slot += 4
print('Room selected: '+ str(room_list[room_list_num]))
if __name__ == '__main__':
room_try()
```
The difficulty I am having in is to how to add the temporary value 'Next' with each set of 4 elements to display and then move into the list based on users response?
|
2017/09/20
|
[
"https://Stackoverflow.com/questions/46327700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2966197/"
] |
This will help you
```
room_list_num = 0
room_list_slot = 0
def room_try():
room_list = ['room 11','room 22','room 33','room 44','room 55','room 66','room 77','room 88','room 99','room 110','room 111','room 112']
inner_list_str = ["%d. Room number: %s" % ((i%4)+1, x)
for i, x in enumerate(room_list, 0)]
global room_list_slot
counter = 0
while counter*4 < len(room_list):
room_list_num = int(input('Following are the available rooms. Please select the corresponding number of the room you want: \n {}'.format( '\n '.join(inner_list_str[room_list_slot:(room_list_slot+4)]) + ['\n 5. Next\n','\n'][room_list_slot+4>=len(room_list)])))
room_list_slot += 4
if room_list_num == 5:
counter += 1
continue
break
print('Room selected: '+ str(room_list[counter*4+room_list_num-1]))
if __name__ == '__main__':
room_try()
```
|
You can do something like this:
```
def room_try():
room_list_num = 0
room_list_slot = 0
room_list = ['room 11', 'room 22', 'room 33', 'room 44', 'room 55', 'room 66', 'room 77', 'room 88', 'room 99', 'room 110', 'room 111', 'room 112']
inner_list_str = ["%d. Room number: %s" % (i, x)
for i, x in enumerate(room_list, 1)]
while room_list_slot < len(room_list):
print('Following are the available rooms. Please select the corresponding number of the room you want: \n {}'.format(
'\n '.join(inner_list_str[room_list_slot:(room_list_slot + 4)])))
room_list_num = int(input(" {}. Next\n".format(room_list_slot + 5)))
if (room_list_slot + 5 != room_list_num):
print('Room selected: ' + str(room_list[room_list_num - 1]))
return
else:
room_list_slot += 4
print("You haven't choose any room.")
if __name__ == '__main__':
room_try()
```
|
53,823,349
|
I have a set of values that I'd like to plot the gaussian kernel density estimation of, however there are two problems that I'm having:
1. I only have the values of bars not the values themselves
2. I am plotting onto a categorical axis
Here's the plot I've generated so far:
[](https://i.stack.imgur.com/xqBFD.png)
The order of the y axis is actually relevant since it is representative of the phylogeny of each bacterial species.
I'd like to add a gaussian kde overlay for each color, but so far I haven't been able to leverage seaborn or scipy to do this.
Here's the code for the above grouped bar plot using python and matplotlib:
```
enterN = len(color1_plotting_values)
fig, ax = plt.subplots(figsize=(20,30))
ind = np.arange(N) # the x locations for the groups
width = .5 # the width of the bars
p1 = ax.barh(Species_Ordering.Species.values, color1_plotting_values, width, label='Color1', log=True)
p2 = ax.barh(Species_Ordering.Species.values, color2_plotting_values, width, label='Color2', log=True)
for b in p2:
b.xy = (b.xy[0], b.xy[1]+width)
```
Thanks!
|
2018/12/17
|
[
"https://Stackoverflow.com/questions/53823349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5540779/"
] |
How to plot a "KDE" starting from a histogram
=============================================
The protocol for kernel density estimation requires the underlying data. You could come up with a new method that uses the empirical pdf (ie the histogram) instead, but then it wouldn't be a KDE distribution.
Not all hope is lost, though. You can get a good approximation of a KDE distribution by first taking samples from the histogram, and then using KDE on those samples. Here's a complete working example:
```
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as sts
n = 100000
# generate some random multimodal histogram data
samples = np.concatenate([np.random.normal(np.random.randint(-8, 8), size=n)*np.random.uniform(.4, 2) for i in range(4)])
h,e = np.histogram(samples, bins=100, density=True)
x = np.linspace(e.min(), e.max())
# plot the histogram
plt.figure(figsize=(8,6))
plt.bar(e[:-1], h, width=np.diff(e), ec='k', align='edge', label='histogram')
# plot the real KDE
kde = sts.gaussian_kde(samples)
plt.plot(x, kde.pdf(x), c='C1', lw=8, label='KDE')
# resample the histogram and find the KDE.
resamples = np.random.choice((e[:-1] + e[1:])/2, size=n*5, p=h/h.sum())
rkde = sts.gaussian_kde(resamples)
# plot the KDE
plt.plot(x, rkde.pdf(x), '--', c='C3', lw=4, label='resampled KDE')
plt.title('n = %d' % n)
plt.legend()
plt.show()
```
Output:
[](https://i.stack.imgur.com/p6ZUY.png)
The red dashed line and the orange line nearly completely overlap in the plot, showing that the real KDE and the KDE calculated by resampling the histogram are in excellent agreement.
If your histograms are really noisy (like what you get if you set `n = 10` in the above code), you should be a bit cautious when using the resampled KDE for anything other than plotting purposes:
[](https://i.stack.imgur.com/OYN64.png)
Overall the agreement between the real and resampled KDEs is still good, but the deviations are noticeable.
Munge your categorial data into an appropriate form
===================================================
Since you haven't posted your actual data I can't give you detailed advice. I think your best bet will be to just number your categories in order, then use that number as the "x" value of each bar in the histogram.
|
I have stated my reservations to applying a KDE to OP's categorical data in my comments above. Basically, as the phylogenetic distance between species does not obey the triangle inequality, there cannot be a valid kernel that could be used for kernel density estimation. However, there are other density estimation methods that do not require the construction of a kernel. One such method is k-nearest neighbour [inverse distance weighting](https://en.wikipedia.org/wiki/Inverse_distance_weighting), which only requires non-negative distances which need not satisfy the triangle inequality (nor even need to be symmetric, I think). The following outlines this approach:
```
import numpy as np
#--------------------------------------------------------------------------------
# simulate data
total_classes = 10
sample_values = np.random.rand(total_classes)
distance_matrix = 100 * np.random.rand(total_classes, total_classes)
# Distances to the values itself are zero; hence remove diagonal.
distance_matrix -= np.diag(np.diag(distance_matrix))
# --------------------------------------------------------------------------------
# For each sample, compute an average based on the values of the k-nearest neighbors.
# Weigh each sample value by the inverse of the corresponding distance.
# Apply a regularizer to the distance matrix.
# This limits the influence of values with very small distances.
# In particular, this affects how the value of the sample itself (which has distance 0)
# is weighted w.r.t. other values.
regularizer = 1.
distance_matrix += regularizer
# Set number of neighbours to "interpolate" over.
k = 3
# Compute average based on sample value itself and k neighbouring values weighted by the inverse distance.
# The following assumes that the value of distance_matrix[ii, jj] corresponds to the distance from ii to jj.
for ii in range(total_classes):
# determine neighbours
indices = np.argsort(distance_matrix[ii, :])[:k+1] # +1 to include the value of the sample itself
# compute weights
distances = distance_matrix[ii, indices]
weights = 1. / distances
weights /= np.sum(weights) # weights need to sum to 1
# compute weighted average
values = sample_values[indices]
new_sample_values[ii] = np.sum(values * weights)
print(new_sample_values)
```
|
53,823,349
|
I have a set of values that I'd like to plot the gaussian kernel density estimation of, however there are two problems that I'm having:
1. I only have the values of bars not the values themselves
2. I am plotting onto a categorical axis
Here's the plot I've generated so far:
[](https://i.stack.imgur.com/xqBFD.png)
The order of the y axis is actually relevant since it is representative of the phylogeny of each bacterial species.
I'd like to add a gaussian kde overlay for each color, but so far I haven't been able to leverage seaborn or scipy to do this.
Here's the code for the above grouped bar plot using python and matplotlib:
```
enterN = len(color1_plotting_values)
fig, ax = plt.subplots(figsize=(20,30))
ind = np.arange(N) # the x locations for the groups
width = .5 # the width of the bars
p1 = ax.barh(Species_Ordering.Species.values, color1_plotting_values, width, label='Color1', log=True)
p2 = ax.barh(Species_Ordering.Species.values, color2_plotting_values, width, label='Color2', log=True)
for b in p2:
b.xy = (b.xy[0], b.xy[1]+width)
```
Thanks!
|
2018/12/17
|
[
"https://Stackoverflow.com/questions/53823349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5540779/"
] |
How to plot a "KDE" starting from a histogram
=============================================
The protocol for kernel density estimation requires the underlying data. You could come up with a new method that uses the empirical pdf (ie the histogram) instead, but then it wouldn't be a KDE distribution.
Not all hope is lost, though. You can get a good approximation of a KDE distribution by first taking samples from the histogram, and then using KDE on those samples. Here's a complete working example:
```
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as sts
n = 100000
# generate some random multimodal histogram data
samples = np.concatenate([np.random.normal(np.random.randint(-8, 8), size=n)*np.random.uniform(.4, 2) for i in range(4)])
h,e = np.histogram(samples, bins=100, density=True)
x = np.linspace(e.min(), e.max())
# plot the histogram
plt.figure(figsize=(8,6))
plt.bar(e[:-1], h, width=np.diff(e), ec='k', align='edge', label='histogram')
# plot the real KDE
kde = sts.gaussian_kde(samples)
plt.plot(x, kde.pdf(x), c='C1', lw=8, label='KDE')
# resample the histogram and find the KDE.
resamples = np.random.choice((e[:-1] + e[1:])/2, size=n*5, p=h/h.sum())
rkde = sts.gaussian_kde(resamples)
# plot the KDE
plt.plot(x, rkde.pdf(x), '--', c='C3', lw=4, label='resampled KDE')
plt.title('n = %d' % n)
plt.legend()
plt.show()
```
Output:
[](https://i.stack.imgur.com/p6ZUY.png)
The red dashed line and the orange line nearly completely overlap in the plot, showing that the real KDE and the KDE calculated by resampling the histogram are in excellent agreement.
If your histograms are really noisy (like what you get if you set `n = 10` in the above code), you should be a bit cautious when using the resampled KDE for anything other than plotting purposes:
[](https://i.stack.imgur.com/OYN64.png)
Overall the agreement between the real and resampled KDEs is still good, but the deviations are noticeable.
Munge your categorial data into an appropriate form
===================================================
Since you haven't posted your actual data I can't give you detailed advice. I think your best bet will be to just number your categories in order, then use that number as the "x" value of each bar in the histogram.
|
THE EASY WAY
============
For now, I am skipping any philosophical argument about the validity of using Kernel density in such settings. Will come around that later.
An **easy way** to do this is using scikit-learn `KernelDensity`:
```
import numpy as np
import pandas as pd
from sklearn.neighbors import KernelDensity
from sklearn import preprocessing
ds=pd.read_csv('data-by-State.csv')
Y=ds.loc[:,'State'].values # State is AL, AK, AZ, etc...
# With categorical data we need some label encoding here...
le = preprocessing.LabelEncoder()
le.fit(Y) # le.classes_ would be ['AL', 'AK', 'AZ',...
y=le.transform(Y) # y would be [0, 2, 3, ..., 6, 7, 9]
y=y[:, np.newaxis] # preparing for kde
kde = KernelDensity(kernel='gaussian', bandwidth=0.75).fit(y)
# You can control the bandwidth so the KDE function performs better
# To find the optimum bandwidth for your data you can try Crossvalidation
x=np.linspace(0,5,100)[:, np.newaxis] # let's get some x values to plot on
log_dens=kde.score_samples(x)
dens=np.exp(log_dens) # these are the density function values
array([0.06625658, 0.06661817, 0.06676005, 0.06669403, 0.06643584,
0.06600488, 0.0654239 , 0.06471854, 0.06391682, 0.06304861,
0.06214499, 0.06123764, 0.06035818, 0.05953754, 0.05880534,
0.05818931, 0.05771472, 0.05740393, 0.057276 , 0.05734634,
0.05762648, 0.05812393, 0.05884214, 0.05978051, 0.06093455,
..............
0.11885574, 0.11883695, 0.11881434, 0.11878766, 0.11875657,
0.11872066, 0.11867943, 0.11863229, 0.11857859, 0.1185176 ,
0.11844852, 0.11837051, 0.11828267, 0.11818407, 0.11807377])
```
And these values are all you need to plot your Kernel Density over your histogram. Capito?
Now, on the theoretical side, if X is a categorical(\*), unordered variable with c possible values, then for 0 ≤ **h** < 1
[](https://i.stack.imgur.com/Yz8K8.png)
is a valid kernel. For an ordered X,
[](https://i.stack.imgur.com/SoW19.png)
where `|x1-x2|`should be understood as how many levels apart x1 and x2 are. As **h** tends to zero, both of these become indicators and return a relative frequency counting. **h** is oftentimes referred to as ***bandwidth***.
---
(\*) No distance needs to be defined on the variable space. Doesn't need to be a metric space.
`Devroye, Luc and Gábor Lugosi (2001). Combinatorial Methods in Density Estimation. Berlin: Springer-Verlag.`
|
57,094,939
|
I am wrote a serializer for the User model in Django with DRF:
the model:
```py
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
from django.db import models
from django.utils.translation import ugettext
class BaseModel(models.Model):
# all models should be inheritted from this model
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class User(AbstractBaseUser, BaseModel):
username = models.CharField(
ugettext('Username'), max_length=255,
db_index=True, unique=True
)
email = models.EmailField(
ugettext('Email'), max_length=255, db_index=True,
blank=True, null=True, unique=True
)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ('email', 'password',)
class Meta:
app_label = 'users'
```
the serializer:
```
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = super().create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, user, validated_data):
user = super().update(user, validated_data)
user.set_password(validated_data['password'])
user.save()
return user
```
It works. But I probably do two calls instead of one on every create/update and the code looks a little bit weird(not DRY).
Is there an idiomatic way to do that?
```
$python -V
Python 3.7.3
Django==2.2.3
djangorestframework==3.10.1
```
|
2019/07/18
|
[
"https://Stackoverflow.com/questions/57094939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1907902/"
] |
I hope this will solve the issue,
```
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
**return models.User.objects.create\_user(\*\*validated\_data)**
def update(self, user, validated_data):
**password = validated\_data.pop('password', None)
if password is not None:
user.set\_password(password)
for field, value in validated\_data.items():
setattr(user, field, value)
user.save()
return user**
```
The **`create_user()`** method uses the **`set_password()`** method to set the hashable password.
|
You can create your own user manager by overriding `BaseUserManager` and use `set_password()` method there. There is a full example in django's [documentation](https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#a-full-example). So your `models.py` will be:
```py
# models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class MyUserManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
username=username,
)
user.set_password(password)
user.save(using=self._db)
return user
class BaseModel(models.Model):
# all models should be inheritted from this model
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class User(AbstractBaseUser, BaseModel):
username = models.CharField(
ugettext('Username'), max_length=255,
db_index=True, unique=True
)
email = models.EmailField(
ugettext('Email'), max_length=255, db_index=True,
blank=True, null=True, unique=True
)
# don't forget to set your custom manager
objects = MyUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ('email', 'password',)
class Meta:
app_label = 'users'
```
Then, you can directly call `create_user()` in your serializer's `create()` method. You can also add a custom update method in your custom manager.
```py
# serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = models.User.objects.create_user(
username=validated_data['username'],
email=validated_data['email'],
password=validated_data['password']
)
return user
```
|
33,493,861
|
I wrote script which create animation (movie) from fits files. One file has size 2.8 MB and the no. of files is 9000.
Here is code
```
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import os
import pyfits
import glob
import re
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
global numbers
numbers=re.compile(r'(\d+)')
def numericalSort(value):
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
image_list=glob.glob('/kalib/*.fits')
image_list= sorted(image_list,key=numericalSort)
print image_list
fig = plt.figure("movie")
img = []
for i in range(0,len(image_list)):
hdulist = pyfits.open(image_list[i])
im = hdulist[0].data
img.append([plt.imshow(im,cmap=plt.cm.Greys_r)])
ani = animation.ArtistAnimation(fig,img, interval=20, blit=True,repeat_delay=0)
ani.save('movie.mp4', writer=writer)
```
I think that my problem is when I create array img[]...I have 8 GB RAM and when the RAM is full my operating system terminate python script.
My question is:
How I can read 9000 files and create animation? Is possible create some buffer or some parallel processing?
Any suggestion?
|
2015/11/03
|
[
"https://Stackoverflow.com/questions/33493861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2952470/"
] |
I would recommend you to use `ffmpeg`. With the command `image2pipe` you don't have to load all the images into your RAM but rather one by one (i think) into a pipe.
In addition to that, `ffmpeg` allows you to manipulate the video (framerate, codec, format, etc...).
<https://ffmpeg.org/ffmpeg.html>
|
You might be better off creating your animation with FuncAnimation instead of ArtistAnimation, as explained in [ArtistAnimation vs FuncAnimation matplotlib animation matplotlib.animation](https://stackoverflow.com/questions/22158395/artistanimation-vs-funcanimation-matplotlib-animation-matplotlib-animation) FuncAnimation is more efficient in its memory usage. You might want to experiment with FuncAnimation's save\_count parameter as well, check out the API documentation for examples.
|
50,438,762
|
The code below is a basic square drawing using Turtle in python.
Running the code the first time works. But running the code again activates a Turtle window that is non-responsive and subsequently crashes every time.
The error message includes `raise Terminator` and `Terminator`
Restarting kernel in Spyder (Python 3.6 on a Dell Desktop) fixes the problem in that I can then run the code again successfully, but the root cause is a mystery?
[Link](https://stackoverflow.com/questions/48637723/python-drawing-in-turtle-window-says-not-responding) to another question that is similar but as yet unanswered.
Please +1 this question if you find it worthy of an answer!!
```
import turtle
bob = turtle.Turtle()
print(bob)
for i in range(4):
bob.fd(100)
bob.lt(90)
turtle.mainloop()
```
|
2018/05/20
|
[
"https://Stackoverflow.com/questions/50438762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9655448/"
] |
I realize this will seem wholly unsatisfactory, but I have found that creating the turtle with:
```
try:
tess = turtle.Turtle()
except:
tess = turtle.Turtle()
```
works (that is, eliminates the "working every other time" piece. I also start with
```
wn = turtle.Screen()
```
and end with
```
from sys import platform
if platform=='win32':
wn.exitonclick()
```
Without those parts, if I try to move the turtle graphics windows in Windows, things break. (running Spyder for Python 3.6 on a Windows machine)
edit: of course, OSX is perfectly happy without the exitonclick() command and unhappy with it so added platform specific version of ending "feature fix." The try...except part is still needed for OSX.
|
The module uses a class variable \_RUNNING which remains true between executions when running in spyder instead of running it as a self contained script. I have requested for the module to be updated.
Meanwhile, work around/working example beyond what DukeEgr93 has proposed
1)
```
import importlib
import turtle
importlib.reload(turtle)
bob = turtle.Turtle()
print(bob)
for i in range(4):
bob.fd(100)
bob.lt(90)
turtle.mainloop()
```
2.
```
import importlib
import turtle
turtle.TurtleScreen._RUNNING=True
bob = turtle.Turtle()
print(bob)
for i in range(4):
bob.fd(100)
bob.lt(90)
turtle.mainloop()
```
|
50,192,322
|
this is my code the I am currently writing for a robot in my university project. This code works, however the loop will constantly print statements every second and I would like it to only print when I change the input condition (break the if condition), so it wouldn't keep on printing. Is there anyway to fix this? Thanks for the help in advance.
PS: this is in python 2.7 (I think)
```
try:
while True:
#some stuff
if 0.01 < joystick.get_axis(1) <= 0.25:
print ('moving backward with 25% speed')
# performing some actions
elif 0.25 < joystick.get_axis(1) <= 0.5:
print ('moving forward with 50% speed')
# performing some actions
elif 0.5 < joystick.get_axis(1) <= 0.75:
print ('moving backward with 75% speed')
# performing some actions
```
the while loop continues in the same fashion...
|
2018/05/05
|
[
"https://Stackoverflow.com/questions/50192322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9746251/"
] |
Keep track of the last category - something like that.
```
previous_category = 0
while True:
#some stuff
if 0.01 < joystick.get_axis(1) <= 0.25:
if previous_category != 1:
print ('moving backward with 25% speed')
previous_category = 1
# performing some actions
elif 0.25 < joystick.get_axis(1) <= 0.5:
if previous_category != 2:
print ('moving forward with 50% speed')
previous_category = 2
# performing some actions
elif 0.5 < joystick.get_axis(1) <= 0.75:
if previous_category != 3:
print ('moving backward with 75% speed')
previous_category = 3
# performing some actions
```
If you're down for reformating your code a bit, I think this would be a better approach:
```
previous_category = 0
while True:
val = joystick.get_axis(1)
if 0.01 < val <= 0.25:
category = 1
#add 2 elif for the other categories, 2 and 3
if category == 1:
# performing some actions
elif category == 2:
# performing some actions
elif category == 3:
# performing some actions
#now that we've moved the object, we check if we need to print or not
if category != previous_category:
print_statement(category)
#and we update previous_category for the next round, which will just be the current category
previous_category = category
def print_statement(category):
#handle printing here based on type, this is more flexible
```
|
You can accomplish this with a global integer that stores the last value printed. Something like this:
```
_last_count = None
def condprint(count):
global _last_count
if count != _last_count:
print('Waiting for joystick '+str(count))
_last_count = count
```
|
63,043,387
|
I have three arrays, such that:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = np.array([1, 2, 3, 4, 5])
Value_Arr = np.array([0.1, 0.6, 0.3, 0.8, 0.2])
```
I want to create a new array which has the dimensions of Data, but where each element is from Values, using the index position in ID. So far I have this in a loop, but its very slow as my Data array is very large:
```
out = np.zeros_like(Data_Arr, dtype=np.float)
for i in range(len(Data_Arr)):
out[i] = Values_Arr[ID_Arr==Data_Arr[I]]
```
is there a more pythonic way of doing this and avoiding this loop (doesn't have to use numpy)?
Actual data looks like:
```
Data_Arr = [ 852116 852116 852116 ... 1001816 1001816 1001816]
ID_Arr = [ 852116 852117 852118 ... 1001814 1001815 1001816]
Value_Arr = [1.5547194 1.5547196 1.5547197 ... 1.5536859 1.5536858 1.5536857]
```
shapes are:
```
Data_Arr = (4021165,)
ID_Arr = (149701,)
Value_Arr = (149701,)
```
|
2020/07/22
|
[
"https://Stackoverflow.com/questions/63043387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868191/"
] |
Since `ID_Arr` is sorted, we can directly use [`np.searchsorted`](https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html) and index `Value_Arr` with the result:
```
Value_Arr[np.searchsorted(ID_Arr, Data_Arr)]
array([0.1, 0.1, 0.1, 0.6, 0.6, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.8, 0.8,
0.2, 0.2, 0.2])
```
If `ID_Arr` isn't sorted (*note*: in case there may be out of bounds indices, we should remove them, see divakar's answer):
```
s_ind = ID_Arr.argsort()
ss = np.searchsorted(ID_Arr, Data_Arr, sorter=s_ind)
out = Value_Arr[s_ind[ss]]
```
---
Checking with the arrays suggested by alaniwi:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = array([2, 1, 3, 4, 5])
Value_Arr = np.array([0.6, 0.1, 0.3, 0.8, 0.2])
out_op = np.zeros_like(Data_Arr, dtype=np.float)
for i in range(len(Data_Arr)):
out_op[i] = Value_Arr[ID_Arr==Data_Arr[i]]
s_ind = ID_Arr.argsort()
ss = np.searchsorted(ID_Arr, Data_Arr, sorter=s_ind)
out_answer = Value_Arr[s_ind[ss]]
np.array_equal(out_op, out_answer)
#True
```
|
Looks like you want:
```
out = Value_Arr[ID_Arr[Data_Arr - 1] - 1]
```
Note that the `- 1` are due to the fact that Python/Numpy is `0`-based index.
|
63,043,387
|
I have three arrays, such that:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = np.array([1, 2, 3, 4, 5])
Value_Arr = np.array([0.1, 0.6, 0.3, 0.8, 0.2])
```
I want to create a new array which has the dimensions of Data, but where each element is from Values, using the index position in ID. So far I have this in a loop, but its very slow as my Data array is very large:
```
out = np.zeros_like(Data_Arr, dtype=np.float)
for i in range(len(Data_Arr)):
out[i] = Values_Arr[ID_Arr==Data_Arr[I]]
```
is there a more pythonic way of doing this and avoiding this loop (doesn't have to use numpy)?
Actual data looks like:
```
Data_Arr = [ 852116 852116 852116 ... 1001816 1001816 1001816]
ID_Arr = [ 852116 852117 852118 ... 1001814 1001815 1001816]
Value_Arr = [1.5547194 1.5547196 1.5547197 ... 1.5536859 1.5536858 1.5536857]
```
shapes are:
```
Data_Arr = (4021165,)
ID_Arr = (149701,)
Value_Arr = (149701,)
```
|
2020/07/22
|
[
"https://Stackoverflow.com/questions/63043387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868191/"
] |
Based off approaches from [`this post`](https://stackoverflow.com/a/62658135/), here are the adaptations.
### Approach #1
```
# https://stackoverflow.com/a/62658135/ @Divakar
a,b,invalid_specifier = ID_Arr, Data_Arr, 0
sidx = a.argsort()
idx = np.searchsorted(a,b,sorter=sidx)
# Remove out of bounds indices as they wont be matches
idx[idx==len(a)] = 0
# Get traced back indices corresponding to original version of a
idx0 = sidx[idx]
# Mask out invalid ones with invalid_specifier and return
out = np.where(a[idx0]==b, Values_Arr[idx0], invalid_specifier)
```
### Approach #2
Lookup based -
```
# https://stackoverflow.com/a/62658135/ @Divakar
def find_indices_lookup(a,b,invalid_specifier=-1):
# Setup array where we will assign ranged numbers
N = max(a.max(), b.max())+1
lookup = np.full(N, invalid_specifier)
# We index into lookup with b to trace back the positions. Non matching ones
# would have invalid_specifier values as wount had been indexed by ranged ones
lookup[a] = np.arange(len(a))
indices = lookup[b]
return indices
idx = find_indices_lookup(ID_Arr, Data_Arr)
out = np.where(idx!=-1, Values_Arr[idx], 0)
```
**Faster/simpler variant**
And a simplified and hopefully faster version would be a direct lookup of values -
```
a,b,invalid_specifier = ID_Arr, Data_Arr, 0
N = max(a.max(), b.max())+1
lookup = np.zeros(N, dtype=Values_Arr.dtype)
lookup[ID_Arr] = Values_Arr
out = lookup[Data_Arr]
```
If all values from `ID_Arr` are guaranteed to be in `Data_Arr`, we can use `np.empty` in place of `np.zeros` for the array-assignment and thus gain further perf. boost.
|
Looks like you want:
```
out = Value_Arr[ID_Arr[Data_Arr - 1] - 1]
```
Note that the `- 1` are due to the fact that Python/Numpy is `0`-based index.
|
63,043,387
|
I have three arrays, such that:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = np.array([1, 2, 3, 4, 5])
Value_Arr = np.array([0.1, 0.6, 0.3, 0.8, 0.2])
```
I want to create a new array which has the dimensions of Data, but where each element is from Values, using the index position in ID. So far I have this in a loop, but its very slow as my Data array is very large:
```
out = np.zeros_like(Data_Arr, dtype=np.float)
for i in range(len(Data_Arr)):
out[i] = Values_Arr[ID_Arr==Data_Arr[I]]
```
is there a more pythonic way of doing this and avoiding this loop (doesn't have to use numpy)?
Actual data looks like:
```
Data_Arr = [ 852116 852116 852116 ... 1001816 1001816 1001816]
ID_Arr = [ 852116 852117 852118 ... 1001814 1001815 1001816]
Value_Arr = [1.5547194 1.5547196 1.5547197 ... 1.5536859 1.5536858 1.5536857]
```
shapes are:
```
Data_Arr = (4021165,)
ID_Arr = (149701,)
Value_Arr = (149701,)
```
|
2020/07/22
|
[
"https://Stackoverflow.com/questions/63043387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868191/"
] |
Since `ID_Arr` is sorted, we can directly use [`np.searchsorted`](https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html) and index `Value_Arr` with the result:
```
Value_Arr[np.searchsorted(ID_Arr, Data_Arr)]
array([0.1, 0.1, 0.1, 0.6, 0.6, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.8, 0.8,
0.2, 0.2, 0.2])
```
If `ID_Arr` isn't sorted (*note*: in case there may be out of bounds indices, we should remove them, see divakar's answer):
```
s_ind = ID_Arr.argsort()
ss = np.searchsorted(ID_Arr, Data_Arr, sorter=s_ind)
out = Value_Arr[s_ind[ss]]
```
---
Checking with the arrays suggested by alaniwi:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = array([2, 1, 3, 4, 5])
Value_Arr = np.array([0.6, 0.1, 0.3, 0.8, 0.2])
out_op = np.zeros_like(Data_Arr, dtype=np.float)
for i in range(len(Data_Arr)):
out_op[i] = Value_Arr[ID_Arr==Data_Arr[i]]
s_ind = ID_Arr.argsort()
ss = np.searchsorted(ID_Arr, Data_Arr, sorter=s_ind)
out_answer = Value_Arr[s_ind[ss]]
np.array_equal(out_op, out_answer)
#True
```
|
Based off approaches from [`this post`](https://stackoverflow.com/a/62658135/), here are the adaptations.
### Approach #1
```
# https://stackoverflow.com/a/62658135/ @Divakar
a,b,invalid_specifier = ID_Arr, Data_Arr, 0
sidx = a.argsort()
idx = np.searchsorted(a,b,sorter=sidx)
# Remove out of bounds indices as they wont be matches
idx[idx==len(a)] = 0
# Get traced back indices corresponding to original version of a
idx0 = sidx[idx]
# Mask out invalid ones with invalid_specifier and return
out = np.where(a[idx0]==b, Values_Arr[idx0], invalid_specifier)
```
### Approach #2
Lookup based -
```
# https://stackoverflow.com/a/62658135/ @Divakar
def find_indices_lookup(a,b,invalid_specifier=-1):
# Setup array where we will assign ranged numbers
N = max(a.max(), b.max())+1
lookup = np.full(N, invalid_specifier)
# We index into lookup with b to trace back the positions. Non matching ones
# would have invalid_specifier values as wount had been indexed by ranged ones
lookup[a] = np.arange(len(a))
indices = lookup[b]
return indices
idx = find_indices_lookup(ID_Arr, Data_Arr)
out = np.where(idx!=-1, Values_Arr[idx], 0)
```
**Faster/simpler variant**
And a simplified and hopefully faster version would be a direct lookup of values -
```
a,b,invalid_specifier = ID_Arr, Data_Arr, 0
N = max(a.max(), b.max())+1
lookup = np.zeros(N, dtype=Values_Arr.dtype)
lookup[ID_Arr] = Values_Arr
out = lookup[Data_Arr]
```
If all values from `ID_Arr` are guaranteed to be in `Data_Arr`, we can use `np.empty` in place of `np.zeros` for the array-assignment and thus gain further perf. boost.
|
33,761,993
|
Here's what I'm doing, I'm web crawling for my personal use on a website to copy the text and put the chapters of a book on text format and then transform it with another program to pdf automatically to put it in my cloud. Everything is fine until this happens: special characters are not copying correctly, for example the accent is showed as: \xe2\x80\x99 on the text file and the - is showed as \xe2\x80\x93. I used this (Python 3):
```
for text in soup.find_all('p'):
texta = text.text
f.write(str(str(texta).encode("utf-8")))
f.write('\n')
```
Because since I had a bug when reading those characters and it just stopped my program, I encoded everything to utf-8 and retransform everything to string with python's method str()
I will post the whole code if anyone has a better solution to my problem, here's the part that crawl the website from page 1 to max\_pages, you can modify it on line 21 to get more or less chapters of the book:
```
import requests
from bs4 import BeautifulSoup
def crawl_ATG(max_pages):
page = 1
while page <= max_pages:
x= page
url = 'http://www.wuxiaworld.com/atg-index/atg-chapter-' + str(x) + "/"
source = requests.get(url)
chapter = source.content
soup = BeautifulSoup(chapter.decode('utf-8', 'ignore'), 'html.parser')
f = open('atg_chapter' + str(x) + '.txt', 'w+')
for text in soup.find_all('p'):
texta = text.text
f.write(str(str(texta).encode("utf-8")))
f.write('\n')
f.close
page +=1
crawl_ATG(10)
```
I will do the clean up of the first useless lines that are copied later when I get a solution to this problem. Thank you
|
2015/11/17
|
[
"https://Stackoverflow.com/questions/33761993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431636/"
] |
The easiest way to fix this problem that I found is adding `encoding= "utf-8"` in the open function:
```
with open('file.txt','w',encoding='utf-8') as file :
file.write('ñoño')
```
|
The only error I can spot is,
```
str(texta).encode("utf-8")
```
In it, you are forcing a conversion to str and encoding it. It should be replaced with,
```
texta.encode("utf-8")
```
**EDIT:**
The error stems in the server not giving the correct encoding for the page. So `requests` assumes a `'ISO-8859-1'`. As noted in this [bug](https://github.com/kennethreitz/requests/issues/1604), it is a deliberate decision.
Luckily, `chardet` library correctly detects the `'utf-8'` encoding, so you can do:
```
source.encoding = source.apparent_encoding
chapter = source.text
```
And there won't be any need to manually decode the text in `chapter`, since `requests` uses it to decode the `content` for you.
|
33,761,993
|
Here's what I'm doing, I'm web crawling for my personal use on a website to copy the text and put the chapters of a book on text format and then transform it with another program to pdf automatically to put it in my cloud. Everything is fine until this happens: special characters are not copying correctly, for example the accent is showed as: \xe2\x80\x99 on the text file and the - is showed as \xe2\x80\x93. I used this (Python 3):
```
for text in soup.find_all('p'):
texta = text.text
f.write(str(str(texta).encode("utf-8")))
f.write('\n')
```
Because since I had a bug when reading those characters and it just stopped my program, I encoded everything to utf-8 and retransform everything to string with python's method str()
I will post the whole code if anyone has a better solution to my problem, here's the part that crawl the website from page 1 to max\_pages, you can modify it on line 21 to get more or less chapters of the book:
```
import requests
from bs4 import BeautifulSoup
def crawl_ATG(max_pages):
page = 1
while page <= max_pages:
x= page
url = 'http://www.wuxiaworld.com/atg-index/atg-chapter-' + str(x) + "/"
source = requests.get(url)
chapter = source.content
soup = BeautifulSoup(chapter.decode('utf-8', 'ignore'), 'html.parser')
f = open('atg_chapter' + str(x) + '.txt', 'w+')
for text in soup.find_all('p'):
texta = text.text
f.write(str(str(texta).encode("utf-8")))
f.write('\n')
f.close
page +=1
crawl_ATG(10)
```
I will do the clean up of the first useless lines that are copied later when I get a solution to this problem. Thank you
|
2015/11/17
|
[
"https://Stackoverflow.com/questions/33761993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431636/"
] |
The easiest way to fix this problem that I found is adding `encoding= "utf-8"` in the open function:
```
with open('file.txt','w',encoding='utf-8') as file :
file.write('ñoño')
```
|
For some reason, you (wrongly) have utf8 encoded data in a Python3 string. The real cause of that is probably that `requests.content` is already a unicode string, so you should not decode it, but use it directly:
```
url = 'http://www.wuxiaworld.com/atg-index/atg-chapter-' + str(x) + "/"
source = requests.get(url)
chapter = source.content
soup = BeautifulSoup(chapter, 'html.parser')
```
If it is not enough, that means if you still have ’ and – (Unicode `u'\u2019'` and `u'\u2013'`) display as `\xe2\x80\x99` and `\xe2\x80\x93'`, that could be caused by the html page not correctly declaring its encoding. In that case you should first encode to a byte string with latin1 encoding, and then decode it as utf8:
```
chapter = source.content.encode('latin1', 'ignore').decode('utf8', 'ignore')
soup = BeautifulSoup(chapter, 'html.parser')
```
Demonstration:
```
t = u'\xe2\x80\x99 \xe2\x80\x93'
t = t.encode('latin1').decode('utf8')
```
Displays : `u'\u2019 \u2013'`
```
print(t)
```
Displays : `’ –`
|
10,080,944
|
I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. J.
CA600802 JB March 20, 1978 9:02 PM
205 4 164
210 4 164
214 4 164
642 4 164
1 5 164
</pre>
</html>
```
|
2012/04/09
|
[
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] |
Here's a regular expression to do that:
```
findData = re.compile('(?<=<pre>).+?(?=[\d\s]*</pre>)', re.S)
# ...
result = findData.search(data).group(0).strip()
```
[Here's a demo.](http://codepad.org/M71yUzqw)
|
Quazi, this calls out for a regex, specifically `<pre>(.+?)(?:\d+\s+){3}` with the DOTALL flag enabled.
You can find out about how to use regex in Python at <http://docs.python.org/library/re.html> and if you do a lot of this sort of string extraction, you'll be very glad you did. Going over my provided regex piece-by-piece:
`<pre>` just directly matches the pre tag
`(.+?)` matches and captures any characters
`(?:\d+\s+){3}` matches against some numbers followed by some whitespace, three times in a row
|
10,080,944
|
I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. J.
CA600802 JB March 20, 1978 9:02 PM
205 4 164
210 4 164
214 4 164
642 4 164
1 5 164
</pre>
</html>
```
|
2012/04/09
|
[
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] |
Quazi, this calls out for a regex, specifically `<pre>(.+?)(?:\d+\s+){3}` with the DOTALL flag enabled.
You can find out about how to use regex in Python at <http://docs.python.org/library/re.html> and if you do a lot of this sort of string extraction, you'll be very glad you did. Going over my provided regex piece-by-piece:
`<pre>` just directly matches the pre tag
`(.+?)` matches and captures any characters
`(?:\d+\s+){3}` matches against some numbers followed by some whitespace, three times in a row
|
Other people have offered up regex solutions, which are good but may behave unexpectedly at times.
If the pages are exactly as shown in your example, that is:
* No other HTML tags are present - only the `<html>` and `<pre>` tags
* The number of lines is always consistent
* The spacing between lines is always consistent
Then a simple approach like like this will do:
```
my_text = """<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. J.
CA600802 JB March 20, 1978 9:02 PM
205 4 164
210 4 164
214 4 164
642 4 164
1 5 164
</pre>
</html>"""
lines = my_text.split("\n")
title = lines[4]
journal = lines[6]
author = lines[8]
date = lines[10]
```
If you can't guarantee the *spacing* between lines, but you can guarantee that you only want the *first four non-whitespace lines* inside the `<html><pre>`;
```
import pprint
max_extracted_lines = 4
extracted_lines = []
for line in lines:
if line == "<html>" or line == "<pre>":
continue
if line:
extracted_lines.append(line)
if len(extracted_lines) >= max_extracted_lines:
break
pprint.pprint(extracted_lines)
```
Giving output:
```
['A Short Study of Notation Efficiency',
'CACM August, 1960',
'Smith Jr., H. J.',
'CA600802 JB March 20, 1978 9:02 PM']
```
Don't use regex where simple string operations will do.
|
10,080,944
|
I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. J.
CA600802 JB March 20, 1978 9:02 PM
205 4 164
210 4 164
214 4 164
642 4 164
1 5 164
</pre>
</html>
```
|
2012/04/09
|
[
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] |
Here's a regular expression to do that:
```
findData = re.compile('(?<=<pre>).+?(?=[\d\s]*</pre>)', re.S)
# ...
result = findData.search(data).group(0).strip()
```
[Here's a demo.](http://codepad.org/M71yUzqw)
|
I'd probably use lxml or BeautifulSoup. IMO, regex's are heavily overused, especially for parsing up HTML.
|
10,080,944
|
I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. J.
CA600802 JB March 20, 1978 9:02 PM
205 4 164
210 4 164
214 4 164
642 4 164
1 5 164
</pre>
</html>
```
|
2012/04/09
|
[
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] |
Here's a regular expression to do that:
```
findData = re.compile('(?<=<pre>).+?(?=[\d\s]*</pre>)', re.S)
# ...
result = findData.search(data).group(0).strip()
```
[Here's a demo.](http://codepad.org/M71yUzqw)
|
Other people have offered up regex solutions, which are good but may behave unexpectedly at times.
If the pages are exactly as shown in your example, that is:
* No other HTML tags are present - only the `<html>` and `<pre>` tags
* The number of lines is always consistent
* The spacing between lines is always consistent
Then a simple approach like like this will do:
```
my_text = """<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. J.
CA600802 JB March 20, 1978 9:02 PM
205 4 164
210 4 164
214 4 164
642 4 164
1 5 164
</pre>
</html>"""
lines = my_text.split("\n")
title = lines[4]
journal = lines[6]
author = lines[8]
date = lines[10]
```
If you can't guarantee the *spacing* between lines, but you can guarantee that you only want the *first four non-whitespace lines* inside the `<html><pre>`;
```
import pprint
max_extracted_lines = 4
extracted_lines = []
for line in lines:
if line == "<html>" or line == "<pre>":
continue
if line:
extracted_lines.append(line)
if len(extracted_lines) >= max_extracted_lines:
break
pprint.pprint(extracted_lines)
```
Giving output:
```
['A Short Study of Notation Efficiency',
'CACM August, 1960',
'Smith Jr., H. J.',
'CA600802 JB March 20, 1978 9:02 PM']
```
Don't use regex where simple string operations will do.
|
10,080,944
|
I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. J.
CA600802 JB March 20, 1978 9:02 PM
205 4 164
210 4 164
214 4 164
642 4 164
1 5 164
</pre>
</html>
```
|
2012/04/09
|
[
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] |
I'd probably use lxml or BeautifulSoup. IMO, regex's are heavily overused, especially for parsing up HTML.
|
Other people have offered up regex solutions, which are good but may behave unexpectedly at times.
If the pages are exactly as shown in your example, that is:
* No other HTML tags are present - only the `<html>` and `<pre>` tags
* The number of lines is always consistent
* The spacing between lines is always consistent
Then a simple approach like like this will do:
```
my_text = """<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. J.
CA600802 JB March 20, 1978 9:02 PM
205 4 164
210 4 164
214 4 164
642 4 164
1 5 164
</pre>
</html>"""
lines = my_text.split("\n")
title = lines[4]
journal = lines[6]
author = lines[8]
date = lines[10]
```
If you can't guarantee the *spacing* between lines, but you can guarantee that you only want the *first four non-whitespace lines* inside the `<html><pre>`;
```
import pprint
max_extracted_lines = 4
extracted_lines = []
for line in lines:
if line == "<html>" or line == "<pre>":
continue
if line:
extracted_lines.append(line)
if len(extracted_lines) >= max_extracted_lines:
break
pprint.pprint(extracted_lines)
```
Giving output:
```
['A Short Study of Notation Efficiency',
'CACM August, 1960',
'Smith Jr., H. J.',
'CA600802 JB March 20, 1978 9:02 PM']
```
Don't use regex where simple string operations will do.
|
61,511,948
|
I am coding a Discord bot in a library for python, discord.py.
I don't need help with that but with scraping some info from the site.
```py
@commands.command(aliases=["rubyuserinfo"])
async def rubyinfo(self, ctx, input):
HEADERS = {
'User-Agent' : 'Magic Browser'
}
url = f'https://rubyrealms.com/user/{input}/'
async with aiohttp.request("GET", url, headers=HEADERS) as response:
if response.status == 200:
print("Site is working!")
content = await response.text()
soup = BeautifulSoup(content, "html.parser")
page = requests.get(url)
tree = html.fromstring(page.content)
stuff = tree.xpath('/html/body/div[4]/div/div[3]/div[3]/div/div[2]/div[1]/div[2]/div/p')
print(stuff)
else:
print(f"The request was invalid\nStatus code: {response.status}")
```
The website I am looking for is "https://rubyrealms.com/user/{input}/" where input is given while running h!rubyinfo USERNAME changing the link to <https://rubyrealms.com/user/username/>.
On the website what I want to get is their BIO which has an XPATH of
>
> `"//*[@id="content-wrap"]/div[3]/div[3]/div/div[2]/div[1]/div[2]/div/p"`
>
>
>
where the element is:
```
<p class="margin-none font-color">
Hey! My name is KOMKO190, you maybe know me from the forums or discord. I am a programmer, I know a bit of JavaScript, small portion of C++, Python and html/css. Mostly python. My user ID is 7364. ||| 5th owner of Space Helmet :) </p>
```
Any help on how I would **scrape** that? The only response my bot gives is "[]"
|
2020/04/29
|
[
"https://Stackoverflow.com/questions/61511948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11251803/"
] |
*How about the following, using .select() method*
```
from bs4 import BeautifulSoup
html = '<p class="margin-none font-color">Hey! My name is KOMKO190 :) </p>'
soup = BeautifulSoup(html, features="lxml")
element = soup.select('p.margin-none')[0]
print(element.text)
```
*Prints out*
>
>
> ```
> Hey! My name is KOMKO190 :)
>
> ```
>
>
|
```
from bs4 import BeautifulSoup as bs
url = 'https://rubyrealms.com/user/username/'
session = requests.Session()
request = session.get(url=url)
if request.status_code == 200:
soup = bs(request.text, 'lxml')
print(soup.find('p', class_='margin-none font-color').text)
else:
print(request.status_code)
```
You need install
```
pip install lxml
pip install beautifulsoup4
```
|
61,511,948
|
I am coding a Discord bot in a library for python, discord.py.
I don't need help with that but with scraping some info from the site.
```py
@commands.command(aliases=["rubyuserinfo"])
async def rubyinfo(self, ctx, input):
HEADERS = {
'User-Agent' : 'Magic Browser'
}
url = f'https://rubyrealms.com/user/{input}/'
async with aiohttp.request("GET", url, headers=HEADERS) as response:
if response.status == 200:
print("Site is working!")
content = await response.text()
soup = BeautifulSoup(content, "html.parser")
page = requests.get(url)
tree = html.fromstring(page.content)
stuff = tree.xpath('/html/body/div[4]/div/div[3]/div[3]/div/div[2]/div[1]/div[2]/div/p')
print(stuff)
else:
print(f"The request was invalid\nStatus code: {response.status}")
```
The website I am looking for is "https://rubyrealms.com/user/{input}/" where input is given while running h!rubyinfo USERNAME changing the link to <https://rubyrealms.com/user/username/>.
On the website what I want to get is their BIO which has an XPATH of
>
> `"//*[@id="content-wrap"]/div[3]/div[3]/div/div[2]/div[1]/div[2]/div/p"`
>
>
>
where the element is:
```
<p class="margin-none font-color">
Hey! My name is KOMKO190, you maybe know me from the forums or discord. I am a programmer, I know a bit of JavaScript, small portion of C++, Python and html/css. Mostly python. My user ID is 7364. ||| 5th owner of Space Helmet :) </p>
```
Any help on how I would **scrape** that? The only response my bot gives is "[]"
|
2020/04/29
|
[
"https://Stackoverflow.com/questions/61511948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11251803/"
] |
Change your XPath expression for a relative one :
```
from lxml import html
import requests
page = requests.get('https://www.rubyrealms.com/user/KOMKO190/')
tree = html.fromstring(page.content)
stuff = tree.xpath('normalize-space(//h3[.="Bio"]/following-sibling::p/text())')
print (stuff)
```
Output :
```
Hey! My name is KOMKO190, you maybe know me from the forums or discord. I am a programmer, I know a bit of JavaScript, small portion of C++, Python and html/css. Mostly python. My user ID is 7364. ||| 5th owner of Space Helmet :)
```
|
*How about the following, using .select() method*
```
from bs4 import BeautifulSoup
html = '<p class="margin-none font-color">Hey! My name is KOMKO190 :) </p>'
soup = BeautifulSoup(html, features="lxml")
element = soup.select('p.margin-none')[0]
print(element.text)
```
*Prints out*
>
>
> ```
> Hey! My name is KOMKO190 :)
>
> ```
>
>
|
61,511,948
|
I am coding a Discord bot in a library for python, discord.py.
I don't need help with that but with scraping some info from the site.
```py
@commands.command(aliases=["rubyuserinfo"])
async def rubyinfo(self, ctx, input):
HEADERS = {
'User-Agent' : 'Magic Browser'
}
url = f'https://rubyrealms.com/user/{input}/'
async with aiohttp.request("GET", url, headers=HEADERS) as response:
if response.status == 200:
print("Site is working!")
content = await response.text()
soup = BeautifulSoup(content, "html.parser")
page = requests.get(url)
tree = html.fromstring(page.content)
stuff = tree.xpath('/html/body/div[4]/div/div[3]/div[3]/div/div[2]/div[1]/div[2]/div/p')
print(stuff)
else:
print(f"The request was invalid\nStatus code: {response.status}")
```
The website I am looking for is "https://rubyrealms.com/user/{input}/" where input is given while running h!rubyinfo USERNAME changing the link to <https://rubyrealms.com/user/username/>.
On the website what I want to get is their BIO which has an XPATH of
>
> `"//*[@id="content-wrap"]/div[3]/div[3]/div/div[2]/div[1]/div[2]/div/p"`
>
>
>
where the element is:
```
<p class="margin-none font-color">
Hey! My name is KOMKO190, you maybe know me from the forums or discord. I am a programmer, I know a bit of JavaScript, small portion of C++, Python and html/css. Mostly python. My user ID is 7364. ||| 5th owner of Space Helmet :) </p>
```
Any help on how I would **scrape** that? The only response my bot gives is "[]"
|
2020/04/29
|
[
"https://Stackoverflow.com/questions/61511948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11251803/"
] |
Change your XPath expression for a relative one :
```
from lxml import html
import requests
page = requests.get('https://www.rubyrealms.com/user/KOMKO190/')
tree = html.fromstring(page.content)
stuff = tree.xpath('normalize-space(//h3[.="Bio"]/following-sibling::p/text())')
print (stuff)
```
Output :
```
Hey! My name is KOMKO190, you maybe know me from the forums or discord. I am a programmer, I know a bit of JavaScript, small portion of C++, Python and html/css. Mostly python. My user ID is 7364. ||| 5th owner of Space Helmet :)
```
|
```
from bs4 import BeautifulSoup as bs
url = 'https://rubyrealms.com/user/username/'
session = requests.Session()
request = session.get(url=url)
if request.status_code == 200:
soup = bs(request.text, 'lxml')
print(soup.find('p', class_='margin-none font-color').text)
else:
print(request.status_code)
```
You need install
```
pip install lxml
pip install beautifulsoup4
```
|
48,136,092
|
I installed the python module tabula-py which is apparently based on the Java version of tabula. When I try to run it I get an error saying that the wrong version of Java is installed, but when I check in system perferences on MacOS it says I've got the latest version (Version 8 update 151). On the github page it mentions that java has to be added to PATH, so I tried doing this from these instructions <http://www.baeldung.com/java-home-on-windows-7-8-10-mac-os-x-linux>, but it still says I've got version 1.6 installed.
```
java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-468-11M4833)
```
Any help would be appreciated to get the plugin working.
This is the error:
```
Exception in thread "main" java.lang.UnsupportedClassVersionError: technology/tabula/CommandLineApp : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
```
|
2018/01/07
|
[
"https://Stackoverflow.com/questions/48136092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6670570/"
] |
This answer on the github issues page fixed the problem. <https://github.com/chezou/tabula-py/issues/54>
```
sudo mv /usr/bin/java /usr/bin/java-1.6
sudo ln -s /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java
```
|
Probably You installed java in mutiple locations.
Typ in terminal
$ wich java
To check where is this java 6 located. Then maybe You will fiund out how to uninstall it from this location.
|
68,992,767
|
I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
desired output:
```
11
12
25
32
64
```
May I know where I'm making mistake?
|
2021/08/31
|
[
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] |
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
I would recommend using i and j instead of element and compare\_index.
Look at line 9. Why does that fix it?
|
Your algorithm is almost correct but
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]` in this line you made the mistake.
It shouldn't be `compare_index`, it should be `element`. Please check the correct algorithm below
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
|
68,992,767
|
I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
desired output:
```
11
12
25
32
64
```
May I know where I'm making mistake?
|
2021/08/31
|
[
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] |
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
I would recommend using i and j instead of element and compare\_index.
Look at line 9. Why does that fix it?
|
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex],element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
swapping is a must between `element_list[element]` and `element_list[mindex]`.
|
68,992,767
|
I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
desired output:
```
11
12
25
32
64
```
May I know where I'm making mistake?
|
2021/08/31
|
[
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] |
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
I would recommend using i and j instead of element and compare\_index.
Look at line 9. Why does that fix it?
|
I think the problem lies in the line
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]`
Here I believe you want to exchange the position of the bigger and the smaller number in the array, but the problem is that you are exchanging the positions of the elements with indexes `compare_index` and `mindex`. And in the very previous line you are doing `mindex = compare_index` so basically you are exchanging one element with itself.
Rather, you must exchange elements with indexes `element` and `mindex`, as `compare_index` is just for temporary use.
Make this change in that line:
`element_list[element], element_list[mindex] = element_list[mindex], element_list[element]`
I hope this solves your problem!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.