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
|
|---|---|---|---|---|---|
576,557
|
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?
---
Remarkably similar to:
[If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626)
|
2009/02/23
|
[
"https://Stackoverflow.com/questions/576557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69746/"
] |
No, 3.x is largely incompatible with 2.x (that was actually a major motivation for doing it). In fact, you probably shouldn't be using 3.0 at all-- it's rather unusable at the moment, and is still mostly intended for library developers to port to it so that it can be usable.
|
In most cases it's not required anymore learn to Python 2 along with Python 3 for the following reasons.
1. Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained, and dedicating effort to learning it doesn't make sense anymore for most people. Also there may be problems installing some Python 2.7 packages that don't have any problems installing them in Python 3.
2. Python 3 is the best way to learn Python for the first time, because it's easier for beginners to understand than Python 2.
|
576,557
|
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?
---
Remarkably similar to:
[If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626)
|
2009/02/23
|
[
"https://Stackoverflow.com/questions/576557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69746/"
] |
Python 2.6 and Python 3.0 are *very* compatible with each other. There honestly aren't very many differences between the two. At this point, third-party library support is far better for the 2.x series (last I checked, a few libraries I use hadn't been updated from 2.5, but going from 2.5 to 2.6 is just a recompile, but 2.6 to 3.0 for C-level stuff is a real pain).
Just start learning 2.6. The infrastructure is there now, and there's plenty of help for when you finally want to move to 3.x. 2.x is not going away: there will be a 2.7 release at some point, so you're not going to be out of luck if you learn 2.6 now.
|
NO. Python 3 code is backwards incompatible with 2.6. I recommend to begin with 2.6, because your code will be more **useful**.
|
576,557
|
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?
---
Remarkably similar to:
[If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626)
|
2009/02/23
|
[
"https://Stackoverflow.com/questions/576557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69746/"
] |
It would be easier to use 2.6 right now because most external libraries are not compatible with 3 yet.
|
NO. Python 3 code is backwards incompatible with 2.6. I recommend to begin with 2.6, because your code will be more **useful**.
|
576,557
|
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?
---
Remarkably similar to:
[If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626)
|
2009/02/23
|
[
"https://Stackoverflow.com/questions/576557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69746/"
] |
NO. Python 3 code is backwards incompatible with 2.6. I recommend to begin with 2.6, because your code will be more **useful**.
|
In most cases it's not required anymore learn to Python 2 along with Python 3 for the following reasons.
1. Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained, and dedicating effort to learning it doesn't make sense anymore for most people. Also there may be problems installing some Python 2.7 packages that don't have any problems installing them in Python 3.
2. Python 3 is the best way to learn Python for the first time, because it's easier for beginners to understand than Python 2.
|
576,557
|
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?
---
Remarkably similar to:
[If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626)
|
2009/02/23
|
[
"https://Stackoverflow.com/questions/576557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69746/"
] |
Python 2.6 and Python 3.0 are *very* compatible with each other. There honestly aren't very many differences between the two. At this point, third-party library support is far better for the 2.x series (last I checked, a few libraries I use hadn't been updated from 2.5, but going from 2.5 to 2.6 is just a recompile, but 2.6 to 3.0 for C-level stuff is a real pain).
Just start learning 2.6. The infrastructure is there now, and there's plenty of help for when you finally want to move to 3.x. 2.x is not going away: there will be a 2.7 release at some point, so you're not going to be out of luck if you learn 2.6 now.
|
It would be easier to use 2.6 right now because most external libraries are not compatible with 3 yet.
|
576,557
|
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?
---
Remarkably similar to:
[If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626)
|
2009/02/23
|
[
"https://Stackoverflow.com/questions/576557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69746/"
] |
Python 2.6 and Python 3.0 are *very* compatible with each other. There honestly aren't very many differences between the two. At this point, third-party library support is far better for the 2.x series (last I checked, a few libraries I use hadn't been updated from 2.5, but going from 2.5 to 2.6 is just a recompile, but 2.6 to 3.0 for C-level stuff is a real pain).
Just start learning 2.6. The infrastructure is there now, and there's plenty of help for when you finally want to move to 3.x. 2.x is not going away: there will be a 2.7 release at some point, so you're not going to be out of luck if you learn 2.6 now.
|
In most cases it's not required anymore learn to Python 2 along with Python 3 for the following reasons.
1. Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained, and dedicating effort to learning it doesn't make sense anymore for most people. Also there may be problems installing some Python 2.7 packages that don't have any problems installing them in Python 3.
2. Python 3 is the best way to learn Python for the first time, because it's easier for beginners to understand than Python 2.
|
576,557
|
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)?
---
Remarkably similar to:
[If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/410626)
|
2009/02/23
|
[
"https://Stackoverflow.com/questions/576557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69746/"
] |
It would be easier to use 2.6 right now because most external libraries are not compatible with 3 yet.
|
In most cases it's not required anymore learn to Python 2 along with Python 3 for the following reasons.
1. Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained, and dedicating effort to learning it doesn't make sense anymore for most people. Also there may be problems installing some Python 2.7 packages that don't have any problems installing them in Python 3.
2. Python 3 is the best way to learn Python for the first time, because it's easier for beginners to understand than Python 2.
|
70,168,761
|
I am trying to click on a check box. Below is the HTML Code
```
<div class="mb-1 p-3 termsCheck">
<input class="form-check-input float-end" type="checkbox" value="" id="flexCheckDefault" required=""> <label class="form-check-label float-end" for="flexCheckDefault"><span>
Agree to Terms & Conditions </span> / <span> أوافق على الشروط والأحكام
</span> </label>
</div>
```
I am using the below code to click on it.
```
check = driver.find_element(By.CSS_SELECTOR, '#flexCheckDefault')
check.click()
```
I am getting this error
```
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (477, 1222)
```
full error:
```
driver.find_element(By.XPATH, "//label[@for='flexCheckDefault']").click()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 81, in click
self._execute(Command.CLICK_ELEMENT)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute
return self._parent.execute(command, params)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (292, 1317)
(Session info: chrome=91.0.4472.101)
Stacktrace:
#0 0x556910005919 <unknown
```
Can some please help me with this.
when I am using the below code I am getting this error::
```
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flexCheckDefault']"))).click()
```
Error
```
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flexCheckDefault']"))).click()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 81, in click
self._execute(Command.CLICK_ELEMENT)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute
return self._parent.execute(command, params)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (292, 467)
(Session info: chrome=91.0.4472.101)
Stacktrace:
#0 0x563f45805919 <unknown>
```
|
2021/11/30
|
[
"https://Stackoverflow.com/questions/70168761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13572791/"
] |
`max_func` should return a function that takes an argument (`x`), applies it to `f` and `g` and then return the maximal value:
```
def max_func(f, g):
def mf(x):
return max(f(x), g(x))
return mf
```
|
In your code, you are calling only f(x) in both if and else statement.
You can try:
```
def max_func(f,g):
if f(x)> g(x):
return f(x)
else:
return g(x)
def new_function (x:int): -> int
return new_function
```
|
70,168,761
|
I am trying to click on a check box. Below is the HTML Code
```
<div class="mb-1 p-3 termsCheck">
<input class="form-check-input float-end" type="checkbox" value="" id="flexCheckDefault" required=""> <label class="form-check-label float-end" for="flexCheckDefault"><span>
Agree to Terms & Conditions </span> / <span> أوافق على الشروط والأحكام
</span> </label>
</div>
```
I am using the below code to click on it.
```
check = driver.find_element(By.CSS_SELECTOR, '#flexCheckDefault')
check.click()
```
I am getting this error
```
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (477, 1222)
```
full error:
```
driver.find_element(By.XPATH, "//label[@for='flexCheckDefault']").click()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 81, in click
self._execute(Command.CLICK_ELEMENT)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute
return self._parent.execute(command, params)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (292, 1317)
(Session info: chrome=91.0.4472.101)
Stacktrace:
#0 0x556910005919 <unknown
```
Can some please help me with this.
when I am using the below code I am getting this error::
```
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flexCheckDefault']"))).click()
```
Error
```
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flexCheckDefault']"))).click()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 81, in click
self._execute(Command.CLICK_ELEMENT)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute
return self._parent.execute(command, params)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (292, 467)
(Session info: chrome=91.0.4472.101)
Stacktrace:
#0 0x563f45805919 <unknown>
```
|
2021/11/30
|
[
"https://Stackoverflow.com/questions/70168761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13572791/"
] |
`max_func` should return a function that takes an argument (`x`), applies it to `f` and `g` and then return the maximal value:
```
def max_func(f, g):
def mf(x):
return max(f(x), g(x))
return mf
```
|
High order functional programming can get real weird real quickly. Since this seems to be a homework exercise, I won't give you the straight answer, but consider this:
```py
def make_function_print_arg(f):
def new_function(x):
print(f"Calling function with {x}")
return f(x)
return new_function
```
This defines a function that modifies the function it gets passed. I can use it like this:
```py
def square(x):
return x**2
print_and_square = make_function_print_arg(square)
arg = 5
ret = print_and_square(arg) # Prints out "Calling function with 5"
print(f"{arg} squared is {ret}") # Prints out "5 squared is 25"
```
So, `make_function_print_arg` is a function which takes a function `f` as an argument. Within its body, it defines a new function. This new function takes a single argument, prints that argument out, then calls `f` with that single argument. Finally, `make_function_print_arg` returns the new function it just defined.
Later on, we can call `make_function_print_arg` with a function that we've already defined, which returns a new function that's a lot like our old function, but with some modified behaviour.
Now, in your case, you want to define a function which takes two functions as arguments, calls both of them, and returns whichever result is greater. I'm pretty certain that one of the lines you need to unscramble should read, `return g(x)`, so I think either you or your teacher made a typo, but working around that, see if you can use the ideas in `make_function_print_arg` to manage it!
For your own education, you might also want to read about how decorators work, which is quite similar to what you're learning about right now: <https://book.pythontips.com/en/latest/decorators.html>
|
70,168,761
|
I am trying to click on a check box. Below is the HTML Code
```
<div class="mb-1 p-3 termsCheck">
<input class="form-check-input float-end" type="checkbox" value="" id="flexCheckDefault" required=""> <label class="form-check-label float-end" for="flexCheckDefault"><span>
Agree to Terms & Conditions </span> / <span> أوافق على الشروط والأحكام
</span> </label>
</div>
```
I am using the below code to click on it.
```
check = driver.find_element(By.CSS_SELECTOR, '#flexCheckDefault')
check.click()
```
I am getting this error
```
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (477, 1222)
```
full error:
```
driver.find_element(By.XPATH, "//label[@for='flexCheckDefault']").click()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 81, in click
self._execute(Command.CLICK_ELEMENT)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute
return self._parent.execute(command, params)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (292, 1317)
(Session info: chrome=91.0.4472.101)
Stacktrace:
#0 0x556910005919 <unknown
```
Can some please help me with this.
when I am using the below code I am getting this error::
```
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flexCheckDefault']"))).click()
```
Error
```
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@for='flexCheckDefault']"))).click()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 81, in click
self._execute(Command.CLICK_ELEMENT)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute
return self._parent.execute(command, params)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point (292, 467)
(Session info: chrome=91.0.4472.101)
Stacktrace:
#0 0x563f45805919 <unknown>
```
|
2021/11/30
|
[
"https://Stackoverflow.com/questions/70168761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13572791/"
] |
High order functional programming can get real weird real quickly. Since this seems to be a homework exercise, I won't give you the straight answer, but consider this:
```py
def make_function_print_arg(f):
def new_function(x):
print(f"Calling function with {x}")
return f(x)
return new_function
```
This defines a function that modifies the function it gets passed. I can use it like this:
```py
def square(x):
return x**2
print_and_square = make_function_print_arg(square)
arg = 5
ret = print_and_square(arg) # Prints out "Calling function with 5"
print(f"{arg} squared is {ret}") # Prints out "5 squared is 25"
```
So, `make_function_print_arg` is a function which takes a function `f` as an argument. Within its body, it defines a new function. This new function takes a single argument, prints that argument out, then calls `f` with that single argument. Finally, `make_function_print_arg` returns the new function it just defined.
Later on, we can call `make_function_print_arg` with a function that we've already defined, which returns a new function that's a lot like our old function, but with some modified behaviour.
Now, in your case, you want to define a function which takes two functions as arguments, calls both of them, and returns whichever result is greater. I'm pretty certain that one of the lines you need to unscramble should read, `return g(x)`, so I think either you or your teacher made a typo, but working around that, see if you can use the ideas in `make_function_print_arg` to manage it!
For your own education, you might also want to read about how decorators work, which is quite similar to what you're learning about right now: <https://book.pythontips.com/en/latest/decorators.html>
|
In your code, you are calling only f(x) in both if and else statement.
You can try:
```
def max_func(f,g):
if f(x)> g(x):
return f(x)
else:
return g(x)
def new_function (x:int): -> int
return new_function
```
|
41,950,021
|
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists.
I'm using `Python3`.
My code:
```
players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
vote = 0
cont = 0
while(vote >= 0 and vote <23):
vote = input('Enter the name of the player you wish to vote for')
if (0 < vote <=24):
players[vote +1] += 1;cont +=1
else:
print('Invalid vote, try again')
```
I get
>
> TypeError: '<=' not supported between instances of 'str' and 'int'
>
>
>
But I don't have any strings here, all variables are integers.
|
2017/01/31
|
[
"https://Stackoverflow.com/questions/41950021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7493136/"
] |
Change
```
vote = input('Enter the name of the player you wish to vote for')
```
to
```
vote = int(input('Enter the name of the player you wish to vote for'))
```
You are getting the input from the console as a string, so you must cast that input string to an `int` object in order to do numerical operations.
|
When you use the input function it automatically turns it into a string. You need to go:
```
vote = int(input('Enter the name of the player you wish to vote for'))
```
which turns the input into a int type value
|
41,950,021
|
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists.
I'm using `Python3`.
My code:
```
players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
vote = 0
cont = 0
while(vote >= 0 and vote <23):
vote = input('Enter the name of the player you wish to vote for')
if (0 < vote <=24):
players[vote +1] += 1;cont +=1
else:
print('Invalid vote, try again')
```
I get
>
> TypeError: '<=' not supported between instances of 'str' and 'int'
>
>
>
But I don't have any strings here, all variables are integers.
|
2017/01/31
|
[
"https://Stackoverflow.com/questions/41950021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7493136/"
] |
Change
```
vote = input('Enter the name of the player you wish to vote for')
```
to
```
vote = int(input('Enter the name of the player you wish to vote for'))
```
You are getting the input from the console as a string, so you must cast that input string to an `int` object in order to do numerical operations.
|
If you're using Python3.x `input` will return a string,so you should use `int` method to convert string to integer.
[Python3 Input](https://docs.python.org/3/library/functions.html#input)
>
> If the prompt argument is present, it is written to standard output
> without a trailing newline. The function then reads a line from input,
> **converts it to a string** (stripping a trailing newline), and returns
> that. When EOF is read, EOFError is raised.
>
>
>
By the way,it's a good way to use `try` `catch` if you want to convert string to int:
```
try:
i = int(s)
except ValueError as err:
pass
```
Hope this helps.
|
41,950,021
|
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists.
I'm using `Python3`.
My code:
```
players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
vote = 0
cont = 0
while(vote >= 0 and vote <23):
vote = input('Enter the name of the player you wish to vote for')
if (0 < vote <=24):
players[vote +1] += 1;cont +=1
else:
print('Invalid vote, try again')
```
I get
>
> TypeError: '<=' not supported between instances of 'str' and 'int'
>
>
>
But I don't have any strings here, all variables are integers.
|
2017/01/31
|
[
"https://Stackoverflow.com/questions/41950021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7493136/"
] |
Change
```
vote = input('Enter the name of the player you wish to vote for')
```
to
```
vote = int(input('Enter the name of the player you wish to vote for'))
```
You are getting the input from the console as a string, so you must cast that input string to an `int` object in order to do numerical operations.
|
`input()` by default takes the input in form of strings.
```
if (0<= vote <=24):
```
vote takes a string input (suppose `4`,`5`,etc) and becomes uncomparable.
The correct way is: `vote = int(input("Enter your message")`will convert the input to integer (`4` to 4 or `5` to 5 depending on the input)
|
41,950,021
|
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists.
I'm using `Python3`.
My code:
```
players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
vote = 0
cont = 0
while(vote >= 0 and vote <23):
vote = input('Enter the name of the player you wish to vote for')
if (0 < vote <=24):
players[vote +1] += 1;cont +=1
else:
print('Invalid vote, try again')
```
I get
>
> TypeError: '<=' not supported between instances of 'str' and 'int'
>
>
>
But I don't have any strings here, all variables are integers.
|
2017/01/31
|
[
"https://Stackoverflow.com/questions/41950021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7493136/"
] |
If you're using Python3.x `input` will return a string,so you should use `int` method to convert string to integer.
[Python3 Input](https://docs.python.org/3/library/functions.html#input)
>
> If the prompt argument is present, it is written to standard output
> without a trailing newline. The function then reads a line from input,
> **converts it to a string** (stripping a trailing newline), and returns
> that. When EOF is read, EOFError is raised.
>
>
>
By the way,it's a good way to use `try` `catch` if you want to convert string to int:
```
try:
i = int(s)
except ValueError as err:
pass
```
Hope this helps.
|
When you use the input function it automatically turns it into a string. You need to go:
```
vote = int(input('Enter the name of the player you wish to vote for'))
```
which turns the input into a int type value
|
41,950,021
|
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists.
I'm using `Python3`.
My code:
```
players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
vote = 0
cont = 0
while(vote >= 0 and vote <23):
vote = input('Enter the name of the player you wish to vote for')
if (0 < vote <=24):
players[vote +1] += 1;cont +=1
else:
print('Invalid vote, try again')
```
I get
>
> TypeError: '<=' not supported between instances of 'str' and 'int'
>
>
>
But I don't have any strings here, all variables are integers.
|
2017/01/31
|
[
"https://Stackoverflow.com/questions/41950021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7493136/"
] |
If you're using Python3.x `input` will return a string,so you should use `int` method to convert string to integer.
[Python3 Input](https://docs.python.org/3/library/functions.html#input)
>
> If the prompt argument is present, it is written to standard output
> without a trailing newline. The function then reads a line from input,
> **converts it to a string** (stripping a trailing newline), and returns
> that. When EOF is read, EOFError is raised.
>
>
>
By the way,it's a good way to use `try` `catch` if you want to convert string to int:
```
try:
i = int(s)
except ValueError as err:
pass
```
Hope this helps.
|
`input()` by default takes the input in form of strings.
```
if (0<= vote <=24):
```
vote takes a string input (suppose `4`,`5`,etc) and becomes uncomparable.
The correct way is: `vote = int(input("Enter your message")`will convert the input to integer (`4` to 4 or `5` to 5 depending on the input)
|
41,908,655
|
i need to create a dataframe containing tuples from a series of dataframes arrays. What I need is the following:
I have dataframes `a` and `b`:
```
a = pd.DataFrame(np.array([[1, 2],[3, 4]]), columns=['one', 'two'])
b = pd.DataFrame(np.array([[5, 6],[7, 8]]), columns=['one', 'two'])
a:
one two
0 1 2
1 3 4
b:
one two
0 5 6
1 7 8
```
I want to create a dataframe `a_b` in which each element is a tuple formed from the corresponding elements in a and b, i.e.
```
a_b = pd.DataFrame([[(1, 5), (2, 6)],[(3, 7), (4, 8)]], columns=['one', 'two'])
a_b:
one two
0 (1, 5) (2, 6)
1 (3, 7) (4, 8)
```
Ideally i would like to do this with an arbitrary number of dataframes.
I was hoping there was a more elegant way than using a for cycle
I'm using python 3
|
2017/01/28
|
[
"https://Stackoverflow.com/questions/41908655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6316272/"
] |
you can use `numpy.rec.fromarrays((a.values, b.values)).tolist()`:
```
In [34]: pd.DataFrame(np.rec.fromarrays((a.values, b.values)).tolist(),
columns=a.columns,
index=a.index)
Out[34]:
one two
0 (1, 5) (2, 6)
1 (3, 7) (4, 8)
```
merging three DF's:
```
In [36]: pd.DataFrame(np.rec.fromarrays((a.values, b.values, a.values)).tolist(),
columns=a.columns,
index=a.index)
Out[36]:
one two
0 (1, 5, 1) (2, 6, 2)
1 (3, 7, 3) (4, 8, 4)
```
**UPDATE:**
>
> suppose you don't know in advance the number of dataframes, how would
> you do?
>
>
>
```
In [60]: dfs = [a,b,a]
In [62]: tuple_of_dfs = (x.values for x in dfs)
In [63]: pd.DataFrame(np.rec.fromarrays(tuple_of_dfs).tolist(), columns=a.columns, index=a.index)
Out[63]:
one two
0 (1, 5, 1) (2, 6, 2)
1 (3, 7, 3) (4, 8, 4)
```
|
You could use `zip` over columns of `a`, `b`
```
In [31]: pd.DataFrame({x: zip(a[x], b[x]) for x in a.columns})
Out[31]:
one two
0 (1, 5) (2, 6)
1 (3, 7) (4, 8)
```
|
68,767,995
|
I have a string like this:
```
txt = ''' lea_po () {
val : 96.9;
wh : "CP D ";
related : DD;
leak () {
va : 0.008;
when : " SI";
in : V;
}
**stagestat (" E I P", "I 2 ") {
data : " H H/L - R : - - - : L - - , \
- : - - - : L - - , \
- - - R : - - : - - , \
- - - : - - : - - L, \
- - - ~R : - - - : N P N ";
}**
...
'''
```
I would like to only extract the bold part which start with the `stagestat` and end with the curly bracket `"}"`.
But I tried to use a python regex to search but it fails.
```
re.search("^stagestat.*}$",txt)
```
Can someone give some comments on this?
|
2021/08/13
|
[
"https://Stackoverflow.com/questions/68767995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13699970/"
] |
* Make sure you have `Unicode True` at the start of your script.
* Make sure you save your script as UTF-8 BOM or UTF-16LE BOM.
* !include nsDialogs before commctrl.nsh
* Make sure you are using the Unicode version of all plug-ins.
Characters that "look Chinese" is a symptom of treating ASCII as UTF-16. Strings cut off after the first character is a symptom of treating UTF-16 as ASCII (not a Unicode plug-in?).
This works for me:
```
Unicode True
RequestExecutionLevel user
!include nsDialogs.nsh
!define _COMMCTRL_NSH_VERBOSE 3
!include commctrl.nsh
Section
SectionEnd
Page custom nsDialogsPage
Var lv
Function msgboxtext
Pop $0
SendMessage $lv ${LVM_GETSELECTIONMARK} 0 0 $8
StrCpy $9 1
${If} $8 = -1
Return
${EndIf}
System::Call '*(&t${NSIS_MAX_STRLEN})p.r3'
System::Call "*(i, i, i, i, i, p, i, i, i) p (0, 0, $9, 0, 0, r3, ${NSIS_MAX_STRLEN}) .r1"
System::Call "User32::SendMessage(p, i, p, p) p ($lv, ${LVM_GETITEMTEXT}, $8, r1)"
System::Call "*$3(&t${NSIS_MAX_STRLEN} .r4)"
System::Free $1
System::Free $3
MessageBox mb_ok $4
FunctionEnd
Function nsDialogsPage
nsDialogs::Create 1018
Pop $0
${NSD_CreateButton} 0 0 100% 12u "Get text"
Pop $9
${NSD_OnClick} $9 msgboxtext
nsDialogs::CreateControl /NOUNLOAD ${WC_LISTVIEW} ${__NSD_ListView_STYLE}|${WS_TABSTOP} ${__NSD_ListView_EXSTYLE} 0 13u 100% -13u ""
Pop $lv
${NSD_LV_InsertColumn} $lv 0 100 "column 0"
${NSD_LV_InsertColumn} $lv 1 70 "서대문"
${NSD_LV_InsertItem} $lv 0 '서대문'
${NSD_LV_SetItemText} $lv 0 1 '서대문 서대문'
${NSD_LV_InsertItem} $lv 1 '2 서대문'
${NSD_LV_SetItemText} $lv 1 1 '2.2 서대문 서대문'
nsDialogs::Show
FunctionEnd
```
|
Have you tried to add command "unicode True" at the top of the script?
|
47,344,625
|
content of my python file
```
class myclass(object):
def __init__(self):
pass
def myfun(self):
pass
print ("hello world")
```
Output on executing file
```
hello world
```
Query
```
since I did not create object of class . How's it still able to print "hello world"
```
|
2017/11/17
|
[
"https://Stackoverflow.com/questions/47344625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3812837/"
] |
The class body executes at class definition time, and that's how the language is designed.
From section [9.3.1 Class Definition](https://docs.python.org/3/tutorial/classes.html#class-definition-syntax) syntax:
>
> In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful.
>
>
>
That is simply how the execution model works in Python, so there's not much more to say about it.
>
> as per my understanding...anything class can not run until we call it by creating a object
>
>
>
Simply a misunderstanding. This applies for `def`, i.e. function blocks, but not for class blocks.
|
It will get a call, as python work like that.
Your code will always return output.
**hello world**
```
class myclass(object):
def __init__(self):
pass
def myfun(self):
print("hello world")
pass
```
If you want to avoid it you have to add print statement inside the method.
|
54,005,909
|
I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on.
I want to loop through the list and score as follows:
for each pair score that pair 2 beats they receive 2 points, for each they tie 1 point and where they don't beat they get 0 points. The loop then continues and compares each pair's score in the same way. In the example below, pair 2 gets 7 points (beating 3 other pairs and a tie with 1), pair 7 gets 0 points, pair 6 gets 12 points beating every other pair.
My list (generated from an elasticsearch json object) is:
```
['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
```
The python code I have tried (after multiple variations) is:
```
nsp_mp = 0
ewp_mp = 0
ns_list = []
for row in arr["hits"]["hits"]:
nsp = row["_source"]["nsp"]
nsscore = row["_source"]["nsscore"]
ns_list.append(nsp)
ns_list.append(nsscore)
print(ns_list)
x = ns_list[1]
for i in range(6): #number of competing pairs
if x > ns_list[1::2][i]:
nsp_mp = nsp_mp + 2
elif x == ns_list[1::2][i]:
nsp_mp = nsp_mp
else:
nsp_mp = nsp_mp + 1
print(nsp_mp)
```
which produces:
```
['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
7
```
which as per calculation above is correct. But when I try to execute a loop it does not return the correct results.
Maybe the approach is wrong. What is the correct way to do this?
The elasticsearch json object is:
```
arr = {'took': 0, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}, 'hits': {'total': 7, 'max_score': 1.0, 'hits': [{'_index': 'match', '_type': 'score', '_id': 'L_L122cBjpp4O0gQG0qd', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '2', 'ewp': '9', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.896151'}}, {'_index': 'match', '_type': 'score', '_id': 'MPL122cBjpp4O0gQHEog', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '3', 'ewp': '10', 'contract': '4S', 'by': 'N', 'tricks': '10', 'nsscore': '420', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.027631'}}, {'_index': 'match', '_type': 'score', '_id': 'MfL122cBjpp4O0gQHEqk', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '4', 'ewp': '11', 'contract': '3NT', 'by': 'N', 'tricks': '11', 'nsscore': '460', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.158060'}}, {'_index': 'match', '_type': 'score', '_id': 'MvL122cBjpp4O0gQHUoj', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '5', 'ewp': '12', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '400', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.285460'}}, {'_index': 'match', '_type': 'score', '_id': 'NPL122cBjpp4O0gQHkof', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '7', 'ewp': '14', 'contract': '3NT', 'by': 'S', 'tricks': '8', 'nsscore': '0', 'ewscore': '50', 'timestamp': '2018-12-23T16:45:33.538710'}}, {'_index': 'match', '_type': 'score', '_id': 'LvL122cBjpp4O0gQGkqt', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '1', 'ewp': '8', 'contract': '3NT', 'by': 'N', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.405998'}}, {'_index': 'match', '_type': 'score', '_id': 'M_L122cBjpp4O0gQHUqg', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '6', 'ewp': '13', 'contract': '4S', 'by': 'S', 'tricks': '11', 'nsscore': '480', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.411104'}}]}}
```
|
2019/01/02
|
[
"https://Stackoverflow.com/questions/54005909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1903663/"
] |
List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object.
>
> Note there are a few minor mistakes in listings below - to make sure
> I'm not solving someone's homework for free. I also realize this is
> not the most efficient way of doing so.
>
>
>
Try with dicts:
1) convert elasticsearch json you have to a dict with a better structure:
```
scores = {}
for row in arr["hits"]["hits"]:
nsp = row["_source"]["nsp"]
nsscore = row["_source"]["nsscore"]
scores[nsp] = nsscore
```
This will give you something like this:
```
{'1': '430',
'2': '430',
'3': '420',
'4': '460',
'5': '400',
'6': '480',
'7': '0'}
```
2) write a function to calculate pair score:
```
def calculate_score(pair, scores):
score = 0
for p in scores:
if p == pair:
continue
if scores[p] < scores[pair]:
score += 2 # win
elif scores[p] == scores[pair]:
score += 1
return score
```
This should give you something like this:
```
In [13]: calculate_score('1', scores)
Out[13]: 7
In [14]: calculate_score('7', scores)
Out[14]: 0
```
3) loop over all pairs, calculating scores. I'll leave this as exercise.
|
The main problem with your code is, that the loop is one short, you have 7 entries. Then you should convert the numbers to `int`, so that the comparison is correct. In your code, you get for ties 0 points.
Instead of having a list, with flattend pairs, you should use tuple pairs.
```
ns_list = []
for row in arr["hits"]["hits"]:
nsp = int(row["_source"]["nsp"])
nsscore = int(row["_source"]["nsscore"])
ns_list.append((nsp, nsscore))
print(ns_list)
x = ns_list[0][1]
nsp_mp = 0
for nsp, nsscore in ns_list:
if x > nsscore:
nsp_mp += 2
elif x == nsscore:
nsp_mp += 1
print(nsp_mp)
```
|
54,005,909
|
I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on.
I want to loop through the list and score as follows:
for each pair score that pair 2 beats they receive 2 points, for each they tie 1 point and where they don't beat they get 0 points. The loop then continues and compares each pair's score in the same way. In the example below, pair 2 gets 7 points (beating 3 other pairs and a tie with 1), pair 7 gets 0 points, pair 6 gets 12 points beating every other pair.
My list (generated from an elasticsearch json object) is:
```
['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
```
The python code I have tried (after multiple variations) is:
```
nsp_mp = 0
ewp_mp = 0
ns_list = []
for row in arr["hits"]["hits"]:
nsp = row["_source"]["nsp"]
nsscore = row["_source"]["nsscore"]
ns_list.append(nsp)
ns_list.append(nsscore)
print(ns_list)
x = ns_list[1]
for i in range(6): #number of competing pairs
if x > ns_list[1::2][i]:
nsp_mp = nsp_mp + 2
elif x == ns_list[1::2][i]:
nsp_mp = nsp_mp
else:
nsp_mp = nsp_mp + 1
print(nsp_mp)
```
which produces:
```
['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
7
```
which as per calculation above is correct. But when I try to execute a loop it does not return the correct results.
Maybe the approach is wrong. What is the correct way to do this?
The elasticsearch json object is:
```
arr = {'took': 0, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}, 'hits': {'total': 7, 'max_score': 1.0, 'hits': [{'_index': 'match', '_type': 'score', '_id': 'L_L122cBjpp4O0gQG0qd', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '2', 'ewp': '9', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.896151'}}, {'_index': 'match', '_type': 'score', '_id': 'MPL122cBjpp4O0gQHEog', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '3', 'ewp': '10', 'contract': '4S', 'by': 'N', 'tricks': '10', 'nsscore': '420', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.027631'}}, {'_index': 'match', '_type': 'score', '_id': 'MfL122cBjpp4O0gQHEqk', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '4', 'ewp': '11', 'contract': '3NT', 'by': 'N', 'tricks': '11', 'nsscore': '460', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.158060'}}, {'_index': 'match', '_type': 'score', '_id': 'MvL122cBjpp4O0gQHUoj', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '5', 'ewp': '12', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '400', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.285460'}}, {'_index': 'match', '_type': 'score', '_id': 'NPL122cBjpp4O0gQHkof', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '7', 'ewp': '14', 'contract': '3NT', 'by': 'S', 'tricks': '8', 'nsscore': '0', 'ewscore': '50', 'timestamp': '2018-12-23T16:45:33.538710'}}, {'_index': 'match', '_type': 'score', '_id': 'LvL122cBjpp4O0gQGkqt', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '1', 'ewp': '8', 'contract': '3NT', 'by': 'N', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.405998'}}, {'_index': 'match', '_type': 'score', '_id': 'M_L122cBjpp4O0gQHUqg', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '6', 'ewp': '13', 'contract': '4S', 'by': 'S', 'tricks': '11', 'nsscore': '480', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.411104'}}]}}
```
|
2019/01/02
|
[
"https://Stackoverflow.com/questions/54005909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1903663/"
] |
List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object.
>
> Note there are a few minor mistakes in listings below - to make sure
> I'm not solving someone's homework for free. I also realize this is
> not the most efficient way of doing so.
>
>
>
Try with dicts:
1) convert elasticsearch json you have to a dict with a better structure:
```
scores = {}
for row in arr["hits"]["hits"]:
nsp = row["_source"]["nsp"]
nsscore = row["_source"]["nsscore"]
scores[nsp] = nsscore
```
This will give you something like this:
```
{'1': '430',
'2': '430',
'3': '420',
'4': '460',
'5': '400',
'6': '480',
'7': '0'}
```
2) write a function to calculate pair score:
```
def calculate_score(pair, scores):
score = 0
for p in scores:
if p == pair:
continue
if scores[p] < scores[pair]:
score += 2 # win
elif scores[p] == scores[pair]:
score += 1
return score
```
This should give you something like this:
```
In [13]: calculate_score('1', scores)
Out[13]: 7
In [14]: calculate_score('7', scores)
Out[14]: 0
```
3) loop over all pairs, calculating scores. I'll leave this as exercise.
|
So we can do it like so:
```
import itertools
d = [(i['_source']['nsp'], i['_source']['nsscore']) for i in arr['hits']['hits']]
d
[('2', '430'),
('3', '420'),
('4', '460'),
('5', '400'),
('7', '0'),
('1', '430'),
('6', '480')]
c = itertools.combinations(d, 2)
counts = {}
for tup in c:
p1, p2 = tup
if not counts.get(p1[0]):
counts[p1[0]] = 0
if int(p1[1]) > int(p2[1]):
counts[p1[0]] += 1
counts
{'2': 3, '3': 2, '4': 3, '5': 1, '7': 0, '1': 0}
```
|
54,005,909
|
I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on.
I want to loop through the list and score as follows:
for each pair score that pair 2 beats they receive 2 points, for each they tie 1 point and where they don't beat they get 0 points. The loop then continues and compares each pair's score in the same way. In the example below, pair 2 gets 7 points (beating 3 other pairs and a tie with 1), pair 7 gets 0 points, pair 6 gets 12 points beating every other pair.
My list (generated from an elasticsearch json object) is:
```
['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
```
The python code I have tried (after multiple variations) is:
```
nsp_mp = 0
ewp_mp = 0
ns_list = []
for row in arr["hits"]["hits"]:
nsp = row["_source"]["nsp"]
nsscore = row["_source"]["nsscore"]
ns_list.append(nsp)
ns_list.append(nsscore)
print(ns_list)
x = ns_list[1]
for i in range(6): #number of competing pairs
if x > ns_list[1::2][i]:
nsp_mp = nsp_mp + 2
elif x == ns_list[1::2][i]:
nsp_mp = nsp_mp
else:
nsp_mp = nsp_mp + 1
print(nsp_mp)
```
which produces:
```
['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
7
```
which as per calculation above is correct. But when I try to execute a loop it does not return the correct results.
Maybe the approach is wrong. What is the correct way to do this?
The elasticsearch json object is:
```
arr = {'took': 0, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0}, 'hits': {'total': 7, 'max_score': 1.0, 'hits': [{'_index': 'match', '_type': 'score', '_id': 'L_L122cBjpp4O0gQG0qd', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '2', 'ewp': '9', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.896151'}}, {'_index': 'match', '_type': 'score', '_id': 'MPL122cBjpp4O0gQHEog', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '3', 'ewp': '10', 'contract': '4S', 'by': 'N', 'tricks': '10', 'nsscore': '420', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.027631'}}, {'_index': 'match', '_type': 'score', '_id': 'MfL122cBjpp4O0gQHEqk', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '4', 'ewp': '11', 'contract': '3NT', 'by': 'N', 'tricks': '11', 'nsscore': '460', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.158060'}}, {'_index': 'match', '_type': 'score', '_id': 'MvL122cBjpp4O0gQHUoj', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '5', 'ewp': '12', 'contract': '3NT', 'by': 'S', 'tricks': '10', 'nsscore': '400', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.285460'}}, {'_index': 'match', '_type': 'score', '_id': 'NPL122cBjpp4O0gQHkof', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '7', 'ewp': '14', 'contract': '3NT', 'by': 'S', 'tricks': '8', 'nsscore': '0', 'ewscore': '50', 'timestamp': '2018-12-23T16:45:33.538710'}}, {'_index': 'match', '_type': 'score', '_id': 'LvL122cBjpp4O0gQGkqt', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '1', 'ewp': '8', 'contract': '3NT', 'by': 'N', 'tricks': '10', 'nsscore': '430', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:32.405998'}}, {'_index': 'match', '_type': 'score', '_id': 'M_L122cBjpp4O0gQHUqg', '_score': 1.0, '_source': {'tournament_id': 1, 'board_number': '1', 'nsp': '6', 'ewp': '13', 'contract': '4S', 'by': 'S', 'tricks': '11', 'nsscore': '480', 'ewscore': '0', 'timestamp': '2018-12-23T16:45:33.411104'}}]}}
```
|
2019/01/02
|
[
"https://Stackoverflow.com/questions/54005909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1903663/"
] |
List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object.
>
> Note there are a few minor mistakes in listings below - to make sure
> I'm not solving someone's homework for free. I also realize this is
> not the most efficient way of doing so.
>
>
>
Try with dicts:
1) convert elasticsearch json you have to a dict with a better structure:
```
scores = {}
for row in arr["hits"]["hits"]:
nsp = row["_source"]["nsp"]
nsscore = row["_source"]["nsscore"]
scores[nsp] = nsscore
```
This will give you something like this:
```
{'1': '430',
'2': '430',
'3': '420',
'4': '460',
'5': '400',
'6': '480',
'7': '0'}
```
2) write a function to calculate pair score:
```
def calculate_score(pair, scores):
score = 0
for p in scores:
if p == pair:
continue
if scores[p] < scores[pair]:
score += 2 # win
elif scores[p] == scores[pair]:
score += 1
return score
```
This should give you something like this:
```
In [13]: calculate_score('1', scores)
Out[13]: 7
In [14]: calculate_score('7', scores)
Out[14]: 0
```
3) loop over all pairs, calculating scores. I'll leave this as exercise.
|
I first convert the list of your score to a dictionary object using itertools, then iterating through each key, and for each key, compare the values available in the list
and add accordingly the score you provided and since in this approach you will always add the value 1 because you will always compare it with itself so at end i decrease 1 from the final score there may be a better approach for this
```
ls = ['2', '430', '3', '420', '4', '460', '5', '400', '7', '0', '1', '430', '6', '480']
d = dict(itertools.zip_longest(*[iter(ls)] * 2, fillvalue=""))
values= d.values()
for item in d.keys():
score=0
for i in values:
if d[item]>i:
score+=2
elif d[item]==i:
score+=1
else:
pass
print(item,":",score-1)
```
**Output:**
```
2 : 7
3 : 4
4 : 10
5 : 2
7 : 0
1 : 7
6 : 12
```
|
50,159,438
|
I tried reproducing some of the examples described [here](https://www.boost.org/doc/libs/1_63_0/libs/python/doc/html/numpy/tutorial/ndarray.html), but I experience the following problem with the code below, which was written by just copy-pasting relevant parts of the linked page.
```
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <iostream>
using namespace std;
namespace p = boost::python;
namespace np = boost::python::numpy;
np::ndarray test()
{
int data[] = {1,2,3,4,5};
p::tuple shape = p::make_tuple(5);
p::tuple stride = p::make_tuple(sizeof(int));
p::object own;
np::dtype dt = np::dtype::get_builtin<int>();
np::ndarray array = np::from_data(data, dt, shape,stride,own);
std::cout << "Selective multidimensional array :: "<<std::endl
<< p::extract<char const *>(p::str(array)) << std::endl ;
return array;
}
BOOST_PYTHON_MODULE(test_module)
{
using namespace boost::python;
// Initialize numpy
Py_Initialize();
boost::python::numpy::initialize();
def("test", test);
}
```
When I compile as a shared library and load the module in python,
```
import test_module as test
print(test.test())
```
it seems that the `ndarray` gets created properly by the C++ code, but the version that python receives is rubbish; the arrays that get printed are:
```
[1 2 3 4 5]
[2121031184 32554 2130927769 32554 0]
```
What could be the cause of such a difference?
|
2018/05/03
|
[
"https://Stackoverflow.com/questions/50159438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7141288/"
] |
This week I had the same issue. To solve my problem I use dynamic memory:
```
np::ndarray test(){
int *data = malloc(sizeof(int) * 5);
for (int i=0; i < 5; ++i){
data[i] = i + 1;
}
p::tuple shape = p::make_tuple(5);
p::tuple stride = p::make_tuple(sizeof(int));
p::object own;
np::dtype dt = np::dtype::get_builtin<int>();
np::ndarray array = np::from_data(data, dt, shape, stride, own);
return array;
}
```
I think the difference according to this answer: <https://stackoverflow.com/a/36322044/4637693> is:
>
> The difference between declaring an array as
>
>
>
> ```
> int array[n];
>
> ```
>
> and
>
>
>
> ```
> int* array = malloc(n * sizeof(int));
>
> ```
>
> In the first version, you are declaring an object with automatic storage duration. This means that the array lives only as long as the function that calls it exists. In the second version, you are getting memory with dynamic storage duration, which means that it will exist until it is explicitly deallocated with free.
>
>
>
I will take more time in the next weeks to see if this works for a matrix too.
**EDIT**
Or you can use a dynamic structure from boost like list:
```
np::ndarray test(){
boost::python::list my_list;
for (int i=0; i < 5; ++i){
my_list.append(i + 1);
}
np::ndarray array = np::from_object(my_list);
return array;
}
```
This work also for a Matrix for example:
```
np::ndarray test(){
//This will use a list of tuples
boost::python::list my_list;
for (int i=0; i < 5; ++i){
my_list.append(boost::python::make_tuple(i + 1, i, i-1));
}
//Just convert the list to a NumPy array.
np::ndarray array = np::from_object(my_list);
return array;
}
```
I assume (for the moment) that by using the boost functions you will be able to avoid the memory conflicts.
|
Creating a new reference to the array before returning it solved the problem. Good news is that `np::ndarray` has a [`copy()`](https://github.com/boostorg/python/blob/4f6d547c0af4c400dc5d059ccd847426ff21852f/src/numpy/ndarray.cpp#L177) method that achieves exactly the same thing. Thus, you should add
```
np::ndarray new_array = array.copy();
```
before the return statement
|
70,042,756
|
I'm running a python code to calculate the distance between certain coordinates. The original data looks like:
```
a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude
```
and I'm looking forward to get the distance between every pair, the result should look like:
```
[1, 2, 100(km)]
[1, 3, 200(km)].
[2, 1, 100(km)]
[2, 3, 300(km)]
[3, 1, 200(km)]
[3, 2, 300(km)]
```
*The result should contan pair(m,n) and pair(n,m)*
the actual data has 39000 columns, thus I have a great demand for code efficiency. Currently I'm using a double-loop which is really stupid:
```
line = 0
result = np.zeros((6,3))
for i in a:
for j in a:
dis = getDistance(i[1],i[2],j[1],j[2]) # this is the function i made to calculate distance between two coordinates
result[line] = [i[0],j[0],dis]
line += 1
```
Can anyone help me to improve the code?
|
2021/11/20
|
[
"https://Stackoverflow.com/questions/70042756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17454717/"
] |
1- run :
```
php artisan make:middleware AccountType
```
2- Add it to the *routeMiddleware* array in your kernel file by opening `app/Http/Kernel.php`:
```
'accType' => \App\Http\Middleware\AccountType::class,
```
3- Edit `AccountType` file:
```
public function handle($request, Closure $next)
{
// If user account type is profile allow to next or else block the request
if (Auth::user() && Auth::user()->account_type == 'profile') {
return $next($request);
}else{
abort(403, 'Unauthorized action.');
}
}
```
4- Apply the middleware to your route:
```
Route::get('/profile', ['middleware' => 'accType', function () {
//
}]);
```
|
If your want to have a multi authenticate system, whit different logics, its better to implement multiple guard and define them in your desire models :
```
[...]
'guards' => [
[...]
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'writer' => [
'driver' => 'session',
'provider' => 'writers',
],
],
[...]
[...]
'providers' => [
[...]
'admins' => [
'driver' => 'eloquent',
'model' => App\BusinessDashboard::class,
],
'writers' => [
'driver' => 'eloquent',
'model' => App\ProfileDashboard::class,
],
],
[...]
```
you can find a complete guide article in bellow code :
[enter link description here](https://pusher.com/tutorials/multiple-authentication-guards-laravel/)
|
70,042,756
|
I'm running a python code to calculate the distance between certain coordinates. The original data looks like:
```
a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude
```
and I'm looking forward to get the distance between every pair, the result should look like:
```
[1, 2, 100(km)]
[1, 3, 200(km)].
[2, 1, 100(km)]
[2, 3, 300(km)]
[3, 1, 200(km)]
[3, 2, 300(km)]
```
*The result should contan pair(m,n) and pair(n,m)*
the actual data has 39000 columns, thus I have a great demand for code efficiency. Currently I'm using a double-loop which is really stupid:
```
line = 0
result = np.zeros((6,3))
for i in a:
for j in a:
dis = getDistance(i[1],i[2],j[1],j[2]) # this is the function i made to calculate distance between two coordinates
result[line] = [i[0],j[0],dis]
line += 1
```
Can anyone help me to improve the code?
|
2021/11/20
|
[
"https://Stackoverflow.com/questions/70042756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17454717/"
] |
In addition to the solution given by @nagidi, you can update the `middleware` handle condition to check either `account_type` is profile or business.
```
public function handle($request, Closure $next, $type)
{
if (Auth::user() && Auth::user()->account_type == $type) {
return $next($request);
}
abort(403, 'Unauthorized action.');
}
```
```
Route::get('/business-profile', ['middleware' => 'accType:business', function () {
//
}]);
Route::get('/profile', ['middleware' => 'accType:profile', function () {
//
}]);
```
|
1- run :
```
php artisan make:middleware AccountType
```
2- Add it to the *routeMiddleware* array in your kernel file by opening `app/Http/Kernel.php`:
```
'accType' => \App\Http\Middleware\AccountType::class,
```
3- Edit `AccountType` file:
```
public function handle($request, Closure $next)
{
// If user account type is profile allow to next or else block the request
if (Auth::user() && Auth::user()->account_type == 'profile') {
return $next($request);
}else{
abort(403, 'Unauthorized action.');
}
}
```
4- Apply the middleware to your route:
```
Route::get('/profile', ['middleware' => 'accType', function () {
//
}]);
```
|
70,042,756
|
I'm running a python code to calculate the distance between certain coordinates. The original data looks like:
```
a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude
```
and I'm looking forward to get the distance between every pair, the result should look like:
```
[1, 2, 100(km)]
[1, 3, 200(km)].
[2, 1, 100(km)]
[2, 3, 300(km)]
[3, 1, 200(km)]
[3, 2, 300(km)]
```
*The result should contan pair(m,n) and pair(n,m)*
the actual data has 39000 columns, thus I have a great demand for code efficiency. Currently I'm using a double-loop which is really stupid:
```
line = 0
result = np.zeros((6,3))
for i in a:
for j in a:
dis = getDistance(i[1],i[2],j[1],j[2]) # this is the function i made to calculate distance between two coordinates
result[line] = [i[0],j[0],dis]
line += 1
```
Can anyone help me to improve the code?
|
2021/11/20
|
[
"https://Stackoverflow.com/questions/70042756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17454717/"
] |
1- run :
```
php artisan make:middleware AccountType
```
2- Add it to the *routeMiddleware* array in your kernel file by opening `app/Http/Kernel.php`:
```
'accType' => \App\Http\Middleware\AccountType::class,
```
3- Edit `AccountType` file:
```
public function handle($request, Closure $next)
{
// If user account type is profile allow to next or else block the request
if (Auth::user() && Auth::user()->account_type == 'profile') {
return $next($request);
}else{
abort(403, 'Unauthorized action.');
}
}
```
4- Apply the middleware to your route:
```
Route::get('/profile', ['middleware' => 'accType', function () {
//
}]);
```
|
**How to create your own middleware for multi User Role in Laravel**
Let assumed your roles array could be `["admin","student","staff"];`
Create a middleware role checking for the role "admin". Repeat steps 1-4 for each role.
I found this much easier for myself, others may have their own approaches
**Step 1**
Run artisan command
```
php artisan make:middleware isAdmin
```
**Step 2**
```
App/Http/Middlewere/isAdmin.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class isAdmin
{
public function handle(Request $request, Closure $next,$is_admin)
{
$role=Auth::user()->role;
//Get the role list
$role_array=explode(",",$role);
if (in_array($is_admin, $role_array)) {
return $next($request);
}
//if not allowed redirect to home page with message
$message="Unauthorized action.";
//return response($message, 401);//if you have friendly 401 page
//otherwise I think is a best to return to home page
$request->session()->flash('error', $message);
return redirect()->route('home');
}
}
```
**Step 3**
```
App/Http/Kernel.php
protected $routeMiddleware = [
'isAdmin' => \App\Http\Middleware\isAdmin::class,
];
```
**Step 4**
Now in your route controller add this line to only allow the user that has an admin role
```
public function __construct()
{
//ONLY ADMIN CAN ACCESS THIS ROUTE
$this->middleware('isAdmin:admin');
//$this->middleware('isStudent:student');
//$this->middleware('isStaff:staff');
}
```
|
70,042,756
|
I'm running a python code to calculate the distance between certain coordinates. The original data looks like:
```
a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude
```
and I'm looking forward to get the distance between every pair, the result should look like:
```
[1, 2, 100(km)]
[1, 3, 200(km)].
[2, 1, 100(km)]
[2, 3, 300(km)]
[3, 1, 200(km)]
[3, 2, 300(km)]
```
*The result should contan pair(m,n) and pair(n,m)*
the actual data has 39000 columns, thus I have a great demand for code efficiency. Currently I'm using a double-loop which is really stupid:
```
line = 0
result = np.zeros((6,3))
for i in a:
for j in a:
dis = getDistance(i[1],i[2],j[1],j[2]) # this is the function i made to calculate distance between two coordinates
result[line] = [i[0],j[0],dis]
line += 1
```
Can anyone help me to improve the code?
|
2021/11/20
|
[
"https://Stackoverflow.com/questions/70042756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17454717/"
] |
In addition to the solution given by @nagidi, you can update the `middleware` handle condition to check either `account_type` is profile or business.
```
public function handle($request, Closure $next, $type)
{
if (Auth::user() && Auth::user()->account_type == $type) {
return $next($request);
}
abort(403, 'Unauthorized action.');
}
```
```
Route::get('/business-profile', ['middleware' => 'accType:business', function () {
//
}]);
Route::get('/profile', ['middleware' => 'accType:profile', function () {
//
}]);
```
|
If your want to have a multi authenticate system, whit different logics, its better to implement multiple guard and define them in your desire models :
```
[...]
'guards' => [
[...]
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'writer' => [
'driver' => 'session',
'provider' => 'writers',
],
],
[...]
[...]
'providers' => [
[...]
'admins' => [
'driver' => 'eloquent',
'model' => App\BusinessDashboard::class,
],
'writers' => [
'driver' => 'eloquent',
'model' => App\ProfileDashboard::class,
],
],
[...]
```
you can find a complete guide article in bellow code :
[enter link description here](https://pusher.com/tutorials/multiple-authentication-guards-laravel/)
|
70,042,756
|
I'm running a python code to calculate the distance between certain coordinates. The original data looks like:
```
a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude
```
and I'm looking forward to get the distance between every pair, the result should look like:
```
[1, 2, 100(km)]
[1, 3, 200(km)].
[2, 1, 100(km)]
[2, 3, 300(km)]
[3, 1, 200(km)]
[3, 2, 300(km)]
```
*The result should contan pair(m,n) and pair(n,m)*
the actual data has 39000 columns, thus I have a great demand for code efficiency. Currently I'm using a double-loop which is really stupid:
```
line = 0
result = np.zeros((6,3))
for i in a:
for j in a:
dis = getDistance(i[1],i[2],j[1],j[2]) # this is the function i made to calculate distance between two coordinates
result[line] = [i[0],j[0],dis]
line += 1
```
Can anyone help me to improve the code?
|
2021/11/20
|
[
"https://Stackoverflow.com/questions/70042756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17454717/"
] |
In addition to the solution given by @nagidi, you can update the `middleware` handle condition to check either `account_type` is profile or business.
```
public function handle($request, Closure $next, $type)
{
if (Auth::user() && Auth::user()->account_type == $type) {
return $next($request);
}
abort(403, 'Unauthorized action.');
}
```
```
Route::get('/business-profile', ['middleware' => 'accType:business', function () {
//
}]);
Route::get('/profile', ['middleware' => 'accType:profile', function () {
//
}]);
```
|
**How to create your own middleware for multi User Role in Laravel**
Let assumed your roles array could be `["admin","student","staff"];`
Create a middleware role checking for the role "admin". Repeat steps 1-4 for each role.
I found this much easier for myself, others may have their own approaches
**Step 1**
Run artisan command
```
php artisan make:middleware isAdmin
```
**Step 2**
```
App/Http/Middlewere/isAdmin.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class isAdmin
{
public function handle(Request $request, Closure $next,$is_admin)
{
$role=Auth::user()->role;
//Get the role list
$role_array=explode(",",$role);
if (in_array($is_admin, $role_array)) {
return $next($request);
}
//if not allowed redirect to home page with message
$message="Unauthorized action.";
//return response($message, 401);//if you have friendly 401 page
//otherwise I think is a best to return to home page
$request->session()->flash('error', $message);
return redirect()->route('home');
}
}
```
**Step 3**
```
App/Http/Kernel.php
protected $routeMiddleware = [
'isAdmin' => \App\Http\Middleware\isAdmin::class,
];
```
**Step 4**
Now in your route controller add this line to only allow the user that has an admin role
```
public function __construct()
{
//ONLY ADMIN CAN ACCESS THIS ROUTE
$this->middleware('isAdmin:admin');
//$this->middleware('isStudent:student');
//$this->middleware('isStaff:staff');
}
```
|
47,845,358
|
Given a string, find the rank of the string amongst its permutations sorted lexicographically.
Note that the characters might be repeated. If the characters are repeated, we need to look at the rank in unique permutations.
Look at the example for more details.
Input : 'aba'
Output : 2
The order permutations with letters 'a', 'a', and 'b' :
aab
aba
baa
I was able to solve for unique characters but not with repeated characters. Can someone help me code this in python?
Thanks
|
2017/12/16
|
[
"https://Stackoverflow.com/questions/47845358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7549959/"
] |
```
long long int pow_mod(long long int a,long long int b)
{
long long MOD=1000003;
if(a == 1)
return 1;
long long int x =1 ,y = a;
while(b>0)
{
if(b%2)
{
x = (x*y)%MOD;
}
y = (y*y)%MOD;
b = b>>1;
}
return x;
}
int Solution::findRank(string A) {
long long ans=0;
long long mod=1000003;
long long arr[300];
long long n=A.length();
long long fact[n];
fact[0]=1;
for(int i=1;i<n;i++)
{
fact[i]=((fact[i-1]%mod)*(i%mod))%mod;
}
for(long long i=0;i<300;i++)
arr[i]=0;
for(long long i=0;i<n;i++)
{
arr[A[i]]++;
}
// for(long long i=0;i<26;i++)
// cout<<arr[i]<<" ";
for(long long i=0;i<n;i++)
{
long long cnt=0;
long long di=1;
for(long long j=(A[i]-1);j>=0;j--)
{
cnt+=arr[j];
}
// cout<<cnt<<" ";
for(int j=0;j<300;j++)
{
di=(di%mod * fact[arr[j]]%mod)%mod;
}
long long a=pow_mod(di,(mod - 2)) % mod;
// cout<<di<<" ";
ans=(ans+((cnt*fact[n-i-1])%mod * a )%mod)%mod;
// cout<<ans<<" ";
arr[A[i]]--;
}
++ans;
return ans%mod;
}
```
|
You could generate the permutations, sort them, and find your original string:
```
from itertools import permutations
def permutation_index(s):
return sorted(''.join(x) for x in permutations(s)).index(s)
```
|
20,048,001
|
```
f = open('file.txt')
print f.read()
```
That was pretty straight forward wasn't it? That works because python knows how to read and write`.txt` files. How do these formats even work? I wish to build a python program to read atleast the major formats of documents (including pdfs), spreadsheets and presentations.
Now please don't tell me, "Go ahead and use PDFMiner!"; "Use IronPython for reading `.doc`!".
I want to understand myself, how the format magic happens. I want to know how formats work, so that I Can build my own "any format reader". I dont want solutions to read various formats. I want to know the theory behind it.
Any links to such resources, or help regarding reading multiple formats is greatly appreciated.
-Thank you
|
2013/11/18
|
[
"https://Stackoverflow.com/questions/20048001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672265/"
] |
No, you have completely misunderstood what your code is doing. Python doesn't "know" how to read .txt files, because there is no "format" here. It is just opening a plain file and printing out the bytes it finds there.
Something like PDF or DOC is completely different. The bytes by themselves do not mean anything: they are the representation of a file format that is understood by the relevant application. In order to "read" them in a way that understands what they contain, you need to build a parser that does the same thing as the original application. That's what those libraries you refer to do (although IronPython is an implementation of Python in .NET, and has nothing to do with reading doc files).
|
You will need to look up the specification for each format you want to deal with, [this](http://www.idpf.org/epub/301/spec/epub-overview.html) is the specification for ePub for example, it's a bit broad but you get the idea, then you need figure out yourself how you want to deal with it.
|
20,048,001
|
```
f = open('file.txt')
print f.read()
```
That was pretty straight forward wasn't it? That works because python knows how to read and write`.txt` files. How do these formats even work? I wish to build a python program to read atleast the major formats of documents (including pdfs), spreadsheets and presentations.
Now please don't tell me, "Go ahead and use PDFMiner!"; "Use IronPython for reading `.doc`!".
I want to understand myself, how the format magic happens. I want to know how formats work, so that I Can build my own "any format reader". I dont want solutions to read various formats. I want to know the theory behind it.
Any links to such resources, or help regarding reading multiple formats is greatly appreciated.
-Thank you
|
2013/11/18
|
[
"https://Stackoverflow.com/questions/20048001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672265/"
] |
No, you have completely misunderstood what your code is doing. Python doesn't "know" how to read .txt files, because there is no "format" here. It is just opening a plain file and printing out the bytes it finds there.
Something like PDF or DOC is completely different. The bytes by themselves do not mean anything: they are the representation of a file format that is understood by the relevant application. In order to "read" them in a way that understands what they contain, you need to build a parser that does the same thing as the original application. That's what those libraries you refer to do (although IronPython is an implementation of Python in .NET, and has nothing to do with reading doc files).
|
There is absolutely no magic involved in reading a `.txt` file—it's just ASCII bytes, and opening and reading a file does just that: reads bytes. It's the simplest possible file format you could ever find (because there is no format). PDF is to plain Plain Text what Coca Cola is to distilled water.
PDFs however have a very complex format that they use; reading a PDF file would just make Python treat it as if it were as `.txt` file.
So I'm sorry to give you that old response you don't like hearing: please go ahead and use PDFMiner, or read its source code to understand how they're reading and parsing PDF files :) (or read the [PDF spec](http://www.adobe.com/devnet/pdf/pdf_reference.html) as devnull pointed out)
|
13,536,350
|
On using this regular expression in python :
`pathstring = '<span class="titletext">(.*)</span>'`
`pathFinderTitle = re.compile(pathstring)`
My output is:
```
Govt has nothing to do with former CAG official RP Singh:
Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper">
<table class="al-attribution single-line-height" cellspacing="0" cellpadding="0">
<tbody><tr><td class="al-attribution-cell source-cell">
<span class='al-attribution-source'>Times of India</span></td>
<td class="al-attribution-cell timestamp-cell">
<span class='dash-separator'> - </span>
<span class='al-attribution-timestamp'>‎46 minutes ago‎
```
The text find should have stopped at first "< /span>".
Please suggest whats wrong here.
|
2012/11/23
|
[
"https://Stackoverflow.com/questions/13536350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/733583/"
] |
`.*` is a *greedy* match of any characters; it is going to consume as many characters as possible. Instead, use the non-greedy version `.*?`, as in
```
pathstring = '<span class="titletext">(.*?)</span>'
```
|
`.*` will match `</span>` so it keeps on going until the last one.
The best answer is: Don't parse html with regular expressions. Use the [lxml](http://lxml.de/installation.html) library (or something similar).
```
from lxml import html
html_string = '<blah>'
tree = html.fromstring(html_string)
titles = tree.xpath("//span[@class='titletext']")
for title in titles:
print title.text
```
Using a proper xml/html parser will save you massive amounts of time and trouble. If you roll your own parser, you'll have to cater for malformed tags, comments, and myriad other things. Don't reinvent the wheel.
|
13,536,350
|
On using this regular expression in python :
`pathstring = '<span class="titletext">(.*)</span>'`
`pathFinderTitle = re.compile(pathstring)`
My output is:
```
Govt has nothing to do with former CAG official RP Singh:
Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper">
<table class="al-attribution single-line-height" cellspacing="0" cellpadding="0">
<tbody><tr><td class="al-attribution-cell source-cell">
<span class='al-attribution-source'>Times of India</span></td>
<td class="al-attribution-cell timestamp-cell">
<span class='dash-separator'> - </span>
<span class='al-attribution-timestamp'>‎46 minutes ago‎
```
The text find should have stopped at first "< /span>".
Please suggest whats wrong here.
|
2012/11/23
|
[
"https://Stackoverflow.com/questions/13536350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/733583/"
] |
`.*` is a *greedy* match of any characters; it is going to consume as many characters as possible. Instead, use the non-greedy version `.*?`, as in
```
pathstring = '<span class="titletext">(.*?)</span>'
```
|
You could also just as easily use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) which is great for doing this kind of thing.
```
#using BeautifulSoup4, install by "pip install BeautifulSoup4"
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
result = soup.find('span', 'titletext')
```
And then `result` would hold the `<span>` with class `titletext` as you're looking for.
|
13,536,350
|
On using this regular expression in python :
`pathstring = '<span class="titletext">(.*)</span>'`
`pathFinderTitle = re.compile(pathstring)`
My output is:
```
Govt has nothing to do with former CAG official RP Singh:
Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper">
<table class="al-attribution single-line-height" cellspacing="0" cellpadding="0">
<tbody><tr><td class="al-attribution-cell source-cell">
<span class='al-attribution-source'>Times of India</span></td>
<td class="al-attribution-cell timestamp-cell">
<span class='dash-separator'> - </span>
<span class='al-attribution-timestamp'>‎46 minutes ago‎
```
The text find should have stopped at first "< /span>".
Please suggest whats wrong here.
|
2012/11/23
|
[
"https://Stackoverflow.com/questions/13536350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/733583/"
] |
I would suggest using [pyquery](http://pypi.python.org/pypi/pyquery) instead of going mad on regular expressions... It's based on lxml and makes HTML parsing easy as using jQuery.
Something like this is everything you need:
```
doc = PyQuery(html)
doc('span.titletext').text()
```
You could also use [beautifulsoup](http://pypi.python.org/pypi/BeautifulSoup/3.2.1), but the result is always the same: don't use regular expressions for parsing HTML, there are tools out there for making your life easier.
|
`.*` will match `</span>` so it keeps on going until the last one.
The best answer is: Don't parse html with regular expressions. Use the [lxml](http://lxml.de/installation.html) library (or something similar).
```
from lxml import html
html_string = '<blah>'
tree = html.fromstring(html_string)
titles = tree.xpath("//span[@class='titletext']")
for title in titles:
print title.text
```
Using a proper xml/html parser will save you massive amounts of time and trouble. If you roll your own parser, you'll have to cater for malformed tags, comments, and myriad other things. Don't reinvent the wheel.
|
13,536,350
|
On using this regular expression in python :
`pathstring = '<span class="titletext">(.*)</span>'`
`pathFinderTitle = re.compile(pathstring)`
My output is:
```
Govt has nothing to do with former CAG official RP Singh:
Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper">
<table class="al-attribution single-line-height" cellspacing="0" cellpadding="0">
<tbody><tr><td class="al-attribution-cell source-cell">
<span class='al-attribution-source'>Times of India</span></td>
<td class="al-attribution-cell timestamp-cell">
<span class='dash-separator'> - </span>
<span class='al-attribution-timestamp'>‎46 minutes ago‎
```
The text find should have stopped at first "< /span>".
Please suggest whats wrong here.
|
2012/11/23
|
[
"https://Stackoverflow.com/questions/13536350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/733583/"
] |
I would suggest using [pyquery](http://pypi.python.org/pypi/pyquery) instead of going mad on regular expressions... It's based on lxml and makes HTML parsing easy as using jQuery.
Something like this is everything you need:
```
doc = PyQuery(html)
doc('span.titletext').text()
```
You could also use [beautifulsoup](http://pypi.python.org/pypi/BeautifulSoup/3.2.1), but the result is always the same: don't use regular expressions for parsing HTML, there are tools out there for making your life easier.
|
You could also just as easily use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) which is great for doing this kind of thing.
```
#using BeautifulSoup4, install by "pip install BeautifulSoup4"
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
result = soup.find('span', 'titletext')
```
And then `result` would hold the `<span>` with class `titletext` as you're looking for.
|
13,536,350
|
On using this regular expression in python :
`pathstring = '<span class="titletext">(.*)</span>'`
`pathFinderTitle = re.compile(pathstring)`
My output is:
```
Govt has nothing to do with former CAG official RP Singh:
Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper">
<table class="al-attribution single-line-height" cellspacing="0" cellpadding="0">
<tbody><tr><td class="al-attribution-cell source-cell">
<span class='al-attribution-source'>Times of India</span></td>
<td class="al-attribution-cell timestamp-cell">
<span class='dash-separator'> - </span>
<span class='al-attribution-timestamp'>‎46 minutes ago‎
```
The text find should have stopped at first "< /span>".
Please suggest whats wrong here.
|
2012/11/23
|
[
"https://Stackoverflow.com/questions/13536350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/733583/"
] |
`.*` will match `</span>` so it keeps on going until the last one.
The best answer is: Don't parse html with regular expressions. Use the [lxml](http://lxml.de/installation.html) library (or something similar).
```
from lxml import html
html_string = '<blah>'
tree = html.fromstring(html_string)
titles = tree.xpath("//span[@class='titletext']")
for title in titles:
print title.text
```
Using a proper xml/html parser will save you massive amounts of time and trouble. If you roll your own parser, you'll have to cater for malformed tags, comments, and myriad other things. Don't reinvent the wheel.
|
You could also just as easily use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) which is great for doing this kind of thing.
```
#using BeautifulSoup4, install by "pip install BeautifulSoup4"
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
result = soup.find('span', 'titletext')
```
And then `result` would hold the `<span>` with class `titletext` as you're looking for.
|
32,878,530
|
I have a Python/Django project that I manage using PyCharm. Everything was working perfectly under Mac OSX Yosemite. This morning I upgraded to the final release version of El Capitan, now I cannot run the project. The error I get is:
>
> Error loading MySQLdb module: No module named MySQLdb
>
>
>
I've tried all the suggestions from past questions, but none has resolved it. The most common suggestion seems to be:
>
> sudo pip install MySQL-python
>
>
>
When I do that, I get:
>
> Requirement already satisfied (use --upgrade to upgrade): MySQL-python in /Library/Python/2.7/site-packages
>
>
>
None of the other suggestions help either. I can try reinstalling MySQL, but I don't think it's the MySQL that's broken. This might have something to do with permissions. Can anyone please help get me going again?
|
2015/10/01
|
[
"https://Stackoverflow.com/questions/32878530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1402166/"
] |
Happened to me as well. I removed the package, installed mysql using [Homebrew](http://brew.sh/) and then reinstall the package.
```
pip uninstall MySQL-python
brew install mysql
pip install MySQL-python
```
If you run into any issues with brew, be sure to check their [troubleshooting page on El Capitan](https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/El_Capitan_and_Homebrew.md).
|
View this post : [MySQL Improperly Configured Reason: unsafe use of relative path](https://stackoverflow.com/questions/31343299/mysql-improperly-configured-reason-unsafe-use-of-relative-path)
And if you have updated Xcode, open 1 time Xcode for agreement the licence.
|
62,804,653
|
I see that all of the examples per the documentation use some form of a simple web application (For example, Flask in Python). Is it possible to use cloud run as a non web application? For example, deploy cloud run to use a python script and then use GCP Scheduler to invoke cloud run every hour to run that script? Basically my thinking for this is to avoid having to deploy and pay for Compute Engine, and only pay for when the cloud run container is invoked via the scheduler.
|
2020/07/08
|
[
"https://Stackoverflow.com/questions/62804653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11287314/"
] |
It's mandatory to answer to HTTP request. It's the contract of Cloud Run
* Stateless (no volume attached to the container)
* Answer to HTTP request
However, if you already have a python script, it's easy to wrap it in a flask webserver. Let's say, you have something like this (I assume that the file name is `main.py` -> *important for the Dockerfile at the end*)
```
import ....
var = todo(...)
connect = connect(...)
connect(var)
```
1. Firstly, wrap it in a function like this
```
import ....
def my_function(request):
var = todo(...)
connect = connect(...)
connect(var)
return 'ok',200
```
2. Secondly, add a flask server
```
from flask import Flask, request
import os
import ....
app = Flask(__name__)
@app.route('/')
def my_function(request):
var = todo(...)
connect = connect(...)
connect(var)
return 'ok',200
if __name__ == "__main__":
app.run(host='0.0.0.0',port=int(os.environ.get('PORT',8080)))
```
3. Add flask in your `requirements.txt`
4. Build a standard container, here an example of Dockerfile
```
FROM python:3-alpine
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV PORT 8080
CMD [ "python", "main.py" ]
```
5. Build (with Cloud Build for example) and deploy the service on Cloud Run
Now you have an URL, that you can call with Cloud Scheduler.
*Be careful, the max request duration is, for now, limited to 15 minutes (soon 4x more) and limited to 2vCPU and 2Gb of memory (again, soon more).*
|
It depends what is being installed in the container image, as there is no requirement that one would have to install a web-server. For [example](https://github.com/syslogic/cloudbuild-android), with such an image I can build Android applications, triggered whenever a repository changes (file excludes recommend) ...and likely could even run a head-less Android emulator for Gradle test tasks and publish test results to Pub/Sub (at least while the test-suite wouldn't run for too long). I mean, one has to understand the possibilities of Cloud Build to understand what Cloud Run can do.
|
62,804,653
|
I see that all of the examples per the documentation use some form of a simple web application (For example, Flask in Python). Is it possible to use cloud run as a non web application? For example, deploy cloud run to use a python script and then use GCP Scheduler to invoke cloud run every hour to run that script? Basically my thinking for this is to avoid having to deploy and pay for Compute Engine, and only pay for when the cloud run container is invoked via the scheduler.
|
2020/07/08
|
[
"https://Stackoverflow.com/questions/62804653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11287314/"
] |
It's mandatory to answer to HTTP request. It's the contract of Cloud Run
* Stateless (no volume attached to the container)
* Answer to HTTP request
However, if you already have a python script, it's easy to wrap it in a flask webserver. Let's say, you have something like this (I assume that the file name is `main.py` -> *important for the Dockerfile at the end*)
```
import ....
var = todo(...)
connect = connect(...)
connect(var)
```
1. Firstly, wrap it in a function like this
```
import ....
def my_function(request):
var = todo(...)
connect = connect(...)
connect(var)
return 'ok',200
```
2. Secondly, add a flask server
```
from flask import Flask, request
import os
import ....
app = Flask(__name__)
@app.route('/')
def my_function(request):
var = todo(...)
connect = connect(...)
connect(var)
return 'ok',200
if __name__ == "__main__":
app.run(host='0.0.0.0',port=int(os.environ.get('PORT',8080)))
```
3. Add flask in your `requirements.txt`
4. Build a standard container, here an example of Dockerfile
```
FROM python:3-alpine
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV PORT 8080
CMD [ "python", "main.py" ]
```
5. Build (with Cloud Build for example) and deploy the service on Cloud Run
Now you have an URL, that you can call with Cloud Scheduler.
*Be careful, the max request duration is, for now, limited to 15 minutes (soon 4x more) and limited to 2vCPU and 2Gb of memory (again, soon more).*
|
I've struggled with deployment my function which no need to handle any request in Cloud Run by putting functions in Flask app and found out that Cloud Run provides us 2 kinds of jobs, services and jobs.
[**Illustration from codelabs**](https://i.stack.imgur.com/LehWZ.png)
From cloud run jobs [documentation](https://cloud.google.com/run/docs/create-jobs),
>
> This page describes how to create and update Cloud Run jobs from an existing container image. Unlike services, which listen for requests, a job does not serve requests but only runs its tasks and exits when finished.
> After you create or update a job, you can execute the job as a one-off, on a schedule or as part of a workflow. You can manage individual job executions and view the execution logs.
>
>
>
You may see that there are two tabs in Cloud Run console. I am not sure when Cloud Run jobs started.
[*See cloud run console*](https://i.stack.imgur.com/Jg99t.png)
|
26,268,268
|
I have the following string in a seperate .txt file:
```
L#$KJ#()JSEFS(DF)(SD*F
#KJ$H#K$JH@#K$JHD)
SF SDFLKJ#{P@$OJ{SDPFODS{PFO{
#K$HK#JHSFHD(*SHF)SF{HP
#L$H@”#$H”@#L$KH#”@L$K
#~L$KJ#:$SD)FJ)S(DJF)(S
#$KJH#$
SDLKFJD(FJ)SDJFSDLFKS
~L#$KJ:@LK$#J$
LSJDF(S*JDF(*SJDF(*J(DSF*J
```
I have to take every element by column position and output how many times in a column an element occurs. For example, Position: 0 or Column 1 ( S: 20.0% #: 50.0% L: 20.0% ~: 10.0% )
I have written this script in python using NumPy to create an array of arrays by line but am getting "TypeError: list indices must be integers, not tuple"
Here is the script when I try to print the first column:
```
import numpy as np
from sys import argv
script, filename = argv
target = open(filename, 'r')
y = []
for x in range(0, 10):
y.append(np.array(list(target.readline())))
print y[:,1]
```
What am I doing wrong?
|
2014/10/08
|
[
"https://Stackoverflow.com/questions/26268268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3643019/"
] |
From <https://docs.recurly.com/api/recurlyjs/jsonp_endpoints>
```
$.ajax({
dataType: 'jsonp',
url: 'https://{subdomain}.recurly.com/jsonp/{subdomain}/plans/{plan_code}',
data: {
currency: 'USD',
},
success: function (data) {
// do stuff
},
}
```
|
You should *not* use the V2 API from the browser. Doing so risks exposing your private API key. If someone has your API key they can make calls charging customers, modifying subscriptions, causing all sorts of problems.
Look at the JSONP endpoints that Byaxy linked to.
|
14,389,513
|
I need to parse html table of the following structure:
```
<table class="table1" width="620" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr width="620">
<th width="620">Smth1</th>
...
</tr>
<tr bgcolor="ffffff" width="620">
<td width="620">Smth2</td>
...
</tr>
<tr bgcolor="E4E4E4" width="620">
<td width="620">Smth3</td>
...
</tr>
<tr bgcolor="ffffff" width="620">
<td width="620">Smth4</td>
...
</tr>
</tbody>
</table>
```
Python code:
```
r = requests.post(url,data)
html = lxml.html.document_fromstring(r.text)
rows = html.xpath(xpath1)[0].findall("tr")
#Getting Xpath with FireBug
data = list()
for row in rows:
data.append([c.text for c in row.getchildren()])
```
But I get this on the third line:
```
IndexError: list index out of range
```
The task is to form python dict from this. Number of rows could be different.
**UPD.**
Changed the way I'm getting html code to avoid possible problems with requests lib. Now it's a simple url:
```
html = lxml.html.parse(test_url)
```
This proves everyting is Ok with html:
```
lxml.html.open_in_browser(html)
```
But still the same problem:
```
rows = html.xpath(xpath1)[0].findall('tr')
data = list()
for row in rows:
data.append([c.text for c in row.getchildren()])
```
Here is the xpath1:
```
'/html/body/table/tbody/tr[5]/td/table/tbody/tr/td[2]/table/tbody/tr/td/center/table'
```
**UPD2.** It was found experimentally, that xpath crashes on:
```
xpath1 = '/html/body/table/tbody'
print html.xpath(xpath1)
#print returns []
```
If xpath1 is shorter, then it seeem to work well and returns `[<Element table at 0x2cbadb0>]` for `xpath1 = '/html/body/table'`
|
2013/01/17
|
[
"https://Stackoverflow.com/questions/14389513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1988698/"
] |
You didn't include the XPath, so I'm not sure what you're trying to do, but if I understood correctly, this should work
```
xpath1 = "tbody/tr"
r = requests.post(url,data)
html = lxml.html.fromstring(r.text)
rows = html.xpath(xpath1)
data = list()
for row in rows:
data.append([c.text for c in row.getchildren()])
```
This is making a list of one item lists though, like this:
```
[['Smth1'], ['Smth2'], ['Smth3'], ['Smth4']]
```
To have a simple list of the values, you can use this code
```
xpath1 = "tbody/tr/*/text()"
r = requests.post(url,data)
html = lxml.html.fromstring(r.text)
data = html.xpath(xpath1)
```
This is all assuming that r.text is exactly what you posted up there.
|
Your `.xpath(xpath1)` XPath expression failed to find any elements. Check that expression for errors.
|
39,448,121
|
I'm trying to upload a file using ftp in python, but I get an error saying:
```
ftplib.error_perm: 550 Filename invalid
```
when I run the following code:
```
ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '')
ftp.cwd("/incoming")
file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb')
ftp.storbinary('STOR c:\Automation\FTP_Files\MaxErrors1.json', file)
ftp.close()
```
I've checked that the file exists in the location I specified, does anyone know what might be causing the issue?
|
2016/09/12
|
[
"https://Stackoverflow.com/questions/39448121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6434729/"
] |
The problem is that on the server, the path `c:\Automation\FTP_Files\MaxErrors1.json` is not valid. Instead try just doing:
```
ftp.storbinary('STOR MaxErrors1.json', file)
```
|
The argument to STOR needs to be the destination file name, not the source path. You should just do `ftp.storbinary('STOR MaxErrors1.json', file)`.
|
39,448,121
|
I'm trying to upload a file using ftp in python, but I get an error saying:
```
ftplib.error_perm: 550 Filename invalid
```
when I run the following code:
```
ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '')
ftp.cwd("/incoming")
file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb')
ftp.storbinary('STOR c:\Automation\FTP_Files\MaxErrors1.json', file)
ftp.close()
```
I've checked that the file exists in the location I specified, does anyone know what might be causing the issue?
|
2016/09/12
|
[
"https://Stackoverflow.com/questions/39448121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6434729/"
] |
The problem is that on the server, the path `c:\Automation\FTP_Files\MaxErrors1.json` is not valid. Instead try just doing:
```
ftp.storbinary('STOR MaxErrors1.json', file)
```
|
you should upload file without absolute path in ftp server
for example :
```
import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('kitten.jpg','rb') # file to send
session.storbinary('STOR kitten.jpg', file) # send the file
file.close() # close file and FTP
session.quit()
```
|
20,457,271
|
So im new at python and i would like some help in making code where:
When an input is typed if the input has a minimum of three words that match any one thing on a list it would replace the input with the text in the list that matches the criteria
Example:
Jan
-Scans List-
-Finds Janice-
-Replaces and gives output as Janice Instead of Jan-
Janice
So far
```
getname = []
for word in args
room.usernames.get(args,word)
```
Room.usernames is the list and args input
Error List item has no attribute .get
there is a module used and its ch.py located at <http://pastebin.com/5BLZ0UA0>
|
2013/12/08
|
[
"https://Stackoverflow.com/questions/20457271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3065432/"
] |
You will need to:
* make a replacement words dictionary
* get some input
* do sanity checking to make sure it fits your parameters
* split it into a `list`
* loop through your new `list` and replace each word with its replacement in your `dict`, if it is in there
I won't write all of this for you. But here's a tip for how to do that last part: use the `get` method of dicts - it allows you to provide a "fallback" in case the word is not found in the `dict`. So just fall back to the word itself.
```
replacement_words = {'jan':'janice','foo':'bar'}
my_list = ['jan','is','cool']
[replacement_words.get(word,word) for word in my_list]
Out[41]: ['janice', 'is', 'cool']
```
|
You Could try this
```
getname = []
for word in args
"%s"% (room.usernames).get(args,word)
```
|
50,641,831
|
I am running a playbook against a RHEL 7.4 image which sits behind a proxy. SELINUX and the firewall have been disabled. I am using Ansible 2.5.3
Here is the task
```
- name: Add Docker repository.
get_url:
url: "{{ docker_yum_repo_url }}"
dest: '/etc/yum.repos.d/docker-{{ docker_edition }}.repo'
owner: root
group: root
mode: 0644
use_proxy: yes
```
And the error
```
fatal: [10.40.12.136]: FAILED! => changed=false
invocation:
module_args:
attributes: null
backup: null
checksum: ''
client_cert: null
client_key: null
content: null
delimiter: null
dest: /etc/yum.repos.d/docker-ce.repo
directory_mode: null
follow: false
force: false
force_basic_auth: false
group: root
headers: null
http_agent: ansible-httpget
mode: 420
owner: root
regexp: null
remote_src: null
selevel: null
serole: null
setype: null
seuser: null
sha256sum: ''
src: null
timeout: 10
tmp_dest: null
unsafe_writes: null
url: https://download.docker.com/linux/centos/docker-ce.repo
url_password: null
url_username: null
use_proxy: true
validate_certs: true
msg: 'Failed to connect to download.docker.com at port 443: [Errno 113] No route to host'
```
If I ssh into the server I can wget or curl the file with no issue at all and as you can see the module is been configured to use my proxy.
UPDATE: It does appear to be trying to use my proxy
```
<10.47.69.136> EXEC /bin/sh -c 'http_proxy=http://192.168.1.240:8080 /usr/bin/python /root/.ansible/tmp/ansible-tmp-1527849642.94-177395007646298/get_url.py && sleep 0'
```
thanks.
|
2018/06/01
|
[
"https://Stackoverflow.com/questions/50641831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768233/"
] |
Build your app with sourcemaps, then use a tool like [`source-map-explorer`](https://www.npmjs.com/package/source-map-explorer) that details the size of every part of library that you're using.
Some tips with common libraries :
* If you're using RxJS 5.5 or higher, use the `.pipe(operator1(), operator2())` syntax, it significantly reduces RxJS size when you don't use many different operators
* If you're using moment.js be sure to import only the locales you're using
* If you're using Angular Material, be sure you don't import unused modules
* If you're using bootstrap and SASS, import only the needed parts of `.scss` files
If you didn't already do it, divide your app into lazy modules, it will reduce the size of the initial chunk.
|
I had a similar issue with large prod bundles and fixed the issue with this command;
```
npm run build
```
I had been using
`npm run ng build --prod`
but the --prod flag doesn't execute and I was left with a vendor.bundle.js which was 2.9mbs
```
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 3.89 kB [entry] [rendered]
chunk {main} main.bundle.js, main.bundle.js.map (main) 122 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 349 kB [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 16.6 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.96 MB [initial] [rendered]
```
With just npm run build (no ng) the whole dist folder is 400kb
```
chunk {0} polyfills.67d5a7eec41ba0d20dc4.bundle.js (polyfills) 101 kB [initial] [rendered]
chunk {1} main.3874ea54d23e70290fa8.bundle.js (main) 327 kB [initial] [rendered]
chunk {2} styles.0aad5eda327b47b9e9fa.bundle.css (styles) 1.56 kB [initial] [rendered]
chunk {3} inline.318b50c57b4eba3d437b.bundle.js (inline) 796 bytes [entry] [rendered]
```
|
50,641,831
|
I am running a playbook against a RHEL 7.4 image which sits behind a proxy. SELINUX and the firewall have been disabled. I am using Ansible 2.5.3
Here is the task
```
- name: Add Docker repository.
get_url:
url: "{{ docker_yum_repo_url }}"
dest: '/etc/yum.repos.d/docker-{{ docker_edition }}.repo'
owner: root
group: root
mode: 0644
use_proxy: yes
```
And the error
```
fatal: [10.40.12.136]: FAILED! => changed=false
invocation:
module_args:
attributes: null
backup: null
checksum: ''
client_cert: null
client_key: null
content: null
delimiter: null
dest: /etc/yum.repos.d/docker-ce.repo
directory_mode: null
follow: false
force: false
force_basic_auth: false
group: root
headers: null
http_agent: ansible-httpget
mode: 420
owner: root
regexp: null
remote_src: null
selevel: null
serole: null
setype: null
seuser: null
sha256sum: ''
src: null
timeout: 10
tmp_dest: null
unsafe_writes: null
url: https://download.docker.com/linux/centos/docker-ce.repo
url_password: null
url_username: null
use_proxy: true
validate_certs: true
msg: 'Failed to connect to download.docker.com at port 443: [Errno 113] No route to host'
```
If I ssh into the server I can wget or curl the file with no issue at all and as you can see the module is been configured to use my proxy.
UPDATE: It does appear to be trying to use my proxy
```
<10.47.69.136> EXEC /bin/sh -c 'http_proxy=http://192.168.1.240:8080 /usr/bin/python /root/.ansible/tmp/ansible-tmp-1527849642.94-177395007646298/get_url.py && sleep 0'
```
thanks.
|
2018/06/01
|
[
"https://Stackoverflow.com/questions/50641831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768233/"
] |
Build your app with sourcemaps, then use a tool like [`source-map-explorer`](https://www.npmjs.com/package/source-map-explorer) that details the size of every part of library that you're using.
Some tips with common libraries :
* If you're using RxJS 5.5 or higher, use the `.pipe(operator1(), operator2())` syntax, it significantly reduces RxJS size when you don't use many different operators
* If you're using moment.js be sure to import only the locales you're using
* If you're using Angular Material, be sure you don't import unused modules
* If you're using bootstrap and SASS, import only the needed parts of `.scss` files
If you didn't already do it, divide your app into lazy modules, it will reduce the size of the initial chunk.
|
Sorry For Late Reply.
This answer will work for all newer versions of Angular.
1. If you are using Angular Material, Then import from the specific package exporter.
Ex:
```
import {MatButtonModule} from '@angular/material/button';
```
istead of
```
import {MatButtonModule} from '@angular/material';
```
2. Avoid using Common Material Module throughout your application.
If you are using LazyLoading module, Import required packages in the specific module.
I followed these steps, I got reduced bundle size from 9.0MB to 1.45MB.
Hope it will work for you guys also :).
|
50,641,831
|
I am running a playbook against a RHEL 7.4 image which sits behind a proxy. SELINUX and the firewall have been disabled. I am using Ansible 2.5.3
Here is the task
```
- name: Add Docker repository.
get_url:
url: "{{ docker_yum_repo_url }}"
dest: '/etc/yum.repos.d/docker-{{ docker_edition }}.repo'
owner: root
group: root
mode: 0644
use_proxy: yes
```
And the error
```
fatal: [10.40.12.136]: FAILED! => changed=false
invocation:
module_args:
attributes: null
backup: null
checksum: ''
client_cert: null
client_key: null
content: null
delimiter: null
dest: /etc/yum.repos.d/docker-ce.repo
directory_mode: null
follow: false
force: false
force_basic_auth: false
group: root
headers: null
http_agent: ansible-httpget
mode: 420
owner: root
regexp: null
remote_src: null
selevel: null
serole: null
setype: null
seuser: null
sha256sum: ''
src: null
timeout: 10
tmp_dest: null
unsafe_writes: null
url: https://download.docker.com/linux/centos/docker-ce.repo
url_password: null
url_username: null
use_proxy: true
validate_certs: true
msg: 'Failed to connect to download.docker.com at port 443: [Errno 113] No route to host'
```
If I ssh into the server I can wget or curl the file with no issue at all and as you can see the module is been configured to use my proxy.
UPDATE: It does appear to be trying to use my proxy
```
<10.47.69.136> EXEC /bin/sh -c 'http_proxy=http://192.168.1.240:8080 /usr/bin/python /root/.ansible/tmp/ansible-tmp-1527849642.94-177395007646298/get_url.py && sleep 0'
```
thanks.
|
2018/06/01
|
[
"https://Stackoverflow.com/questions/50641831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768233/"
] |
I had a similar issue with large prod bundles and fixed the issue with this command;
```
npm run build
```
I had been using
`npm run ng build --prod`
but the --prod flag doesn't execute and I was left with a vendor.bundle.js which was 2.9mbs
```
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 3.89 kB [entry] [rendered]
chunk {main} main.bundle.js, main.bundle.js.map (main) 122 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 349 kB [initial] [rendered]
chunk {styles} styles.bundle.js, styles.bundle.js.map (styles) 16.6 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.96 MB [initial] [rendered]
```
With just npm run build (no ng) the whole dist folder is 400kb
```
chunk {0} polyfills.67d5a7eec41ba0d20dc4.bundle.js (polyfills) 101 kB [initial] [rendered]
chunk {1} main.3874ea54d23e70290fa8.bundle.js (main) 327 kB [initial] [rendered]
chunk {2} styles.0aad5eda327b47b9e9fa.bundle.css (styles) 1.56 kB [initial] [rendered]
chunk {3} inline.318b50c57b4eba3d437b.bundle.js (inline) 796 bytes [entry] [rendered]
```
|
Sorry For Late Reply.
This answer will work for all newer versions of Angular.
1. If you are using Angular Material, Then import from the specific package exporter.
Ex:
```
import {MatButtonModule} from '@angular/material/button';
```
istead of
```
import {MatButtonModule} from '@angular/material';
```
2. Avoid using Common Material Module throughout your application.
If you are using LazyLoading module, Import required packages in the specific module.
I followed these steps, I got reduced bundle size from 9.0MB to 1.45MB.
Hope it will work for you guys also :).
|
49,520,600
|
I'm creating a program in python where i need to ask the user for there team name and team members. I need to have the team names in a list and have the team members embedded within the team name. Any Help?
```
# Creating Teams
print("Welcome to the program")
print("======================================================")
Teams = []
# Looping to find out the four different team names and players.
for x in range(0, 4) :
# Asking for the Team name and the team players names
TeamName = input("What is the name of the team?")
Player1 = input("What is the first name of the player in your team?")
Player2 = input("What is the second name of the player in your team?")
Player3 = input("What is the third name of the player in your team?")
Player4 = input("What is the last name of the player in your team?")
Teams.extend([TeamName, Player1, Player2, Player3, Player4])
TeamPlayers = int(input("What Team do you want to see? (0-4)"))
print([Teams, Player1, Player2, Player3, Player4])
```
|
2018/03/27
|
[
"https://Stackoverflow.com/questions/49520600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9560138/"
] |
`equalsIgnoreCase` just returns a boolean, which indicates, whether two strings are equal if the case of the strings is not considered.
What you need is
```
String aLower = a.toLowerCase();
String bLower = b.toLowerCase();
if(aLower.startsWith(bLower))
{
// do something
}
```
That way you just convert both strings to lower case to compare them afterwards.
|
Try this :
```
System.out.println((a.toLowerCase()).startsWith(b.toLowerCase()));
```
|
38,064,044
|
I am implementing a simple DSL. I have the following input string:
```
txt = 'Hi, my name is <<name>>. I was born in <<city>>.'
```
And I have the following data:
```
{
'name': 'John',
'city': 'Paris',
'more': 'xxx',
'data': 'yyy',
...
}
```
I need to implement the following function:
```
def tokenize(txt):
...
return fmt, vars
```
Where I get:
```
fmt = 'Hi, my name is {name}. I was born in {city}.'
vars = ['name', 'city']
```
That is, `fmt` can be passed to the [str.format()](https://docs.python.org/2/library/stdtypes.html#str.format) function, and `vars` is a list of the detected tokens (so that I can perform lookup in the data, which can be more complex than what I described, since it can be split in several namespaces)
After this, processing the format would be simple:
```
def expand(fmt, vars, data):
params = get_params(vars, data)
return fmt.format(params)
```
Where `get_params` is performing simple lookup of the data, and returning something like:
```
params = {
'name': 'John',
'city': 'Paris',
}
```
My question is:
How can I implement tokenize? How can I detect the tokens, knowing that the delitimers are `<<` and `>>`? Should I go for regexes, or is there an easier path?
This is something similar to what `pystache`, or even `.format` itself, are doing, but I would like a light-weight implementation. Robustness is not very critical at this stage.
|
2016/06/27
|
[
"https://Stackoverflow.com/questions/38064044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647991/"
] |
Yes, this is a perfect target for regexp. Find the begin/end quotation marks, replace them with braces, and extract the symbol names into a list. Do you have a solid description of legal symbols? You'll want a search such as
```
/\<\<([a-zA-Z]+[a-zA-Z0-9_]*)\>\>/
```
For classical variable names (note that this excludes leading underscores). Are you familiar enough with regexps to take it from here?
|
```
import re
def tokenize(text):
found_variables = []
def replace_and_capture(match):
found_variables.append(match.group(1))
return "{{{}}}".format(match.group(1))
return re.sub(r'<<([^>]+)>>', replace_and_capture, text), found_variables
fmt, vars = tokenize('Hi, my name is <<name>>. I was born in <<city>>.')
print(fmt)
print(vars)
# Output:
# Hi, my name is {name}. I was born in {city}.
# ['name', 'city']
```
|
66,565,415
|
basically im new to python programming and I've just learnt about user input. Im trying to make an if statement that checks if the input is a str or int and then prints a message. If anyone knows how then please comment it, thanks.
```
print("How old are you?")
dog = input()
final = int(dog) + int(100)
if dog == str:
print("No")
else:
print("\nHeres you name + 100!")
print(f"{final}")
print("Thanks for playing!")
```
btw the if statement that I put doesn't work, I dont know if I need to put an exception so it responds with not an error message.
|
2021/03/10
|
[
"https://Stackoverflow.com/questions/66565415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15051671/"
] |
Re how to check types, you can do like this:
```py
my_string = "hello"
if isinstance(my_string, str):
print("I'm a string")
else:
print("I'm not")
# outputs: "I'm a string"
```
However, as commented the input method is always returning a value of type str. So if you want to ensure that the value is only consisting of numerical characters, you can use the string method `isdigit()`
```py
my_string = "asd"
my_string.isdigit() # returns False
my_string = "123"
my_string.isdigit() # returns True
```
|
I would use the `type` method to check:
```
print("How old are you?")
dog = input()
final = int(dog) + int(100)
#use type method to check the type of the variable
if type(dog) == str:
print("No")
else:
print("\nHeres you name + 100!")
print(f"{final}")
print("Thanks for playing!")
```
Another thing you can do is set prevent the user from entering anything but an `int` and force a proper variable, something like:
```
while True:
dog = input('How old are you? ')
try:
dog = int(dog)
break
except ValueError:
print('No')
final = dog + 100
print("\nHeres you name + 100!")
print(f"{final}")
print("Thanks for playing!")
```
Also, don't waste processing power by converting an `int` to an `int` so that means `int(100)` is the same as `100`
|
57,899,891
|
I read this (from [here](https://docs.python.org/3.5/reference/datamodel.html#object.__hash__)):
>
> User-defined classes have `__eq__()` and `__hash__()` methods by default; with them, all objects compare unequal (except with themselves) and `x.__hash__()` returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).
>
>
>
And I wish to know if the `__eq__()` method by default is defined like:
```
def __eq__(self, other):
return hash(self) == hash(other)
```
|
2019/09/12
|
[
"https://Stackoverflow.com/questions/57899891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3530284/"
] |
No, it's more like:
```
def __eq__(self, other)
return self is other
```
You can't use `hash()` because it's possible for different objects to have the same hash value.
|
You can read the following reference: <https://eev.ee/blog/2012/03/24/python-faq-equality/>
in the default method where you just try to compare 2 objects while not override the ***eq*** it will see if they are the same 2 objects, more like the following:
```
def __eq__(self, other)
return self is other
```
|
57,899,891
|
I read this (from [here](https://docs.python.org/3.5/reference/datamodel.html#object.__hash__)):
>
> User-defined classes have `__eq__()` and `__hash__()` methods by default; with them, all objects compare unequal (except with themselves) and `x.__hash__()` returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).
>
>
>
And I wish to know if the `__eq__()` method by default is defined like:
```
def __eq__(self, other):
return hash(self) == hash(other)
```
|
2019/09/12
|
[
"https://Stackoverflow.com/questions/57899891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3530284/"
] |
No, it's more like:
```
def __eq__(self, other)
return self is other
```
You can't use `hash()` because it's possible for different objects to have the same hash value.
|
You can refer to [existing question](https://stackoverflow.com/questions/2909106/whats-a-correct-and-good-way-to-implement-hash)
It explains how to use `__hash__()` with `__eq__()` correctly
|
57,899,891
|
I read this (from [here](https://docs.python.org/3.5/reference/datamodel.html#object.__hash__)):
>
> User-defined classes have `__eq__()` and `__hash__()` methods by default; with them, all objects compare unequal (except with themselves) and `x.__hash__()` returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).
>
>
>
And I wish to know if the `__eq__()` method by default is defined like:
```
def __eq__(self, other):
return hash(self) == hash(other)
```
|
2019/09/12
|
[
"https://Stackoverflow.com/questions/57899891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3530284/"
] |
You can read the following reference: <https://eev.ee/blog/2012/03/24/python-faq-equality/>
in the default method where you just try to compare 2 objects while not override the ***eq*** it will see if they are the same 2 objects, more like the following:
```
def __eq__(self, other)
return self is other
```
|
You can refer to [existing question](https://stackoverflow.com/questions/2909106/whats-a-correct-and-good-way-to-implement-hash)
It explains how to use `__hash__()` with `__eq__()` correctly
|
12,757,832
|
I began learning Python a little time ago, and I got the first problem. Here's the code:
```
fh = open('/usr/share/dict/words')
for line in fh.readlines():
print(line, end='')
```
When I execute it in the Terminal (OS X), it tells me `invalid syntax` error where `end` equal sign is placed. What's the problem here? Didn't find the solution...
I installed Python 3.3.0 from this [page](http://python.org/download), Python 3.3.0 Mac OS X 64-bit/32-bit x86-64/i386 Installer
Sorry for so nooby questions :(
|
2012/10/06
|
[
"https://Stackoverflow.com/questions/12757832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764638/"
] |
Apparently because the `WebView` had editable content the events were being consumed by a child responder.
The workaround was to listen to `WebViewDidChangeNotification` when this happens.
|
Here is what I think is occurring
NSFontManager apparently sends the messages along the responder chain and not to the delegate.
I would set my CustomWebViewController to be the delegate of the window.
|
5,919,318
|
I want to nest my custom validators within my schema, like this:
```
MySchema(Schema):
class MyValidator(validators.FancyValidator):
def _to_python(self, value, state):
...
class MyOtherValidator(validators.FancyValidator):
def _to_python(self, value, state):
...
field_foo = All(validators.NotEmpty(),
MyValidator())
field_bar = All(validators.NotEmpty(),
MyOtherValidator())
```
However, it seems to think that `MyValidator` and `MyOtherValidator` are fields b/c it's `form_errors` contain:
```
{
'MyValidator': 'Missing value',
'MyOtherValidator': 'Missing value'
}
```
If I don't nest them, they seem fine. What am I missing?
|
2011/05/07
|
[
"https://Stackoverflow.com/questions/5919318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/315709/"
] |
My advice is: you should move the `FancyValidator` subclass definitions to global scope, either (1) in the same module just before the definition of the `Schema` in which they're used, or (2) in a separate module for greater reuse. Unless there is a specific reason why nesting is required, a few extra class names in the module namespace shouldn't hurt.
For example:
```
from formencode import All, FancyValidator, Schema, validators
class MyValidator(FancyValidator):
def _to_python(self, value, state):
return value + '_foo'
class MyOtherValidator(FancyValidator):
def _to_python(self, value, state):
return value + '_bar'
class MySchema(Schema):
field_foo = All(validators.NotEmpty(), MyValidator())
field_bar = All(validators.NotEmpty(), MyOtherValidator())
print MySchema().to_python({'field_foo': 'x', 'field_bar': 'y'}, None)
```
Result:
```
{'field_foo': 'x_foo', 'field_bar': 'y_bar'}
```
|
In python, anything that you define in your class is a field.
Be it static variables, variables set with self, methods or classes.
If you want to "hide" the classes, or make them "less public", as is probably the right wording in the python dictionary, you should start their names with \_\_.
```
>>> dir(X())
['A', '_B', '_X__C', '__doc__', '__module__']
>>> class X:
... class A: pass
... class __B: pass
... c = 0
... __d = 1
...
>>> dir(X())
['A', '_X__B', '_X__d', '__doc__', '__module__', 'c']
```
As you can see, there is a loophole for this kind of privacy, but most automatic tools will recognize that you are trying to make something private.
|
50,294,263
|
I'm trying to write simple multi-threaded python script:
```
from multiprocessing.dummy import Pool as ThreadPool
def resize_img_folder_multithreaded(img_fldr_src,img_fldr_dst,max_num_of_thread):
images = glob.glob(img_fldr_src+'/*.'+img_file_extension)
pool = ThreadPool(max_num_of_thread)
pool.starmap(resize_img,zip(images,itertools.repeat(img_fldr_dst)))
# close the pool and wait for the work to finish
pool.close()
pool.join()
def resize_img(img_path_src,img_fldr_dest):
#print("about to resize image=",img_path_src)
image = io.imread(img_path_src)
image = transform.resize(image, [300,300])
io.imsave(os.path.join(img_fldr_dest,os.path.basename(img_path_src)),image)
label = img_path_src[:-4] + '.xml'
if copyLabels is True and os.path.exists(label) is True :
copyfile(label,os.path.join(img_fldr_dest,os.path.basename(label)))
```
setting the argument `max_num_of_thread` to any number in [1...10]
doesn't improve my run time at all (`for 60 images it stays around 30 sec`) , the `max_num_of_thread`=10 my PC got stuck
my question is : what is the bottle neck in my code , why can't I see any improvement?
some data about my PC :
```
python -V
Python 3.6.4 :: Anaconda, Inc.
cat /proc/cpuinfo | grep 'processor' | wc -l
4
cat /proc/meminfo
MemTotal: 8075960 kB
MemFree: 3943796 kB
MemAvailable: 4560308 kB
cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=17.10
```
|
2018/05/11
|
[
"https://Stackoverflow.com/questions/50294263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3134181/"
] |
Blame the GIL.
Python has this mechanism called the GIL, global interpreter lock. It is basically a mutex that prevents native threads from executing Python bytecodes at once. This must be done since Python's (at least, CPython) memory management is not thread-safe.
In other words, the GIL will prevent you from running multiple threads at the same time. Essentially, you're running one thread at a time. Multi-threading, in the sense of exploiting multiple CPU cores, is more like an illusion in Python.
Fortunately, there is a way to solve this problem. it's a bit more expensive resource-wise though. You can utilize multiprocessing instead. Python has excellent support for this through the `multiprocessing` module. This way, you will be able to achieve parallelism[1].
You might ask why isn't multiprocessing affected by the GIL limitations. The answer is pretty simple. Each new process of your program has a different instance (I think there's a better word for this) of the Python interpreter. This means that each process has its own GIL. So, the processes are not managed by the GIL, but by the OS itself. This provides you with parallelism[2].
---
### References
* [1] <https://softwareengineering.stackexchange.com/questions/186889/why-was-python-written-with-the-gil>
* [2] <https://jeffknupp.com/blog/2013/06/30/pythons-hardest-problem-revisited/>
|
You should only use multiprocessing with the number of cpu cores you have available. You are also not using a Queue, so the pool of resources are doing the same work. You need to add a queue to your code.
[Filling a queue and managing multiprocessing in python](https://stackoverflow.com/questions/17241663/filling-a-queue-and-managing-multiprocessing-in-python)
|
50,294,263
|
I'm trying to write simple multi-threaded python script:
```
from multiprocessing.dummy import Pool as ThreadPool
def resize_img_folder_multithreaded(img_fldr_src,img_fldr_dst,max_num_of_thread):
images = glob.glob(img_fldr_src+'/*.'+img_file_extension)
pool = ThreadPool(max_num_of_thread)
pool.starmap(resize_img,zip(images,itertools.repeat(img_fldr_dst)))
# close the pool and wait for the work to finish
pool.close()
pool.join()
def resize_img(img_path_src,img_fldr_dest):
#print("about to resize image=",img_path_src)
image = io.imread(img_path_src)
image = transform.resize(image, [300,300])
io.imsave(os.path.join(img_fldr_dest,os.path.basename(img_path_src)),image)
label = img_path_src[:-4] + '.xml'
if copyLabels is True and os.path.exists(label) is True :
copyfile(label,os.path.join(img_fldr_dest,os.path.basename(label)))
```
setting the argument `max_num_of_thread` to any number in [1...10]
doesn't improve my run time at all (`for 60 images it stays around 30 sec`) , the `max_num_of_thread`=10 my PC got stuck
my question is : what is the bottle neck in my code , why can't I see any improvement?
some data about my PC :
```
python -V
Python 3.6.4 :: Anaconda, Inc.
cat /proc/cpuinfo | grep 'processor' | wc -l
4
cat /proc/meminfo
MemTotal: 8075960 kB
MemFree: 3943796 kB
MemAvailable: 4560308 kB
cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=17.10
```
|
2018/05/11
|
[
"https://Stackoverflow.com/questions/50294263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3134181/"
] |
Blame the GIL.
Python has this mechanism called the GIL, global interpreter lock. It is basically a mutex that prevents native threads from executing Python bytecodes at once. This must be done since Python's (at least, CPython) memory management is not thread-safe.
In other words, the GIL will prevent you from running multiple threads at the same time. Essentially, you're running one thread at a time. Multi-threading, in the sense of exploiting multiple CPU cores, is more like an illusion in Python.
Fortunately, there is a way to solve this problem. it's a bit more expensive resource-wise though. You can utilize multiprocessing instead. Python has excellent support for this through the `multiprocessing` module. This way, you will be able to achieve parallelism[1].
You might ask why isn't multiprocessing affected by the GIL limitations. The answer is pretty simple. Each new process of your program has a different instance (I think there's a better word for this) of the Python interpreter. This means that each process has its own GIL. So, the processes are not managed by the GIL, but by the OS itself. This provides you with parallelism[2].
---
### References
* [1] <https://softwareengineering.stackexchange.com/questions/186889/why-was-python-written-with-the-gil>
* [2] <https://jeffknupp.com/blog/2013/06/30/pythons-hardest-problem-revisited/>
|
The problem come from the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) or GIL. GIL only let one thread run at a time so if you want to do parallel computation use [Processing.Pool](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool):
```
import multiprocessing
pool = multiprocessing.Pool(max_num_of_process) # Use number of core as max number
```
!!! [multiprocessing.dummy](https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy) Is a wrapper arround the threading module, it let you interact with threading Pool as you where using Processing Pool.
|
50,294,263
|
I'm trying to write simple multi-threaded python script:
```
from multiprocessing.dummy import Pool as ThreadPool
def resize_img_folder_multithreaded(img_fldr_src,img_fldr_dst,max_num_of_thread):
images = glob.glob(img_fldr_src+'/*.'+img_file_extension)
pool = ThreadPool(max_num_of_thread)
pool.starmap(resize_img,zip(images,itertools.repeat(img_fldr_dst)))
# close the pool and wait for the work to finish
pool.close()
pool.join()
def resize_img(img_path_src,img_fldr_dest):
#print("about to resize image=",img_path_src)
image = io.imread(img_path_src)
image = transform.resize(image, [300,300])
io.imsave(os.path.join(img_fldr_dest,os.path.basename(img_path_src)),image)
label = img_path_src[:-4] + '.xml'
if copyLabels is True and os.path.exists(label) is True :
copyfile(label,os.path.join(img_fldr_dest,os.path.basename(label)))
```
setting the argument `max_num_of_thread` to any number in [1...10]
doesn't improve my run time at all (`for 60 images it stays around 30 sec`) , the `max_num_of_thread`=10 my PC got stuck
my question is : what is the bottle neck in my code , why can't I see any improvement?
some data about my PC :
```
python -V
Python 3.6.4 :: Anaconda, Inc.
cat /proc/cpuinfo | grep 'processor' | wc -l
4
cat /proc/meminfo
MemTotal: 8075960 kB
MemFree: 3943796 kB
MemAvailable: 4560308 kB
cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=17.10
```
|
2018/05/11
|
[
"https://Stackoverflow.com/questions/50294263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3134181/"
] |
The problem come from the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) or GIL. GIL only let one thread run at a time so if you want to do parallel computation use [Processing.Pool](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool):
```
import multiprocessing
pool = multiprocessing.Pool(max_num_of_process) # Use number of core as max number
```
!!! [multiprocessing.dummy](https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy) Is a wrapper arround the threading module, it let you interact with threading Pool as you where using Processing Pool.
|
You should only use multiprocessing with the number of cpu cores you have available. You are also not using a Queue, so the pool of resources are doing the same work. You need to add a queue to your code.
[Filling a queue and managing multiprocessing in python](https://stackoverflow.com/questions/17241663/filling-a-queue-and-managing-multiprocessing-in-python)
|
35,814,637
|
I am trying to call a Torch 7 program from within a Python cgi-bin script.
If I run the following Python script from the command line:
```
# -*- coding: utf-8 -*-
from subprocess import call
call (['th', 'sample.lua', 'cv/lm_lstm_epoch3.54_0.9324.t7', '-gpuid', '-1', '-primetext', '"אמר הגאון הגרפקא המן איש טוב היה שנאמר"', '-temperature', '1.0', '-length', '1000'])
```
This works fine and I get the following output
>
> ubuntu@ip-172-31-45-110:/usr/lib/cgi-bin$ python test2.py
> creating an lstm...
>
>
> seeding with "אמר הגאון הגרפקא המן איש טוב היה שנאמר"
> -----------------------------------------------------
>
>
> "אמר הגאון הגרפקא המן איש טוב היה שנאמר"זה יקרק ידו מי שכן בלבד ומחללין עליו אותוממנו וזכה זה לא סולד דינר הקדשו מחופה את אשתו מבית הרן וביניהןאבל יום אחד ולמנין שניה ימיבתן ככלום זכותדכתיב אשר בחרם אם אשר עשו לא כל חטאת קמיהבדין נקרא ולא מהוציאה ולא ניקבה לא אמר ליה אם תימצילומר עד דכם ראשון בגובהו הרי ז] נידוןטומאה מידקיסא אי תלמודה ומי איכא למיפרך מהלשרעתו לאהתנאו לא א"ל הכי קאמר אפילושחי ושוברו של מקום הראשוןכסיפו והרי חילין בבית המקדש והיכיממעיטרים אחרינא ועיבור בישראל מי איכא מידיאישתי מירחו דשקיל אמר להו אי שבעים שנה שעוריםעלין א"כ רבי ינאי בר מישראלאמר לו נפש גזר קונשי ב תרצות
>
>
>
However if I try calling Torch 7 from a cgi-bin script
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import os, sys
import cgi, cgitb
print "Content-Type: text/html"
print
print "<TITLE>CGI script output</TITLE>"
output = ""
output = subprocess.call (['th', 'sample.lua', 'cv/lm_lstm_epoch3.54_0.9324.t7', '-gpuid', '-1', '-primetext', '"אמר הגאון הגרפקא המן איש טוב היה שנאמר"', '-temperature', '1.0', '-length', '1000'])
print output
```
Then I get no output at all to the webpage, there is also no error in the apache error log.
Thanks
|
2016/03/05
|
[
"https://Stackoverflow.com/questions/35814637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6001121/"
] |
You want to use [check\_output](https://docs.python.org/3/library/subprocess.html#subprocess.check_output) to store the output of the command you are executing. [call](https://docs.python.org/3/library/subprocess.html#subprocess.call) will not do this. Call will only give you the return code of what you are executing.
```
subprocess.check_output(['th', 'sample.lua', 'cv/lm_lstm_epoch3.54_0.9324.t7', '-gpuid', '-1', '-primetext', '"אמר הגאון הגרפקא המן איש טוב היה שנאמר"', '-temperature', '1.0', '-length', '1000'])
```
|
May be you could try [lutorpy](https://github.com/imodpasteur/lutorpy) then you can run the torch code directly with python. You can use require("sample") to import your sample.lua module, and then run the inner function just like you run a python function.
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
**EDIT:**
The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
dhi = 9 - the_list
dlo = 3 - the_list
idx = dhi + dlo < 0
the_rounded = the_list + np.where(idx, dhi, dlo)
# array([9., 9., 9., 3., 3.])
```
---
I'd apply round function to the offsetless normalized list and scale back and add offset afterwards:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
hi = 9
lo = 3
dlt = hi - lo
the_rounded = np.round((the_list - lo)/dlt) * dlt + lo
# [9. 9. 9. 3. 3.]
```
|
A one liner list comprehension using inbuilt `min` function by modifying the key argument to look for an absolute difference
```
upper_lower_bound_list=[3,9]
myNumberlist=[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
List comprehension
```
[min(upper_lower_bound_list, key=lambda x:abs(x-myNumber)) for myNumber in myNumberlist]
```
**Output**
```
[9, 9, 9, 3, 3]
```
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
**EDIT:**
The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
dhi = 9 - the_list
dlo = 3 - the_list
idx = dhi + dlo < 0
the_rounded = the_list + np.where(idx, dhi, dlo)
# array([9., 9., 9., 3., 3.])
```
---
I'd apply round function to the offsetless normalized list and scale back and add offset afterwards:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
hi = 9
lo = 3
dlt = hi - lo
the_rounded = np.round((the_list - lo)/dlt) * dlt + lo
# [9. 9. 9. 3. 3.]
```
|
Another option using list comprehensions and lambda functions:
```
round_the_num = lambda list, upper, lower: [upper if x > (upper + lower) / 2 else lower for x in list]
round_the_num(l, 9, 3)
```
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
***Timing comparison*** *of available answers*
[](https://i.stack.imgur.com/nwLAw.png)
My interpretation would be:
From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists.
For lists containing several dozens of values and more, numpy array and then adding conditionally the differences with the smaller absolute values seems to be the fastest solution.
---
Code used for timing comparison:
```
import timeit
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
rep = 5
timings = dict()
for n in range(7):
print(f'N = 10^{n}')
N = 10**n
setup = f'''import numpy as np\nthe_list = np.random.random({N})*6+3\nhi = 9\nlo = 3\ndlt = hi - lo\nmid = (hi + lo) / 2\ndef return_the_num(l, lst, h):\n return [l if abs(l-x) < abs(h-x) else h for x in lst]'''
fct = 'np.round((the_list - lo)/dlt) * dlt + lo'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_np'] = timings.get('SpghttCd_np', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'return_the_num(3, the_list, 9)'
t = timeit.Timer(fct, setup=setup)
timings['Austin'] = timings.get('Austin', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = '[(lo, hi)[mid < v] for v in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_lc'] = timings.get('SpghttCd_lc', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nround_the_num = lambda list, upper, lower: [upper if x > (upper + lower) / 2 else lower for x in list]'
fct = 'round_the_num(the_list, 9, 3)'
t = timeit.Timer(fct, setup=setup)
timings['Carles Mitjans'] = timings.get('Carles Mitjans', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nupper_lower_bound_list=[3,9]'
fct = '[min(upper_lower_bound_list, key=lambda x:abs(x-myNumber)) for myNumber in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['mad_'] = timings.get('mad_', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef return_bound(x, l, h):\n low = abs(x - l)\n high = abs(x - h)\n if low < high:\n return l\n else:\n return h'
fct = '[return_bound(x, 3, 9) for x in the_list]'
t = timeit.Timer(fct, setup=setup)
timings["Scratch'N'Purr"] = timings.get("Scratch'N'Purr", []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef round_the_list(list, bound_1, bound_2):\n\tmid = (bound_1+bound_2)/2\n\tfor i in range(len(list)):\n\t\tif list[i] > mid:\n\t\t\tlist[i] = bound_2\n\t\telse:\n\t\t\tlist[i] = bound_1'
fct = 'round_the_list(the_list, 3, 9)'
t = timeit.Timer(fct, setup=setup)
timings["Abhishek Patel"] = timings.get("Abhishek Patel", []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'dhi = 9 - the_list\ndlo = 3 - the_list\nidx = dhi + dlo < 0\nthe_list + np.where(idx, dhi, dlo)'
t = timeit.Timer(fct, setup=setup)
timings["SpghttCd_where"] = timings.get("SpghttCd_where", []) + [np.min(t.repeat(repeat=rep, number=1))]
print('done')
df = pd.DataFrame(timings, 10**np.arange(n+1))
ax = df.plot(logx=True, logy=True)
ax.set_xlabel('length of the list')
ax.set_ylabel('seconds to run')
ax.get_lines()[-1].set_c('g')
plt.legend()
print(df)
```
|
You can write a custom function that does a list-comprehension, like:
```
lst = [ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
def return_the_num(l, lst, h):
return [l if abs(l-x) < abs(h-x) else h for x in lst]
print(return_the_num(3, lst, 9))
# [9, 9, 9, 3, 3]
```
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
**EDIT:**
The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
dhi = 9 - the_list
dlo = 3 - the_list
idx = dhi + dlo < 0
the_rounded = the_list + np.where(idx, dhi, dlo)
# array([9., 9., 9., 3., 3.])
```
---
I'd apply round function to the offsetless normalized list and scale back and add offset afterwards:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
hi = 9
lo = 3
dlt = hi - lo
the_rounded = np.round((the_list - lo)/dlt) * dlt + lo
# [9. 9. 9. 3. 3.]
```
|
You can write a custom function that does a list-comprehension, like:
```
lst = [ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
def return_the_num(l, lst, h):
return [l if abs(l-x) < abs(h-x) else h for x in lst]
print(return_the_num(3, lst, 9))
# [9, 9, 9, 3, 3]
```
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
**EDIT:**
The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
dhi = 9 - the_list
dlo = 3 - the_list
idx = dhi + dlo < 0
the_rounded = the_list + np.where(idx, dhi, dlo)
# array([9., 9., 9., 3., 3.])
```
---
I'd apply round function to the offsetless normalized list and scale back and add offset afterwards:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
hi = 9
lo = 3
dlt = hi - lo
the_rounded = np.round((the_list - lo)/dlt) * dlt + lo
# [9. 9. 9. 3. 3.]
```
|
***Timing comparison*** *of available answers*
[](https://i.stack.imgur.com/nwLAw.png)
My interpretation would be:
From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists.
For lists containing several dozens of values and more, numpy array and then adding conditionally the differences with the smaller absolute values seems to be the fastest solution.
---
Code used for timing comparison:
```
import timeit
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
rep = 5
timings = dict()
for n in range(7):
print(f'N = 10^{n}')
N = 10**n
setup = f'''import numpy as np\nthe_list = np.random.random({N})*6+3\nhi = 9\nlo = 3\ndlt = hi - lo\nmid = (hi + lo) / 2\ndef return_the_num(l, lst, h):\n return [l if abs(l-x) < abs(h-x) else h for x in lst]'''
fct = 'np.round((the_list - lo)/dlt) * dlt + lo'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_np'] = timings.get('SpghttCd_np', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'return_the_num(3, the_list, 9)'
t = timeit.Timer(fct, setup=setup)
timings['Austin'] = timings.get('Austin', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = '[(lo, hi)[mid < v] for v in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_lc'] = timings.get('SpghttCd_lc', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nround_the_num = lambda list, upper, lower: [upper if x > (upper + lower) / 2 else lower for x in list]'
fct = 'round_the_num(the_list, 9, 3)'
t = timeit.Timer(fct, setup=setup)
timings['Carles Mitjans'] = timings.get('Carles Mitjans', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nupper_lower_bound_list=[3,9]'
fct = '[min(upper_lower_bound_list, key=lambda x:abs(x-myNumber)) for myNumber in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['mad_'] = timings.get('mad_', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef return_bound(x, l, h):\n low = abs(x - l)\n high = abs(x - h)\n if low < high:\n return l\n else:\n return h'
fct = '[return_bound(x, 3, 9) for x in the_list]'
t = timeit.Timer(fct, setup=setup)
timings["Scratch'N'Purr"] = timings.get("Scratch'N'Purr", []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef round_the_list(list, bound_1, bound_2):\n\tmid = (bound_1+bound_2)/2\n\tfor i in range(len(list)):\n\t\tif list[i] > mid:\n\t\t\tlist[i] = bound_2\n\t\telse:\n\t\t\tlist[i] = bound_1'
fct = 'round_the_list(the_list, 3, 9)'
t = timeit.Timer(fct, setup=setup)
timings["Abhishek Patel"] = timings.get("Abhishek Patel", []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'dhi = 9 - the_list\ndlo = 3 - the_list\nidx = dhi + dlo < 0\nthe_list + np.where(idx, dhi, dlo)'
t = timeit.Timer(fct, setup=setup)
timings["SpghttCd_where"] = timings.get("SpghttCd_where", []) + [np.min(t.repeat(repeat=rep, number=1))]
print('done')
df = pd.DataFrame(timings, 10**np.arange(n+1))
ax = df.plot(logx=True, logy=True)
ax.set_xlabel('length of the list')
ax.set_ylabel('seconds to run')
ax.get_lines()[-1].set_c('g')
plt.legend()
print(df)
```
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
**EDIT:**
The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
dhi = 9 - the_list
dlo = 3 - the_list
idx = dhi + dlo < 0
the_rounded = the_list + np.where(idx, dhi, dlo)
# array([9., 9., 9., 3., 3.])
```
---
I'd apply round function to the offsetless normalized list and scale back and add offset afterwards:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
hi = 9
lo = 3
dlt = hi - lo
the_rounded = np.round((the_list - lo)/dlt) * dlt + lo
# [9. 9. 9. 3. 3.]
```
|
I really like @AbhishekPatel's idea about comparing against the mid point. But I'd put it into a LC using the result as an index for a bounds tuple:
```
the_list = [ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
hi = 9
lo = 3
mid = (hi + lo) / 2
[(lo, hi)[mid < v] for v in the_list]
# [9, 9, 9, 3, 3]
```
---
... but this is over 15 times slower than the numpy approach.
However, this here can handle numbers bigger than `hi` or lower than `lo`.
... but this again only for a 100000 entry list. In case of the original list posted by OP the two variants are very close together...
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
**EDIT:**
The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
dhi = 9 - the_list
dlo = 3 - the_list
idx = dhi + dlo < 0
the_rounded = the_list + np.where(idx, dhi, dlo)
# array([9., 9., 9., 3., 3.])
```
---
I'd apply round function to the offsetless normalized list and scale back and add offset afterwards:
```
import numpy as np
the_list = np.array([ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ])
hi = 9
lo = 3
dlt = hi - lo
the_rounded = np.round((the_list - lo)/dlt) * dlt + lo
# [9. 9. 9. 3. 3.]
```
|
Perhaps you could write a function and use it in a list comprehension.
```
def return_bound(x, l, h):
low = abs(x - l)
high = abs(x - h)
if low < high:
return l
else:
return h
```
Test:
```
>>> mylist = [7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156]
>>> [return_bound(x, 3, 9) for x in mylist]
[9, 9, 9, 3, 3]
```
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
***Timing comparison*** *of available answers*
[](https://i.stack.imgur.com/nwLAw.png)
My interpretation would be:
From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists.
For lists containing several dozens of values and more, numpy array and then adding conditionally the differences with the smaller absolute values seems to be the fastest solution.
---
Code used for timing comparison:
```
import timeit
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
rep = 5
timings = dict()
for n in range(7):
print(f'N = 10^{n}')
N = 10**n
setup = f'''import numpy as np\nthe_list = np.random.random({N})*6+3\nhi = 9\nlo = 3\ndlt = hi - lo\nmid = (hi + lo) / 2\ndef return_the_num(l, lst, h):\n return [l if abs(l-x) < abs(h-x) else h for x in lst]'''
fct = 'np.round((the_list - lo)/dlt) * dlt + lo'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_np'] = timings.get('SpghttCd_np', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'return_the_num(3, the_list, 9)'
t = timeit.Timer(fct, setup=setup)
timings['Austin'] = timings.get('Austin', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = '[(lo, hi)[mid < v] for v in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_lc'] = timings.get('SpghttCd_lc', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nround_the_num = lambda list, upper, lower: [upper if x > (upper + lower) / 2 else lower for x in list]'
fct = 'round_the_num(the_list, 9, 3)'
t = timeit.Timer(fct, setup=setup)
timings['Carles Mitjans'] = timings.get('Carles Mitjans', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nupper_lower_bound_list=[3,9]'
fct = '[min(upper_lower_bound_list, key=lambda x:abs(x-myNumber)) for myNumber in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['mad_'] = timings.get('mad_', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef return_bound(x, l, h):\n low = abs(x - l)\n high = abs(x - h)\n if low < high:\n return l\n else:\n return h'
fct = '[return_bound(x, 3, 9) for x in the_list]'
t = timeit.Timer(fct, setup=setup)
timings["Scratch'N'Purr"] = timings.get("Scratch'N'Purr", []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef round_the_list(list, bound_1, bound_2):\n\tmid = (bound_1+bound_2)/2\n\tfor i in range(len(list)):\n\t\tif list[i] > mid:\n\t\t\tlist[i] = bound_2\n\t\telse:\n\t\t\tlist[i] = bound_1'
fct = 'round_the_list(the_list, 3, 9)'
t = timeit.Timer(fct, setup=setup)
timings["Abhishek Patel"] = timings.get("Abhishek Patel", []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'dhi = 9 - the_list\ndlo = 3 - the_list\nidx = dhi + dlo < 0\nthe_list + np.where(idx, dhi, dlo)'
t = timeit.Timer(fct, setup=setup)
timings["SpghttCd_where"] = timings.get("SpghttCd_where", []) + [np.min(t.repeat(repeat=rep, number=1))]
print('done')
df = pd.DataFrame(timings, 10**np.arange(n+1))
ax = df.plot(logx=True, logy=True)
ax.set_xlabel('length of the list')
ax.set_ylabel('seconds to run')
ax.get_lines()[-1].set_c('g')
plt.legend()
print(df)
```
|
A one liner list comprehension using inbuilt `min` function by modifying the key argument to look for an absolute difference
```
upper_lower_bound_list=[3,9]
myNumberlist=[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
List comprehension
```
[min(upper_lower_bound_list, key=lambda x:abs(x-myNumber)) for myNumber in myNumberlist]
```
**Output**
```
[9, 9, 9, 3, 3]
```
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
***Timing comparison*** *of available answers*
[](https://i.stack.imgur.com/nwLAw.png)
My interpretation would be:
From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists.
For lists containing several dozens of values and more, numpy array and then adding conditionally the differences with the smaller absolute values seems to be the fastest solution.
---
Code used for timing comparison:
```
import timeit
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
rep = 5
timings = dict()
for n in range(7):
print(f'N = 10^{n}')
N = 10**n
setup = f'''import numpy as np\nthe_list = np.random.random({N})*6+3\nhi = 9\nlo = 3\ndlt = hi - lo\nmid = (hi + lo) / 2\ndef return_the_num(l, lst, h):\n return [l if abs(l-x) < abs(h-x) else h for x in lst]'''
fct = 'np.round((the_list - lo)/dlt) * dlt + lo'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_np'] = timings.get('SpghttCd_np', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'return_the_num(3, the_list, 9)'
t = timeit.Timer(fct, setup=setup)
timings['Austin'] = timings.get('Austin', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = '[(lo, hi)[mid < v] for v in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_lc'] = timings.get('SpghttCd_lc', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nround_the_num = lambda list, upper, lower: [upper if x > (upper + lower) / 2 else lower for x in list]'
fct = 'round_the_num(the_list, 9, 3)'
t = timeit.Timer(fct, setup=setup)
timings['Carles Mitjans'] = timings.get('Carles Mitjans', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nupper_lower_bound_list=[3,9]'
fct = '[min(upper_lower_bound_list, key=lambda x:abs(x-myNumber)) for myNumber in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['mad_'] = timings.get('mad_', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef return_bound(x, l, h):\n low = abs(x - l)\n high = abs(x - h)\n if low < high:\n return l\n else:\n return h'
fct = '[return_bound(x, 3, 9) for x in the_list]'
t = timeit.Timer(fct, setup=setup)
timings["Scratch'N'Purr"] = timings.get("Scratch'N'Purr", []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef round_the_list(list, bound_1, bound_2):\n\tmid = (bound_1+bound_2)/2\n\tfor i in range(len(list)):\n\t\tif list[i] > mid:\n\t\t\tlist[i] = bound_2\n\t\telse:\n\t\t\tlist[i] = bound_1'
fct = 'round_the_list(the_list, 3, 9)'
t = timeit.Timer(fct, setup=setup)
timings["Abhishek Patel"] = timings.get("Abhishek Patel", []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'dhi = 9 - the_list\ndlo = 3 - the_list\nidx = dhi + dlo < 0\nthe_list + np.where(idx, dhi, dlo)'
t = timeit.Timer(fct, setup=setup)
timings["SpghttCd_where"] = timings.get("SpghttCd_where", []) + [np.min(t.repeat(repeat=rep, number=1))]
print('done')
df = pd.DataFrame(timings, 10**np.arange(n+1))
ax = df.plot(logx=True, logy=True)
ax.set_xlabel('length of the list')
ax.set_ylabel('seconds to run')
ax.get_lines()[-1].set_c('g')
plt.legend()
print(df)
```
|
I really like @AbhishekPatel's idea about comparing against the mid point. But I'd put it into a LC using the result as an index for a bounds tuple:
```
the_list = [ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
hi = 9
lo = 3
mid = (hi + lo) / 2
[(lo, hi)[mid < v] for v in the_list]
# [9, 9, 9, 3, 3]
```
---
... but this is over 15 times slower than the numpy approach.
However, this here can handle numbers bigger than `hi` or lower than `lo`.
... but this again only for a 100000 entry list. In case of the original list posted by OP the two variants are very close together...
|
53,728,124
|
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound.
eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like -
```
[ 7.453511737983394,
8.10917072790058,
6.2377799380575,
5.225853201122676,
4.067932296134156 ]
```
and we want to list to be rounded to either 3 or 9 like -
```
[ 9,
9,
9,
3,
3 ]
```
I know we can do that in a good old fashion like iterating in the array and finding the difference and then getting the one which is closest.
my-approach-code:
```
for i in the_list[:]:
three = abs(3-the_list[i])
nine = abs(9-the_list[i])
if three < nine:
the_list[i] = three
else:
the_list[i] = nine
```
I'm wondering if there is a *quick and dirty* way which is inbuilt in python like:
```
hey_bound = round_the_num(number, bound_1, bound_2)
```
I know that we can `my-approach-code` but I'm pretty much sure that out there this has been implemented in much better way, I tried to find it but had no luck finding it, and here we are.
any guesses or direct links for solution to this will be amazing.
|
2018/12/11
|
[
"https://Stackoverflow.com/questions/53728124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618421/"
] |
***Timing comparison*** *of available answers*
[](https://i.stack.imgur.com/nwLAw.png)
My interpretation would be:
From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists.
For lists containing several dozens of values and more, numpy array and then adding conditionally the differences with the smaller absolute values seems to be the fastest solution.
---
Code used for timing comparison:
```
import timeit
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
rep = 5
timings = dict()
for n in range(7):
print(f'N = 10^{n}')
N = 10**n
setup = f'''import numpy as np\nthe_list = np.random.random({N})*6+3\nhi = 9\nlo = 3\ndlt = hi - lo\nmid = (hi + lo) / 2\ndef return_the_num(l, lst, h):\n return [l if abs(l-x) < abs(h-x) else h for x in lst]'''
fct = 'np.round((the_list - lo)/dlt) * dlt + lo'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_np'] = timings.get('SpghttCd_np', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'return_the_num(3, the_list, 9)'
t = timeit.Timer(fct, setup=setup)
timings['Austin'] = timings.get('Austin', []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = '[(lo, hi)[mid < v] for v in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['SpghttCd_lc'] = timings.get('SpghttCd_lc', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nround_the_num = lambda list, upper, lower: [upper if x > (upper + lower) / 2 else lower for x in list]'
fct = 'round_the_num(the_list, 9, 3)'
t = timeit.Timer(fct, setup=setup)
timings['Carles Mitjans'] = timings.get('Carles Mitjans', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\nupper_lower_bound_list=[3,9]'
fct = '[min(upper_lower_bound_list, key=lambda x:abs(x-myNumber)) for myNumber in the_list]'
t = timeit.Timer(fct, setup=setup)
timings['mad_'] = timings.get('mad_', []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef return_bound(x, l, h):\n low = abs(x - l)\n high = abs(x - h)\n if low < high:\n return l\n else:\n return h'
fct = '[return_bound(x, 3, 9) for x in the_list]'
t = timeit.Timer(fct, setup=setup)
timings["Scratch'N'Purr"] = timings.get("Scratch'N'Purr", []) + [np.min(t.repeat(repeat=rep, number=1))]
setup += '\ndef round_the_list(list, bound_1, bound_2):\n\tmid = (bound_1+bound_2)/2\n\tfor i in range(len(list)):\n\t\tif list[i] > mid:\n\t\t\tlist[i] = bound_2\n\t\telse:\n\t\t\tlist[i] = bound_1'
fct = 'round_the_list(the_list, 3, 9)'
t = timeit.Timer(fct, setup=setup)
timings["Abhishek Patel"] = timings.get("Abhishek Patel", []) + [np.min(t.repeat(repeat=rep, number=1))]
fct = 'dhi = 9 - the_list\ndlo = 3 - the_list\nidx = dhi + dlo < 0\nthe_list + np.where(idx, dhi, dlo)'
t = timeit.Timer(fct, setup=setup)
timings["SpghttCd_where"] = timings.get("SpghttCd_where", []) + [np.min(t.repeat(repeat=rep, number=1))]
print('done')
df = pd.DataFrame(timings, 10**np.arange(n+1))
ax = df.plot(logx=True, logy=True)
ax.set_xlabel('length of the list')
ax.set_ylabel('seconds to run')
ax.get_lines()[-1].set_c('g')
plt.legend()
print(df)
```
|
You can generalize by finding the midpoint, and checking which side of the midpoint each number in the list is on
```
def round_the_list(list, bound_1, bound_2):
mid = (bound_1+bound_2)/2
for i in range(len(list)):
if list[i] > mid: # or >= depending on your rounding decision
list[i] = bound_2
else:
list[i] = bound_1
```
|
67,374,632
|
I want to take two lists and want to count the values that appear in both but considering **the same position**.
```
a = [1, 2, 3, 4, 5]
b = [4, 5, 3, 6, 5]
returnMatches(a, b)
```
would return `2`, for instance.
```
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 3, 5]
returnMatches(a, b)
```
would return `4`, for instance.
Is there a pythonic one line option or do I really need to iterate over both lists?
Thanks
|
2021/05/03
|
[
"https://Stackoverflow.com/questions/67374632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152497/"
] |
Try
```py
output = sum([x == y for x, y in zip(a, b)])
```
I am not sure if it needs further clarification. You might want to look into "list comprehension" and `zip()` if you are not familiar with them.
|
```py
returnMatches = lambda a,b:sum([x==y for x,y in zip(a,b)]
```
This is the same as:
```py
def returnMatches(a, b):
matches = 0
for x, y in zip(a, b):
matches += 1
return matches
```
Take a look at `zip()` for more information on that builtin
|
67,374,632
|
I want to take two lists and want to count the values that appear in both but considering **the same position**.
```
a = [1, 2, 3, 4, 5]
b = [4, 5, 3, 6, 5]
returnMatches(a, b)
```
would return `2`, for instance.
```
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 3, 5]
returnMatches(a, b)
```
would return `4`, for instance.
Is there a pythonic one line option or do I really need to iterate over both lists?
Thanks
|
2021/05/03
|
[
"https://Stackoverflow.com/questions/67374632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152497/"
] |
Look up what [`zip`](https://docs.python.org/3.3/library/functions.html#zip) is and how [list comprehension and generator expressions](https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions) work:
```
def count_matches(a, b):
return sum(x == y for x, y in zip(a, b))
```
|
```py
returnMatches = lambda a,b:sum([x==y for x,y in zip(a,b)]
```
This is the same as:
```py
def returnMatches(a, b):
matches = 0
for x, y in zip(a, b):
matches += 1
return matches
```
Take a look at `zip()` for more information on that builtin
|
74,575,794
|
Consider the following simple code:
```
import re
def my_match(s):
if re.match("^[a-zA-Z]+", s):
return True
else:
return False
```
Is there a way to collapse this in a single `return` statement? In `C` we could do for example:
```
return match("^[a-zA-Z]+", s) ? true : false;
```
Is there something similar in python?
|
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738154/"
] |
Python also supports this, although the syntaxes is a little different than most languages.
```
import re
def my_match(s):
return True if re.match("^[a-zA-Z]+", s) else False
```
In general, the Python syntax is `val_when_true if cond else val_when_false`, compared to the `cond ? val_when_true : val_when_false` you see in other languages.
In your particular case though, you can just write:
```
import re
def my_match(s):
return bool(re.match("^[a-zA-Z]+", s))
```
|
A more generell solution would be to use the following code line. It excludes a fit with length 0 as it specificly checks for the None statement. In this case an empty string is impossible but it is more explicit.
```py
return re.match("^[a-zA-Z]+", s) is not None
```
|
74,575,794
|
Consider the following simple code:
```
import re
def my_match(s):
if re.match("^[a-zA-Z]+", s):
return True
else:
return False
```
Is there a way to collapse this in a single `return` statement? In `C` we could do for example:
```
return match("^[a-zA-Z]+", s) ? true : false;
```
Is there something similar in python?
|
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738154/"
] |
A more generell solution would be to use the following code line. It excludes a fit with length 0 as it specificly checks for the None statement. In this case an empty string is impossible but it is more explicit.
```py
return re.match("^[a-zA-Z]+", s) is not None
```
|
The other answers show the ternary equivalent in Python. But since Python also assigns `truthiness` to values and expressions, you could simply use:
```
my_match = lambda s : bool(re.match("^[a-zA-Z]+", s))
```
|
74,575,794
|
Consider the following simple code:
```
import re
def my_match(s):
if re.match("^[a-zA-Z]+", s):
return True
else:
return False
```
Is there a way to collapse this in a single `return` statement? In `C` we could do for example:
```
return match("^[a-zA-Z]+", s) ? true : false;
```
Is there something similar in python?
|
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738154/"
] |
A more generell solution would be to use the following code line. It excludes a fit with length 0 as it specificly checks for the None statement. In this case an empty string is impossible but it is more explicit.
```py
return re.match("^[a-zA-Z]+", s) is not None
```
|
`re.match()` returns a value that can be evaluated for *truthiness*. So if you don't need to return the *exact* values `True` and `False`, you can just directly return the result of the `match()` function:
```
def my_match(s):
return re.match("^[a-zA-Z]+", s)
```
And then the caller can say:
```
if my_match(x):
...
else:
...
```
Although in this specific case, `my_match()` becomes a mostly useless wrapper function, and you could just call `re.match(...)` directly.
```
if re.match(...):
...
else:
...
```
|
74,575,794
|
Consider the following simple code:
```
import re
def my_match(s):
if re.match("^[a-zA-Z]+", s):
return True
else:
return False
```
Is there a way to collapse this in a single `return` statement? In `C` we could do for example:
```
return match("^[a-zA-Z]+", s) ? true : false;
```
Is there something similar in python?
|
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738154/"
] |
Python also supports this, although the syntaxes is a little different than most languages.
```
import re
def my_match(s):
return True if re.match("^[a-zA-Z]+", s) else False
```
In general, the Python syntax is `val_when_true if cond else val_when_false`, compared to the `cond ? val_when_true : val_when_false` you see in other languages.
In your particular case though, you can just write:
```
import re
def my_match(s):
return bool(re.match("^[a-zA-Z]+", s))
```
|
The other answers show the ternary equivalent in Python. But since Python also assigns `truthiness` to values and expressions, you could simply use:
```
my_match = lambda s : bool(re.match("^[a-zA-Z]+", s))
```
|
74,575,794
|
Consider the following simple code:
```
import re
def my_match(s):
if re.match("^[a-zA-Z]+", s):
return True
else:
return False
```
Is there a way to collapse this in a single `return` statement? In `C` we could do for example:
```
return match("^[a-zA-Z]+", s) ? true : false;
```
Is there something similar in python?
|
2022/11/25
|
[
"https://Stackoverflow.com/questions/74575794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/738154/"
] |
Python also supports this, although the syntaxes is a little different than most languages.
```
import re
def my_match(s):
return True if re.match("^[a-zA-Z]+", s) else False
```
In general, the Python syntax is `val_when_true if cond else val_when_false`, compared to the `cond ? val_when_true : val_when_false` you see in other languages.
In your particular case though, you can just write:
```
import re
def my_match(s):
return bool(re.match("^[a-zA-Z]+", s))
```
|
`re.match()` returns a value that can be evaluated for *truthiness*. So if you don't need to return the *exact* values `True` and `False`, you can just directly return the result of the `match()` function:
```
def my_match(s):
return re.match("^[a-zA-Z]+", s)
```
And then the caller can say:
```
if my_match(x):
...
else:
...
```
Although in this specific case, `my_match()` becomes a mostly useless wrapper function, and you could just call `re.match(...)` directly.
```
if re.match(...):
...
else:
...
```
|
17,217,225
|
Consider:
```
>>> a = {'foo': {'bar': 3}}
>>> b = {'foo': {'bar': 3}}
>>> a == b
True
```
According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries.
What is actually happening here? Is Python recursively checking each element of the dictionaries to ensure equality? Is it making sure the keys are identically matched, and the values are also identically matched?
Is there documentation that specifies exactly what `==` on a dictionary means? Or whether I have to implement my own version of checking for equality?
(If the `==` operator works, why aren't dicts hashable? That is, why can't I create a set() of dicts, or use a dict as a dictionary key?)
|
2013/06/20
|
[
"https://Stackoverflow.com/questions/17217225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3788/"
] |
Python is recursively checking each element of the dictionaries to ensure equality. See the [C `dict_equal()` implementation](http://hg.python.org/cpython/file/6f535c725b27/Objects/dictobject.c#l1839), which checks each and every key and value (provided the dictionaries are the same length); if dictionary `b` has the same key, then a `PyObject_RichCompareBool` tests if the values match too; this is essentially a recursive call.
Dictionaries are not hashable because their [`__hash__` attribute is set to `None`](http://docs.python.org/2/reference/datamodel.html#object.__hash__), and most of all they are *mutable*, which is disallowed when used as a dictionary key.
If you were to use a dictionary as a key, and through an existing reference then change the key, then that key would no longer slot to the same position in the hash table. Using another, equal dictionary (be it equal to the unchanged dictionary or the changed dictionary) to try and retrieve the value would now no longer work because the wrong slot would be picked, or the key would no longer be equal.
|
The dictionaries are equal if they have the same keys and the same values for each corresponding key.
See some examples:
```
dict(a=1, b=2) == dict(a=2, b=1)
False
dict(a=1, b=2) == dict(a=1, b=2, c=0)
False
dict(a=1, b=2) == dict(b=2, a=1)
True
```
|
17,217,225
|
Consider:
```
>>> a = {'foo': {'bar': 3}}
>>> b = {'foo': {'bar': 3}}
>>> a == b
True
```
According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries.
What is actually happening here? Is Python recursively checking each element of the dictionaries to ensure equality? Is it making sure the keys are identically matched, and the values are also identically matched?
Is there documentation that specifies exactly what `==` on a dictionary means? Or whether I have to implement my own version of checking for equality?
(If the `==` operator works, why aren't dicts hashable? That is, why can't I create a set() of dicts, or use a dict as a dictionary key?)
|
2013/06/20
|
[
"https://Stackoverflow.com/questions/17217225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3788/"
] |
Python is recursively checking each element of the dictionaries to ensure equality. See the [C `dict_equal()` implementation](http://hg.python.org/cpython/file/6f535c725b27/Objects/dictobject.c#l1839), which checks each and every key and value (provided the dictionaries are the same length); if dictionary `b` has the same key, then a `PyObject_RichCompareBool` tests if the values match too; this is essentially a recursive call.
Dictionaries are not hashable because their [`__hash__` attribute is set to `None`](http://docs.python.org/2/reference/datamodel.html#object.__hash__), and most of all they are *mutable*, which is disallowed when used as a dictionary key.
If you were to use a dictionary as a key, and through an existing reference then change the key, then that key would no longer slot to the same position in the hash table. Using another, equal dictionary (be it equal to the unchanged dictionary or the changed dictionary) to try and retrieve the value would now no longer work because the wrong slot would be picked, or the key would no longer be equal.
|
From [docs](http://docs.python.org/2/reference/expressions.html#not-in):
>
> Mappings (dictionaries) compare equal if and only if their sorted
> (key, value) lists compare equal .[[5]](http://docs.python.org/2/reference/expressions.html#id24) Outcomes other than equality are
> resolved consistently, but are not otherwise defined. [[6]](http://docs.python.org/2/reference/expressions.html#id25)
>
>
>
Footnote [[5]](http://docs.python.org/2/reference/expressions.html#id24):
>
> The implementation computes this efficiently, without constructing
> lists or sorting.
>
>
>
Footnote [[6]](http://docs.python.org/2/reference/expressions.html#id25):
>
> Earlier versions of Python used lexicographic comparison of the sorted
> (key, value) lists, but this was very expensive for the common case of
> comparing for equality. An even earlier version of Python compared
> dictionaries by identity only, but this caused surprises because
> people expected to be able to test a dictionary for emptiness by
> comparing it to {}.
>
>
>
|
17,217,225
|
Consider:
```
>>> a = {'foo': {'bar': 3}}
>>> b = {'foo': {'bar': 3}}
>>> a == b
True
```
According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries.
What is actually happening here? Is Python recursively checking each element of the dictionaries to ensure equality? Is it making sure the keys are identically matched, and the values are also identically matched?
Is there documentation that specifies exactly what `==` on a dictionary means? Or whether I have to implement my own version of checking for equality?
(If the `==` operator works, why aren't dicts hashable? That is, why can't I create a set() of dicts, or use a dict as a dictionary key?)
|
2013/06/20
|
[
"https://Stackoverflow.com/questions/17217225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3788/"
] |
From [docs](http://docs.python.org/2/reference/expressions.html#not-in):
>
> Mappings (dictionaries) compare equal if and only if their sorted
> (key, value) lists compare equal .[[5]](http://docs.python.org/2/reference/expressions.html#id24) Outcomes other than equality are
> resolved consistently, but are not otherwise defined. [[6]](http://docs.python.org/2/reference/expressions.html#id25)
>
>
>
Footnote [[5]](http://docs.python.org/2/reference/expressions.html#id24):
>
> The implementation computes this efficiently, without constructing
> lists or sorting.
>
>
>
Footnote [[6]](http://docs.python.org/2/reference/expressions.html#id25):
>
> Earlier versions of Python used lexicographic comparison of the sorted
> (key, value) lists, but this was very expensive for the common case of
> comparing for equality. An even earlier version of Python compared
> dictionaries by identity only, but this caused surprises because
> people expected to be able to test a dictionary for emptiness by
> comparing it to {}.
>
>
>
|
The dictionaries are equal if they have the same keys and the same values for each corresponding key.
See some examples:
```
dict(a=1, b=2) == dict(a=2, b=1)
False
dict(a=1, b=2) == dict(a=1, b=2, c=0)
False
dict(a=1, b=2) == dict(b=2, a=1)
True
```
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
OPSIN (<https://opsin.ch.cam.ac.uk/>) is another solution for name2structure conversion.
It can be used by installing the cli, or via <https://github.com/gorgitko/molminer>
(OPSIN is used by the RDKit KNIME nodes also)
|
The accepted answer uses the [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) but for some reason the website seems to be buggy for me and the API seems to be messed up.
So another way to connvert smiles to IUPAC name is with the the PubChem python API, which can work if your smiles is in their database
e.g.
```
#!/usr/bin/env python
import sys
import pubchempy as pcp
smiles = str(sys.argv[1])
print(smiles)
s= pcp.get_compounds(smiles,'smiles')
print(s[0].iupac_name)
```
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
RDKit cant convert names to SMILES.
[Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) can convert names and other identifiers (like CAS No) and has an API so you can convert with a script.
```
from urllib.request import urlopen
from urllib.parse import quote
def CIRconvert(ids):
try:
url = 'http://cactus.nci.nih.gov/chemical/structure/' + quote(ids) + '/smiles'
ans = urlopen(url).read().decode('utf8')
return ans
except:
return 'Did not work'
identifiers = ['3-Methylheptane', 'Aspirin', 'Diethylsulfate', 'Diethyl sulfate', '50-78-2', 'Adamant']
for ids in identifiers :
print(ids, CIRconvert(ids))
```
Output
```
3-Methylheptane CCCCC(C)CC
Aspirin CC(=O)Oc1ccccc1C(O)=O
Diethylsulfate CCO[S](=O)(=O)OCC
Diethyl sulfate CCO[S](=O)(=O)OCC
50-78-2 CC(=O)Oc1ccccc1C(O)=O
Adamant Did not work
```
|
PubChemPy has some great features that can be used for this purpose. It supports IUPAC systematic names, trade names and all known synonyms for a given Compound as documented in PubChem database:
<https://pubchempy.readthedocs.io/en/latest/>
```
>>> import pubchempy as pcp
>>> results = pcp.get_compounds('Glucose', 'name')
>>> print results
[Compound(79025), Compound(5793), Compound(64689), Compound(206)]
```
The first argument is the identifier, and the second argument is the identifier type, which must be one of name, smiles, sdf, inchi, inchikey or formula. It looks like there are 4 compounds in the PubChem Database that have the name Glucose associated with them. Let’s take a look at them in more detail:
```
>>> for compound in results:
>>> print compound.isomeric_smiles
C([C@@H]1[C@H]([C@@H]([C@H]([C@H](O1)O)O)O)O)O
C([C@@H]1[C@H]([C@@H]([C@H](C(O1)O)O)O)O)O
C([C@@H]1[C@H]([C@@H]([C@H]([C@@H](O1)O)O)O)O)O
C(C1C(C(C(C(O1)O)O)O)O)O
```
It looks like they all have different stereochemistry information !
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
RDKit cant convert names to SMILES.
[Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) can convert names and other identifiers (like CAS No) and has an API so you can convert with a script.
```
from urllib.request import urlopen
from urllib.parse import quote
def CIRconvert(ids):
try:
url = 'http://cactus.nci.nih.gov/chemical/structure/' + quote(ids) + '/smiles'
ans = urlopen(url).read().decode('utf8')
return ans
except:
return 'Did not work'
identifiers = ['3-Methylheptane', 'Aspirin', 'Diethylsulfate', 'Diethyl sulfate', '50-78-2', 'Adamant']
for ids in identifiers :
print(ids, CIRconvert(ids))
```
Output
```
3-Methylheptane CCCCC(C)CC
Aspirin CC(=O)Oc1ccccc1C(O)=O
Diethylsulfate CCO[S](=O)(=O)OCC
Diethyl sulfate CCO[S](=O)(=O)OCC
50-78-2 CC(=O)Oc1ccccc1C(O)=O
Adamant Did not work
```
|
if you change the first line to:
from urllib2 import url open
it should work for python 2.7
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
PubChemPy has some great features that can be used for this purpose. It supports IUPAC systematic names, trade names and all known synonyms for a given Compound as documented in PubChem database:
<https://pubchempy.readthedocs.io/en/latest/>
```
>>> import pubchempy as pcp
>>> results = pcp.get_compounds('Glucose', 'name')
>>> print results
[Compound(79025), Compound(5793), Compound(64689), Compound(206)]
```
The first argument is the identifier, and the second argument is the identifier type, which must be one of name, smiles, sdf, inchi, inchikey or formula. It looks like there are 4 compounds in the PubChem Database that have the name Glucose associated with them. Let’s take a look at them in more detail:
```
>>> for compound in results:
>>> print compound.isomeric_smiles
C([C@@H]1[C@H]([C@@H]([C@H]([C@H](O1)O)O)O)O)O
C([C@@H]1[C@H]([C@@H]([C@H](C(O1)O)O)O)O)O
C([C@@H]1[C@H]([C@@H]([C@H]([C@@H](O1)O)O)O)O)O
C(C1C(C(C(C(O1)O)O)O)O)O
```
It looks like they all have different stereochemistry information !
|
You can use batch query of pubchem:
* <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange.cgi>
* <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange-help.html>
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
PubChemPy has some great features that can be used for this purpose. It supports IUPAC systematic names, trade names and all known synonyms for a given Compound as documented in PubChem database:
<https://pubchempy.readthedocs.io/en/latest/>
```
>>> import pubchempy as pcp
>>> results = pcp.get_compounds('Glucose', 'name')
>>> print results
[Compound(79025), Compound(5793), Compound(64689), Compound(206)]
```
The first argument is the identifier, and the second argument is the identifier type, which must be one of name, smiles, sdf, inchi, inchikey or formula. It looks like there are 4 compounds in the PubChem Database that have the name Glucose associated with them. Let’s take a look at them in more detail:
```
>>> for compound in results:
>>> print compound.isomeric_smiles
C([C@@H]1[C@H]([C@@H]([C@H]([C@H](O1)O)O)O)O)O
C([C@@H]1[C@H]([C@@H]([C@H](C(O1)O)O)O)O)O
C([C@@H]1[C@H]([C@@H]([C@H]([C@@H](O1)O)O)O)O)O
C(C1C(C(C(C(O1)O)O)O)O)O
```
It looks like they all have different stereochemistry information !
|
You can use the pubchem API (PUG REST) for this
(<https://pubchemdocs.ncbi.nlm.nih.gov/pug-rest-tutorial>)
Basically, the url you are calling will take the compound as a "name", you then give the name, then you specify that you want the "property" of "CanonicalSMILES", as text
```
identifiers = ['3-Methylheptane', 'Aspirin', 'Diethylsulfate', 'Diethyl sulfate', '50-78-2', 'Adamant']
smiles_df = pd.DataFrame(columns = ['Name', 'Smiles'])
for x in identifiers :
try:
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/' + x + '/property/CanonicalSMILES/TXT'
# remove new line character with rstrip
smiles = requests.get(url).text.rstrip()
if('NotFound' in smiles):
print(x, " not found")
else:
smiles_df = smiles_df.append({'Name' : x, 'Smiles' : smiles}, ignore_index = True)
except:
print("boo ", x)
print(smiles_df)
```
[](https://i.stack.imgur.com/p0IaK.png)
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
OPSIN (<https://opsin.ch.cam.ac.uk/>) is another solution for name2structure conversion.
It can be used by installing the cli, or via <https://github.com/gorgitko/molminer>
(OPSIN is used by the RDKit KNIME nodes also)
|
You can use the pubchem API (PUG REST) for this
(<https://pubchemdocs.ncbi.nlm.nih.gov/pug-rest-tutorial>)
Basically, the url you are calling will take the compound as a "name", you then give the name, then you specify that you want the "property" of "CanonicalSMILES", as text
```
identifiers = ['3-Methylheptane', 'Aspirin', 'Diethylsulfate', 'Diethyl sulfate', '50-78-2', 'Adamant']
smiles_df = pd.DataFrame(columns = ['Name', 'Smiles'])
for x in identifiers :
try:
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/' + x + '/property/CanonicalSMILES/TXT'
# remove new line character with rstrip
smiles = requests.get(url).text.rstrip()
if('NotFound' in smiles):
print(x, " not found")
else:
smiles_df = smiles_df.append({'Name' : x, 'Smiles' : smiles}, ignore_index = True)
except:
print("boo ", x)
print(smiles_df)
```
[](https://i.stack.imgur.com/p0IaK.png)
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
RDKit cant convert names to SMILES.
[Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) can convert names and other identifiers (like CAS No) and has an API so you can convert with a script.
```
from urllib.request import urlopen
from urllib.parse import quote
def CIRconvert(ids):
try:
url = 'http://cactus.nci.nih.gov/chemical/structure/' + quote(ids) + '/smiles'
ans = urlopen(url).read().decode('utf8')
return ans
except:
return 'Did not work'
identifiers = ['3-Methylheptane', 'Aspirin', 'Diethylsulfate', 'Diethyl sulfate', '50-78-2', 'Adamant']
for ids in identifiers :
print(ids, CIRconvert(ids))
```
Output
```
3-Methylheptane CCCCC(C)CC
Aspirin CC(=O)Oc1ccccc1C(O)=O
Diethylsulfate CCO[S](=O)(=O)OCC
Diethyl sulfate CCO[S](=O)(=O)OCC
50-78-2 CC(=O)Oc1ccccc1C(O)=O
Adamant Did not work
```
|
The accepted answer uses the [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) but for some reason the website seems to be buggy for me and the API seems to be messed up.
So another way to connvert smiles to IUPAC name is with the the PubChem python API, which can work if your smiles is in their database
e.g.
```
#!/usr/bin/env python
import sys
import pubchempy as pcp
smiles = str(sys.argv[1])
print(smiles)
s= pcp.get_compounds(smiles,'smiles')
print(s[0].iupac_name)
```
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
OPSIN (<https://opsin.ch.cam.ac.uk/>) is another solution for name2structure conversion.
It can be used by installing the cli, or via <https://github.com/gorgitko/molminer>
(OPSIN is used by the RDKit KNIME nodes also)
|
You can use batch query of pubchem:
* <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange.cgi>
* <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange-help.html>
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
RDKit cant convert names to SMILES.
[Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) can convert names and other identifiers (like CAS No) and has an API so you can convert with a script.
```
from urllib.request import urlopen
from urllib.parse import quote
def CIRconvert(ids):
try:
url = 'http://cactus.nci.nih.gov/chemical/structure/' + quote(ids) + '/smiles'
ans = urlopen(url).read().decode('utf8')
return ans
except:
return 'Did not work'
identifiers = ['3-Methylheptane', 'Aspirin', 'Diethylsulfate', 'Diethyl sulfate', '50-78-2', 'Adamant']
for ids in identifiers :
print(ids, CIRconvert(ids))
```
Output
```
3-Methylheptane CCCCC(C)CC
Aspirin CC(=O)Oc1ccccc1C(O)=O
Diethylsulfate CCO[S](=O)(=O)OCC
Diethyl sulfate CCO[S](=O)(=O)OCC
50-78-2 CC(=O)Oc1ccccc1C(O)=O
Adamant Did not work
```
|
You can use batch query of pubchem:
* <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange.cgi>
* <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange-help.html>
|
54,930,121
|
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated!
For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could do this and I was just unaware. My current data is in the csv format.
Thank you!
|
2019/02/28
|
[
"https://Stackoverflow.com/questions/54930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11131756/"
] |
PubChemPy has some great features that can be used for this purpose. It supports IUPAC systematic names, trade names and all known synonyms for a given Compound as documented in PubChem database:
<https://pubchempy.readthedocs.io/en/latest/>
```
>>> import pubchempy as pcp
>>> results = pcp.get_compounds('Glucose', 'name')
>>> print results
[Compound(79025), Compound(5793), Compound(64689), Compound(206)]
```
The first argument is the identifier, and the second argument is the identifier type, which must be one of name, smiles, sdf, inchi, inchikey or formula. It looks like there are 4 compounds in the PubChem Database that have the name Glucose associated with them. Let’s take a look at them in more detail:
```
>>> for compound in results:
>>> print compound.isomeric_smiles
C([C@@H]1[C@H]([C@@H]([C@H]([C@H](O1)O)O)O)O)O
C([C@@H]1[C@H]([C@@H]([C@H](C(O1)O)O)O)O)O
C([C@@H]1[C@H]([C@@H]([C@H]([C@@H](O1)O)O)O)O)O
C(C1C(C(C(C(O1)O)O)O)O)O
```
It looks like they all have different stereochemistry information !
|
The accepted answer uses the [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) but for some reason the website seems to be buggy for me and the API seems to be messed up.
So another way to connvert smiles to IUPAC name is with the the PubChem python API, which can work if your smiles is in their database
e.g.
```
#!/usr/bin/env python
import sys
import pubchempy as pcp
smiles = str(sys.argv[1])
print(smiles)
s= pcp.get_compounds(smiles,'smiles')
print(s[0].iupac_name)
```
|
46,289,914
|
I have python code as follow.
jv\_list is populated from resultset retrieve from D.B. query.
```
jv_list = list(result.get_points())
print(jv_list)
```
I am printing jv\_list and it is giving me below mention output.
```
[{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
```
How can i get division result which is actually second value divided by first value. for. `i.e. 79923888/ 19834`
|
2017/09/19
|
[
"https://Stackoverflow.com/questions/46289914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597746/"
] |
Try this sequence of commands
```
>>> X = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
>>> for x in X:
... x['answer'] = float(x['length-bytes'])/float(x['in'])
...
>>> X
[{'in': '19834', 'length-bytes': '79923888', 'run-time': '1h50m43.489993955s', 'time': '2017-09-08T21:20:39.846582783Z', 'answer': 4029.64041544822}]
```
|
You can't reliably do that, dictionaries are unordered.
With this data structure, you will need to address the elements via their keys.
that is `jv_list[0]['length_bytes'] / jv_list[0]['in']` for each pair of elements you want to divide by each other.
|
46,289,914
|
I have python code as follow.
jv\_list is populated from resultset retrieve from D.B. query.
```
jv_list = list(result.get_points())
print(jv_list)
```
I am printing jv\_list and it is giving me below mention output.
```
[{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
```
How can i get division result which is actually second value divided by first value. for. `i.e. 79923888/ 19834`
|
2017/09/19
|
[
"https://Stackoverflow.com/questions/46289914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597746/"
] |
If this is what you mean
```
x = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
for i in x:
print(float(i['length-bytes'])/float(i['in']))
```
results as
```
4029.64041544822
```
|
You can't reliably do that, dictionaries are unordered.
With this data structure, you will need to address the elements via their keys.
that is `jv_list[0]['length_bytes'] / jv_list[0]['in']` for each pair of elements you want to divide by each other.
|
46,289,914
|
I have python code as follow.
jv\_list is populated from resultset retrieve from D.B. query.
```
jv_list = list(result.get_points())
print(jv_list)
```
I am printing jv\_list and it is giving me below mention output.
```
[{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
```
How can i get division result which is actually second value divided by first value. for. `i.e. 79923888/ 19834`
|
2017/09/19
|
[
"https://Stackoverflow.com/questions/46289914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597746/"
] |
Try this sequence of commands
```
>>> X = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
>>> for x in X:
... x['answer'] = float(x['length-bytes'])/float(x['in'])
...
>>> X
[{'in': '19834', 'length-bytes': '79923888', 'run-time': '1h50m43.489993955s', 'time': '2017-09-08T21:20:39.846582783Z', 'answer': 4029.64041544822}]
```
|
If you want the result of `length-bytes / in`, you can use those keys and retrieve their values:
```
jv_list = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
result = float(jv_list[0]['length-bytes']) / float(jv_list[0]['in'])
print(result) # => 4029.64041544822
```
|
46,289,914
|
I have python code as follow.
jv\_list is populated from resultset retrieve from D.B. query.
```
jv_list = list(result.get_points())
print(jv_list)
```
I am printing jv\_list and it is giving me below mention output.
```
[{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
```
How can i get division result which is actually second value divided by first value. for. `i.e. 79923888/ 19834`
|
2017/09/19
|
[
"https://Stackoverflow.com/questions/46289914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597746/"
] |
Try this sequence of commands
```
>>> X = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
>>> for x in X:
... x['answer'] = float(x['length-bytes'])/float(x['in'])
...
>>> X
[{'in': '19834', 'length-bytes': '79923888', 'run-time': '1h50m43.489993955s', 'time': '2017-09-08T21:20:39.846582783Z', 'answer': 4029.64041544822}]
```
|
Based on your data structure it seems this would be the answer.
```
float(jv_list[0]['length-bytes']) / float(jv_list[0]['in'])
```
|
46,289,914
|
I have python code as follow.
jv\_list is populated from resultset retrieve from D.B. query.
```
jv_list = list(result.get_points())
print(jv_list)
```
I am printing jv\_list and it is giving me below mention output.
```
[{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
```
How can i get division result which is actually second value divided by first value. for. `i.e. 79923888/ 19834`
|
2017/09/19
|
[
"https://Stackoverflow.com/questions/46289914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597746/"
] |
If this is what you mean
```
x = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
for i in x:
print(float(i['length-bytes'])/float(i['in']))
```
results as
```
4029.64041544822
```
|
Try this sequence of commands
```
>>> X = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
>>> for x in X:
... x['answer'] = float(x['length-bytes'])/float(x['in'])
...
>>> X
[{'in': '19834', 'length-bytes': '79923888', 'run-time': '1h50m43.489993955s', 'time': '2017-09-08T21:20:39.846582783Z', 'answer': 4029.64041544822}]
```
|
46,289,914
|
I have python code as follow.
jv\_list is populated from resultset retrieve from D.B. query.
```
jv_list = list(result.get_points())
print(jv_list)
```
I am printing jv\_list and it is giving me below mention output.
```
[{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
```
How can i get division result which is actually second value divided by first value. for. `i.e. 79923888/ 19834`
|
2017/09/19
|
[
"https://Stackoverflow.com/questions/46289914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597746/"
] |
If this is what you mean
```
x = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
for i in x:
print(float(i['length-bytes'])/float(i['in']))
```
results as
```
4029.64041544822
```
|
If you want the result of `length-bytes / in`, you can use those keys and retrieve their values:
```
jv_list = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
result = float(jv_list[0]['length-bytes']) / float(jv_list[0]['in'])
print(result) # => 4029.64041544822
```
|
46,289,914
|
I have python code as follow.
jv\_list is populated from resultset retrieve from D.B. query.
```
jv_list = list(result.get_points())
print(jv_list)
```
I am printing jv\_list and it is giving me below mention output.
```
[{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
```
How can i get division result which is actually second value divided by first value. for. `i.e. 79923888/ 19834`
|
2017/09/19
|
[
"https://Stackoverflow.com/questions/46289914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597746/"
] |
If this is what you mean
```
x = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}]
for i in x:
print(float(i['length-bytes'])/float(i['in']))
```
results as
```
4029.64041544822
```
|
Based on your data structure it seems this would be the answer.
```
float(jv_list[0]['length-bytes']) / float(jv_list[0]['in'])
```
|
30,702,519
|
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between:
```
#!/bin/bash
#your bash code
python -c "
#your py code
"
```
vs
```
python - <<DOC
#your py code
DOC
```
I checked the web but couldn't compile the bits around the topic. Do you think one is better over the other?
If you wanted to return a value from Python code block to your Bash script then is a heredoc the only way?
|
2015/06/08
|
[
"https://Stackoverflow.com/questions/30702519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3598271/"
] |
The main flaw of using a here document is that the script's standard input will be the here document. So if you have a script which wants to process its standard input, `python -c` is pretty much your only option.
On the other hand, using `python -c '...'` ties up the single-quote for the shell's needs, so you can only use double-quoted strings in your Python script; using double-quotes instead to protect the script from the shell introduces additional problems (strings in double-quotes undergo various substitutions, whereas single-quoted strings are literal in the shell).
As an aside, notice that you probably want to single-quote the here-doc delimiter, too, otherwise the Python script is subject to similar substitutions.
```
python - <<'____HERE'
print("""Look, we can have double quotes!""")
print('And single quotes! And `back ticks`!')
print("$(and what looks to the shell like process substitutions and $variables!)")
____HERE
```
As an alternative, escaping the delimiter works identically, if you prefer that (`python - <<\____HERE`)
|
If you prefer to use `python -c '...'` without having to escape with the double-quotes you can first load the code in a bash variable using here-documents:
```
read -r -d '' CMD << '--END'
print ("'quoted'")
--END
python -c "$CMD"
```
The python code is loaded verbatim into the CMD variable and there's no need to escape double quotes.
|
30,702,519
|
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between:
```
#!/bin/bash
#your bash code
python -c "
#your py code
"
```
vs
```
python - <<DOC
#your py code
DOC
```
I checked the web but couldn't compile the bits around the topic. Do you think one is better over the other?
If you wanted to return a value from Python code block to your Bash script then is a heredoc the only way?
|
2015/06/08
|
[
"https://Stackoverflow.com/questions/30702519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3598271/"
] |
The main flaw of using a here document is that the script's standard input will be the here document. So if you have a script which wants to process its standard input, `python -c` is pretty much your only option.
On the other hand, using `python -c '...'` ties up the single-quote for the shell's needs, so you can only use double-quoted strings in your Python script; using double-quotes instead to protect the script from the shell introduces additional problems (strings in double-quotes undergo various substitutions, whereas single-quoted strings are literal in the shell).
As an aside, notice that you probably want to single-quote the here-doc delimiter, too, otherwise the Python script is subject to similar substitutions.
```
python - <<'____HERE'
print("""Look, we can have double quotes!""")
print('And single quotes! And `back ticks`!')
print("$(and what looks to the shell like process substitutions and $variables!)")
____HERE
```
As an alternative, escaping the delimiter works identically, if you prefer that (`python - <<\____HERE`)
|
If you are using bash, you can avoid heredoc problems if you apply a little bit more of boilerplate:
```
python <(cat <<EoF
name = input()
print(f'hello, {name}!')
EoF
)
```
This will let you run your embedded Python script without you giving up the standard input. The overhead is mostly the same of using `cmda | cmdb`. [This technique is known as Process Substitution](http://tldp.org/LDP/abs/html/process-sub.html).
If want to be able to somehow validate the script, I suggest that you dump it to a temporary file:
```
#!/bin/bash
temp_file=$(mktemp my_generated_python_script.XXXXXX.py)
cat > $temp_file <<EoF
# embedded python script
EoF
python3 $temp_file && rm $temp_file
```
This will keep the script if it fails to run.
|
30,702,519
|
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between:
```
#!/bin/bash
#your bash code
python -c "
#your py code
"
```
vs
```
python - <<DOC
#your py code
DOC
```
I checked the web but couldn't compile the bits around the topic. Do you think one is better over the other?
If you wanted to return a value from Python code block to your Bash script then is a heredoc the only way?
|
2015/06/08
|
[
"https://Stackoverflow.com/questions/30702519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3598271/"
] |
The main flaw of using a here document is that the script's standard input will be the here document. So if you have a script which wants to process its standard input, `python -c` is pretty much your only option.
On the other hand, using `python -c '...'` ties up the single-quote for the shell's needs, so you can only use double-quoted strings in your Python script; using double-quotes instead to protect the script from the shell introduces additional problems (strings in double-quotes undergo various substitutions, whereas single-quoted strings are literal in the shell).
As an aside, notice that you probably want to single-quote the here-doc delimiter, too, otherwise the Python script is subject to similar substitutions.
```
python - <<'____HERE'
print("""Look, we can have double quotes!""")
print('And single quotes! And `back ticks`!')
print("$(and what looks to the shell like process substitutions and $variables!)")
____HERE
```
As an alternative, escaping the delimiter works identically, if you prefer that (`python - <<\____HERE`)
|
How to use here-docs with input
===============================
[tripleee's answer](https://stackoverflow.com/a/30703682/1136208) has all the details, but there's Unix tricks to work around this limitation:
>
> So if you have a script which wants to process its standard input, `python -c` is pretty much your only option.
>
>
>
This trick applies to all programs that want to read from a redirected stdin (e.g., `./script.py < myinputs`) and *also* take user input:
```
python - <<'____HERE'
import os
os.dup2(1, 0)
print(input("--> "))
____HERE
```
Running this works:
```
$ bash heredocpy.sh
--> Hello World!
Hello World!
```
If you want to get the original stdin, run `os.dup(0)` first. [Here](https://github.com/facebookresearch/nle/blob/main/nle/scripts/ttyplay.py#L190) is a real-world example.
---
This works because as long as either stdout or stderr are a tty, one can read from them as well as write to them. (Otherwise, you could just open `/dev/tty`. This is what `less` does.)
In case you want to process inputs from a file instead, that's possible too -- you just have to use a new fd:
Example with a file
-------------------
```
cat <<'____HERE' > file.txt
With software there are only two possibilites:
either the users control the programme
or the programme controls the users.
____HERE
python - <<'____HERE' 4< file.txt
import os
for line in os.fdopen(4):
print(line.rstrip().upper())
____HERE
```
Example with a command
----------------------
Unfortunately, pipelines don't work here -- but [process substitution](https://tldp.org/LDP/abs/html/process-sub.html) does:
```
python - <<'____HERE' 4< <(fortune)
import os
for line in os.fdopen(4):
print(line.rstrip().upper())
____HERE
```
|
30,702,519
|
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between:
```
#!/bin/bash
#your bash code
python -c "
#your py code
"
```
vs
```
python - <<DOC
#your py code
DOC
```
I checked the web but couldn't compile the bits around the topic. Do you think one is better over the other?
If you wanted to return a value from Python code block to your Bash script then is a heredoc the only way?
|
2015/06/08
|
[
"https://Stackoverflow.com/questions/30702519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3598271/"
] |
If you prefer to use `python -c '...'` without having to escape with the double-quotes you can first load the code in a bash variable using here-documents:
```
read -r -d '' CMD << '--END'
print ("'quoted'")
--END
python -c "$CMD"
```
The python code is loaded verbatim into the CMD variable and there's no need to escape double quotes.
|
How to use here-docs with input
===============================
[tripleee's answer](https://stackoverflow.com/a/30703682/1136208) has all the details, but there's Unix tricks to work around this limitation:
>
> So if you have a script which wants to process its standard input, `python -c` is pretty much your only option.
>
>
>
This trick applies to all programs that want to read from a redirected stdin (e.g., `./script.py < myinputs`) and *also* take user input:
```
python - <<'____HERE'
import os
os.dup2(1, 0)
print(input("--> "))
____HERE
```
Running this works:
```
$ bash heredocpy.sh
--> Hello World!
Hello World!
```
If you want to get the original stdin, run `os.dup(0)` first. [Here](https://github.com/facebookresearch/nle/blob/main/nle/scripts/ttyplay.py#L190) is a real-world example.
---
This works because as long as either stdout or stderr are a tty, one can read from them as well as write to them. (Otherwise, you could just open `/dev/tty`. This is what `less` does.)
In case you want to process inputs from a file instead, that's possible too -- you just have to use a new fd:
Example with a file
-------------------
```
cat <<'____HERE' > file.txt
With software there are only two possibilites:
either the users control the programme
or the programme controls the users.
____HERE
python - <<'____HERE' 4< file.txt
import os
for line in os.fdopen(4):
print(line.rstrip().upper())
____HERE
```
Example with a command
----------------------
Unfortunately, pipelines don't work here -- but [process substitution](https://tldp.org/LDP/abs/html/process-sub.html) does:
```
python - <<'____HERE' 4< <(fortune)
import os
for line in os.fdopen(4):
print(line.rstrip().upper())
____HERE
```
|
30,702,519
|
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between:
```
#!/bin/bash
#your bash code
python -c "
#your py code
"
```
vs
```
python - <<DOC
#your py code
DOC
```
I checked the web but couldn't compile the bits around the topic. Do you think one is better over the other?
If you wanted to return a value from Python code block to your Bash script then is a heredoc the only way?
|
2015/06/08
|
[
"https://Stackoverflow.com/questions/30702519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3598271/"
] |
If you are using bash, you can avoid heredoc problems if you apply a little bit more of boilerplate:
```
python <(cat <<EoF
name = input()
print(f'hello, {name}!')
EoF
)
```
This will let you run your embedded Python script without you giving up the standard input. The overhead is mostly the same of using `cmda | cmdb`. [This technique is known as Process Substitution](http://tldp.org/LDP/abs/html/process-sub.html).
If want to be able to somehow validate the script, I suggest that you dump it to a temporary file:
```
#!/bin/bash
temp_file=$(mktemp my_generated_python_script.XXXXXX.py)
cat > $temp_file <<EoF
# embedded python script
EoF
python3 $temp_file && rm $temp_file
```
This will keep the script if it fails to run.
|
How to use here-docs with input
===============================
[tripleee's answer](https://stackoverflow.com/a/30703682/1136208) has all the details, but there's Unix tricks to work around this limitation:
>
> So if you have a script which wants to process its standard input, `python -c` is pretty much your only option.
>
>
>
This trick applies to all programs that want to read from a redirected stdin (e.g., `./script.py < myinputs`) and *also* take user input:
```
python - <<'____HERE'
import os
os.dup2(1, 0)
print(input("--> "))
____HERE
```
Running this works:
```
$ bash heredocpy.sh
--> Hello World!
Hello World!
```
If you want to get the original stdin, run `os.dup(0)` first. [Here](https://github.com/facebookresearch/nle/blob/main/nle/scripts/ttyplay.py#L190) is a real-world example.
---
This works because as long as either stdout or stderr are a tty, one can read from them as well as write to them. (Otherwise, you could just open `/dev/tty`. This is what `less` does.)
In case you want to process inputs from a file instead, that's possible too -- you just have to use a new fd:
Example with a file
-------------------
```
cat <<'____HERE' > file.txt
With software there are only two possibilites:
either the users control the programme
or the programme controls the users.
____HERE
python - <<'____HERE' 4< file.txt
import os
for line in os.fdopen(4):
print(line.rstrip().upper())
____HERE
```
Example with a command
----------------------
Unfortunately, pipelines don't work here -- but [process substitution](https://tldp.org/LDP/abs/html/process-sub.html) does:
```
python - <<'____HERE' 4< <(fortune)
import os
for line in os.fdopen(4):
print(line.rstrip().upper())
____HERE
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.