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 |
|---|---|---|---|---|---|
48,275,466 | I was trying to install [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-install-macos.html) on mac but was facing some challenges as aws command was unable to parse the credential file. So I decided to re-install the whole stuff but facing some issues here again.
I am trying `pip uninstall awscli` which... | 2018/01/16 | [
"https://Stackoverflow.com/questions/48275466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471314/"
] | You run **pip3** `install awscli` but **pip** `uninstall awscli`. Shouldn't it be **pip3** `uninstall awscli`? | I had a similar issue.
And I used the following command to fix it.
```
pip3 install --no-cache-dir awscli==1.14.39
``` |
52,977,914 | I'm trying to segment the numbers and/or characters of the following image then converting each individual num/char to text using ocr:
[](https://i.stack.imgur.com/rWMEa.png)
This is the code (in python) used:
```
new, contours, hierarchy = cv2.fin... | 2018/10/24 | [
"https://Stackoverflow.com/questions/52977914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1261829/"
] | As far as I know, most of OpenCV methods for binary images operate `white objects on the black background`.
Src:
[](https://i.stack.imgur.com/fc1Ld.png)
Threahold INV and morph-open:
[
new, contours, hierarchy = cv2.findContours(gray, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(gray, contours, -1, 127, 5)
digitCnts = []
final = gray.copy()
# loop over ... |
9,101,800 | So I've been experimenting with numpy and matplotlib and have stumbled across some bug when running python from the emacs inferior shell.
When I send the py file to the shell interpreter I can run commands after the code executed. The command prompt ">>>" appears fine. However, after I invoke a matplotlib show command... | 2012/02/01 | [
"https://Stackoverflow.com/questions/9101800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752726/"
] | I think there are two ways to do it.
1. Use ipython. Then you can use `-pylab` option.
I don't use Fabian Gallina's python.el, but I guess you will need something like this:
```
(setq python-shell-interpreter-args "-pylab")
```
Please read the documentation of python.el.
2. You can manually activate interactive mod... | I think that this might have something to do with the behavior of the show function:
>
> [matplotlib.pyplot.show(\*args, \*\*kw)](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.show)
>
>
> When running in ipython with its pylab mode, display all figures and
> return to the ipython prompt.
... |
9,101,800 | So I've been experimenting with numpy and matplotlib and have stumbled across some bug when running python from the emacs inferior shell.
When I send the py file to the shell interpreter I can run commands after the code executed. The command prompt ">>>" appears fine. However, after I invoke a matplotlib show command... | 2012/02/01 | [
"https://Stackoverflow.com/questions/9101800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752726/"
] | You can use different back-end:
```
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
```
Other GUI backends:
* `TkAgg`
* `WX`
* `QTAgg`
* `QT4Agg`
If you are using Elpy run your code using `C-u C-c C-c` | I think that this might have something to do with the behavior of the show function:
>
> [matplotlib.pyplot.show(\*args, \*\*kw)](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.show)
>
>
> When running in ipython with its pylab mode, display all figures and
> return to the ipython prompt.
... |
9,101,800 | So I've been experimenting with numpy and matplotlib and have stumbled across some bug when running python from the emacs inferior shell.
When I send the py file to the shell interpreter I can run commands after the code executed. The command prompt ">>>" appears fine. However, after I invoke a matplotlib show command... | 2012/02/01 | [
"https://Stackoverflow.com/questions/9101800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752726/"
] | I think there are two ways to do it.
1. Use ipython. Then you can use `-pylab` option.
I don't use Fabian Gallina's python.el, but I guess you will need something like this:
```
(setq python-shell-interpreter-args "-pylab")
```
Please read the documentation of python.el.
2. You can manually activate interactive mod... | I think I have found an even simpler way to hang the inferior shell but only when pdb is invoked. Start pdb by supplying 'python' as the program to run.
Try this code:
```
print "> {<console>(1)<module>() }"
``` |
9,101,800 | So I've been experimenting with numpy and matplotlib and have stumbled across some bug when running python from the emacs inferior shell.
When I send the py file to the shell interpreter I can run commands after the code executed. The command prompt ">>>" appears fine. However, after I invoke a matplotlib show command... | 2012/02/01 | [
"https://Stackoverflow.com/questions/9101800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752726/"
] | I think there are two ways to do it.
1. Use ipython. Then you can use `-pylab` option.
I don't use Fabian Gallina's python.el, but I guess you will need something like this:
```
(setq python-shell-interpreter-args "-pylab")
```
Please read the documentation of python.el.
2. You can manually activate interactive mod... | Well after a tremendous amount of time and posting the bug on the matplotlib project page and the python-mode page I found out that supplying the arguments console --matplotlib in ipython.bat will do the trick with matplotlib 1.3.1 and ipython 1.2.0
This is what I have in my iphython.bat
@python.exe -i D:\devel\Pytho... |
9,101,800 | So I've been experimenting with numpy and matplotlib and have stumbled across some bug when running python from the emacs inferior shell.
When I send the py file to the shell interpreter I can run commands after the code executed. The command prompt ">>>" appears fine. However, after I invoke a matplotlib show command... | 2012/02/01 | [
"https://Stackoverflow.com/questions/9101800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752726/"
] | I think there are two ways to do it.
1. Use ipython. Then you can use `-pylab` option.
I don't use Fabian Gallina's python.el, but I guess you will need something like this:
```
(setq python-shell-interpreter-args "-pylab")
```
Please read the documentation of python.el.
2. You can manually activate interactive mod... | You can use different back-end:
```
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
```
Other GUI backends:
* `TkAgg`
* `WX`
* `QTAgg`
* `QT4Agg`
If you are using Elpy run your code using `C-u C-c C-c` |
9,101,800 | So I've been experimenting with numpy and matplotlib and have stumbled across some bug when running python from the emacs inferior shell.
When I send the py file to the shell interpreter I can run commands after the code executed. The command prompt ">>>" appears fine. However, after I invoke a matplotlib show command... | 2012/02/01 | [
"https://Stackoverflow.com/questions/9101800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752726/"
] | You can use different back-end:
```
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
```
Other GUI backends:
* `TkAgg`
* `WX`
* `QTAgg`
* `QT4Agg`
If you are using Elpy run your code using `C-u C-c C-c` | I think I have found an even simpler way to hang the inferior shell but only when pdb is invoked. Start pdb by supplying 'python' as the program to run.
Try this code:
```
print "> {<console>(1)<module>() }"
``` |
9,101,800 | So I've been experimenting with numpy and matplotlib and have stumbled across some bug when running python from the emacs inferior shell.
When I send the py file to the shell interpreter I can run commands after the code executed. The command prompt ">>>" appears fine. However, after I invoke a matplotlib show command... | 2012/02/01 | [
"https://Stackoverflow.com/questions/9101800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752726/"
] | You can use different back-end:
```
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
```
Other GUI backends:
* `TkAgg`
* `WX`
* `QTAgg`
* `QT4Agg`
If you are using Elpy run your code using `C-u C-c C-c` | Well after a tremendous amount of time and posting the bug on the matplotlib project page and the python-mode page I found out that supplying the arguments console --matplotlib in ipython.bat will do the trick with matplotlib 1.3.1 and ipython 1.2.0
This is what I have in my iphython.bat
@python.exe -i D:\devel\Pytho... |
58,498,100 | I have a complicated nested numpy array which contains list. I am trying to converted the elements to float32. However, it gives me following error:
```
ValueError Traceback (most recent call last)
<ipython-input-225-22d2824961c2> in <module>
----> 1 x_train_single.astype(np.float32)
Va... | 2019/10/22 | [
"https://Stackoverflow.com/questions/58498100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1584253/"
] | As your array contains lists of different sizes and nesting depths, I doubt that there is a simple or fast solution.
Here is a "get-the-job-done-no-matter-what" approach. It comes in two flavors. One creates arrays for leaves, the other one lists.
```
>>> a
array([[list([[[0, 0, 0, 0, 0, 0]], [-1.0], [0]]),
l... | if number of columns is fixed then
```
np.array([l.astype(np.float) for l in x_train_single.squeeze()])
```
But it will remove the redundant dimensions, convert everything into numpy array.
Before: (1, 1, 1, 11, 6)
After: (11,6) |
58,498,100 | I have a complicated nested numpy array which contains list. I am trying to converted the elements to float32. However, it gives me following error:
```
ValueError Traceback (most recent call last)
<ipython-input-225-22d2824961c2> in <module>
----> 1 x_train_single.astype(np.float32)
Va... | 2019/10/22 | [
"https://Stackoverflow.com/questions/58498100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1584253/"
] | As your array contains lists of different sizes and nesting depths, I doubt that there is a simple or fast solution.
Here is a "get-the-job-done-no-matter-what" approach. It comes in two flavors. One creates arrays for leaves, the other one lists.
```
>>> a
array([[list([[[0, 0, 0, 0, 0, 0]], [-1.0], [0]]),
l... | Try this:
```
np.array(x_train_single.tolist())
```
Looks like you have a (1,1) shaped array, where the single element is a list. And the sublists a consistent in size.
I expect you will get an array with shape (1, 1, 1, 11, 6) and int dtype.
or:
```
np.array(x_train_single[0,0])
```
Again this extracts the... |
18,662,264 | from the documents, the urllib.unquote\_plus should replce plus signs by spaces.
but when I tried the below code in IDLE for python 2.7, it did not.
```
>>s = 'http://stackoverflow.com/questions/?q1=xx%2Bxx%2Bxx'
>>urllib.unquote_plus(s)
>>'http://stackoverflow.com/questions/?q1=xx+xx+xx'
```
I also tried doing some... | 2013/09/06 | [
"https://Stackoverflow.com/questions/18662264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/251024/"
] | `%2B` is the escape code for a *literal* `+`; it is being unescaped entirely correctly.
Don't confuse this with the *URL escaped* `+`, which is the escape character for spaces:
```
>>> s = 'http://stackoverflow.com/questions/?q1=xx+xx+xx'
>>> urllib.parse.unquote_plus(s)
'http://stackoverflow.com/questions/?q1=xx xx ... | Those aren't spaces, those are actual pluses. A space is %20, which in that part of the URL is indeed equivalent to +, but %2B means a literal plus. |
34,495,839 | I saw the following coding gif, which depicts a user typing commands (e.g. `import`) and a pop up message would describe the usage for that command.
How can I set up something similar?[](https://i.stack.imgur.com/7OUwv.gif) | 2015/12/28 | [
"https://Stackoverflow.com/questions/34495839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2636317/"
] | According to the github issues in the repo of that gif, the video was taken using [bpython](http://bpython-interpreter.org)
Source: <https://github.com/tqdm/tqdm/issues/67> | Code editors like [`vim`](http://www.vim.org/) (with [`jedi`](https://github.com/davidhalter/jedi-vim) or [`python-mode`](https://github.com/klen/python-mode.git)) or [`emacs`](https://www.gnu.org/software/emacs/) and integrated development environments like [`pycharm`](https://www.jetbrains.com/pycharm/) can offer the... |
51,060,433 | I coded a jQuery with flask where on-click it should perform an SQL search and export the dataframe as excel, the script is:
```
<script type=text/javascript>
$(function () {
$('a#export_to_excel').bind('click', function () {
$.getJSON($SCRIPT_ROOT + ' /api/sanctionsSearch/download', {
nm: $('... | 2018/06/27 | [
"https://Stackoverflow.com/questions/51060433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9979747/"
] | The solution is not ideal, but what I did is adding a window.open(url) command in the jquery which will call another function, this function will send\_file to the user. | You should use return statement
```
return send_file()
``` |
59,959,629 | I've been stuck on this for the last week and I'm fairly lost as to what do for next steps.
I have a Django application that uses a MySQL database. I've deployed it using AWS Elastic Beanstalk using the following tutorial : <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html>
It s... | 2020/01/29 | [
"https://Stackoverflow.com/questions/59959629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3310212/"
] | This should be sufficient to hide all but one sheet.
```
function hideAllSheetsExceptThisOne(sheetName) {
var sheetName=sh||'Student Report';//default for testing
var ss = SpreadsheetApp.getActive();
var sheets=ss.getSheets();
for(var i=0;i<sheets.length; i++){
if(sheets[i].getName()!=sheetName){
she... | I had to do something similar earlier this year, and this code proved to be very helpful. <https://gist.github.com/ixhd/3660885> |
67,111,664 | I created a little app with Python as backend and React as frontend. I receive some data from the frontend and I want to eliminate the first 20 words of the text I receive if a condition is satisfyed.
```
@app.route("/translate", methods=["GET", "POST"])
def translate():
prompt = request.json["prompt"]
max_tokens... | 2021/04/15 | [
"https://Stackoverflow.com/questions/67111664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14880010/"
] | ```
import pandas as pd
```
Use `to_datetime()` method and convert your date column from string to datetime:
```
df['Date']=pd.to_datetime(df['Date'])
```
Finally use `apply()` method:
```
df['comm0']=df['Date'].apply(lambda x:1 if x==pd.to_datetime('2021-01-07') else 0)
```
Or as suggested by @anky:
Simply us... | It's a problem with types.
df['Date'] is a string and not a datetime object, so when you compare each element with '2021-01-07' (another string) they differ because the time informations (00:00:00).
as solution you can convert elements to datetime, as following:
```
def int_21(x):
if x == pd.to_datetime('2021-01... |
39,815,551 | I am trying to make a program in python that will accept a user's input and check if it is a Kaprekar number.
I'm still a beginner, and have been having a lot of issues, but my main issue now that I can't seem to solve is how I would add up all possibilities in a list, with only two variables. I'm probably not explaini... | 2016/10/02 | [
"https://Stackoverflow.com/questions/39815551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Say you start with
```
a = ['2', '0', '2', '5']
```
Then you can run
```
>>> [(a[: i], a[i: ]) for i in range(1, len(a))]
[(['2'], ['0', '2', '5']), (['2', '0'], ['2', '5']), (['2', '0', '2'], ['5'])]
```
to obtain all the possible contiguous splits.
If you want to process it further, you can change it to numb... | Not a direct answer to your question, but you can write an expression to determine whether a number, N, is a Krapekar number more concisely.
```
>>> N=45
>>> digits=str(N**2)
>>> Krapekar=any([N==int(digits[:_])+int(digits[_:]) for _ in range(1,len(digits))])
>>> Krapekar
True
``` |
8,827,304 | I'm using Plone v4.1.2, and I'd like to know if there a way to include more than one author in the by line of a page? I have two authors listed in ownership, but only one author is listed in the byline.
I'd like the byline to look something like this:
by First Author and Second Author — last modified Jan 11, 2012 01:... | 2012/01/11 | [
"https://Stackoverflow.com/questions/8827304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144225/"
] | In order to browse more than one author you'll need a little bit of coding:
That piece of page is called `viewlets`.
That specific viewlet is called `plone.belowcontenttitle.documentbyline`.
You can use [z3c.jbot](http://pypi.python.org/pypi/z3c.jbot) to override the viewlet template. Take a look at [this howto](htt... | you could use the contributors- instead of the owners-field. they are listed by default in the docByLine. hth, i |
65,433,038 | So I'm trying to run Django developing server on a container but I can't access it through my browser. I have 2 containers using the same docker network, one with postgress and the other is Django. I manage to ping both containers and successfully connect 2 of them together and run `./manage.py runserver` ok but can't ... | 2020/12/24 | [
"https://Stackoverflow.com/questions/65433038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11386561/"
] | Think of it this way:
Your React application is the U-Haul truck that delivers **everything** from the Web Server (Back-End) to the Browser (Front-End)

Now you say you want everything wrapped in a (native) Web Component:
`<move-house></move-house>`
It is do-able, but you as ... | It is possible in react using direflow. <https://direflow.io/> |
19,037,928 | I am using python + beautifulsoup to parse html. My problem is that I have a variable amount of text items. In this case, for example, I want to extract 'Text 1', 'Text 2', ... 'Text 4'. In other webpages, there may be only 'Text 1' or possibly two, etc. So it changes. If the 'Text x's were contained in a tag, it would... | 2013/09/26 | [
"https://Stackoverflow.com/questions/19037928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2049545/"
] | You might try something like this:
```
>>> test ="""<b>Header 1</b>
<br/>
Text 1
<br/>
Text 2
<br/>
Text 3
<br/>
Text 4
<br/>
<b>Header 2</b>"""
>>> soup = BeautifulSoup(test)
>>> test = soup.find('b')
>>> desired_text = [x.strip() for x in str(test.parent).split('<br />')]
['<b>Header 1</b>', 'Text 1', 'Text 2', 'Te... | Here is a different solution. nextSibling can get parts of the structured document that follow a named tag.
```
from BeautifulSoup import BeautifulSoup
text="""
<b>Header 1</b>
<br/>
Text 1
<br/>
Text 2
<br/>
Text 3
<br/>
Text 4
<br/>
<b>Header 2</b>
"""
soup = BeautifulSoup(text)
for br in soup.findAll('br'):
... |
19,037,928 | I am using python + beautifulsoup to parse html. My problem is that I have a variable amount of text items. In this case, for example, I want to extract 'Text 1', 'Text 2', ... 'Text 4'. In other webpages, there may be only 'Text 1' or possibly two, etc. So it changes. If the 'Text x's were contained in a tag, it would... | 2013/09/26 | [
"https://Stackoverflow.com/questions/19037928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2049545/"
] | You can just combine everything using `get_text`:
```
test ="""<div id='DIVID'>
<b>Header 1</b>
<br/>
Text 1
<br/>
Text 2
<br/>
Text 3
<br/>
Text 4
<br/>
<b>Header 2</b>
</div>"""
def divid(tag):
return tag.name=='div' and tag.has_attr('id') and tag['id'].startswith('DIVID')
soup = BeautifulSoup(test)
print soup... | Here is a different solution. nextSibling can get parts of the structured document that follow a named tag.
```
from BeautifulSoup import BeautifulSoup
text="""
<b>Header 1</b>
<br/>
Text 1
<br/>
Text 2
<br/>
Text 3
<br/>
Text 4
<br/>
<b>Header 2</b>
"""
soup = BeautifulSoup(text)
for br in soup.findAll('br'):
... |
10,899,197 | ```
#include <ext/hash_map>
using namespace std;
class hash_t : public __gnu_cxx::hash_map<const char*, list<time_t> > { };
hash_t hash;
...
```
I'm having some problems using this hash\_map. The const char\* im using as a key is always a 12 length number with this format 58412xxxxxxx. I know there are 483809 diff... | 2012/06/05 | [
"https://Stackoverflow.com/questions/10899197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430913/"
] | `const char*` is not good for a key, since you now have pointer comparison instead of string comparison (also, you probably have dangling pointers, the return value of `c_str()` is not usable long-term).
Use `hash_map<std::string, list<time_t> >` instead. | If your key is `char*`, you are comparing no the strings, but pointers, which makes your hashmap work differently than what you expect. Consider using `const std::string` for the keys, so they are compared using lexicographical ordering |
39,599,596 | I´m writing a simple calculator program that will let a user add a list of integers together as a kind of entry to the syntax of python. I want the program to allow the user to add as many numbers together as they want. My error is:
```
Traceback (most recent call last):
File "Calculator.py", line 17, in <module>
... | 2016/09/20 | [
"https://Stackoverflow.com/questions/39599596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6854420/"
] | [`raw_input`](https://docs.python.org/2/library/functions.html#raw_input) returns strings, not numbers. [`sum`](https://docs.python.org/2/library/functions.html#sum) operates only on numbers.
You can convert each item to an int as you add it to the list: `inputs.append(int(value))`. If you use `float` rather than `int... | When using `raw_input()` you're storing a string in `value`. Convert it to an int before appending it to your list, e.g.
```
inputs.append( int( value ) )
``` |
63,640,435 | SSO is not enabled for bot on Teams channel.
I develop a bot on Bot Framework and Azure Service, using python 3.7. I needed user authentication in the Microsoft system to use Graph API, etc.
Previously successfully used the [example](https://github.com/microsoft/BotBuilder-Samples/tree/main/samples/python) 18.bot-aut... | 2020/08/28 | [
"https://Stackoverflow.com/questions/63640435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13382091/"
] | Please check the following articles:
<https://learn.microsoft.com/en-us/power-virtual-agents/advanced-end-user-authentication>
<https://learn.microsoft.com/en-us/power-virtual-agents/configuration-end-user-authentication>
<https://learn.microsoft.com/en-us/power-virtual-agents/publication-add-bot-to-microsoft-teams>
... | Please refer to the Teams-Auth [sample](https://github.com/microsoft/BotBuilder-Samples/tree/main/samples/python/46.teams-auth) and the [documentation](https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/add-authentication?tabs=dotnet%2Cdotnet-sample) which helps you get started with au... |
24,136,733 | ```
process_name = "CCC.exe"
for proc in psutil.process_iter():
if proc.name == process_name:
print ("have")
else:
print ("Dont have")
```
I know for the fact that CCC.exe is running. I tried this code with both 2.7 and 3.4 python
I have imported psutil as well. However the process is there b... | 2014/06/10 | [
"https://Stackoverflow.com/questions/24136733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016977/"
] | Here is the modified version that worked for me on Windows 7 with python v2.7
You were doing it in a wrong way here `if proc.name == process_name:` in your code. Try to `print proc.name` and you'll notice why your code didn't work as you were expecting.
Code:
```
import psutil
process_name = "System"
for proc in p... | I solved it by using WMI instead of psutil.
<https://pypi.python.org/pypi/WMI/>
install it on windows.
`import wmi
c = wmi.WMI ()
for process in c.Win32_Process ():
if "a" in process.Name:
print (process.ProcessId, process.Name)` |
24,136,733 | ```
process_name = "CCC.exe"
for proc in psutil.process_iter():
if proc.name == process_name:
print ("have")
else:
print ("Dont have")
```
I know for the fact that CCC.exe is running. I tried this code with both 2.7 and 3.4 python
I have imported psutil as well. However the process is there b... | 2014/06/10 | [
"https://Stackoverflow.com/questions/24136733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016977/"
] | `name` is a method of `proc`:
```
process_name = "CCC.exe"
for proc in psutil.process_iter():
if proc.name() == process_name:
print ("have")
else:
print ("Dont have")
``` | Here is the modified version that worked for me on Windows 7 with python v2.7
You were doing it in a wrong way here `if proc.name == process_name:` in your code. Try to `print proc.name` and you'll notice why your code didn't work as you were expecting.
Code:
```
import psutil
process_name = "System"
for proc in p... |
24,136,733 | ```
process_name = "CCC.exe"
for proc in psutil.process_iter():
if proc.name == process_name:
print ("have")
else:
print ("Dont have")
```
I know for the fact that CCC.exe is running. I tried this code with both 2.7 and 3.4 python
I have imported psutil as well. However the process is there b... | 2014/06/10 | [
"https://Stackoverflow.com/questions/24136733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016977/"
] | `name` is a method of `proc`:
```
process_name = "CCC.exe"
for proc in psutil.process_iter():
if proc.name() == process_name:
print ("have")
else:
print ("Dont have")
``` | I solved it by using WMI instead of psutil.
<https://pypi.python.org/pypi/WMI/>
install it on windows.
`import wmi
c = wmi.WMI ()
for process in c.Win32_Process ():
if "a" in process.Name:
print (process.ProcessId, process.Name)` |
57,640,451 | I'm trying to iterate each row in a Pandas dataframe named 'cd'.
If a specific cell, e.g. [row,empl\_accept] in a row contains a substring, then updates the value of an other cell, e.g.[row,empl\_accept\_a] in the same dataframe.
```py
for row in range(0,len(cd.index),1):
if 'Master' in cd.at[row,empl_accept]:
... | 2019/08/24 | [
"https://Stackoverflow.com/questions/57640451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10609069/"
] | Please do *not* use loops for this. You can do this in bulk with:
```
cd['empl_accept_a'] = cd['empl_accept'].str.contains('Master').astype(int).astype(str)
```
This will store `'0`' and `'1'` in the column. That being said, I am not convinced if storing this as strings is a good idea. You can just store these as `bo... | You need to check in your dataframe what value is placed at [row,empl\_accept]. I'm sure there will be some numeric value at this location in your dataframe. Just print the value and you'll see the problem if any.
```
print (cd.at[row,empl_accept])
``` |
52,338,706 | I already split the data into test and training set into the different folder. Now I need to load the patient data. Each patient has 8 images.
```py
def load_dataset(root_dir, split):
"""
load the data set numpy arrays saved by the preprocessing script
:param root_dir: path to input data
:param split: ... | 2018/09/14 | [
"https://Stackoverflow.com/questions/52338706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403249/"
] | It seems that `./data/preprocessed_data/train/Patient009969` is a directory, not a file.
`os.listdir()` returns both files and directories.
Maybe try using `os.walk()` instead. It treats files and directories separately, and can recurse inside the subdirectories to find more files in a iterative way:
```
data_paths ... | Do you have both files and directories inside your path? `os.listdir` will list both files and directories, so when you try to open a directory with `np.load` it will give that error. You can filter only files to avoid the error:
```
data_paths = [os.path.join(in_dir, f) for f in os.listdir(in_dir)]
data_paths = [i fo... |
52,338,706 | I already split the data into test and training set into the different folder. Now I need to load the patient data. Each patient has 8 images.
```py
def load_dataset(root_dir, split):
"""
load the data set numpy arrays saved by the preprocessing script
:param root_dir: path to input data
:param split: ... | 2018/09/14 | [
"https://Stackoverflow.com/questions/52338706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403249/"
] | Do you have both files and directories inside your path? `os.listdir` will list both files and directories, so when you try to open a directory with `np.load` it will give that error. You can filter only files to avoid the error:
```
data_paths = [os.path.join(in_dir, f) for f in os.listdir(in_dir)]
data_paths = [i fo... | I had the same problem but i resolved by changing my path from `Data/Train_Data/myDataset/(my images)` to `Data/Train_Data/(my images)` where the script python is in the same path as Data.
Hope this help. |
52,338,706 | I already split the data into test and training set into the different folder. Now I need to load the patient data. Each patient has 8 images.
```py
def load_dataset(root_dir, split):
"""
load the data set numpy arrays saved by the preprocessing script
:param root_dir: path to input data
:param split: ... | 2018/09/14 | [
"https://Stackoverflow.com/questions/52338706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403249/"
] | It seems that `./data/preprocessed_data/train/Patient009969` is a directory, not a file.
`os.listdir()` returns both files and directories.
Maybe try using `os.walk()` instead. It treats files and directories separately, and can recurse inside the subdirectories to find more files in a iterative way:
```
data_paths ... | I had the same problem but i resolved by changing my path from `Data/Train_Data/myDataset/(my images)` to `Data/Train_Data/(my images)` where the script python is in the same path as Data.
Hope this help. |
57,690,881 | Interested in the scala spark implementation of this
[split-column-of-list-into-multiple-columns-in-the-same-pyspark-dataframe](https://stackoverflow.com/questions/49650907/split-column-of-list-into-multiple-columns-in-the-same-pyspark-dataframe)
Given this Dataframe:
```
| X | Y|
+------... | 2019/08/28 | [
"https://Stackoverflow.com/questions/57690881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800939/"
] | I modified the loss functions and used the *metrics* in compile finction.
```
def recon_loss(inputs,outputs):
reconstruction_loss = original_dim*binary_crossentropy(inputs,outputs)
return K.mean(reconstruction_loss)
def latent_loss(inputs,outputs):
kl_loss = ... | Please check the type of each loss in your losses dictionary.
```
print (type(losses['recon_loss']))
``` |
56,034,031 | I am a new user of python and the neo4j. I just want to run the python file in Pycharm and connect to Neo4j. But the import of py2neo always does not work, I tried to use Virtualenv but still does not work. I have tried to put my py file inside env folder or outside and both don't work.
I really install the py2neo and... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56034031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11467790/"
] | check which python version is configured to run the project and make sure that module is installed for that version.
here is how to:
[Pycharm](https://www.jetbrains.com/help/idea/configuring-local-python-interpreters.html) | You need to install py2neo in virtual environment. if you haven't install.
and Check you python version on your machine and project.
```
pip install py2neo
``` |
56,034,031 | I am a new user of python and the neo4j. I just want to run the python file in Pycharm and connect to Neo4j. But the import of py2neo always does not work, I tried to use Virtualenv but still does not work. I have tried to put my py file inside env folder or outside and both don't work.
I really install the py2neo and... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56034031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11467790/"
] | check which python version is configured to run the project and make sure that module is installed for that version.
here is how to:
[Pycharm](https://www.jetbrains.com/help/idea/configuring-local-python-interpreters.html) | Go to Pycharm Preferences Plugins and look for Graph Database Support and install the plugin, then it should work. |
13,584,524 | In the old world I had a pretty ideal development setup going to work together with a webdesigner. Keep in mind we mostly do small/fast projects, so this is how it worked:
* I have a staging site on a server (Webfaction or other)
* Designer accesses that site and edits templates and assets to his satisfaction
* I SSH ... | 2012/11/27 | [
"https://Stackoverflow.com/questions/13584524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/102315/"
] | Reformat a string to display it as a MAC address:
```
var macadres = "0018103AB839";
var regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})";
var replace = "$1:$2:$3:$4:$5:$6";
var newformat = Regex.Replace(macadres, regex, replace);
// newformat = "00:18:10:3A:B8:39"
```
If you want to validate the input string us... | Suppose that we have the Mac Address stored in a long. This is how to have it in a formatted string:
```
ulong lMacAddr = 0x0018103AB839L;
string strMacAddr = String.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}",
(lMacAddr >> (8 * 5)) & 0xff,
(lMacAddr >> (8 * 4)) & 0xff,
(lMacAddr >> (8 * 3)) & 0xff... |
13,584,524 | In the old world I had a pretty ideal development setup going to work together with a webdesigner. Keep in mind we mostly do small/fast projects, so this is how it worked:
* I have a staging site on a server (Webfaction or other)
* Designer accesses that site and edits templates and assets to his satisfaction
* I SSH ... | 2012/11/27 | [
"https://Stackoverflow.com/questions/13584524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/102315/"
] | Reformat a string to display it as a MAC address:
```
var macadres = "0018103AB839";
var regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})";
var replace = "$1:$2:$3:$4:$5:$6";
var newformat = Regex.Replace(macadres, regex, replace);
// newformat = "00:18:10:3A:B8:39"
```
If you want to validate the input string us... | ```
string input = "0018103AB839";
var output = string.Join(":", Enumerable.Range(0, 6)
.Select(i => input.Substring(i * 2, 2)));
``` |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | You can replace the condition with itself:
```
s.format(table_name='users', condition='{condition}')
```
which gives us:
```
SELECT * FROM users WHERE {condition}
```
You can use this string later to fill in the condition. | I have been using this function for some time now, which casts the `Dict` of inputted keyword arguments as a `SafeDict` object that subclasses `Dict`.
```
def safeformat(str, **kwargs):
class SafeDict(dict):
def __missing__(self, key):
return '{' + key + '}'
replacem... |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | You can replace the condition with itself:
```
s.format(table_name='users', condition='{condition}')
```
which gives us:
```
SELECT * FROM users WHERE {condition}
```
You can use this string later to fill in the condition. | This builds on @Karoly Horvath's answer to add support for index keys and attribute access on named keys:
```
import re
def my_format(template, *args, **kwargs):
next_index = len(args)
while True:
try:
return template.format(*args, **kwargs)
except KeyError as e:
key = e.args[0]
finder =... |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | You can't use the format function because it will raise a KeyError.
`string.Template` supports safe substituion:
```
from string import Template
s = Template('SELECT * FROM $table_name WHERE $condition')
s.safe_substitute(table_name='users')
'SELECT * FROM users WHERE $condition'
```
If you use plain variable name... | I have been using this function for some time now, which casts the `Dict` of inputted keyword arguments as a `SafeDict` object that subclasses `Dict`.
```
def safeformat(str, **kwargs):
class SafeDict(dict):
def __missing__(self, key):
return '{' + key + '}'
replacem... |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | You can't use the format function because it will raise a KeyError.
`string.Template` supports safe substituion:
```
from string import Template
s = Template('SELECT * FROM $table_name WHERE $condition')
s.safe_substitute(table_name='users')
'SELECT * FROM users WHERE $condition'
```
If you use plain variable name... | This builds on @Karoly Horvath's answer to add support for index keys and attribute access on named keys:
```
import re
def my_format(template, *args, **kwargs):
next_index = len(args)
while True:
try:
return template.format(*args, **kwargs)
except KeyError as e:
key = e.args[0]
finder =... |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | You can't use the format function because it will raise a KeyError.
`string.Template` supports safe substituion:
```
from string import Template
s = Template('SELECT * FROM $table_name WHERE $condition')
s.safe_substitute(table_name='users')
'SELECT * FROM users WHERE $condition'
```
If you use plain variable name... | You can replace the condition with itself:
```
s.format(table_name='users', condition='{condition}')
```
which gives us:
```
SELECT * FROM users WHERE {condition}
```
You can use this string later to fill in the condition. |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | This builds on @Karoly Horvath's answer to add support for index keys and attribute access on named keys:
```
import re
def my_format(template, *args, **kwargs):
next_index = len(args)
while True:
try:
return template.format(*args, **kwargs)
except KeyError as e:
key = e.args[0]
finder =... | An alternative to `string.Template.safe_substitute` could be subclassing `string.Formatter` like so:
```
class LazyFormatter(string.Formatter):
def get_value(self, key, args, kwargs):
'''Overrides string.Formatter.get_value'''
if isinstance(key, (int, long)):
return args[key]
el... |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | You can replace the condition with itself:
```
s.format(table_name='users', condition='{condition}')
```
which gives us:
```
SELECT * FROM users WHERE {condition}
```
You can use this string later to fill in the condition. | This is a slight change to @ShawnFumo's answer which has a small bug. We need to add a word boundary check (the \b in the regular expression) to ensure that we are matching only the failing key and another key that starts with the same string. This prevents a missing {foo} key from also treating {food} and {foolish} as... |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | You can't use the format function because it will raise a KeyError.
`string.Template` supports safe substituion:
```
from string import Template
s = Template('SELECT * FROM $table_name WHERE $condition')
s.safe_substitute(table_name='users')
'SELECT * FROM users WHERE $condition'
```
If you use plain variable name... | An alternative to `string.Template.safe_substitute` could be subclassing `string.Formatter` like so:
```
class LazyFormatter(string.Formatter):
def get_value(self, key, args, kwargs):
'''Overrides string.Formatter.get_value'''
if isinstance(key, (int, long)):
return args[key]
el... |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | I have been using this function for some time now, which casts the `Dict` of inputted keyword arguments as a `SafeDict` object that subclasses `Dict`.
```
def safeformat(str, **kwargs):
class SafeDict(dict):
def __missing__(self, key):
return '{' + key + '}'
replacem... | This is a slight change to @ShawnFumo's answer which has a small bug. We need to add a word boundary check (the \b in the regular expression) to ensure that we are matching only the failing key and another key that starts with the same string. This prevents a missing {foo} key from also treating {food} and {foolish} as... |
9,955,715 | i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this:
```
s = "SELECT * FROM {table_name} WHERE {condition}"
```
I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this:
```
s1 = s.format(table_name = "users")
```
... | 2012/03/31 | [
"https://Stackoverflow.com/questions/9955715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198212/"
] | This builds on @Karoly Horvath's answer to add support for index keys and attribute access on named keys:
```
import re
def my_format(template, *args, **kwargs):
next_index = len(args)
while True:
try:
return template.format(*args, **kwargs)
except KeyError as e:
key = e.args[0]
finder =... | This is a slight change to @ShawnFumo's answer which has a small bug. We need to add a word boundary check (the \b in the regular expression) to ensure that we are matching only the failing key and another key that starts with the same string. This prevents a missing {foo} key from also treating {food} and {foolish} as... |
39,689,012 | i have written a code (python 2.7) that goes to a website [Cricket score](http://www.cricbuzz.com/live-cricket-scorecard/16822/ind-vs-nz-1st-test-new-zealand-tour-of-india-2016) and then takes out some data out of it to display just its score .It also periodically repeats and keeps running because the scores keep chang... | 2016/09/25 | [
"https://Stackoverflow.com/questions/39689012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6878406/"
] | i am sorry, i added a bit too many double-quotes in the above code. instead it should be this way:
```
asm (".section .drectve\n\t.ascii \" -export:DllInitialize=api.DllInitialize @2\"");
```
If you need to use it many times, consider putting it in a macro, e.g.
```
#ifdef _MSC_VER
#define FORWARDED_EXPORT_WITH... | here is how you can do it:
```
#ifdef _MSC_VER
#pragma comment (linker, "/export:DllInitialize=api.DllInitialize,@2")
#endif
#ifdef __GNUC__
asm (".section .drectve\n\t.ascii \" -export:\\\"DllInitialize=api.DllInitialize\\\" @2\"");
#endif
```
Note that "drectve" is not a typo, thats how it must be written ... |
71,940,988 | I have trained a model based on YOLOv5 on a custom dataset which has two classes (for example human and car)
I am using `detect.py` with the following command:
```
> python detect.py --weights best.pt --source video.mp4
```
I want only car class to be detected without detecting humans, how it could be done? | 2022/04/20 | [
"https://Stackoverflow.com/questions/71940988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16637958/"
] | You can specify classes, which you want to detect **[--classes]** arguments will be used.
**Example**
```
python detect.py --weights "your weights.pt" --source "video/image/stream" --classes 0,1,2
```
In above command, 0,1,2 are classId, so when you will run it, only mentioned classes will be detect. | I think you can use the argument --classes of detect.py. Just use the index of the classes. |
23,784,951 | I have a string that looks like this:
`POLYGON ((148210.445767647 172418.761192525, 148183.930888667 172366.054787545, 148183.866770629 172365.316772032, 148184.328078148 172364.737139913, 148220.543522168 172344.042601933, 148221.383518338 172343.971823159), (148221.97916844 172344.568316375, 148244.61381946 172406.6... | 2014/05/21 | [
"https://Stackoverflow.com/questions/23784951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1300454/"
] | The data structure you have defining your Polygon object looks very similar to a python tuple declaration. One option, albeit a bit hacky would be to use python's [AST parser](https://docs.python.org/2/library/ast.html#ast.literal_eval).
You would have to strip off the POLYGON part and this solution may not work for o... | Lets say u have a string that looks like this
my\_str = 'POLYGON ((148210.445767647 172418.761192525, 148183.930888667 172366.054787545, 148183.866770629 172365.316772032, 148184.328078148 172364.737139913, 148220.543522168 172344.042601933, 148221.383518338 172343.971823159), (148221.97916844 172344.568316375, 148244... |
23,784,951 | I have a string that looks like this:
`POLYGON ((148210.445767647 172418.761192525, 148183.930888667 172366.054787545, 148183.866770629 172365.316772032, 148184.328078148 172364.737139913, 148220.543522168 172344.042601933, 148221.383518338 172343.971823159), (148221.97916844 172344.568316375, 148244.61381946 172406.6... | 2014/05/21 | [
"https://Stackoverflow.com/questions/23784951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1300454/"
] | can you try?
```
import ast
POLYGON = '((148210.445767647 172418.761192525, 148183.930888667 172366.054787545, 148183.866770629 172365.316772032, 148184.328078148 172364.737139913, 148220.543522168 172344.042601933, 148221.383518338 172343.971823159), (148221.97916844 172344.568316375, 148244.61381946 172406.65193239... | Lets say u have a string that looks like this
my\_str = 'POLYGON ((148210.445767647 172418.761192525, 148183.930888667 172366.054787545, 148183.866770629 172365.316772032, 148184.328078148 172364.737139913, 148220.543522168 172344.042601933, 148221.383518338 172343.971823159), (148221.97916844 172344.568316375, 148244... |
54,485,654 | Simplified example of my code, please ignore syntax errors:
```
import numpy as np
import pandas as pd
import pymysql.cursors
from datetime import date, datetime
connection = pymysql.connect(host=,
user=,
password=,
... | 2019/02/01 | [
"https://Stackoverflow.com/questions/54485654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9637684/"
] | Have you seen the join command? This in combination with sort maybe what you are looking for. <https://shapeshed.com/unix-join/>
for example:
```
$ cat a
aaaa bbbb
cccc dddd
$ cat b
aaaa eeee
ffff gggg
$ join a b
aaaa bbbb eeee
```
If the values in the first column are not sorted, than you have to sort them... | There are different kinds and different tools to compare:
* diff
* cmp
* comm
* ...
All commands have options to vary the comparison.
For each command, you can specify filters. E.g.
```
# remove comments before comparison
diff <( grep -v ^# file1) <( grep -v ^# file2)
```
Without concrete examples, it is impossib... |
54,485,654 | Simplified example of my code, please ignore syntax errors:
```
import numpy as np
import pandas as pd
import pymysql.cursors
from datetime import date, datetime
connection = pymysql.connect(host=,
user=,
password=,
... | 2019/02/01 | [
"https://Stackoverflow.com/questions/54485654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9637684/"
] | There are different kinds and different tools to compare:
* diff
* cmp
* comm
* ...
All commands have options to vary the comparison.
For each command, you can specify filters. E.g.
```
# remove comments before comparison
diff <( grep -v ^# file1) <( grep -v ^# file2)
```
Without concrete examples, it is impossib... | You can use `awk`, like this:
```
awk 'NR==FNR{a[NR]=$1;b[NR]=$2;next}
a[FNR]==$1{printf "%s and %s match\n", b[FNR], $2}' file1 file2
```
Output:
```
bbbb and eeee match
```
Explanation (the same code broken into multiple lines):
```
# As long as we are reading file1, the overall record
# number NR is the ... |
54,485,654 | Simplified example of my code, please ignore syntax errors:
```
import numpy as np
import pandas as pd
import pymysql.cursors
from datetime import date, datetime
connection = pymysql.connect(host=,
user=,
password=,
... | 2019/02/01 | [
"https://Stackoverflow.com/questions/54485654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9637684/"
] | Have you seen the join command? This in combination with sort maybe what you are looking for. <https://shapeshed.com/unix-join/>
for example:
```
$ cat a
aaaa bbbb
cccc dddd
$ cat b
aaaa eeee
ffff gggg
$ join a b
aaaa bbbb eeee
```
If the values in the first column are not sorted, than you have to sort them... | Assuming your tab separated file maintains the correct file structure, this should work:
```
diff <(awk '{print $2}' f1) <(awk '{print $2}' f2)
# File names: f1, f2
# Column: 2nd column.
```
The output when there is something different,
```
2c2
< dx
---
> ldx
```
No output when the column is the same.
I tried @... |
54,485,654 | Simplified example of my code, please ignore syntax errors:
```
import numpy as np
import pandas as pd
import pymysql.cursors
from datetime import date, datetime
connection = pymysql.connect(host=,
user=,
password=,
... | 2019/02/01 | [
"https://Stackoverflow.com/questions/54485654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9637684/"
] | Assuming your tab separated file maintains the correct file structure, this should work:
```
diff <(awk '{print $2}' f1) <(awk '{print $2}' f2)
# File names: f1, f2
# Column: 2nd column.
```
The output when there is something different,
```
2c2
< dx
---
> ldx
```
No output when the column is the same.
I tried @... | You can use `awk`, like this:
```
awk 'NR==FNR{a[NR]=$1;b[NR]=$2;next}
a[FNR]==$1{printf "%s and %s match\n", b[FNR], $2}' file1 file2
```
Output:
```
bbbb and eeee match
```
Explanation (the same code broken into multiple lines):
```
# As long as we are reading file1, the overall record
# number NR is the ... |
54,485,654 | Simplified example of my code, please ignore syntax errors:
```
import numpy as np
import pandas as pd
import pymysql.cursors
from datetime import date, datetime
connection = pymysql.connect(host=,
user=,
password=,
... | 2019/02/01 | [
"https://Stackoverflow.com/questions/54485654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9637684/"
] | Have you seen the join command? This in combination with sort maybe what you are looking for. <https://shapeshed.com/unix-join/>
for example:
```
$ cat a
aaaa bbbb
cccc dddd
$ cat b
aaaa eeee
ffff gggg
$ join a b
aaaa bbbb eeee
```
If the values in the first column are not sorted, than you have to sort them... | You can use `awk`, like this:
```
awk 'NR==FNR{a[NR]=$1;b[NR]=$2;next}
a[FNR]==$1{printf "%s and %s match\n", b[FNR], $2}' file1 file2
```
Output:
```
bbbb and eeee match
```
Explanation (the same code broken into multiple lines):
```
# As long as we are reading file1, the overall record
# number NR is the ... |
26,506,830 | I have the expectation that `reduce(add,lst)` and `sum(lst)` should give me the same result, but
```
In [18]: class p():
def __init__(self, x, y):
self.x=x ; self.y=y
def __repr__(self):
return "(%r,%r)"%(self.x,self.y)
def __add__(self, P):
return p(self.x+P.x, self.y+P.y)
....:... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26506830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2749397/"
] | `reduce()` starts with `pts[0]` as the initial value (unless you give it an explicit starting value), but `sum()` defaults with `0`. From the [`sum()` function documentation](https://docs.python.org/2/library/functions.html#sum):
>
> `sum(iterable[, start])`
>
> Sums *start* and the items of an iterable from left... | If you define `__radd__` to special case if 0 is added to an instance of your object, then you can just use `sum()`.
```
... rest of Point class defn ...
def __radd__(self, other):
if other == 0:
return self
raise TypeError("invalid type to add to point")
print sum(pts)
```
will give `(0,5)`. |
63,940,481 | I know that my view is correct, however, when I put `{% url 'sub_detail' subc.id %}`in index.html it suddenly gives an error of no reverse match. Once I remove it index works fine. I tried changing id, but it did not change anything as it still gives the same error.
Thanks in advance.
views.py:
```
from django.shortc... | 2020/09/17 | [
"https://Stackoverflow.com/questions/63940481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14294805/"
] | Rather than many `if` statements, I just reproduced the `match` statement
with a repetition `$( ... )*` for all the available branches.
It seems to behave like the extensive `match` expression.
```rust
macro_rules! run_questions {
( $chosen_question: expr, $( $question_num: expr, $question_mod: expr ), * ) => {
... | The error message explained:
```
macro_rules! run_questions {
($chosen_question: expr, $($question_num: expr, $question_mod: expr),*) => {{
```
In the above pattern you have a repetition with the `*` operator that involves variables `$question_num` and `$question_mod`
```
if $chosen_question == $questio... |
70,699,537 | Given two arrays:
```
import numpy as np
array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
```
and WITHOUT the use of any loop or if-else statement; I am trying to create a third array that will take the value equal to the sum of the
(corresponding) elements from a... | 2022/01/13 | [
"https://Stackoverflow.com/questions/70699537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12256590/"
] | You can use three mask arrays, like so:
```
>>> array3 = np.zeros(array1.shape, dtype=array1.dtype)
>>> a1_gt = array1 > array2 # for when element at array 1 is greater
>>> a2_gt = array1 < array2 # for when element at array 2 is greater
>>> a1_eq_a2 = array1 == array2 # for when elements at array 1 and array 2 ... | I renamed your arrays to `a` and `b`
```
print((a>b)*(a+b)+(a==b)*(a*b)+(a<b)*(b-a))
```
direct comparison between arrays give you boolean reasults that you can interpret as `0` or `1`. That means a simple multiplication can turn an element "on" or "off". So we can just piece everything together. |
70,699,537 | Given two arrays:
```
import numpy as np
array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
```
and WITHOUT the use of any loop or if-else statement; I am trying to create a third array that will take the value equal to the sum of the
(corresponding) elements from a... | 2022/01/13 | [
"https://Stackoverflow.com/questions/70699537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12256590/"
] | You can use `np.select` here:
```
>>> import numpy as np
>>> array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
>>> array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
```
Here is the `help` for `np.select`:
```
select(condlist, choicelist, default=0)
Return an array drawn from elements in choicelist, depending ... | You can use three mask arrays, like so:
```
>>> array3 = np.zeros(array1.shape, dtype=array1.dtype)
>>> a1_gt = array1 > array2 # for when element at array 1 is greater
>>> a2_gt = array1 < array2 # for when element at array 2 is greater
>>> a1_eq_a2 = array1 == array2 # for when elements at array 1 and array 2 ... |
70,699,537 | Given two arrays:
```
import numpy as np
array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
```
and WITHOUT the use of any loop or if-else statement; I am trying to create a third array that will take the value equal to the sum of the
(corresponding) elements from a... | 2022/01/13 | [
"https://Stackoverflow.com/questions/70699537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12256590/"
] | You can use `np.select` here:
```
>>> import numpy as np
>>> array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
>>> array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
```
Here is the `help` for `np.select`:
```
select(condlist, choicelist, default=0)
Return an array drawn from elements in choicelist, depending ... | I renamed your arrays to `a` and `b`
```
print((a>b)*(a+b)+(a==b)*(a*b)+(a<b)*(b-a))
```
direct comparison between arrays give you boolean reasults that you can interpret as `0` or `1`. That means a simple multiplication can turn an element "on" or "off". So we can just piece everything together. |
70,699,537 | Given two arrays:
```
import numpy as np
array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
```
and WITHOUT the use of any loop or if-else statement; I am trying to create a third array that will take the value equal to the sum of the
(corresponding) elements from a... | 2022/01/13 | [
"https://Stackoverflow.com/questions/70699537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12256590/"
] | Using `numpy.select` with a default value:
```
array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
np.select([array1>array2, array1<array2],
[array1+array2, array2-array1],
default=array1*array2)
```
output: `array([ 9, 2, 16, 2, 30])` | I renamed your arrays to `a` and `b`
```
print((a>b)*(a+b)+(a==b)*(a*b)+(a<b)*(b-a))
```
direct comparison between arrays give you boolean reasults that you can interpret as `0` or `1`. That means a simple multiplication can turn an element "on" or "off". So we can just piece everything together. |
70,699,537 | Given two arrays:
```
import numpy as np
array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
```
and WITHOUT the use of any loop or if-else statement; I am trying to create a third array that will take the value equal to the sum of the
(corresponding) elements from a... | 2022/01/13 | [
"https://Stackoverflow.com/questions/70699537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12256590/"
] | You can use `np.select` here:
```
>>> import numpy as np
>>> array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
>>> array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
```
Here is the `help` for `np.select`:
```
select(condlist, choicelist, default=0)
Return an array drawn from elements in choicelist, depending ... | Using `numpy.select` with a default value:
```
array1 = np.array([7, 2, 4, 1, 20], dtype = "int")
array2 = np.array([2, 4, 4, 3, 10], dtype = "int")
np.select([array1>array2, array1<array2],
[array1+array2, array2-array1],
default=array1*array2)
```
output: `array([ 9, 2, 16, 2, 30])` |
39,372,494 | ```
#!/usr/bin/python
# -*- coding: utf-8 -*-
def to_weird_case(string):
lines = string.split()
new_word = ''
new_line = ''
for word in lines:
for item in word:
if word.index(item) %2 ==0:
item = item.upper()
new_word += item
else:
... | 2016/09/07 | [
"https://Stackoverflow.com/questions/39372494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6511336/"
] | First, you overwrite `new_line` with every iteration. Second, `new_word` is getting longer because you never "clear" it. Third, you add space to the end of the entire `new_line` and not after every new word (because of *Second*).
*See comments*
```
def to_weird_case(string):
lines = string.split()
new_line =... | It is correct that your code did not reset the value of `new_word` and you overwrote the `new_line` within the loop, but I'd like to share a next to one-liner solution with a regex:
```
import re
def to_weird_case(string):
return re.sub(r'(\S)(\S?)', lambda m: "{0}{1}".format(m.group(1).upper(), m.group(2)), strin... |
26,650,057 | I am working on a simple python script for retrieving information from a mysql database.
Here are my two examples which are almost IDENTICAL and the first successfully compiles while the second returns:
```
File "dbconnection.py", line 17
print ip
^
SyntaxError: invalid syntax
```
I have tried ... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26650057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210196/"
] | You used:
```
from __future__ import print_function
```
at the top of your module. This *disables* the `print` statement for that module so you can use the [`print()` **function**](https://docs.python.org/2/library/functions.html#print) instead:
```
print(id)
```
From the function documentation:
>
> **Note**: T... | from **future** import print\_function, division require Python 2.6 or later. **print\_function** will allow you to use print as a function. So you can't use it as **print ip**.
```
>>> from __future__ import print_function
>>>print('# of entries', len(dictionary), file=sys.stderr)
``` |
58,048,079 | Upon attempting to compile python 3.7 I hit `Could not import runpy module`:
```
jeremyr@b88:$ wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz
....
jeremyr@b88:~/Python-3.7.3$ ./configure --enable-optimizations
jeremyr@b88:~/Python-3.7.3$ make clean
jeremyr@b88:~/Python-3.7.3$ make -j32
....
g... | 2019/09/22 | [
"https://Stackoverflow.com/questions/58048079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3817456/"
] | It seems the enable-optimizations was the problem,
```
jeremyr@b88:~/Python-3.7.3$ ./configure
jeremyr@b88:~/Python-3.7.3$ make clean
```
takes care of it in my case. | In case others come across this question: I encountered the same problem on Centos 7. I also had `--enable-optimizations` but didn't want to remove that flag. Updating my build dependencies and then re-running solved the problem. To do that I ran:
```
sudo yum groupinstall "Development Tools" -y
```
In case the yum ... |
58,048,079 | Upon attempting to compile python 3.7 I hit `Could not import runpy module`:
```
jeremyr@b88:$ wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz
....
jeremyr@b88:~/Python-3.7.3$ ./configure --enable-optimizations
jeremyr@b88:~/Python-3.7.3$ make clean
jeremyr@b88:~/Python-3.7.3$ make -j32
....
g... | 2019/09/22 | [
"https://Stackoverflow.com/questions/58048079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3817456/"
] | It seems the enable-optimizations was the problem,
```
jeremyr@b88:~/Python-3.7.3$ ./configure
jeremyr@b88:~/Python-3.7.3$ make clean
```
takes care of it in my case. | For whomever MicGer's answer didn't work and would like to retain --enable-optimizations, check your gcc version. The error was solved for me on gcc 8.3.0. |
58,048,079 | Upon attempting to compile python 3.7 I hit `Could not import runpy module`:
```
jeremyr@b88:$ wget https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tar.xz
....
jeremyr@b88:~/Python-3.7.3$ ./configure --enable-optimizations
jeremyr@b88:~/Python-3.7.3$ make clean
jeremyr@b88:~/Python-3.7.3$ make -j32
....
g... | 2019/09/22 | [
"https://Stackoverflow.com/questions/58048079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3817456/"
] | In case others come across this question: I encountered the same problem on Centos 7. I also had `--enable-optimizations` but didn't want to remove that flag. Updating my build dependencies and then re-running solved the problem. To do that I ran:
```
sudo yum groupinstall "Development Tools" -y
```
In case the yum ... | For whomever MicGer's answer didn't work and would like to retain --enable-optimizations, check your gcc version. The error was solved for me on gcc 8.3.0. |
50,685,300 | I want to upload a flask server to bluemix. The structure of my project is something like this
* Classes
+ functions.py
* Watson
+ bot.py
* requirements.txt
* runtime.txt
* Procfile
* manifest.yml
my bot.py has this dependency:
```
from classes import functions
```
I have tried to include it in the manifest usi... | 2018/06/04 | [
"https://Stackoverflow.com/questions/50685300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4590839/"
] | You don't need to include it into the manifest file. Your entire app directory and its subdirectories are uploaded as part of the `push` command. Thereafter, it is possible to reference the file as shown.
This imports a file in the current directory:
```
import myfile
```
This should work for your `functions.py`:
... | Thanks a lot, this finally worked for me, the answered you pointed me to gave me the solution, thanks a lot again!
```
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
``` |
14,594,402 | I have 3 files a.py, b.py, c.py
I am trying to dynamically import a class called "C" defined in c.py from within a.py
and have the evaluated name available in b.py
python a.py is currently catching the NameError. I'm trying to avoid this and create an
instance in b.py which calls C.do\_int(10)
a.py
```
import b
#o... | 2013/01/30 | [
"https://Stackoverflow.com/questions/14594402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/566741/"
] | One way would be to use indexOf() to see if /admin is at pos 0.
```
var msg = "/admin this is a message";
var n = msg.indexOf("/admin");
```
If n = 0, then you know /admin was at the start of the message.
If the string does not exist in the message, n would equal -1. | You could use [`Array.slice(beg, end)`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice):
```javascript
var message = '/admin this is a message';
if (message.slice(0, 6) === '/admin') {
var adminMessage = message.slice(6).trim();
// Now do something with the "adminMessage".... |
14,594,402 | I have 3 files a.py, b.py, c.py
I am trying to dynamically import a class called "C" defined in c.py from within a.py
and have the evaluated name available in b.py
python a.py is currently catching the NameError. I'm trying to avoid this and create an
instance in b.py which calls C.do\_int(10)
a.py
```
import b
#o... | 2013/01/30 | [
"https://Stackoverflow.com/questions/14594402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/566741/"
] | One way would be to use indexOf() to see if /admin is at pos 0.
```
var msg = "/admin this is a message";
var n = msg.indexOf("/admin");
```
If n = 0, then you know /admin was at the start of the message.
If the string does not exist in the message, n would equal -1. | To achieve this, you could look for a "special command character" `/` and if found, get the text until next whitespace/end of line, check this against your list of commands and if there is a match, do some special action
```
var msg = "/admin this is a message", command, i;
if (msg.charAt(0) === '/') { // special
... |
14,594,402 | I have 3 files a.py, b.py, c.py
I am trying to dynamically import a class called "C" defined in c.py from within a.py
and have the evaluated name available in b.py
python a.py is currently catching the NameError. I'm trying to avoid this and create an
instance in b.py which calls C.do\_int(10)
a.py
```
import b
#o... | 2013/01/30 | [
"https://Stackoverflow.com/questions/14594402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/566741/"
] | One way would be to use indexOf() to see if /admin is at pos 0.
```
var msg = "/admin this is a message";
var n = msg.indexOf("/admin");
```
If n = 0, then you know /admin was at the start of the message.
If the string does not exist in the message, n would equal -1. | Or,
```
string.match(/^\/admin/)
```
According to <http://jsperf.com/matching-initial-substring>, this is up to two times faster than either `indexOf` or `slice` in the case that there is no match, but slower when there is a match. So if you expect to mainly have non-matches, this is faster, it would appear. |
14,594,402 | I have 3 files a.py, b.py, c.py
I am trying to dynamically import a class called "C" defined in c.py from within a.py
and have the evaluated name available in b.py
python a.py is currently catching the NameError. I'm trying to avoid this and create an
instance in b.py which calls C.do\_int(10)
a.py
```
import b
#o... | 2013/01/30 | [
"https://Stackoverflow.com/questions/14594402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/566741/"
] | Or,
```
string.match(/^\/admin/)
```
According to <http://jsperf.com/matching-initial-substring>, this is up to two times faster than either `indexOf` or `slice` in the case that there is no match, but slower when there is a match. So if you expect to mainly have non-matches, this is faster, it would appear. | You could use [`Array.slice(beg, end)`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice):
```javascript
var message = '/admin this is a message';
if (message.slice(0, 6) === '/admin') {
var adminMessage = message.slice(6).trim();
// Now do something with the "adminMessage".... |
14,594,402 | I have 3 files a.py, b.py, c.py
I am trying to dynamically import a class called "C" defined in c.py from within a.py
and have the evaluated name available in b.py
python a.py is currently catching the NameError. I'm trying to avoid this and create an
instance in b.py which calls C.do\_int(10)
a.py
```
import b
#o... | 2013/01/30 | [
"https://Stackoverflow.com/questions/14594402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/566741/"
] | Or,
```
string.match(/^\/admin/)
```
According to <http://jsperf.com/matching-initial-substring>, this is up to two times faster than either `indexOf` or `slice` in the case that there is no match, but slower when there is a match. So if you expect to mainly have non-matches, this is faster, it would appear. | To achieve this, you could look for a "special command character" `/` and if found, get the text until next whitespace/end of line, check this against your list of commands and if there is a match, do some special action
```
var msg = "/admin this is a message", command, i;
if (msg.charAt(0) === '/') { // special
... |
25,395,915 | I'm after a threadsafe queue that can be pickled or serialized to disk. Are there any datastructures in python that do this. The standard python Queue could not be pickled. | 2014/08/20 | [
"https://Stackoverflow.com/questions/25395915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3716723/"
] | This can be done using the [`copy_reg`](https://docs.python.org/2/library/copy_reg.html) module, but it's not the most elegant thing in the world:
```
import copy_reg
import threading
import pickle
from Queue import Queue as _Queue
# Make Queue a new-style class, so it can be used with copy_reg
class Queue(_Queue, ob... | There are modules like `dill` and `cloudpickle` that already know how to serialize a `Queue`.
They already have done the `copy_reg` for you.
```
>>> from Queue import Queue
>>> q = Queue()
>>> q.put('hey')
>>> import dill as pickle
>>> d = pickle.dumps(q)
>>> _q = pickle.loads(d)
>>> print _q.get()
hey
>>>
```
It's... |
45,447,325 | I am using service workers to create an offline page for my website.
At the moment I am saving `offline.html` into cache so that the browser can show this file if there is no interent connection.
In the `fetch` event of my service worker I attempt to load `index.html`, and if this fails (no internet connection) I loa... | 2017/08/01 | [
"https://Stackoverflow.com/questions/45447325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541397/"
] | I think we have all forgotten how the network request works from a browser's point of view.
The issue here is, `index.html` is served from the disk cache when the service worker intercepts requests.
**browser** ===> **Service Worker** ===>**fetch event**
>
> inside the fetch event, we have ,
>
>
> * Check If there... | David, you have two errors in one line.
Your line
```
return catches.match(event.request.url + OFFLINE_URL);
```
should be
```
return caches.match('offline.html');
```
It's `catches` and you haven't defined `OFFLINE_URL` and you don't need event request url |
45,447,325 | I am using service workers to create an offline page for my website.
At the moment I am saving `offline.html` into cache so that the browser can show this file if there is no interent connection.
In the `fetch` event of my service worker I attempt to load `index.html`, and if this fails (no internet connection) I loa... | 2017/08/01 | [
"https://Stackoverflow.com/questions/45447325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541397/"
] | I think we have all forgotten how the network request works from a browser's point of view.
The issue here is, `index.html` is served from the disk cache when the service worker intercepts requests.
**browser** ===> **Service Worker** ===>**fetch event**
>
> inside the fetch event, we have ,
>
>
> * Check If there... | I tried your code and I got the same result as you in the dev tools network tab. The network tab says it loaded the index.html from service-worker, but actually the service-worker returns the cached Offline Page as expected!
[](https://i.stack.imgur.com/m0OL... |
73,558,009 | I am attempting to run celery on it's own container from my Flask app. Right now I am just setting up a simple email app. The container CMD is
>
> "["celery", "worker", "--loglevel=info"]"
>
>
>
The message gets sent to the redis broker and celery picks it up, but celery gives me the error.
>
> "Received unregi... | 2022/08/31 | [
"https://Stackoverflow.com/questions/73558009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2236794/"
] | You need to pass the celery app to the worker with `--app` or `-A` flag (see my answer/example [here](https://stackoverflow.com/a/45908901/1011253)).
I would recommend to refactor a bit and extract this snippet:
```
celery = Celery(views.name,
broker='redis://redis:6379/0',
include=["v... | I finally figured it out. I used <https://blog.miguelgrinberg.com/post/celery-and-the-flask-application-factory-pattern>
as a reference. Now I can register new blueprints without touching the celery config. It is a work in progress, but now the containers are all up and running.
```
.
├── Docker
│ ├── celery
│ │ ... |
69,776,068 | I created a list of files in a directory using os.listdir(), and I'm trying to move percentages of the files(which are images) to different folders. So, I'm trying to move 70%, 15%, and 15% of the files to three different target folders.
Here is a slice of the file list:
```
print(cnv_list[0:5])
['CNV-9890872-5.jpeg'... | 2021/10/30 | [
"https://Stackoverflow.com/questions/69776068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7248794/"
] | If you can partition a list 70/30, and partition a list 50/50, then you can get 70/15/15 just by partitioning twice (once 70/30, once 50/50).
```
def partition_pct(lst, point):
idx = int(len(lst) * point)
return lst[:idx], lst[idx:]
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
l_70, l_30 = partiti... | Don't know if there's a better way but that's what i have:
```
def split(lst, weights):
sizes = []
fractions = []
for i in weights:
sizes.append(round(i * len(lst)))
fractions.append((i * len(lst)) % 1)
if sum(sizes) < len(lst):
i = max(range(len(fractions)), key=fractions.__get... |
54,758,444 | We have 32 V-CPUs with 28 GB ram with `Local Executor` but still airflow is utilizing all the resources and this is resulting in over-utilization of resources which ultimately breaks the system execution.
Below is the output for ps -aux ordered by memory usage.
```
PID %CPU %MEM VSZ RSS TTY STAT START ... | 2019/02/19 | [
"https://Stackoverflow.com/questions/54758444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6823560/"
] | [The size shown in `RSS` field is in `KB`](http://man7.org/linux/man-pages/man1/ps.1.html). The first process is using about 265 MB, not something over 10 GB.
The `MEM` field shows the memory usage in *percentage*, not GB. 0.9% of 28 GB is 252 MB. You can see stats about memory with the `free` command.
See <http://ma... | A recommended method is to set the CPUQuota of Airflow to max 80%. This will ensure that Airflow process does not eat up all the CPU resources which sometimes cause the system to hang.
You can use a ready-made AMI (namely, LightningFLow) from AWS Marketplace which is pre-configured with the recommended configurations.... |
56,791,917 | In the shell:
```
$ date
Do 27. Jun 15:13:13 CEST 2019
```
In python:
```
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2019, 6, 27, 15, 14, 51, 314560)
>>> a = datetime.now()
>>> a.strftime("%Y%m%d")
'20190627'
```
What is the format specifier needed to get the *exactly same output* as `... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56791917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10895273/"
] | Looks like you need to use the [locale](https://docs.python.org/2/library/locale.html) module
Playing in the shell:
```
$ date
Thu Jun 27 10:01:03 EDT 2019
$ LC_ALL=fr_FR.UTF-8 date
jeu. juin 27 10:01:12 EDT 2019
```
In python
```
$ LC_ALL=fr_FR.UTF-8 python
Python 2.7.5 (default, Jun 20 2019, 20:27:34)
[GCC 4.8.... | you can use [`.strftime`](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) to get your own string format.
in your case you want:
```py
from datetime import datetime
now = datetime.now()
print(now.strftime("%a %d. %b %H:%M:%S %Z %Y"))
```
**NOTE:** how the day/month name are printed will... |
56,791,917 | In the shell:
```
$ date
Do 27. Jun 15:13:13 CEST 2019
```
In python:
```
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2019, 6, 27, 15, 14, 51, 314560)
>>> a = datetime.now()
>>> a.strftime("%Y%m%d")
'20190627'
```
What is the format specifier needed to get the *exactly same output* as `... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56791917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10895273/"
] | you can use [`.strftime`](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) to get your own string format.
in your case you want:
```py
from datetime import datetime
now = datetime.now()
print(now.strftime("%a %d. %b %H:%M:%S %Z %Y"))
```
**NOTE:** how the day/month name are printed will... | ```
from datetime import datetime
now=datetime.now()
year=now.strftime("%Y")
print("Year:",year)
month=now.strftime("%m")
print("Month:",month)
day=now.strftime("%d")
print("Day:",day)
time=now.strftime("%H:%M:%S")
print("Time:",time)
date_time=now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
```
... |
56,791,917 | In the shell:
```
$ date
Do 27. Jun 15:13:13 CEST 2019
```
In python:
```
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2019, 6, 27, 15, 14, 51, 314560)
>>> a = datetime.now()
>>> a.strftime("%Y%m%d")
'20190627'
```
What is the format specifier needed to get the *exactly same output* as `... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56791917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10895273/"
] | Looks like you need to use the [locale](https://docs.python.org/2/library/locale.html) module
Playing in the shell:
```
$ date
Thu Jun 27 10:01:03 EDT 2019
$ LC_ALL=fr_FR.UTF-8 date
jeu. juin 27 10:01:12 EDT 2019
```
In python
```
$ LC_ALL=fr_FR.UTF-8 python
Python 2.7.5 (default, Jun 20 2019, 20:27:34)
[GCC 4.8.... | ```
from datetime import datetime
now=datetime.now()
year=now.strftime("%Y")
print("Year:",year)
month=now.strftime("%m")
print("Month:",month)
day=now.strftime("%d")
print("Day:",day)
time=now.strftime("%H:%M:%S")
print("Time:",time)
date_time=now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
```
... |
34,636,391 | I've been searching for the last few hours and cannot find a library that allows me to add hyperlinks to a word document using python. In my ideal world I'd be able to manipulate a word doc using python to add hyperlinks to footnotes which link to internal documents. Python-docx doesn't seem to have this feature.
It b... | 2016/01/06 | [
"https://Stackoverflow.com/questions/34636391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3368835/"
] | Hyperlinks can be added using the win32com package:
```
import win32com.client
#connect to Word (start it if it isn't already running)
wordapp = win32com.client.Dispatch("Word.Application")
#add a new document
doc = wordapp.Documents.Add()
#add some text and turn it into a hyperlink
para = doc.Paragraphs.Add()
para... | ```
# How to insert hyperlinks into an existing MS Word document using win32com:
# Use the same call as in the example above to connect to Word:
wordapp = win32com.client.Dispatch("Word.Application")
# Open the input file where you want to insert the hyperlinks:
wordapp.Documents.Open("my_input_file.docx")
# Select ... |
27,310,426 | I am trying to create an application which can detect heartbeat using your computer webcam. I am working on the code since 2 weeks and developed this code and here I got so far
How does it works? Illustrated below ...
1. Detecting face using opencv
2. Getting image of forehead
3. Applying filter to convert it into gr... | 2014/12/05 | [
"https://Stackoverflow.com/questions/27310426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3789164/"
] | The FFT is applied in a window with 128 samples.
```
int bufferSize = 128;
```
During the draw method the samples are stored in a array until fill the buffer for the FFT to be applied. Then after that the buffer is keep full. To insert a new sample the oldest is removed. gavg is the average gray channel color.
```
... | After you get samples size 128 that is bufferSize value or greater than that, forward the fft with the samples array and then get the peak value of the spectrum which would be our heartBeatRate
Following Papers explains the same :
1. Measuring Heart Rate from Video - *Isabel Bush* - Stanford - [link](https://web.stanf... |
53,477,114 | When i run `sudo docker-compose build` i get
```
Building web
Step 1/8 : FROM python:3.7-alpine
ERROR: Service 'web' failed to build: error parsing HTTP 403 response body: invalid character '<' looking for beginning of value: "<html><body><h1>403 Forbidden</h1>\nSince Docker is a US company, we must comply with US exp... | 2018/11/26 | [
"https://Stackoverflow.com/questions/53477114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4626485/"
] | You must be from restricted countries which are banned by docker (from [403](https://httpstatuses.com/403) status code). only way is to use proxies in your docker service.
>
> [Service]
>
>
> ...
>
>
> Environment="HTTP\_PROXY=http://proxy.example.com:80/
> HTTPS\_PROXY=http://proxy.example.com:80/"
>
>
> ...
>... | Include proxy details for each service in docker-compose.yml file, the sample configuration looks as below mentioned. Restart the docker and then run "docker-compose build" again. You might also run "docker-compose ps" to see if all the services mentioned in the compose file running successfully.
```
services:
<serv... |
53,477,114 | When i run `sudo docker-compose build` i get
```
Building web
Step 1/8 : FROM python:3.7-alpine
ERROR: Service 'web' failed to build: error parsing HTTP 403 response body: invalid character '<' looking for beginning of value: "<html><body><h1>403 Forbidden</h1>\nSince Docker is a US company, we must comply with US exp... | 2018/11/26 | [
"https://Stackoverflow.com/questions/53477114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4626485/"
] | You must be from restricted countries which are banned by docker (from [403](https://httpstatuses.com/403) status code). only way is to use proxies in your docker service.
>
> [Service]
>
>
> ...
>
>
> Environment="HTTP\_PROXY=http://proxy.example.com:80/
> HTTPS\_PROXY=http://proxy.example.com:80/"
>
>
> ...
>... | 1: edit resolve.conf in linux, add [ip](https://shecan.ir/) to the top of line in `resolv.conf`
```
nameserver {type ip}
```
2: use a poxy and create an account in docker hub (<https://hub.docker.com/>)
3:login into docker
```
sudo docker login
user:
password:
```
4: if you have problem try step 3 again |
53,477,114 | When i run `sudo docker-compose build` i get
```
Building web
Step 1/8 : FROM python:3.7-alpine
ERROR: Service 'web' failed to build: error parsing HTTP 403 response body: invalid character '<' looking for beginning of value: "<html><body><h1>403 Forbidden</h1>\nSince Docker is a US company, we must comply with US exp... | 2018/11/26 | [
"https://Stackoverflow.com/questions/53477114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4626485/"
] | You must be from restricted countries which are banned by docker (from [403](https://httpstatuses.com/403) status code). only way is to use proxies in your docker service.
>
> [Service]
>
>
> ...
>
>
> Environment="HTTP\_PROXY=http://proxy.example.com:80/
> HTTPS\_PROXY=http://proxy.example.com:80/"
>
>
> ...
>... | You need to make an env file which you put proxy settings in
/usr/local/etc/myproxy.env
```
HTTP_PROXY=http://proxy.mydomain.net:3128
HTTPS_PROXY=http://proxy.mydomain.net:3128
```
Then run docker-compose with something like:
```
docker-compose -f /opt/docker-compose.yml --env-file /usr/local/etc/myproxy.env up
``... |
53,477,114 | When i run `sudo docker-compose build` i get
```
Building web
Step 1/8 : FROM python:3.7-alpine
ERROR: Service 'web' failed to build: error parsing HTTP 403 response body: invalid character '<' looking for beginning of value: "<html><body><h1>403 Forbidden</h1>\nSince Docker is a US company, we must comply with US exp... | 2018/11/26 | [
"https://Stackoverflow.com/questions/53477114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4626485/"
] | Include proxy details for each service in docker-compose.yml file, the sample configuration looks as below mentioned. Restart the docker and then run "docker-compose build" again. You might also run "docker-compose ps" to see if all the services mentioned in the compose file running successfully.
```
services:
<serv... | 1: edit resolve.conf in linux, add [ip](https://shecan.ir/) to the top of line in `resolv.conf`
```
nameserver {type ip}
```
2: use a poxy and create an account in docker hub (<https://hub.docker.com/>)
3:login into docker
```
sudo docker login
user:
password:
```
4: if you have problem try step 3 again |
53,477,114 | When i run `sudo docker-compose build` i get
```
Building web
Step 1/8 : FROM python:3.7-alpine
ERROR: Service 'web' failed to build: error parsing HTTP 403 response body: invalid character '<' looking for beginning of value: "<html><body><h1>403 Forbidden</h1>\nSince Docker is a US company, we must comply with US exp... | 2018/11/26 | [
"https://Stackoverflow.com/questions/53477114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4626485/"
] | Include proxy details for each service in docker-compose.yml file, the sample configuration looks as below mentioned. Restart the docker and then run "docker-compose build" again. You might also run "docker-compose ps" to see if all the services mentioned in the compose file running successfully.
```
services:
<serv... | You need to make an env file which you put proxy settings in
/usr/local/etc/myproxy.env
```
HTTP_PROXY=http://proxy.mydomain.net:3128
HTTPS_PROXY=http://proxy.mydomain.net:3128
```
Then run docker-compose with something like:
```
docker-compose -f /opt/docker-compose.yml --env-file /usr/local/etc/myproxy.env up
``... |
27,058,171 | I am fairly new to python coding, I am getting this error when i try to run my python script, can anyone tell me what i am doing wrong here?
I am trying to make a maths competition program, it should first ask for both player's names, then continue on to give each player a question until both players have answered 10 q... | 2014/11/21 | [
"https://Stackoverflow.com/questions/27058171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4277883/"
] | ```
num2 = random.randrange(35)
```
can give you zero and will lead to a division by zero in this line:
```
ans2 = num1 / num2
```
you probably want something like:
```
random.randrange(start = 1, stop = 35 + 1)
```
which will generate numbers between 1 and 35 (both inclusive).
---
A side remark: unless yo... | Andre Holzner is correct. Here is some Examples of basic usage:
`>>> random.random() # Random float x, 0.0 <= x < 1.0
0.37444887175646646`
`>>> random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0
1.1800146073117523`
`>>> random.randint(1, 10) # Integer from 1 to 10, endpoints included
7`
`>>> random.randrange(0... |
41,241,005 | I am new to python and pandas. Trying to implement below condition but getting below error:
```
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
```
Below is my code:
```
df['col2'].fillna('.', inplace=True)
import copy
dict_YM = {}
for yearmonth in [201104, 201105,... | 2016/12/20 | [
"https://Stackoverflow.com/questions/41241005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7320512/"
] | You are printing `result` to `stdout`. The objects in this list are of type `Person`. That is the `Person.toString()` method is used to get a string representation of `result`.
As mentioned in the comments either change the `toString` method of Person to just return the value of `age` or iterate over the result and wr... | The method `public static <T> List<T> searchIn( List<T> list , Matcher<T> m )` returns `List<T>`, in your case Person if you want to get person age
try `result.stream().map(Person::getAge).forEach(System.out::println);` |
39,800,524 | The below function retains the values in its list every time it is run. I recently learned about this issue as a Python ['gotcha'](http://docs.python-guide.org/en/latest/writing/gotchas/) due to using a mutable default argument.
How do I fix it? Creating a global variable outside the function causes the same issue. P... | 2016/09/30 | [
"https://Stackoverflow.com/questions/39800524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827174/"
] | There is no need to pass the list inside the recursive function, just concatenate the results of the subsequent calls to the current list:
```
def build_category_list(categories, depth=0):
'''Builds category data for parent select field'''
items = []
for category in categories:
items.append((catego... | Passing the list in or by checking a null value would solve the issue. But you need to pass the list down the recursion:
```
def build_category_list(categories, depth=0, items=None):
if not items:
items = []
'''Builds category data for parent select field'''
for category in categories:
item... |
48,621,360 | I was browsing the python `asyncio` module documentation this night looking for some ideas for one of my course projects, but I soon find that there might be a lack of feature in python's standard `aysncio` module.
If you look through the documentation, you'll find that there's a callback based API and a coroutine bas... | 2018/02/05 | [
"https://Stackoverflow.com/questions/48621360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1548129/"
] | The reason a stream-based API is not provided is because streams offer *ordering* on top of the callbacks, and UDP communication is inherently unordered, so the two are fundamentally incompatible.
But none of that means you can't invoke coroutines from your callbacks - it's in fact quite easy! Starting from the [`Echo... | You might be interested in [this module providing high-level UDP endpoints for asyncio](https://gist.github.com/vxgmichel/e47bff34b68adb3cf6bd4845c4bed448):
```
async def main():
# Create a local UDP enpoint
local = await open_local_endpoint('localhost', 8888)
# Create a remote UDP enpoint, pointing to th... |
48,621,360 | I was browsing the python `asyncio` module documentation this night looking for some ideas for one of my course projects, but I soon find that there might be a lack of feature in python's standard `aysncio` module.
If you look through the documentation, you'll find that there's a callback based API and a coroutine bas... | 2018/02/05 | [
"https://Stackoverflow.com/questions/48621360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1548129/"
] | The reason a stream-based API is not provided is because streams offer *ordering* on top of the callbacks, and UDP communication is inherently unordered, so the two are fundamentally incompatible.
But none of that means you can't invoke coroutines from your callbacks - it's in fact quite easy! Starting from the [`Echo... | [asyncudp](https://github.com/eerimoq/asyncudp) provides easy to use UDP sockets in asyncio.
Here is an example:
```py
import asyncio
import asyncudp
async def main():
sock = await asyncudp.create_socket(remote_addr=('127.0.0.1', 9999))
sock.sendto(b'Hello!')
print(await sock.recvfrom())
sock.close()... |
48,621,360 | I was browsing the python `asyncio` module documentation this night looking for some ideas for one of my course projects, but I soon find that there might be a lack of feature in python's standard `aysncio` module.
If you look through the documentation, you'll find that there's a callback based API and a coroutine bas... | 2018/02/05 | [
"https://Stackoverflow.com/questions/48621360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1548129/"
] | You might be interested in [this module providing high-level UDP endpoints for asyncio](https://gist.github.com/vxgmichel/e47bff34b68adb3cf6bd4845c4bed448):
```
async def main():
# Create a local UDP enpoint
local = await open_local_endpoint('localhost', 8888)
# Create a remote UDP enpoint, pointing to th... | [asyncudp](https://github.com/eerimoq/asyncudp) provides easy to use UDP sockets in asyncio.
Here is an example:
```py
import asyncio
import asyncudp
async def main():
sock = await asyncudp.create_socket(remote_addr=('127.0.0.1', 9999))
sock.sendto(b'Hello!')
print(await sock.recvfrom())
sock.close()... |
31,221,586 | I was wondering if anyone could give me a hand with this...
Basically I am trying to modernize the news system of my site but I can't seem to limit the amount of posts showing in the foreach loop that is on my blog part of the site. I need to skip the first instance as it is already promoted at the top of the page. I'v... | 2015/07/04 | [
"https://Stackoverflow.com/questions/31221586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3925360/"
] | I assume that the $articles array has keys starting with 0. How about modifying the loop like this:
```
foreach ($articles as $key => $article)
```
and checking if $key is 0 at the beginning?
```
if($key == 0)
continue;
```
If the array keys are different: Create a new variable $i, set it to 0 and increase th... | To remove the first instance you can manually unset the item ($articles[0]) after making a copy of it or printing it as a featured news.
To limit the number of post you can use the mysql LIMIT Clause;
Or you can do something like this
```
foreach($articles as $key => $article){
if($key===0)
continue;
... |
31,221,586 | I was wondering if anyone could give me a hand with this...
Basically I am trying to modernize the news system of my site but I can't seem to limit the amount of posts showing in the foreach loop that is on my blog part of the site. I need to skip the first instance as it is already promoted at the top of the page. I'v... | 2015/07/04 | [
"https://Stackoverflow.com/questions/31221586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3925360/"
] | I assume that the $articles array has keys starting with 0. How about modifying the loop like this:
```
foreach ($articles as $key => $article)
```
and checking if $key is 0 at the beginning?
```
if($key == 0)
continue;
```
If the array keys are different: Create a new variable $i, set it to 0 and increase th... | There are a few things you can do:
1. If you $articles is an array of array, having continous indexes, use a `for` loop instead of `foreach` and do something like
```
for ($i = 1; $i < 8 : $i++ ) {
// and access it like
$articles[$i]['some_index'] ...
}
```
2. If it is not then you can use an external counte... |
56,513,918 | I have created a python script with a single function in it. Is there a way to call the function from the python terminal to test some arguments?
```py
import time
import random
def string_teletyper(string):
'''Prints out each character in a string with time delay'''
for chr in string:
print(chr, end... | 2019/06/09 | [
"https://Stackoverflow.com/questions/56513918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9906064/"
] | You can use `itertools.count()` to make infinite loop and `itertools.filterfalse` to filter values you don't need:
```
from random import randint
from itertools import count, filterfalse
f = filterfalse(lambda i: i % 2 == 0, [(yield randint(1, 99)) for i in count()])
for i in f:
print(i)
```
Prints:
```
...
6... | Do this: (Python 3)
```py
stream = (lambda min_, max_: type("randint_stream", (), {'__next__': (lambda self: 1+2*__import__('random').randint(min_-1,max_//2))}))(1,99)()
```
Get randint with `next(stream)`.
Change min and max by changing the `(1,99)`.
Real 1 line! Can change min & max!
```
... |
56,513,918 | I have created a python script with a single function in it. Is there a way to call the function from the python terminal to test some arguments?
```py
import time
import random
def string_teletyper(string):
'''Prints out each character in a string with time delay'''
for chr in string:
print(chr, end... | 2019/06/09 | [
"https://Stackoverflow.com/questions/56513918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9906064/"
] | ```
import random as rdm
g = (1+2*rdm.randint(0, 49) for r in iter(int, 1))
```
`rdm.randint(0, 49)` gives you a random int between 0 and 49. So `(1+2*rdm.randint(0, 49)` gives you a random number odd number between 1 and 99.
`iter(int, 1)` is an infinite iterator (which is always 0 and just used to keep the genera... | Do this: (Python 3)
```py
stream = (lambda min_, max_: type("randint_stream", (), {'__next__': (lambda self: 1+2*__import__('random').randint(min_-1,max_//2))}))(1,99)()
```
Get randint with `next(stream)`.
Change min and max by changing the `(1,99)`.
Real 1 line! Can change min & max!
```
... |
11,254,763 | I am making a script to test some software that is always running and I want to test it's recovery from a BSOD. Is there a way to throw a bsod from python without calling an external script or executable like OSR's BANG! | 2012/06/29 | [
"https://Stackoverflow.com/questions/11254763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470373/"
] | Funny thing. There is Windows kernel function that does just that.
I'm assuming that this is intended behaviour as the function has been ther
The following python code will crash any windows computer from usermode without any additional setup.
```
from ctypes import windll
from ctypes import c_int
from ctypes import... | i hope this helps (:
```
import ctypes
ntdll = ctypes.windll.ntdll
prev_value = ctypes.c_bool()
res = ctypes.c_ulong()
ntdll.RtlAdjustPrivilege(19, True, False, ctypes.byref(prev_value))
if not ntdll.NtRaiseHardError(0xDEADDEAD, 0, 0, 0, 6, ctypes.byref(res)):
print("BSOD Successfull!")
else:
print("BSOD Faile... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.